skillfit 0.9.0 → 0.10.0

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 (305) hide show
  1. package/README.md +41 -15
  2. package/README.zh-CN.md +41 -15
  3. package/benches/README.md +23 -0
  4. package/benches/contrib/README.md +1 -0
  5. package/benches/contrib/oss-skill-independent/README.md +60 -0
  6. package/benches/contrib/oss-skill-independent/bench.json +79 -0
  7. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/LICENSE +22 -0
  8. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/Readme.md +1015 -0
  9. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/esm.mjs +15 -0
  10. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/index.js +27 -0
  11. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/argument.js +147 -0
  12. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/command.js +1944 -0
  13. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/error.js +45 -0
  14. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/help.js +396 -0
  15. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/option.js +208 -0
  16. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/lib/suggestSimilar.js +100 -0
  17. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/package-support.json +16 -0
  18. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/package.json +63 -0
  19. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/test-clock.mjs +65 -0
  20. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/test.mjs +4 -0
  21. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/typings/index.d.ts +774 -0
  22. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/typings/index.test-d.ts +416 -0
  23. package/benches/contrib/oss-skill-independent/fixtures/commander-async-listener-order/upstream-package.json +69 -0
  24. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/LICENSE +22 -0
  25. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/Readme.md +1149 -0
  26. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/esm.mjs +16 -0
  27. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/index.js +24 -0
  28. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/argument.js +149 -0
  29. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/command.js +2662 -0
  30. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/error.js +39 -0
  31. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/help.js +713 -0
  32. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/option.js +367 -0
  33. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/lib/suggestSimilar.js +101 -0
  34. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/package-support.json +16 -0
  35. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/package.json +71 -0
  36. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/test-clock.mjs +65 -0
  37. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/test.mjs +4 -0
  38. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/typings/esm.d.mts +3 -0
  39. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/typings/index.d.ts +1045 -0
  40. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/typings/index.test-d.ts +737 -0
  41. package/benches/contrib/oss-skill-independent/fixtures/commander-output-isolation/upstream-package.json +82 -0
  42. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/index.d.ts +40 -0
  43. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/index.js +68 -0
  44. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/license +9 -0
  45. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/package.json +54 -0
  46. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/readme.md +99 -0
  47. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/test-clock.mjs +65 -0
  48. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/test.mjs +4 -0
  49. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/upstream-package.json +54 -0
  50. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/vendor/yocto-queue/index.js +67 -0
  51. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/vendor/yocto-queue/license +9 -0
  52. package/benches/contrib/oss-skill-independent/fixtures/limit-async-context/vendor/yocto-queue/package.json +46 -0
  53. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/index.d.ts +136 -0
  54. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/index.js +132 -0
  55. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/license +9 -0
  56. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/package.json +57 -0
  57. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/readme.md +181 -0
  58. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/test-clock.mjs +65 -0
  59. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/test.mjs +4 -0
  60. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/upstream-package.json +58 -0
  61. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/vendor/yocto-queue/index.js +84 -0
  62. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/vendor/yocto-queue/license +9 -0
  63. package/benches/contrib/oss-skill-independent/fixtures/limit-map-iteration-rejection/vendor/yocto-queue/package.json +48 -0
  64. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/index.d.ts +136 -0
  65. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/index.js +116 -0
  66. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/license +9 -0
  67. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/package.json +60 -0
  68. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/readme.md +170 -0
  69. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/test-clock.mjs +65 -0
  70. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/test.mjs +4 -0
  71. package/benches/contrib/oss-skill-independent/fixtures/throttle-sync-throw/upstream-package.json +60 -0
  72. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/index.d.ts +149 -0
  73. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/index.js +93 -0
  74. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/license +9 -0
  75. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/package.json +52 -0
  76. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/readme.md +192 -0
  77. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/test-clock.mjs +65 -0
  78. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/test.mjs +4 -0
  79. package/benches/contrib/oss-skill-independent/fixtures/timeout-custom-timers/upstream-package.json +52 -0
  80. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/index.d.ts +151 -0
  81. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/index.js +114 -0
  82. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/license +9 -0
  83. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/package.json +48 -0
  84. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/readme.md +158 -0
  85. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/test-clock.mjs +65 -0
  86. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/test.mjs +4 -0
  87. package/benches/contrib/oss-skill-independent/fixtures/timeout-infinity-abort/upstream-package.json +48 -0
  88. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/index.d.ts +151 -0
  89. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/index.js +122 -0
  90. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/license +9 -0
  91. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/package.json +50 -0
  92. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/readme.md +190 -0
  93. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/test-clock.mjs +65 -0
  94. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/test.mjs +4 -0
  95. package/benches/contrib/oss-skill-independent/fixtures/timeout-rejection-listener/upstream-package.json +50 -0
  96. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/LICENSE +22 -0
  97. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/Readme.md +1015 -0
  98. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/esm.mjs +15 -0
  99. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/index.js +27 -0
  100. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/argument.js +147 -0
  101. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/command.js +1948 -0
  102. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/error.js +45 -0
  103. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/help.js +396 -0
  104. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/option.js +208 -0
  105. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/lib/suggestSimilar.js +100 -0
  106. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/package-support.json +16 -0
  107. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/package.json +63 -0
  108. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/regression.test.mjs +5 -0
  109. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/test-clock.mjs +65 -0
  110. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/test.mjs +4 -0
  111. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/typings/index.d.ts +774 -0
  112. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/typings/index.test-d.ts +416 -0
  113. package/benches/contrib/oss-skill-independent/ground-truth/commander-async-listener-order/upstream-package.json +69 -0
  114. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/LICENSE +22 -0
  115. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/Readme.md +1149 -0
  116. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/esm.mjs +16 -0
  117. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/index.js +24 -0
  118. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/argument.js +149 -0
  119. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/command.js +2666 -0
  120. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/error.js +39 -0
  121. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/help.js +713 -0
  122. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/option.js +367 -0
  123. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/lib/suggestSimilar.js +101 -0
  124. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/package-support.json +16 -0
  125. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/package.json +71 -0
  126. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/regression.test.mjs +5 -0
  127. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/test-clock.mjs +65 -0
  128. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/test.mjs +4 -0
  129. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/typings/esm.d.mts +3 -0
  130. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/typings/index.d.ts +1045 -0
  131. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/typings/index.test-d.ts +737 -0
  132. package/benches/contrib/oss-skill-independent/ground-truth/commander-output-isolation/upstream-package.json +82 -0
  133. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/async-hooks-stub.js +15 -0
  134. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/index.d.ts +40 -0
  135. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/index.js +71 -0
  136. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/license +9 -0
  137. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/package.json +61 -0
  138. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/readme.md +99 -0
  139. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/regression.test.mjs +6 -0
  140. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/test-clock.mjs +65 -0
  141. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/test.mjs +4 -0
  142. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/upstream-package.json +54 -0
  143. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/vendor/yocto-queue/index.js +67 -0
  144. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/vendor/yocto-queue/license +9 -0
  145. package/benches/contrib/oss-skill-independent/ground-truth/limit-async-context/vendor/yocto-queue/package.json +46 -0
  146. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/index.d.ts +136 -0
  147. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/index.js +148 -0
  148. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/license +9 -0
  149. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/package.json +57 -0
  150. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/readme.md +181 -0
  151. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/regression.test.mjs +5 -0
  152. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/test-clock.mjs +65 -0
  153. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/test.mjs +4 -0
  154. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/upstream-package.json +58 -0
  155. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/vendor/yocto-queue/index.js +84 -0
  156. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/vendor/yocto-queue/license +9 -0
  157. package/benches/contrib/oss-skill-independent/ground-truth/limit-map-iteration-rejection/vendor/yocto-queue/package.json +48 -0
  158. package/benches/contrib/oss-skill-independent/ground-truth/oracle-commander-async-listener-order.mjs +1 -0
  159. package/benches/contrib/oss-skill-independent/ground-truth/oracle-commander-output-isolation.mjs +1 -0
  160. package/benches/contrib/oss-skill-independent/ground-truth/oracle-limit-async-context.mjs +1 -0
  161. package/benches/contrib/oss-skill-independent/ground-truth/oracle-limit-map-iteration-rejection.mjs +1 -0
  162. package/benches/contrib/oss-skill-independent/ground-truth/oracle-throttle-sync-throw.mjs +1 -0
  163. package/benches/contrib/oss-skill-independent/ground-truth/oracle-timeout-custom-timers.mjs +1 -0
  164. package/benches/contrib/oss-skill-independent/ground-truth/oracle-timeout-infinity-abort.mjs +1 -0
  165. package/benches/contrib/oss-skill-independent/ground-truth/oracle-timeout-rejection-listener.mjs +1 -0
  166. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/index.d.ts +136 -0
  167. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/index.js +121 -0
  168. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/license +9 -0
  169. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/package.json +60 -0
  170. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/readme.md +170 -0
  171. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/regression.test.mjs +6 -0
  172. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/test-clock.mjs +65 -0
  173. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/test.mjs +4 -0
  174. package/benches/contrib/oss-skill-independent/ground-truth/throttle-sync-throw/upstream-package.json +60 -0
  175. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/index.d.ts +149 -0
  176. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/index.js +95 -0
  177. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/license +9 -0
  178. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/package.json +52 -0
  179. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/readme.md +192 -0
  180. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/regression.test.mjs +5 -0
  181. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/test-clock.mjs +65 -0
  182. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/test.mjs +4 -0
  183. package/benches/contrib/oss-skill-independent/ground-truth/timeout-custom-timers/upstream-package.json +52 -0
  184. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/index.d.ts +151 -0
  185. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/index.js +114 -0
  186. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/license +9 -0
  187. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/package.json +48 -0
  188. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/readme.md +158 -0
  189. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/regression.test.mjs +5 -0
  190. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/test-clock.mjs +65 -0
  191. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/test.mjs +4 -0
  192. package/benches/contrib/oss-skill-independent/ground-truth/timeout-infinity-abort/upstream-package.json +48 -0
  193. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/index.d.ts +151 -0
  194. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/index.js +122 -0
  195. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/license +9 -0
  196. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/package.json +50 -0
  197. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/readme.md +190 -0
  198. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/regression.test.mjs +5 -0
  199. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/test-clock.mjs +65 -0
  200. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/test.mjs +4 -0
  201. package/benches/contrib/oss-skill-independent/ground-truth/timeout-rejection-listener/upstream-package.json +50 -0
  202. package/benches/contrib/oss-skill-independent/prompts/commander-async-listener-order.md +3 -0
  203. package/benches/contrib/oss-skill-independent/prompts/commander-output-isolation.md +3 -0
  204. package/benches/contrib/oss-skill-independent/prompts/limit-async-context.md +3 -0
  205. package/benches/contrib/oss-skill-independent/prompts/limit-map-iteration-rejection.md +3 -0
  206. package/benches/contrib/oss-skill-independent/prompts/throttle-sync-throw.md +3 -0
  207. package/benches/contrib/oss-skill-independent/prompts/timeout-custom-timers.md +3 -0
  208. package/benches/contrib/oss-skill-independent/prompts/timeout-infinity-abort.md +3 -0
  209. package/benches/contrib/oss-skill-independent/prompts/timeout-rejection-listener.md +3 -0
  210. package/benches/contrib/oss-skill-independent/provenance.json +1903 -0
  211. package/benches/contrib/oss-skill-independent/task-specs.json +63 -0
  212. package/benches/contrib/oss-skill-independent/test-clock.mjs +65 -0
  213. package/benches/contrib/oss-skill-independent/verifiers/cases.mjs +197 -0
  214. package/benches/contrib/oss-skill-independent/verifiers/commander-async-listener-order.mjs +1 -0
  215. package/benches/contrib/oss-skill-independent/verifiers/commander-output-isolation.mjs +1 -0
  216. package/benches/contrib/oss-skill-independent/verifiers/grade.mjs +48 -0
  217. package/benches/contrib/oss-skill-independent/verifiers/limit-async-context.mjs +1 -0
  218. package/benches/contrib/oss-skill-independent/verifiers/limit-map-iteration-rejection.mjs +1 -0
  219. package/benches/contrib/oss-skill-independent/verifiers/probe.mjs +16 -0
  220. package/benches/contrib/oss-skill-independent/verifiers/regression-evidence.mjs +105 -0
  221. package/benches/contrib/oss-skill-independent/verifiers/test-reporter.mjs +29 -0
  222. package/benches/contrib/oss-skill-independent/verifiers/throttle-sync-throw.mjs +1 -0
  223. package/benches/contrib/oss-skill-independent/verifiers/timeout-custom-timers.mjs +1 -0
  224. package/benches/contrib/oss-skill-independent/verifiers/timeout-infinity-abort.mjs +1 -0
  225. package/benches/contrib/oss-skill-independent/verifiers/timeout-rejection-listener.mjs +1 -0
  226. package/dist/cli.js +166 -53
  227. package/dist/commands/bench-check-json.test.js +221 -0
  228. package/dist/commands/bench-check-report.js +48 -0
  229. package/dist/commands/bench-command-template.js +129 -0
  230. package/dist/commands/bench-manage.js +91 -0
  231. package/dist/commands/bench-manage.test.js +87 -0
  232. package/dist/commands/bench.js +68 -38
  233. package/dist/commands/bench.test.js +101 -0
  234. package/dist/commands/eval-component.js +17 -0
  235. package/dist/commands/eval-export.js +152 -0
  236. package/dist/commands/eval-export.test.js +122 -0
  237. package/dist/commands/eval.js +14 -3
  238. package/dist/commands/eval.test.js +58 -1
  239. package/dist/harness/bench.js +21 -2
  240. package/dist/harness/eval-audit.js +42 -4
  241. package/dist/harness/eval-budget.js +51 -0
  242. package/dist/harness/eval-budget.test.js +210 -0
  243. package/dist/harness/eval-component.test.js +36 -0
  244. package/dist/harness/eval-contract.js +5 -1
  245. package/dist/harness/replay-package.js +85 -0
  246. package/dist/harness/runner.js +22 -1
  247. package/docs/bench-authoring.md +40 -0
  248. package/docs/bench-check-json.md +115 -0
  249. package/docs/case-management.md +65 -0
  250. package/docs/eval-component.md +60 -49
  251. package/docs/examples/check-receiver-mechanism-proposal.mjs +124 -0
  252. package/docs/examples/prepare-native-diff-probe.mjs +75 -0
  253. package/docs/examples/reproduce-independent-comparison-budget.mjs +73 -0
  254. package/docs/first-real-eval.md +6 -0
  255. package/docs/growth-roadmap-2026-10.md +57 -93
  256. package/docs/metrics.md +21 -0
  257. package/docs/plans/2026-10-14-evidence-and-release-sequence.md +30 -13
  258. package/docs/plans/2026-10-15-independent-comparison-budget.json +1769 -0
  259. package/docs/plans/2026-10-15-independent-comparison-inputs.json +373 -0
  260. package/docs/plans/2026-10-15-independent-comparison-proposal.md +177 -0
  261. package/docs/plans/2026-10-15-native-diff-mechanism.md +105 -0
  262. package/docs/plans/2026-10-15-receiver-mechanism-proposal.json +342 -0
  263. package/docs/plans/2026-10-15-receiver-mechanism-proposal.md +146 -0
  264. package/docs/plans/2026-10-15-receiver-mechanism-verification.json +105 -0
  265. package/docs/plans/2026-10-16-case-workflow-and-release.md +30 -0
  266. package/docs/releases/0.10.0.md +45 -0
  267. package/docs/releases/0.9.0-verification.json +38 -0
  268. package/docs/releases/0.9.0.md +20 -3
  269. package/docs/releases/0.9.1-first-publication.json +249 -0
  270. package/docs/releases/0.9.1-verification.json +122 -0
  271. package/docs/releases/0.9.1.md +65 -0
  272. package/docs/releases/trusted-publishing.md +114 -0
  273. package/docs/replay-packages.md +88 -0
  274. package/docs/schemas/bench-check.schema.json +109 -0
  275. package/docs/schemas/eval-request.schema.json +12 -0
  276. package/docs/sharing-results.md +6 -0
  277. package/docs/skill-evaluation-evidence.md +52 -0
  278. package/evidence/2026-10-15-diagnosing-receiver-correction.md +140 -0
  279. package/evidence/2026-10-15-independent-comparison-regression-stop.md +162 -0
  280. package/evidence/2026-10-15-independent-offline-readiness.md +144 -0
  281. package/evidence/2026-10-15-native-diff-mechanism.md +196 -0
  282. package/evidence/2026-10-15-receiver-mechanism-stop.md +154 -0
  283. package/evidence/artifacts/2026-10-15-diagnosing-receiver-correction/README.md +35 -0
  284. package/evidence/artifacts/2026-10-15-diagnosing-receiver-correction/expected.json +577 -0
  285. package/evidence/artifacts/2026-10-15-diagnosing-receiver-correction/receiver-contract.test.mjs +138 -0
  286. package/evidence/artifacts/2026-10-15-diagnosing-receiver-correction/replay.mjs +127 -0
  287. package/evidence/artifacts/2026-10-15-diagnosing-receiver-correction/verification.json +105 -0
  288. package/evidence/artifacts/2026-10-15-independent-comparison-regression-stop/README.md +32 -0
  289. package/evidence/artifacts/2026-10-15-independent-comparison-regression-stop/checks.json +32 -0
  290. package/evidence/artifacts/2026-10-15-independent-comparison-regression-stop/package.tar.gz +0 -0
  291. package/evidence/artifacts/2026-10-15-independent-comparison-regression-stop/verification.json +25 -0
  292. package/evidence/artifacts/2026-10-15-independent-offline-readiness/README.md +17 -0
  293. package/evidence/artifacts/2026-10-15-independent-offline-readiness/verification.json +1548 -0
  294. package/evidence/artifacts/2026-10-15-native-diff-mechanism/README.md +48 -0
  295. package/evidence/artifacts/2026-10-15-native-diff-mechanism/package.tar.gz +0 -0
  296. package/evidence/artifacts/2026-10-15-receiver-mechanism-stop/README.md +38 -0
  297. package/evidence/artifacts/2026-10-15-receiver-mechanism-stop/checks.json +118 -0
  298. package/evidence/artifacts/2026-10-15-receiver-mechanism-stop/package.tar.gz +0 -0
  299. package/evidence/artifacts/2026-10-15-receiver-mechanism-stop/verification.json +36 -0
  300. package/evidence/inputs/diagnosing-bugs-compact-v4.1-receiver/LICENSE +21 -0
  301. package/evidence/inputs/diagnosing-bugs-compact-v4.1-receiver/SKILL.md +51 -0
  302. package/evidence/inputs/diagnosing-bugs-compact-v4.1-receiver/agents/openai.yaml +3 -0
  303. package/evidence/inputs/diagnosing-bugs-compact-v4.1-receiver/scripts/hitl-loop.template.sh +44 -0
  304. package/package.json +3 -3
  305. package/skills/skillfit/SKILL.md +17 -5
@@ -0,0 +1,2666 @@
1
+ const EventEmitter = require('node:events').EventEmitter;
2
+ const childProcess = require('node:child_process');
3
+ const path = require('node:path');
4
+ const fs = require('node:fs');
5
+ const process = require('node:process');
6
+
7
+ const { Argument, humanReadableArgName } = require('./argument.js');
8
+ const { CommanderError } = require('./error.js');
9
+ const { Help, stripColor } = require('./help.js');
10
+ const { Option, DualOptions } = require('./option.js');
11
+ const { suggestSimilar } = require('./suggestSimilar');
12
+
13
+ class Command extends EventEmitter {
14
+ /**
15
+ * Initialize a new `Command`.
16
+ *
17
+ * @param {string} [name]
18
+ */
19
+
20
+ constructor(name) {
21
+ super();
22
+ /** @type {Command[]} */
23
+ this.commands = [];
24
+ /** @type {Option[]} */
25
+ this.options = [];
26
+ this.parent = null;
27
+ this._allowUnknownOption = false;
28
+ this._allowExcessArguments = false;
29
+ /** @type {Argument[]} */
30
+ this.registeredArguments = [];
31
+ this._args = this.registeredArguments; // deprecated old name
32
+ /** @type {string[]} */
33
+ this.args = []; // cli args with options removed
34
+ this.rawArgs = [];
35
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
36
+ this._scriptPath = null;
37
+ this._name = name || '';
38
+ this._optionValues = {};
39
+ this._optionValueSources = {}; // default, env, cli etc
40
+ this._storeOptionsAsProperties = false;
41
+ this._actionHandler = null;
42
+ this._executableHandler = false;
43
+ this._executableFile = null; // custom name for executable
44
+ this._executableDir = null; // custom search directory for subcommands
45
+ this._defaultCommandName = null;
46
+ this._exitCallback = null;
47
+ this._aliases = [];
48
+ this._combineFlagAndOptionalValue = true;
49
+ this._description = '';
50
+ this._summary = '';
51
+ this._argsDescription = undefined; // legacy
52
+ this._enablePositionalOptions = false;
53
+ this._passThroughOptions = false;
54
+ this._lifeCycleHooks = {}; // a hash of arrays
55
+ /** @type {(boolean | string)} */
56
+ this._showHelpAfterError = false;
57
+ this._showSuggestionAfterError = true;
58
+ this._savedState = null; // used in save/restoreStateBeforeParse
59
+
60
+ // see configureOutput() for docs
61
+ this._outputConfiguration = {
62
+ writeOut: (str) => process.stdout.write(str),
63
+ writeErr: (str) => process.stderr.write(str),
64
+ outputError: (str, write) => write(str),
65
+ getOutHelpWidth: () =>
66
+ process.stdout.isTTY ? process.stdout.columns : undefined,
67
+ getErrHelpWidth: () =>
68
+ process.stderr.isTTY ? process.stderr.columns : undefined,
69
+ getOutHasColors: () =>
70
+ useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
71
+ getErrHasColors: () =>
72
+ useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
73
+ stripColor: (str) => stripColor(str),
74
+ };
75
+
76
+ this._hidden = false;
77
+ /** @type {(Option | null | undefined)} */
78
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
79
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
80
+ /** @type {Command} */
81
+ this._helpCommand = undefined; // lazy initialised, inherited
82
+ this._helpConfiguration = {};
83
+ }
84
+
85
+ /**
86
+ * Copy settings that are useful to have in common across root command and subcommands.
87
+ *
88
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
89
+ *
90
+ * @param {Command} sourceCommand
91
+ * @return {Command} `this` command for chaining
92
+ */
93
+ copyInheritedSettings(sourceCommand) {
94
+ this._outputConfiguration = sourceCommand._outputConfiguration;
95
+ this._helpOption = sourceCommand._helpOption;
96
+ this._helpCommand = sourceCommand._helpCommand;
97
+ this._helpConfiguration = sourceCommand._helpConfiguration;
98
+ this._exitCallback = sourceCommand._exitCallback;
99
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
100
+ this._combineFlagAndOptionalValue =
101
+ sourceCommand._combineFlagAndOptionalValue;
102
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
103
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
104
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
105
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
106
+
107
+ return this;
108
+ }
109
+
110
+ /**
111
+ * @returns {Command[]}
112
+ * @private
113
+ */
114
+
115
+ _getCommandAndAncestors() {
116
+ const result = [];
117
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
118
+ for (let command = this; command; command = command.parent) {
119
+ result.push(command);
120
+ }
121
+ return result;
122
+ }
123
+
124
+ /**
125
+ * Define a command.
126
+ *
127
+ * There are two styles of command: pay attention to where to put the description.
128
+ *
129
+ * @example
130
+ * // Command implemented using action handler (description is supplied separately to `.command`)
131
+ * program
132
+ * .command('clone <source> [destination]')
133
+ * .description('clone a repository into a newly created directory')
134
+ * .action((source, destination) => {
135
+ * console.log('clone command called');
136
+ * });
137
+ *
138
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
139
+ * program
140
+ * .command('start <service>', 'start named service')
141
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
142
+ *
143
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
144
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
145
+ * @param {object} [execOpts] - configuration options (for executable)
146
+ * @return {Command} returns new command for action handler, or `this` for executable command
147
+ */
148
+
149
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
150
+ let desc = actionOptsOrExecDesc;
151
+ let opts = execOpts;
152
+ if (typeof desc === 'object' && desc !== null) {
153
+ opts = desc;
154
+ desc = null;
155
+ }
156
+ opts = opts || {};
157
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
158
+
159
+ const cmd = this.createCommand(name);
160
+ if (desc) {
161
+ cmd.description(desc);
162
+ cmd._executableHandler = true;
163
+ }
164
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
165
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
166
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
167
+ if (args) cmd.arguments(args);
168
+ this._registerCommand(cmd);
169
+ cmd.parent = this;
170
+ cmd.copyInheritedSettings(this);
171
+
172
+ if (desc) return this;
173
+ return cmd;
174
+ }
175
+
176
+ /**
177
+ * Factory routine to create a new unattached command.
178
+ *
179
+ * See .command() for creating an attached subcommand, which uses this routine to
180
+ * create the command. You can override createCommand to customise subcommands.
181
+ *
182
+ * @param {string} [name]
183
+ * @return {Command} new command
184
+ */
185
+
186
+ createCommand(name) {
187
+ return new Command(name);
188
+ }
189
+
190
+ /**
191
+ * You can customise the help with a subclass of Help by overriding createHelp,
192
+ * or by overriding Help properties using configureHelp().
193
+ *
194
+ * @return {Help}
195
+ */
196
+
197
+ createHelp() {
198
+ return Object.assign(new Help(), this.configureHelp());
199
+ }
200
+
201
+ /**
202
+ * You can customise the help by overriding Help properties using configureHelp(),
203
+ * or with a subclass of Help by overriding createHelp().
204
+ *
205
+ * @param {object} [configuration] - configuration options
206
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
207
+ */
208
+
209
+ configureHelp(configuration) {
210
+ if (configuration === undefined) return this._helpConfiguration;
211
+
212
+ this._helpConfiguration = configuration;
213
+ return this;
214
+ }
215
+
216
+ /**
217
+ * The default output goes to stdout and stderr. You can customise this for special
218
+ * applications. You can also customise the display of errors by overriding outputError.
219
+ *
220
+ * The configuration properties are all functions:
221
+ *
222
+ * // change how output being written, defaults to stdout and stderr
223
+ * writeOut(str)
224
+ * writeErr(str)
225
+ * // change how output being written for errors, defaults to writeErr
226
+ * outputError(str, write) // used for displaying errors and not used for displaying help
227
+ * // specify width for wrapping help
228
+ * getOutHelpWidth()
229
+ * getErrHelpWidth()
230
+ * // color support, currently only used with Help
231
+ * getOutHasColors()
232
+ * getErrHasColors()
233
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
234
+ *
235
+ * @param {object} [configuration] - configuration options
236
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
237
+ */
238
+
239
+ configureOutput(configuration) {
240
+ if (configuration === undefined) return this._outputConfiguration;
241
+
242
+ this._outputConfiguration = Object.assign(
243
+ {},
244
+ this._outputConfiguration,
245
+ configuration,
246
+ );
247
+ return this;
248
+ }
249
+
250
+ /**
251
+ * Display the help or a custom message after an error occurs.
252
+ *
253
+ * @param {(boolean|string)} [displayHelp]
254
+ * @return {Command} `this` command for chaining
255
+ */
256
+ showHelpAfterError(displayHelp = true) {
257
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
258
+ this._showHelpAfterError = displayHelp;
259
+ return this;
260
+ }
261
+
262
+ /**
263
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
264
+ *
265
+ * @param {boolean} [displaySuggestion]
266
+ * @return {Command} `this` command for chaining
267
+ */
268
+ showSuggestionAfterError(displaySuggestion = true) {
269
+ this._showSuggestionAfterError = !!displaySuggestion;
270
+ return this;
271
+ }
272
+
273
+ /**
274
+ * Add a prepared subcommand.
275
+ *
276
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
277
+ *
278
+ * @param {Command} cmd - new subcommand
279
+ * @param {object} [opts] - configuration options
280
+ * @return {Command} `this` command for chaining
281
+ */
282
+
283
+ addCommand(cmd, opts) {
284
+ if (!cmd._name) {
285
+ throw new Error(`Command passed to .addCommand() must have a name
286
+ - specify the name in Command constructor or using .name()`);
287
+ }
288
+
289
+ opts = opts || {};
290
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
291
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
292
+
293
+ this._registerCommand(cmd);
294
+ cmd.parent = this;
295
+ cmd._checkForBrokenPassThrough();
296
+
297
+ return this;
298
+ }
299
+
300
+ /**
301
+ * Factory routine to create a new unattached argument.
302
+ *
303
+ * See .argument() for creating an attached argument, which uses this routine to
304
+ * create the argument. You can override createArgument to return a custom argument.
305
+ *
306
+ * @param {string} name
307
+ * @param {string} [description]
308
+ * @return {Argument} new argument
309
+ */
310
+
311
+ createArgument(name, description) {
312
+ return new Argument(name, description);
313
+ }
314
+
315
+ /**
316
+ * Define argument syntax for command.
317
+ *
318
+ * The default is that the argument is required, and you can explicitly
319
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
320
+ *
321
+ * @example
322
+ * program.argument('<input-file>');
323
+ * program.argument('[output-file]');
324
+ *
325
+ * @param {string} name
326
+ * @param {string} [description]
327
+ * @param {(Function|*)} [fn] - custom argument processing function
328
+ * @param {*} [defaultValue]
329
+ * @return {Command} `this` command for chaining
330
+ */
331
+ argument(name, description, fn, defaultValue) {
332
+ const argument = this.createArgument(name, description);
333
+ if (typeof fn === 'function') {
334
+ argument.default(defaultValue).argParser(fn);
335
+ } else {
336
+ argument.default(fn);
337
+ }
338
+ this.addArgument(argument);
339
+ return this;
340
+ }
341
+
342
+ /**
343
+ * Define argument syntax for command, adding multiple at once (without descriptions).
344
+ *
345
+ * See also .argument().
346
+ *
347
+ * @example
348
+ * program.arguments('<cmd> [env]');
349
+ *
350
+ * @param {string} names
351
+ * @return {Command} `this` command for chaining
352
+ */
353
+
354
+ arguments(names) {
355
+ names
356
+ .trim()
357
+ .split(/ +/)
358
+ .forEach((detail) => {
359
+ this.argument(detail);
360
+ });
361
+ return this;
362
+ }
363
+
364
+ /**
365
+ * Define argument syntax for command, adding a prepared argument.
366
+ *
367
+ * @param {Argument} argument
368
+ * @return {Command} `this` command for chaining
369
+ */
370
+ addArgument(argument) {
371
+ const previousArgument = this.registeredArguments.slice(-1)[0];
372
+ if (previousArgument && previousArgument.variadic) {
373
+ throw new Error(
374
+ `only the last argument can be variadic '${previousArgument.name()}'`,
375
+ );
376
+ }
377
+ if (
378
+ argument.required &&
379
+ argument.defaultValue !== undefined &&
380
+ argument.parseArg === undefined
381
+ ) {
382
+ throw new Error(
383
+ `a default value for a required argument is never used: '${argument.name()}'`,
384
+ );
385
+ }
386
+ this.registeredArguments.push(argument);
387
+ return this;
388
+ }
389
+
390
+ /**
391
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
392
+ *
393
+ * @example
394
+ * program.helpCommand('help [cmd]');
395
+ * program.helpCommand('help [cmd]', 'show help');
396
+ * program.helpCommand(false); // suppress default help command
397
+ * program.helpCommand(true); // add help command even if no subcommands
398
+ *
399
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
400
+ * @param {string} [description] - custom description
401
+ * @return {Command} `this` command for chaining
402
+ */
403
+
404
+ helpCommand(enableOrNameAndArgs, description) {
405
+ if (typeof enableOrNameAndArgs === 'boolean') {
406
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
407
+ return this;
408
+ }
409
+
410
+ enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
411
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
412
+ const helpDescription = description ?? 'display help for command';
413
+
414
+ const helpCommand = this.createCommand(helpName);
415
+ helpCommand.helpOption(false);
416
+ if (helpArgs) helpCommand.arguments(helpArgs);
417
+ if (helpDescription) helpCommand.description(helpDescription);
418
+
419
+ this._addImplicitHelpCommand = true;
420
+ this._helpCommand = helpCommand;
421
+
422
+ return this;
423
+ }
424
+
425
+ /**
426
+ * Add prepared custom help command.
427
+ *
428
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
429
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
430
+ * @return {Command} `this` command for chaining
431
+ */
432
+ addHelpCommand(helpCommand, deprecatedDescription) {
433
+ // If not passed an object, call through to helpCommand for backwards compatibility,
434
+ // as addHelpCommand was originally used like helpCommand is now.
435
+ if (typeof helpCommand !== 'object') {
436
+ this.helpCommand(helpCommand, deprecatedDescription);
437
+ return this;
438
+ }
439
+
440
+ this._addImplicitHelpCommand = true;
441
+ this._helpCommand = helpCommand;
442
+ return this;
443
+ }
444
+
445
+ /**
446
+ * Lazy create help command.
447
+ *
448
+ * @return {(Command|null)}
449
+ * @package
450
+ */
451
+ _getHelpCommand() {
452
+ const hasImplicitHelpCommand =
453
+ this._addImplicitHelpCommand ??
454
+ (this.commands.length &&
455
+ !this._actionHandler &&
456
+ !this._findCommand('help'));
457
+
458
+ if (hasImplicitHelpCommand) {
459
+ if (this._helpCommand === undefined) {
460
+ this.helpCommand(undefined, undefined); // use default name and description
461
+ }
462
+ return this._helpCommand;
463
+ }
464
+ return null;
465
+ }
466
+
467
+ /**
468
+ * Add hook for life cycle event.
469
+ *
470
+ * @param {string} event
471
+ * @param {Function} listener
472
+ * @return {Command} `this` command for chaining
473
+ */
474
+
475
+ hook(event, listener) {
476
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
477
+ if (!allowedValues.includes(event)) {
478
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
479
+ Expecting one of '${allowedValues.join("', '")}'`);
480
+ }
481
+ if (this._lifeCycleHooks[event]) {
482
+ this._lifeCycleHooks[event].push(listener);
483
+ } else {
484
+ this._lifeCycleHooks[event] = [listener];
485
+ }
486
+ return this;
487
+ }
488
+
489
+ /**
490
+ * Register callback to use as replacement for calling process.exit.
491
+ *
492
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
493
+ * @return {Command} `this` command for chaining
494
+ */
495
+
496
+ exitOverride(fn) {
497
+ if (fn) {
498
+ this._exitCallback = fn;
499
+ } else {
500
+ this._exitCallback = (err) => {
501
+ if (err.code !== 'commander.executeSubCommandAsync') {
502
+ throw err;
503
+ } else {
504
+ // Async callback from spawn events, not useful to throw.
505
+ }
506
+ };
507
+ }
508
+ return this;
509
+ }
510
+
511
+ /**
512
+ * Call process.exit, and _exitCallback if defined.
513
+ *
514
+ * @param {number} exitCode exit code for using with process.exit
515
+ * @param {string} code an id string representing the error
516
+ * @param {string} message human-readable description of the error
517
+ * @return never
518
+ * @private
519
+ */
520
+
521
+ _exit(exitCode, code, message) {
522
+ if (this._exitCallback) {
523
+ this._exitCallback(new CommanderError(exitCode, code, message));
524
+ // Expecting this line is not reached.
525
+ }
526
+ process.exit(exitCode);
527
+ }
528
+
529
+ /**
530
+ * Register callback `fn` for the command.
531
+ *
532
+ * @example
533
+ * program
534
+ * .command('serve')
535
+ * .description('start service')
536
+ * .action(function() {
537
+ * // do work here
538
+ * });
539
+ *
540
+ * @param {Function} fn
541
+ * @return {Command} `this` command for chaining
542
+ */
543
+
544
+ action(fn) {
545
+ const listener = (args) => {
546
+ // The .action callback takes an extra parameter which is the command or options.
547
+ const expectedArgsCount = this.registeredArguments.length;
548
+ const actionArgs = args.slice(0, expectedArgsCount);
549
+ if (this._storeOptionsAsProperties) {
550
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
551
+ } else {
552
+ actionArgs[expectedArgsCount] = this.opts();
553
+ }
554
+ actionArgs.push(this);
555
+
556
+ return fn.apply(this, actionArgs);
557
+ };
558
+ this._actionHandler = listener;
559
+ return this;
560
+ }
561
+
562
+ /**
563
+ * Factory routine to create a new unattached option.
564
+ *
565
+ * See .option() for creating an attached option, which uses this routine to
566
+ * create the option. You can override createOption to return a custom option.
567
+ *
568
+ * @param {string} flags
569
+ * @param {string} [description]
570
+ * @return {Option} new option
571
+ */
572
+
573
+ createOption(flags, description) {
574
+ return new Option(flags, description);
575
+ }
576
+
577
+ /**
578
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
579
+ *
580
+ * @param {(Option | Argument)} target
581
+ * @param {string} value
582
+ * @param {*} previous
583
+ * @param {string} invalidArgumentMessage
584
+ * @private
585
+ */
586
+
587
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
588
+ try {
589
+ return target.parseArg(value, previous);
590
+ } catch (err) {
591
+ if (err.code === 'commander.invalidArgument') {
592
+ const message = `${invalidArgumentMessage} ${err.message}`;
593
+ this.error(message, { exitCode: err.exitCode, code: err.code });
594
+ }
595
+ throw err;
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Check for option flag conflicts.
601
+ * Register option if no conflicts found, or throw on conflict.
602
+ *
603
+ * @param {Option} option
604
+ * @private
605
+ */
606
+
607
+ _registerOption(option) {
608
+ const matchingOption =
609
+ (option.short && this._findOption(option.short)) ||
610
+ (option.long && this._findOption(option.long));
611
+ if (matchingOption) {
612
+ const matchingFlag =
613
+ option.long && this._findOption(option.long)
614
+ ? option.long
615
+ : option.short;
616
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
617
+ - already used by option '${matchingOption.flags}'`);
618
+ }
619
+
620
+ this.options.push(option);
621
+ }
622
+
623
+ /**
624
+ * Check for command name and alias conflicts with existing commands.
625
+ * Register command if no conflicts found, or throw on conflict.
626
+ *
627
+ * @param {Command} command
628
+ * @private
629
+ */
630
+
631
+ _registerCommand(command) {
632
+ const knownBy = (cmd) => {
633
+ return [cmd.name()].concat(cmd.aliases());
634
+ };
635
+
636
+ const alreadyUsed = knownBy(command).find((name) =>
637
+ this._findCommand(name),
638
+ );
639
+ if (alreadyUsed) {
640
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
641
+ const newCmd = knownBy(command).join('|');
642
+ throw new Error(
643
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
644
+ );
645
+ }
646
+
647
+ this.commands.push(command);
648
+ }
649
+
650
+ /**
651
+ * Add an option.
652
+ *
653
+ * @param {Option} option
654
+ * @return {Command} `this` command for chaining
655
+ */
656
+ addOption(option) {
657
+ this._registerOption(option);
658
+
659
+ const oname = option.name();
660
+ const name = option.attributeName();
661
+
662
+ // store default value
663
+ if (option.negate) {
664
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
665
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
666
+ if (!this._findOption(positiveLongFlag)) {
667
+ this.setOptionValueWithSource(
668
+ name,
669
+ option.defaultValue === undefined ? true : option.defaultValue,
670
+ 'default',
671
+ );
672
+ }
673
+ } else if (option.defaultValue !== undefined) {
674
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
675
+ }
676
+
677
+ // handler for cli and env supplied values
678
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
679
+ // val is null for optional option used without an optional-argument.
680
+ // val is undefined for boolean and negated option.
681
+ if (val == null && option.presetArg !== undefined) {
682
+ val = option.presetArg;
683
+ }
684
+
685
+ // custom processing
686
+ const oldValue = this.getOptionValue(name);
687
+ if (val !== null && option.parseArg) {
688
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
689
+ } else if (val !== null && option.variadic) {
690
+ val = option._concatValue(val, oldValue);
691
+ }
692
+
693
+ // Fill-in appropriate missing values. Long winded but easy to follow.
694
+ if (val == null) {
695
+ if (option.negate) {
696
+ val = false;
697
+ } else if (option.isBoolean() || option.optional) {
698
+ val = true;
699
+ } else {
700
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
701
+ }
702
+ }
703
+ this.setOptionValueWithSource(name, val, valueSource);
704
+ };
705
+
706
+ this.on('option:' + oname, (val) => {
707
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
708
+ handleOptionValue(val, invalidValueMessage, 'cli');
709
+ });
710
+
711
+ if (option.envVar) {
712
+ this.on('optionEnv:' + oname, (val) => {
713
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
714
+ handleOptionValue(val, invalidValueMessage, 'env');
715
+ });
716
+ }
717
+
718
+ return this;
719
+ }
720
+
721
+ /**
722
+ * Internal implementation shared by .option() and .requiredOption()
723
+ *
724
+ * @return {Command} `this` command for chaining
725
+ * @private
726
+ */
727
+ _optionEx(config, flags, description, fn, defaultValue) {
728
+ if (typeof flags === 'object' && flags instanceof Option) {
729
+ throw new Error(
730
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
731
+ );
732
+ }
733
+ const option = this.createOption(flags, description);
734
+ option.makeOptionMandatory(!!config.mandatory);
735
+ if (typeof fn === 'function') {
736
+ option.default(defaultValue).argParser(fn);
737
+ } else if (fn instanceof RegExp) {
738
+ // deprecated
739
+ const regex = fn;
740
+ fn = (val, def) => {
741
+ const m = regex.exec(val);
742
+ return m ? m[0] : def;
743
+ };
744
+ option.default(defaultValue).argParser(fn);
745
+ } else {
746
+ option.default(fn);
747
+ }
748
+
749
+ return this.addOption(option);
750
+ }
751
+
752
+ /**
753
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
754
+ *
755
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
756
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
757
+ *
758
+ * See the README for more details, and see also addOption() and requiredOption().
759
+ *
760
+ * @example
761
+ * program
762
+ * .option('-p, --pepper', 'add pepper')
763
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
764
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
765
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
766
+ *
767
+ * @param {string} flags
768
+ * @param {string} [description]
769
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
770
+ * @param {*} [defaultValue]
771
+ * @return {Command} `this` command for chaining
772
+ */
773
+
774
+ option(flags, description, parseArg, defaultValue) {
775
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
776
+ }
777
+
778
+ /**
779
+ * Add a required option which must have a value after parsing. This usually means
780
+ * the option must be specified on the command line. (Otherwise the same as .option().)
781
+ *
782
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
783
+ *
784
+ * @param {string} flags
785
+ * @param {string} [description]
786
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
787
+ * @param {*} [defaultValue]
788
+ * @return {Command} `this` command for chaining
789
+ */
790
+
791
+ requiredOption(flags, description, parseArg, defaultValue) {
792
+ return this._optionEx(
793
+ { mandatory: true },
794
+ flags,
795
+ description,
796
+ parseArg,
797
+ defaultValue,
798
+ );
799
+ }
800
+
801
+ /**
802
+ * Alter parsing of short flags with optional values.
803
+ *
804
+ * @example
805
+ * // for `.option('-f,--flag [value]'):
806
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
807
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
808
+ *
809
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
810
+ * @return {Command} `this` command for chaining
811
+ */
812
+ combineFlagAndOptionalValue(combine = true) {
813
+ this._combineFlagAndOptionalValue = !!combine;
814
+ return this;
815
+ }
816
+
817
+ /**
818
+ * Allow unknown options on the command line.
819
+ *
820
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
821
+ * @return {Command} `this` command for chaining
822
+ */
823
+ allowUnknownOption(allowUnknown = true) {
824
+ this._allowUnknownOption = !!allowUnknown;
825
+ return this;
826
+ }
827
+
828
+ /**
829
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
830
+ *
831
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
832
+ * @return {Command} `this` command for chaining
833
+ */
834
+ allowExcessArguments(allowExcess = true) {
835
+ this._allowExcessArguments = !!allowExcess;
836
+ return this;
837
+ }
838
+
839
+ /**
840
+ * Enable positional options. Positional means global options are specified before subcommands which lets
841
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
842
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
843
+ *
844
+ * @param {boolean} [positional]
845
+ * @return {Command} `this` command for chaining
846
+ */
847
+ enablePositionalOptions(positional = true) {
848
+ this._enablePositionalOptions = !!positional;
849
+ return this;
850
+ }
851
+
852
+ /**
853
+ * Pass through options that come after command-arguments rather than treat them as command-options,
854
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
855
+ * positional options to have been enabled on the program (parent commands).
856
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
857
+ *
858
+ * @param {boolean} [passThrough] for unknown options.
859
+ * @return {Command} `this` command for chaining
860
+ */
861
+ passThroughOptions(passThrough = true) {
862
+ this._passThroughOptions = !!passThrough;
863
+ this._checkForBrokenPassThrough();
864
+ return this;
865
+ }
866
+
867
+ /**
868
+ * @private
869
+ */
870
+
871
+ _checkForBrokenPassThrough() {
872
+ if (
873
+ this.parent &&
874
+ this._passThroughOptions &&
875
+ !this.parent._enablePositionalOptions
876
+ ) {
877
+ throw new Error(
878
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
879
+ );
880
+ }
881
+ }
882
+
883
+ /**
884
+ * Whether to store option values as properties on command object,
885
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
886
+ *
887
+ * @param {boolean} [storeAsProperties=true]
888
+ * @return {Command} `this` command for chaining
889
+ */
890
+
891
+ storeOptionsAsProperties(storeAsProperties = true) {
892
+ if (this.options.length) {
893
+ throw new Error('call .storeOptionsAsProperties() before adding options');
894
+ }
895
+ if (Object.keys(this._optionValues).length) {
896
+ throw new Error(
897
+ 'call .storeOptionsAsProperties() before setting option values',
898
+ );
899
+ }
900
+ this._storeOptionsAsProperties = !!storeAsProperties;
901
+ return this;
902
+ }
903
+
904
+ /**
905
+ * Retrieve option value.
906
+ *
907
+ * @param {string} key
908
+ * @return {object} value
909
+ */
910
+
911
+ getOptionValue(key) {
912
+ if (this._storeOptionsAsProperties) {
913
+ return this[key];
914
+ }
915
+ return this._optionValues[key];
916
+ }
917
+
918
+ /**
919
+ * Store option value.
920
+ *
921
+ * @param {string} key
922
+ * @param {object} value
923
+ * @return {Command} `this` command for chaining
924
+ */
925
+
926
+ setOptionValue(key, value) {
927
+ return this.setOptionValueWithSource(key, value, undefined);
928
+ }
929
+
930
+ /**
931
+ * Store option value and where the value came from.
932
+ *
933
+ * @param {string} key
934
+ * @param {object} value
935
+ * @param {string} source - expected values are default/config/env/cli/implied
936
+ * @return {Command} `this` command for chaining
937
+ */
938
+
939
+ setOptionValueWithSource(key, value, source) {
940
+ if (this._storeOptionsAsProperties) {
941
+ this[key] = value;
942
+ } else {
943
+ this._optionValues[key] = value;
944
+ }
945
+ this._optionValueSources[key] = source;
946
+ return this;
947
+ }
948
+
949
+ /**
950
+ * Get source of option value.
951
+ * Expected values are default | config | env | cli | implied
952
+ *
953
+ * @param {string} key
954
+ * @return {string}
955
+ */
956
+
957
+ getOptionValueSource(key) {
958
+ return this._optionValueSources[key];
959
+ }
960
+
961
+ /**
962
+ * Get source of option value. See also .optsWithGlobals().
963
+ * Expected values are default | config | env | cli | implied
964
+ *
965
+ * @param {string} key
966
+ * @return {string}
967
+ */
968
+
969
+ getOptionValueSourceWithGlobals(key) {
970
+ // global overwrites local, like optsWithGlobals
971
+ let source;
972
+ this._getCommandAndAncestors().forEach((cmd) => {
973
+ if (cmd.getOptionValueSource(key) !== undefined) {
974
+ source = cmd.getOptionValueSource(key);
975
+ }
976
+ });
977
+ return source;
978
+ }
979
+
980
+ /**
981
+ * Get user arguments from implied or explicit arguments.
982
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
983
+ *
984
+ * @private
985
+ */
986
+
987
+ _prepareUserArgs(argv, parseOptions) {
988
+ if (argv !== undefined && !Array.isArray(argv)) {
989
+ throw new Error('first parameter to parse must be array or undefined');
990
+ }
991
+ parseOptions = parseOptions || {};
992
+
993
+ // auto-detect argument conventions if nothing supplied
994
+ if (argv === undefined && parseOptions.from === undefined) {
995
+ if (process.versions?.electron) {
996
+ parseOptions.from = 'electron';
997
+ }
998
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
999
+ const execArgv = process.execArgv ?? [];
1000
+ if (
1001
+ execArgv.includes('-e') ||
1002
+ execArgv.includes('--eval') ||
1003
+ execArgv.includes('-p') ||
1004
+ execArgv.includes('--print')
1005
+ ) {
1006
+ parseOptions.from = 'eval'; // internal usage, not documented
1007
+ }
1008
+ }
1009
+
1010
+ // default to using process.argv
1011
+ if (argv === undefined) {
1012
+ argv = process.argv;
1013
+ }
1014
+ this.rawArgs = argv.slice();
1015
+
1016
+ // extract the user args and scriptPath
1017
+ let userArgs;
1018
+ switch (parseOptions.from) {
1019
+ case undefined:
1020
+ case 'node':
1021
+ this._scriptPath = argv[1];
1022
+ userArgs = argv.slice(2);
1023
+ break;
1024
+ case 'electron':
1025
+ // @ts-ignore: because defaultApp is an unknown property
1026
+ if (process.defaultApp) {
1027
+ this._scriptPath = argv[1];
1028
+ userArgs = argv.slice(2);
1029
+ } else {
1030
+ userArgs = argv.slice(1);
1031
+ }
1032
+ break;
1033
+ case 'user':
1034
+ userArgs = argv.slice(0);
1035
+ break;
1036
+ case 'eval':
1037
+ userArgs = argv.slice(1);
1038
+ break;
1039
+ default:
1040
+ throw new Error(
1041
+ `unexpected parse option { from: '${parseOptions.from}' }`,
1042
+ );
1043
+ }
1044
+
1045
+ // Find default name for program from arguments.
1046
+ if (!this._name && this._scriptPath)
1047
+ this.nameFromFilename(this._scriptPath);
1048
+ this._name = this._name || 'program';
1049
+
1050
+ return userArgs;
1051
+ }
1052
+
1053
+ /**
1054
+ * Parse `argv`, setting options and invoking commands when defined.
1055
+ *
1056
+ * Use parseAsync instead of parse if any of your action handlers are async.
1057
+ *
1058
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1059
+ *
1060
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1061
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1062
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1063
+ * - `'user'`: just user arguments
1064
+ *
1065
+ * @example
1066
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1067
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1068
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1069
+ *
1070
+ * @param {string[]} [argv] - optional, defaults to process.argv
1071
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1072
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1073
+ * @return {Command} `this` command for chaining
1074
+ */
1075
+
1076
+ parse(argv, parseOptions) {
1077
+ this._prepareForParse();
1078
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1079
+ this._parseCommand([], userArgs);
1080
+
1081
+ return this;
1082
+ }
1083
+
1084
+ /**
1085
+ * Parse `argv`, setting options and invoking commands when defined.
1086
+ *
1087
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1088
+ *
1089
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1090
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1091
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1092
+ * - `'user'`: just user arguments
1093
+ *
1094
+ * @example
1095
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1096
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1097
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1098
+ *
1099
+ * @param {string[]} [argv]
1100
+ * @param {object} [parseOptions]
1101
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1102
+ * @return {Promise}
1103
+ */
1104
+
1105
+ async parseAsync(argv, parseOptions) {
1106
+ this._prepareForParse();
1107
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1108
+ await this._parseCommand([], userArgs);
1109
+
1110
+ return this;
1111
+ }
1112
+
1113
+ _prepareForParse() {
1114
+ if (this._savedState === null) {
1115
+ this.saveStateBeforeParse();
1116
+ } else {
1117
+ this.restoreStateBeforeParse();
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1123
+ * Not usually called directly, but available for subclasses to save their custom state.
1124
+ *
1125
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1126
+ */
1127
+ saveStateBeforeParse() {
1128
+ this._savedState = {
1129
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
1130
+ _name: this._name,
1131
+ // option values before parse have default values (including false for negated options)
1132
+ // shallow clones
1133
+ _optionValues: { ...this._optionValues },
1134
+ _optionValueSources: { ...this._optionValueSources },
1135
+ };
1136
+ }
1137
+
1138
+ /**
1139
+ * Restore state before parse for calls after the first.
1140
+ * Not usually called directly, but available for subclasses to save their custom state.
1141
+ *
1142
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1143
+ */
1144
+ restoreStateBeforeParse() {
1145
+ if (this._storeOptionsAsProperties)
1146
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1147
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1148
+
1149
+ // clear state from _prepareUserArgs
1150
+ this._name = this._savedState._name;
1151
+ this._scriptPath = null;
1152
+ this.rawArgs = [];
1153
+ // clear state from setOptionValueWithSource
1154
+ this._optionValues = { ...this._savedState._optionValues };
1155
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1156
+ // clear state from _parseCommand
1157
+ this.args = [];
1158
+ // clear state from _processArguments
1159
+ this.processedArgs = [];
1160
+ }
1161
+
1162
+ /**
1163
+ * Throw if expected executable is missing. Add lots of help for author.
1164
+ *
1165
+ * @param {string} executableFile
1166
+ * @param {string} executableDir
1167
+ * @param {string} subcommandName
1168
+ */
1169
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1170
+ if (fs.existsSync(executableFile)) return;
1171
+
1172
+ const executableDirMessage = executableDir
1173
+ ? `searched for local subcommand relative to directory '${executableDir}'`
1174
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1175
+ const executableMissing = `'${executableFile}' does not exist
1176
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1177
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1178
+ - ${executableDirMessage}`;
1179
+ throw new Error(executableMissing);
1180
+ }
1181
+
1182
+ /**
1183
+ * Execute a sub-command executable.
1184
+ *
1185
+ * @private
1186
+ */
1187
+
1188
+ _executeSubCommand(subcommand, args) {
1189
+ args = args.slice();
1190
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
1191
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1192
+
1193
+ function findFile(baseDir, baseName) {
1194
+ // Look for specified file
1195
+ const localBin = path.resolve(baseDir, baseName);
1196
+ if (fs.existsSync(localBin)) return localBin;
1197
+
1198
+ // Stop looking if candidate already has an expected extension.
1199
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
1200
+
1201
+ // Try all the extensions.
1202
+ const foundExt = sourceExt.find((ext) =>
1203
+ fs.existsSync(`${localBin}${ext}`),
1204
+ );
1205
+ if (foundExt) return `${localBin}${foundExt}`;
1206
+
1207
+ return undefined;
1208
+ }
1209
+
1210
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1211
+ this._checkForMissingMandatoryOptions();
1212
+ this._checkForConflictingOptions();
1213
+
1214
+ // executableFile and executableDir might be full path, or just a name
1215
+ let executableFile =
1216
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
1217
+ let executableDir = this._executableDir || '';
1218
+ if (this._scriptPath) {
1219
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1220
+ try {
1221
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1222
+ } catch {
1223
+ resolvedScriptPath = this._scriptPath;
1224
+ }
1225
+ executableDir = path.resolve(
1226
+ path.dirname(resolvedScriptPath),
1227
+ executableDir,
1228
+ );
1229
+ }
1230
+
1231
+ // Look for a local file in preference to a command in PATH.
1232
+ if (executableDir) {
1233
+ let localFile = findFile(executableDir, executableFile);
1234
+
1235
+ // Legacy search using prefix of script name instead of command name
1236
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1237
+ const legacyName = path.basename(
1238
+ this._scriptPath,
1239
+ path.extname(this._scriptPath),
1240
+ );
1241
+ if (legacyName !== this._name) {
1242
+ localFile = findFile(
1243
+ executableDir,
1244
+ `${legacyName}-${subcommand._name}`,
1245
+ );
1246
+ }
1247
+ }
1248
+ executableFile = localFile || executableFile;
1249
+ }
1250
+
1251
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1252
+
1253
+ let proc;
1254
+ if (process.platform !== 'win32') {
1255
+ if (launchWithNode) {
1256
+ args.unshift(executableFile);
1257
+ // add executable arguments to spawn
1258
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1259
+
1260
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1261
+ } else {
1262
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1263
+ }
1264
+ } else {
1265
+ this._checkForMissingExecutable(
1266
+ executableFile,
1267
+ executableDir,
1268
+ subcommand._name,
1269
+ );
1270
+ args.unshift(executableFile);
1271
+ // add executable arguments to spawn
1272
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1273
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1274
+ }
1275
+
1276
+ if (!proc.killed) {
1277
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
1278
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1279
+ signals.forEach((signal) => {
1280
+ process.on(signal, () => {
1281
+ if (proc.killed === false && proc.exitCode === null) {
1282
+ // @ts-ignore because signals not typed to known strings
1283
+ proc.kill(signal);
1284
+ }
1285
+ });
1286
+ });
1287
+ }
1288
+
1289
+ // By default terminate process when spawned process terminates.
1290
+ const exitCallback = this._exitCallback;
1291
+ proc.on('close', (code) => {
1292
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1293
+ if (!exitCallback) {
1294
+ process.exit(code);
1295
+ } else {
1296
+ exitCallback(
1297
+ new CommanderError(
1298
+ code,
1299
+ 'commander.executeSubCommandAsync',
1300
+ '(close)',
1301
+ ),
1302
+ );
1303
+ }
1304
+ });
1305
+ proc.on('error', (err) => {
1306
+ // @ts-ignore: because err.code is an unknown property
1307
+ if (err.code === 'ENOENT') {
1308
+ this._checkForMissingExecutable(
1309
+ executableFile,
1310
+ executableDir,
1311
+ subcommand._name,
1312
+ );
1313
+ // @ts-ignore: because err.code is an unknown property
1314
+ } else if (err.code === 'EACCES') {
1315
+ throw new Error(`'${executableFile}' not executable`);
1316
+ }
1317
+ if (!exitCallback) {
1318
+ process.exit(1);
1319
+ } else {
1320
+ const wrappedError = new CommanderError(
1321
+ 1,
1322
+ 'commander.executeSubCommandAsync',
1323
+ '(error)',
1324
+ );
1325
+ wrappedError.nestedError = err;
1326
+ exitCallback(wrappedError);
1327
+ }
1328
+ });
1329
+
1330
+ // Store the reference to the child process
1331
+ this.runningCommand = proc;
1332
+ }
1333
+
1334
+ /**
1335
+ * @private
1336
+ */
1337
+
1338
+ _dispatchSubcommand(commandName, operands, unknown) {
1339
+ const subCommand = this._findCommand(commandName);
1340
+ if (!subCommand) this.help({ error: true });
1341
+
1342
+ subCommand._prepareForParse();
1343
+ let promiseChain;
1344
+ promiseChain = this._chainOrCallSubCommandHook(
1345
+ promiseChain,
1346
+ subCommand,
1347
+ 'preSubcommand',
1348
+ );
1349
+ promiseChain = this._chainOrCall(promiseChain, () => {
1350
+ if (subCommand._executableHandler) {
1351
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1352
+ } else {
1353
+ return subCommand._parseCommand(operands, unknown);
1354
+ }
1355
+ });
1356
+ return promiseChain;
1357
+ }
1358
+
1359
+ /**
1360
+ * Invoke help directly if possible, or dispatch if necessary.
1361
+ * e.g. help foo
1362
+ *
1363
+ * @private
1364
+ */
1365
+
1366
+ _dispatchHelpCommand(subcommandName) {
1367
+ if (!subcommandName) {
1368
+ this.help();
1369
+ }
1370
+ const subCommand = this._findCommand(subcommandName);
1371
+ if (subCommand && !subCommand._executableHandler) {
1372
+ subCommand.help();
1373
+ }
1374
+
1375
+ // Fallback to parsing the help flag to invoke the help.
1376
+ return this._dispatchSubcommand(
1377
+ subcommandName,
1378
+ [],
1379
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
1380
+ );
1381
+ }
1382
+
1383
+ /**
1384
+ * Check this.args against expected this.registeredArguments.
1385
+ *
1386
+ * @private
1387
+ */
1388
+
1389
+ _checkNumberOfArguments() {
1390
+ // too few
1391
+ this.registeredArguments.forEach((arg, i) => {
1392
+ if (arg.required && this.args[i] == null) {
1393
+ this.missingArgument(arg.name());
1394
+ }
1395
+ });
1396
+ // too many
1397
+ if (
1398
+ this.registeredArguments.length > 0 &&
1399
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
1400
+ ) {
1401
+ return;
1402
+ }
1403
+ if (this.args.length > this.registeredArguments.length) {
1404
+ this._excessArguments(this.args);
1405
+ }
1406
+ }
1407
+
1408
+ /**
1409
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1410
+ *
1411
+ * @private
1412
+ */
1413
+
1414
+ _processArguments() {
1415
+ const myParseArg = (argument, value, previous) => {
1416
+ // Extra processing for nice error message on parsing failure.
1417
+ let parsedValue = value;
1418
+ if (value !== null && argument.parseArg) {
1419
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1420
+ parsedValue = this._callParseArg(
1421
+ argument,
1422
+ value,
1423
+ previous,
1424
+ invalidValueMessage,
1425
+ );
1426
+ }
1427
+ return parsedValue;
1428
+ };
1429
+
1430
+ this._checkNumberOfArguments();
1431
+
1432
+ const processedArgs = [];
1433
+ this.registeredArguments.forEach((declaredArg, index) => {
1434
+ let value = declaredArg.defaultValue;
1435
+ if (declaredArg.variadic) {
1436
+ // Collect together remaining arguments for passing together as an array.
1437
+ if (index < this.args.length) {
1438
+ value = this.args.slice(index);
1439
+ if (declaredArg.parseArg) {
1440
+ value = value.reduce((processed, v) => {
1441
+ return myParseArg(declaredArg, v, processed);
1442
+ }, declaredArg.defaultValue);
1443
+ }
1444
+ } else if (value === undefined) {
1445
+ value = [];
1446
+ }
1447
+ } else if (index < this.args.length) {
1448
+ value = this.args[index];
1449
+ if (declaredArg.parseArg) {
1450
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1451
+ }
1452
+ }
1453
+ processedArgs[index] = value;
1454
+ });
1455
+ this.processedArgs = processedArgs;
1456
+ }
1457
+
1458
+ /**
1459
+ * Once we have a promise we chain, but call synchronously until then.
1460
+ *
1461
+ * @param {(Promise|undefined)} promise
1462
+ * @param {Function} fn
1463
+ * @return {(Promise|undefined)}
1464
+ * @private
1465
+ */
1466
+
1467
+ _chainOrCall(promise, fn) {
1468
+ // thenable
1469
+ if (promise && promise.then && typeof promise.then === 'function') {
1470
+ // already have a promise, chain callback
1471
+ return promise.then(() => fn());
1472
+ }
1473
+ // callback might return a promise
1474
+ return fn();
1475
+ }
1476
+
1477
+ /**
1478
+ *
1479
+ * @param {(Promise|undefined)} promise
1480
+ * @param {string} event
1481
+ * @return {(Promise|undefined)}
1482
+ * @private
1483
+ */
1484
+
1485
+ _chainOrCallHooks(promise, event) {
1486
+ let result = promise;
1487
+ const hooks = [];
1488
+ this._getCommandAndAncestors()
1489
+ .reverse()
1490
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1491
+ .forEach((hookedCommand) => {
1492
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1493
+ hooks.push({ hookedCommand, callback });
1494
+ });
1495
+ });
1496
+ if (event === 'postAction') {
1497
+ hooks.reverse();
1498
+ }
1499
+
1500
+ hooks.forEach((hookDetail) => {
1501
+ result = this._chainOrCall(result, () => {
1502
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1503
+ });
1504
+ });
1505
+ return result;
1506
+ }
1507
+
1508
+ /**
1509
+ *
1510
+ * @param {(Promise|undefined)} promise
1511
+ * @param {Command} subCommand
1512
+ * @param {string} event
1513
+ * @return {(Promise|undefined)}
1514
+ * @private
1515
+ */
1516
+
1517
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1518
+ let result = promise;
1519
+ if (this._lifeCycleHooks[event] !== undefined) {
1520
+ this._lifeCycleHooks[event].forEach((hook) => {
1521
+ result = this._chainOrCall(result, () => {
1522
+ return hook(this, subCommand);
1523
+ });
1524
+ });
1525
+ }
1526
+ return result;
1527
+ }
1528
+
1529
+ /**
1530
+ * Process arguments in context of this command.
1531
+ * Returns action result, in case it is a promise.
1532
+ *
1533
+ * @private
1534
+ */
1535
+
1536
+ _parseCommand(operands, unknown) {
1537
+ const parsed = this.parseOptions(unknown);
1538
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
1539
+ this._parseOptionsImplied();
1540
+ operands = operands.concat(parsed.operands);
1541
+ unknown = parsed.unknown;
1542
+ this.args = operands.concat(unknown);
1543
+
1544
+ if (operands && this._findCommand(operands[0])) {
1545
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1546
+ }
1547
+ if (
1548
+ this._getHelpCommand() &&
1549
+ operands[0] === this._getHelpCommand().name()
1550
+ ) {
1551
+ return this._dispatchHelpCommand(operands[1]);
1552
+ }
1553
+ if (this._defaultCommandName) {
1554
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
1555
+ return this._dispatchSubcommand(
1556
+ this._defaultCommandName,
1557
+ operands,
1558
+ unknown,
1559
+ );
1560
+ }
1561
+ if (
1562
+ this.commands.length &&
1563
+ this.args.length === 0 &&
1564
+ !this._actionHandler &&
1565
+ !this._defaultCommandName
1566
+ ) {
1567
+ // probably missing subcommand and no handler, user needs help (and exit)
1568
+ this.help({ error: true });
1569
+ }
1570
+
1571
+ this._outputHelpIfRequested(parsed.unknown);
1572
+ this._checkForMissingMandatoryOptions();
1573
+ this._checkForConflictingOptions();
1574
+
1575
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1576
+ const checkForUnknownOptions = () => {
1577
+ if (parsed.unknown.length > 0) {
1578
+ this.unknownOption(parsed.unknown[0]);
1579
+ }
1580
+ };
1581
+
1582
+ const commandEvent = `command:${this.name()}`;
1583
+ if (this._actionHandler) {
1584
+ checkForUnknownOptions();
1585
+ this._processArguments();
1586
+
1587
+ let promiseChain;
1588
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
1589
+ promiseChain = this._chainOrCall(promiseChain, () =>
1590
+ this._actionHandler(this.processedArgs),
1591
+ );
1592
+ if (this.parent) {
1593
+ promiseChain = this._chainOrCall(promiseChain, () => {
1594
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1595
+ });
1596
+ }
1597
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1598
+ return promiseChain;
1599
+ }
1600
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1601
+ checkForUnknownOptions();
1602
+ this._processArguments();
1603
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1604
+ } else if (operands.length) {
1605
+ if (this._findCommand('*')) {
1606
+ // legacy default command
1607
+ return this._dispatchSubcommand('*', operands, unknown);
1608
+ }
1609
+ if (this.listenerCount('command:*')) {
1610
+ // skip option check, emit event for possible misspelling suggestion
1611
+ this.emit('command:*', operands, unknown);
1612
+ } else if (this.commands.length) {
1613
+ this.unknownCommand();
1614
+ } else {
1615
+ checkForUnknownOptions();
1616
+ this._processArguments();
1617
+ }
1618
+ } else if (this.commands.length) {
1619
+ checkForUnknownOptions();
1620
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1621
+ this.help({ error: true });
1622
+ } else {
1623
+ checkForUnknownOptions();
1624
+ this._processArguments();
1625
+ // fall through for caller to handle after calling .parse()
1626
+ }
1627
+ }
1628
+
1629
+ /**
1630
+ * Find matching command.
1631
+ *
1632
+ * @private
1633
+ * @return {Command | undefined}
1634
+ */
1635
+ _findCommand(name) {
1636
+ if (!name) return undefined;
1637
+ return this.commands.find(
1638
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
1639
+ );
1640
+ }
1641
+
1642
+ /**
1643
+ * Return an option matching `arg` if any.
1644
+ *
1645
+ * @param {string} arg
1646
+ * @return {Option}
1647
+ * @package
1648
+ */
1649
+
1650
+ _findOption(arg) {
1651
+ return this.options.find((option) => option.is(arg));
1652
+ }
1653
+
1654
+ /**
1655
+ * Display an error message if a mandatory option does not have a value.
1656
+ * Called after checking for help flags in leaf subcommand.
1657
+ *
1658
+ * @private
1659
+ */
1660
+
1661
+ _checkForMissingMandatoryOptions() {
1662
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1663
+ this._getCommandAndAncestors().forEach((cmd) => {
1664
+ cmd.options.forEach((anOption) => {
1665
+ if (
1666
+ anOption.mandatory &&
1667
+ cmd.getOptionValue(anOption.attributeName()) === undefined
1668
+ ) {
1669
+ cmd.missingMandatoryOptionValue(anOption);
1670
+ }
1671
+ });
1672
+ });
1673
+ }
1674
+
1675
+ /**
1676
+ * Display an error message if conflicting options are used together in this.
1677
+ *
1678
+ * @private
1679
+ */
1680
+ _checkForConflictingLocalOptions() {
1681
+ const definedNonDefaultOptions = this.options.filter((option) => {
1682
+ const optionKey = option.attributeName();
1683
+ if (this.getOptionValue(optionKey) === undefined) {
1684
+ return false;
1685
+ }
1686
+ return this.getOptionValueSource(optionKey) !== 'default';
1687
+ });
1688
+
1689
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
1690
+ (option) => option.conflictsWith.length > 0,
1691
+ );
1692
+
1693
+ optionsWithConflicting.forEach((option) => {
1694
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
1695
+ option.conflictsWith.includes(defined.attributeName()),
1696
+ );
1697
+ if (conflictingAndDefined) {
1698
+ this._conflictingOption(option, conflictingAndDefined);
1699
+ }
1700
+ });
1701
+ }
1702
+
1703
+ /**
1704
+ * Display an error message if conflicting options are used together.
1705
+ * Called after checking for help flags in leaf subcommand.
1706
+ *
1707
+ * @private
1708
+ */
1709
+ _checkForConflictingOptions() {
1710
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1711
+ this._getCommandAndAncestors().forEach((cmd) => {
1712
+ cmd._checkForConflictingLocalOptions();
1713
+ });
1714
+ }
1715
+
1716
+ /**
1717
+ * Parse options from `argv` removing known options,
1718
+ * and return argv split into operands and unknown arguments.
1719
+ *
1720
+ * Side effects: modifies command by storing options. Does not reset state if called again.
1721
+ *
1722
+ * Examples:
1723
+ *
1724
+ * argv => operands, unknown
1725
+ * --known kkk op => [op], []
1726
+ * op --known kkk => [op], []
1727
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1728
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1729
+ *
1730
+ * @param {string[]} argv
1731
+ * @return {{operands: string[], unknown: string[]}}
1732
+ */
1733
+
1734
+ parseOptions(argv) {
1735
+ const operands = []; // operands, not options or values
1736
+ const unknown = []; // first unknown option and remaining unknown args
1737
+ let dest = operands;
1738
+ const args = argv.slice();
1739
+
1740
+ function maybeOption(arg) {
1741
+ return arg.length > 1 && arg[0] === '-';
1742
+ }
1743
+
1744
+ // parse options
1745
+ let activeVariadicOption = null;
1746
+ while (args.length) {
1747
+ const arg = args.shift();
1748
+
1749
+ // literal
1750
+ if (arg === '--') {
1751
+ if (dest === unknown) dest.push(arg);
1752
+ dest.push(...args);
1753
+ break;
1754
+ }
1755
+
1756
+ if (activeVariadicOption && !maybeOption(arg)) {
1757
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1758
+ continue;
1759
+ }
1760
+ activeVariadicOption = null;
1761
+
1762
+ if (maybeOption(arg)) {
1763
+ const option = this._findOption(arg);
1764
+ // recognised option, call listener to assign value with possible custom processing
1765
+ if (option) {
1766
+ if (option.required) {
1767
+ const value = args.shift();
1768
+ if (value === undefined) this.optionMissingArgument(option);
1769
+ this.emit(`option:${option.name()}`, value);
1770
+ } else if (option.optional) {
1771
+ let value = null;
1772
+ // historical behaviour is optional value is following arg unless an option
1773
+ if (args.length > 0 && !maybeOption(args[0])) {
1774
+ value = args.shift();
1775
+ }
1776
+ this.emit(`option:${option.name()}`, value);
1777
+ } else {
1778
+ // boolean flag
1779
+ this.emit(`option:${option.name()}`);
1780
+ }
1781
+ activeVariadicOption = option.variadic ? option : null;
1782
+ continue;
1783
+ }
1784
+ }
1785
+
1786
+ // Look for combo options following single dash, eat first one if known.
1787
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1788
+ const option = this._findOption(`-${arg[1]}`);
1789
+ if (option) {
1790
+ if (
1791
+ option.required ||
1792
+ (option.optional && this._combineFlagAndOptionalValue)
1793
+ ) {
1794
+ // option with value following in same argument
1795
+ this.emit(`option:${option.name()}`, arg.slice(2));
1796
+ } else {
1797
+ // boolean option, emit and put back remainder of arg for further processing
1798
+ this.emit(`option:${option.name()}`);
1799
+ args.unshift(`-${arg.slice(2)}`);
1800
+ }
1801
+ continue;
1802
+ }
1803
+ }
1804
+
1805
+ // Look for known long flag with value, like --foo=bar
1806
+ if (/^--[^=]+=/.test(arg)) {
1807
+ const index = arg.indexOf('=');
1808
+ const option = this._findOption(arg.slice(0, index));
1809
+ if (option && (option.required || option.optional)) {
1810
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1811
+ continue;
1812
+ }
1813
+ }
1814
+
1815
+ // Not a recognised option by this command.
1816
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1817
+
1818
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1819
+ if (maybeOption(arg)) {
1820
+ dest = unknown;
1821
+ }
1822
+
1823
+ // If using positionalOptions, stop processing our options at subcommand.
1824
+ if (
1825
+ (this._enablePositionalOptions || this._passThroughOptions) &&
1826
+ operands.length === 0 &&
1827
+ unknown.length === 0
1828
+ ) {
1829
+ if (this._findCommand(arg)) {
1830
+ operands.push(arg);
1831
+ if (args.length > 0) unknown.push(...args);
1832
+ break;
1833
+ } else if (
1834
+ this._getHelpCommand() &&
1835
+ arg === this._getHelpCommand().name()
1836
+ ) {
1837
+ operands.push(arg);
1838
+ if (args.length > 0) operands.push(...args);
1839
+ break;
1840
+ } else if (this._defaultCommandName) {
1841
+ unknown.push(arg);
1842
+ if (args.length > 0) unknown.push(...args);
1843
+ break;
1844
+ }
1845
+ }
1846
+
1847
+ // If using passThroughOptions, stop processing options at first command-argument.
1848
+ if (this._passThroughOptions) {
1849
+ dest.push(arg);
1850
+ if (args.length > 0) dest.push(...args);
1851
+ break;
1852
+ }
1853
+
1854
+ // add arg
1855
+ dest.push(arg);
1856
+ }
1857
+
1858
+ return { operands, unknown };
1859
+ }
1860
+
1861
+ /**
1862
+ * Return an object containing local option values as key-value pairs.
1863
+ *
1864
+ * @return {object}
1865
+ */
1866
+ opts() {
1867
+ if (this._storeOptionsAsProperties) {
1868
+ // Preserve original behaviour so backwards compatible when still using properties
1869
+ const result = {};
1870
+ const len = this.options.length;
1871
+
1872
+ for (let i = 0; i < len; i++) {
1873
+ const key = this.options[i].attributeName();
1874
+ result[key] =
1875
+ key === this._versionOptionName ? this._version : this[key];
1876
+ }
1877
+ return result;
1878
+ }
1879
+
1880
+ return this._optionValues;
1881
+ }
1882
+
1883
+ /**
1884
+ * Return an object containing merged local and global option values as key-value pairs.
1885
+ *
1886
+ * @return {object}
1887
+ */
1888
+ optsWithGlobals() {
1889
+ // globals overwrite locals
1890
+ return this._getCommandAndAncestors().reduce(
1891
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
1892
+ {},
1893
+ );
1894
+ }
1895
+
1896
+ /**
1897
+ * Display error message and exit (or call exitOverride).
1898
+ *
1899
+ * @param {string} message
1900
+ * @param {object} [errorOptions]
1901
+ * @param {string} [errorOptions.code] - an id string representing the error
1902
+ * @param {number} [errorOptions.exitCode] - used with process.exit
1903
+ */
1904
+ error(message, errorOptions) {
1905
+ // output handling
1906
+ this._outputConfiguration.outputError(
1907
+ `${message}\n`,
1908
+ this._outputConfiguration.writeErr,
1909
+ );
1910
+ if (typeof this._showHelpAfterError === 'string') {
1911
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1912
+ } else if (this._showHelpAfterError) {
1913
+ this._outputConfiguration.writeErr('\n');
1914
+ this.outputHelp({ error: true });
1915
+ }
1916
+
1917
+ // exit handling
1918
+ const config = errorOptions || {};
1919
+ const exitCode = config.exitCode || 1;
1920
+ const code = config.code || 'commander.error';
1921
+ this._exit(exitCode, code, message);
1922
+ }
1923
+
1924
+ /**
1925
+ * Apply any option related environment variables, if option does
1926
+ * not have a value from cli or client code.
1927
+ *
1928
+ * @private
1929
+ */
1930
+ _parseOptionsEnv() {
1931
+ this.options.forEach((option) => {
1932
+ if (option.envVar && option.envVar in process.env) {
1933
+ const optionKey = option.attributeName();
1934
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
1935
+ if (
1936
+ this.getOptionValue(optionKey) === undefined ||
1937
+ ['default', 'config', 'env'].includes(
1938
+ this.getOptionValueSource(optionKey),
1939
+ )
1940
+ ) {
1941
+ if (option.required || option.optional) {
1942
+ // option can take a value
1943
+ // keep very simple, optional always takes value
1944
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1945
+ } else {
1946
+ // boolean
1947
+ // keep very simple, only care that envVar defined and not the value
1948
+ this.emit(`optionEnv:${option.name()}`);
1949
+ }
1950
+ }
1951
+ }
1952
+ });
1953
+ }
1954
+
1955
+ /**
1956
+ * Apply any implied option values, if option is undefined or default value.
1957
+ *
1958
+ * @private
1959
+ */
1960
+ _parseOptionsImplied() {
1961
+ const dualHelper = new DualOptions(this.options);
1962
+ const hasCustomOptionValue = (optionKey) => {
1963
+ return (
1964
+ this.getOptionValue(optionKey) !== undefined &&
1965
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
1966
+ );
1967
+ };
1968
+ this.options
1969
+ .filter(
1970
+ (option) =>
1971
+ option.implied !== undefined &&
1972
+ hasCustomOptionValue(option.attributeName()) &&
1973
+ dualHelper.valueFromOption(
1974
+ this.getOptionValue(option.attributeName()),
1975
+ option,
1976
+ ),
1977
+ )
1978
+ .forEach((option) => {
1979
+ Object.keys(option.implied)
1980
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
1981
+ .forEach((impliedKey) => {
1982
+ this.setOptionValueWithSource(
1983
+ impliedKey,
1984
+ option.implied[impliedKey],
1985
+ 'implied',
1986
+ );
1987
+ });
1988
+ });
1989
+ }
1990
+
1991
+ /**
1992
+ * Argument `name` is missing.
1993
+ *
1994
+ * @param {string} name
1995
+ * @private
1996
+ */
1997
+
1998
+ missingArgument(name) {
1999
+ const message = `error: missing required argument '${name}'`;
2000
+ this.error(message, { code: 'commander.missingArgument' });
2001
+ }
2002
+
2003
+ /**
2004
+ * `Option` is missing an argument.
2005
+ *
2006
+ * @param {Option} option
2007
+ * @private
2008
+ */
2009
+
2010
+ optionMissingArgument(option) {
2011
+ const message = `error: option '${option.flags}' argument missing`;
2012
+ this.error(message, { code: 'commander.optionMissingArgument' });
2013
+ }
2014
+
2015
+ /**
2016
+ * `Option` does not have a value, and is a mandatory option.
2017
+ *
2018
+ * @param {Option} option
2019
+ * @private
2020
+ */
2021
+
2022
+ missingMandatoryOptionValue(option) {
2023
+ const message = `error: required option '${option.flags}' not specified`;
2024
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
2025
+ }
2026
+
2027
+ /**
2028
+ * `Option` conflicts with another option.
2029
+ *
2030
+ * @param {Option} option
2031
+ * @param {Option} conflictingOption
2032
+ * @private
2033
+ */
2034
+ _conflictingOption(option, conflictingOption) {
2035
+ // The calling code does not know whether a negated option is the source of the
2036
+ // value, so do some work to take an educated guess.
2037
+ const findBestOptionFromValue = (option) => {
2038
+ const optionKey = option.attributeName();
2039
+ const optionValue = this.getOptionValue(optionKey);
2040
+ const negativeOption = this.options.find(
2041
+ (target) => target.negate && optionKey === target.attributeName(),
2042
+ );
2043
+ const positiveOption = this.options.find(
2044
+ (target) => !target.negate && optionKey === target.attributeName(),
2045
+ );
2046
+ if (
2047
+ negativeOption &&
2048
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
2049
+ (negativeOption.presetArg !== undefined &&
2050
+ optionValue === negativeOption.presetArg))
2051
+ ) {
2052
+ return negativeOption;
2053
+ }
2054
+ return positiveOption || option;
2055
+ };
2056
+
2057
+ const getErrorMessage = (option) => {
2058
+ const bestOption = findBestOptionFromValue(option);
2059
+ const optionKey = bestOption.attributeName();
2060
+ const source = this.getOptionValueSource(optionKey);
2061
+ if (source === 'env') {
2062
+ return `environment variable '${bestOption.envVar}'`;
2063
+ }
2064
+ return `option '${bestOption.flags}'`;
2065
+ };
2066
+
2067
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2068
+ this.error(message, { code: 'commander.conflictingOption' });
2069
+ }
2070
+
2071
+ /**
2072
+ * Unknown option `flag`.
2073
+ *
2074
+ * @param {string} flag
2075
+ * @private
2076
+ */
2077
+
2078
+ unknownOption(flag) {
2079
+ if (this._allowUnknownOption) return;
2080
+ let suggestion = '';
2081
+
2082
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2083
+ // Looping to pick up the global options too
2084
+ let candidateFlags = [];
2085
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2086
+ let command = this;
2087
+ do {
2088
+ const moreFlags = command
2089
+ .createHelp()
2090
+ .visibleOptions(command)
2091
+ .filter((option) => option.long)
2092
+ .map((option) => option.long);
2093
+ candidateFlags = candidateFlags.concat(moreFlags);
2094
+ command = command.parent;
2095
+ } while (command && !command._enablePositionalOptions);
2096
+ suggestion = suggestSimilar(flag, candidateFlags);
2097
+ }
2098
+
2099
+ const message = `error: unknown option '${flag}'${suggestion}`;
2100
+ this.error(message, { code: 'commander.unknownOption' });
2101
+ }
2102
+
2103
+ /**
2104
+ * Excess arguments, more than expected.
2105
+ *
2106
+ * @param {string[]} receivedArgs
2107
+ * @private
2108
+ */
2109
+
2110
+ _excessArguments(receivedArgs) {
2111
+ if (this._allowExcessArguments) return;
2112
+
2113
+ const expected = this.registeredArguments.length;
2114
+ const s = expected === 1 ? '' : 's';
2115
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2116
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2117
+ this.error(message, { code: 'commander.excessArguments' });
2118
+ }
2119
+
2120
+ /**
2121
+ * Unknown command.
2122
+ *
2123
+ * @private
2124
+ */
2125
+
2126
+ unknownCommand() {
2127
+ const unknownName = this.args[0];
2128
+ let suggestion = '';
2129
+
2130
+ if (this._showSuggestionAfterError) {
2131
+ const candidateNames = [];
2132
+ this.createHelp()
2133
+ .visibleCommands(this)
2134
+ .forEach((command) => {
2135
+ candidateNames.push(command.name());
2136
+ // just visible alias
2137
+ if (command.alias()) candidateNames.push(command.alias());
2138
+ });
2139
+ suggestion = suggestSimilar(unknownName, candidateNames);
2140
+ }
2141
+
2142
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2143
+ this.error(message, { code: 'commander.unknownCommand' });
2144
+ }
2145
+
2146
+ /**
2147
+ * Get or set the program version.
2148
+ *
2149
+ * This method auto-registers the "-V, --version" option which will print the version number.
2150
+ *
2151
+ * You can optionally supply the flags and description to override the defaults.
2152
+ *
2153
+ * @param {string} [str]
2154
+ * @param {string} [flags]
2155
+ * @param {string} [description]
2156
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2157
+ */
2158
+
2159
+ version(str, flags, description) {
2160
+ if (str === undefined) return this._version;
2161
+ this._version = str;
2162
+ flags = flags || '-V, --version';
2163
+ description = description || 'output the version number';
2164
+ const versionOption = this.createOption(flags, description);
2165
+ this._versionOptionName = versionOption.attributeName();
2166
+ this._registerOption(versionOption);
2167
+
2168
+ this.on('option:' + versionOption.name(), () => {
2169
+ this._outputConfiguration.writeOut(`${str}\n`);
2170
+ this._exit(0, 'commander.version', str);
2171
+ });
2172
+ return this;
2173
+ }
2174
+
2175
+ /**
2176
+ * Set the description.
2177
+ *
2178
+ * @param {string} [str]
2179
+ * @param {object} [argsDescription]
2180
+ * @return {(string|Command)}
2181
+ */
2182
+ description(str, argsDescription) {
2183
+ if (str === undefined && argsDescription === undefined)
2184
+ return this._description;
2185
+ this._description = str;
2186
+ if (argsDescription) {
2187
+ this._argsDescription = argsDescription;
2188
+ }
2189
+ return this;
2190
+ }
2191
+
2192
+ /**
2193
+ * Set the summary. Used when listed as subcommand of parent.
2194
+ *
2195
+ * @param {string} [str]
2196
+ * @return {(string|Command)}
2197
+ */
2198
+ summary(str) {
2199
+ if (str === undefined) return this._summary;
2200
+ this._summary = str;
2201
+ return this;
2202
+ }
2203
+
2204
+ /**
2205
+ * Set an alias for the command.
2206
+ *
2207
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2208
+ *
2209
+ * @param {string} [alias]
2210
+ * @return {(string|Command)}
2211
+ */
2212
+
2213
+ alias(alias) {
2214
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2215
+
2216
+ /** @type {Command} */
2217
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2218
+ let command = this;
2219
+ if (
2220
+ this.commands.length !== 0 &&
2221
+ this.commands[this.commands.length - 1]._executableHandler
2222
+ ) {
2223
+ // assume adding alias for last added executable subcommand, rather than this
2224
+ command = this.commands[this.commands.length - 1];
2225
+ }
2226
+
2227
+ if (alias === command._name)
2228
+ throw new Error("Command alias can't be the same as its name");
2229
+ const matchingCommand = this.parent?._findCommand(alias);
2230
+ if (matchingCommand) {
2231
+ // c.f. _registerCommand
2232
+ const existingCmd = [matchingCommand.name()]
2233
+ .concat(matchingCommand.aliases())
2234
+ .join('|');
2235
+ throw new Error(
2236
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
2237
+ );
2238
+ }
2239
+
2240
+ command._aliases.push(alias);
2241
+ return this;
2242
+ }
2243
+
2244
+ /**
2245
+ * Set aliases for the command.
2246
+ *
2247
+ * Only the first alias is shown in the auto-generated help.
2248
+ *
2249
+ * @param {string[]} [aliases]
2250
+ * @return {(string[]|Command)}
2251
+ */
2252
+
2253
+ aliases(aliases) {
2254
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2255
+ if (aliases === undefined) return this._aliases;
2256
+
2257
+ aliases.forEach((alias) => this.alias(alias));
2258
+ return this;
2259
+ }
2260
+
2261
+ /**
2262
+ * Set / get the command usage `str`.
2263
+ *
2264
+ * @param {string} [str]
2265
+ * @return {(string|Command)}
2266
+ */
2267
+
2268
+ usage(str) {
2269
+ if (str === undefined) {
2270
+ if (this._usage) return this._usage;
2271
+
2272
+ const args = this.registeredArguments.map((arg) => {
2273
+ return humanReadableArgName(arg);
2274
+ });
2275
+ return []
2276
+ .concat(
2277
+ this.options.length || this._helpOption !== null ? '[options]' : [],
2278
+ this.commands.length ? '[command]' : [],
2279
+ this.registeredArguments.length ? args : [],
2280
+ )
2281
+ .join(' ');
2282
+ }
2283
+
2284
+ this._usage = str;
2285
+ return this;
2286
+ }
2287
+
2288
+ /**
2289
+ * Get or set the name of the command.
2290
+ *
2291
+ * @param {string} [str]
2292
+ * @return {(string|Command)}
2293
+ */
2294
+
2295
+ name(str) {
2296
+ if (str === undefined) return this._name;
2297
+ this._name = str;
2298
+ return this;
2299
+ }
2300
+
2301
+ /**
2302
+ * Set the name of the command from script filename, such as process.argv[1],
2303
+ * or require.main.filename, or __filename.
2304
+ *
2305
+ * (Used internally and public although not documented in README.)
2306
+ *
2307
+ * @example
2308
+ * program.nameFromFilename(require.main.filename);
2309
+ *
2310
+ * @param {string} filename
2311
+ * @return {Command}
2312
+ */
2313
+
2314
+ nameFromFilename(filename) {
2315
+ this._name = path.basename(filename, path.extname(filename));
2316
+
2317
+ return this;
2318
+ }
2319
+
2320
+ /**
2321
+ * Get or set the directory for searching for executable subcommands of this command.
2322
+ *
2323
+ * @example
2324
+ * program.executableDir(__dirname);
2325
+ * // or
2326
+ * program.executableDir('subcommands');
2327
+ *
2328
+ * @param {string} [path]
2329
+ * @return {(string|null|Command)}
2330
+ */
2331
+
2332
+ executableDir(path) {
2333
+ if (path === undefined) return this._executableDir;
2334
+ this._executableDir = path;
2335
+ return this;
2336
+ }
2337
+
2338
+ /**
2339
+ * Return program help documentation.
2340
+ *
2341
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2342
+ * @return {string}
2343
+ */
2344
+
2345
+ helpInformation(contextOptions) {
2346
+ const helper = this.createHelp();
2347
+ const context = this._getOutputContext(contextOptions);
2348
+ helper.prepareContext({
2349
+ error: context.error,
2350
+ helpWidth: context.helpWidth,
2351
+ outputHasColors: context.hasColors,
2352
+ });
2353
+ const text = helper.formatHelp(this, helper);
2354
+ if (context.hasColors) return text;
2355
+ return this._outputConfiguration.stripColor(text);
2356
+ }
2357
+
2358
+ /**
2359
+ * @typedef HelpContext
2360
+ * @type {object}
2361
+ * @property {boolean} error
2362
+ * @property {number} helpWidth
2363
+ * @property {boolean} hasColors
2364
+ * @property {function} write - includes stripColor if needed
2365
+ *
2366
+ * @returns {HelpContext}
2367
+ * @private
2368
+ */
2369
+
2370
+ _getOutputContext(contextOptions) {
2371
+ contextOptions = contextOptions || {};
2372
+ const error = !!contextOptions.error;
2373
+ let baseWrite;
2374
+ let hasColors;
2375
+ let helpWidth;
2376
+ if (error) {
2377
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2378
+ hasColors = this._outputConfiguration.getErrHasColors();
2379
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2380
+ } else {
2381
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2382
+ hasColors = this._outputConfiguration.getOutHasColors();
2383
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2384
+ }
2385
+ const write = (str) => {
2386
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2387
+ return baseWrite(str);
2388
+ };
2389
+ return { error, write, hasColors, helpWidth };
2390
+ }
2391
+
2392
+ /**
2393
+ * Output help information for this command.
2394
+ *
2395
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2396
+ *
2397
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2398
+ */
2399
+
2400
+ outputHelp(contextOptions) {
2401
+ let deprecatedCallback;
2402
+ if (typeof contextOptions === 'function') {
2403
+ deprecatedCallback = contextOptions;
2404
+ contextOptions = undefined;
2405
+ }
2406
+
2407
+ const outputContext = this._getOutputContext(contextOptions);
2408
+ /** @type {HelpTextEventContext} */
2409
+ const eventContext = {
2410
+ error: outputContext.error,
2411
+ write: outputContext.write,
2412
+ command: this,
2413
+ };
2414
+
2415
+ this._getCommandAndAncestors()
2416
+ .reverse()
2417
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
2418
+ this.emit('beforeHelp', eventContext);
2419
+
2420
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2421
+ if (deprecatedCallback) {
2422
+ helpInformation = deprecatedCallback(helpInformation);
2423
+ if (
2424
+ typeof helpInformation !== 'string' &&
2425
+ !Buffer.isBuffer(helpInformation)
2426
+ ) {
2427
+ throw new Error('outputHelp callback must return a string or a Buffer');
2428
+ }
2429
+ }
2430
+ outputContext.write(helpInformation);
2431
+
2432
+ if (this._getHelpOption()?.long) {
2433
+ this.emit(this._getHelpOption().long); // deprecated
2434
+ }
2435
+ this.emit('afterHelp', eventContext);
2436
+ this._getCommandAndAncestors().forEach((command) =>
2437
+ command.emit('afterAllHelp', eventContext),
2438
+ );
2439
+ }
2440
+
2441
+ /**
2442
+ * You can pass in flags and a description to customise the built-in help option.
2443
+ * Pass in false to disable the built-in help option.
2444
+ *
2445
+ * @example
2446
+ * program.helpOption('-?, --help' 'show help'); // customise
2447
+ * program.helpOption(false); // disable
2448
+ *
2449
+ * @param {(string | boolean)} flags
2450
+ * @param {string} [description]
2451
+ * @return {Command} `this` command for chaining
2452
+ */
2453
+
2454
+ helpOption(flags, description) {
2455
+ // Support disabling built-in help option.
2456
+ if (typeof flags === 'boolean') {
2457
+ // true is not an expected value. Do something sensible but no unit-test.
2458
+ // istanbul ignore if
2459
+ if (flags) {
2460
+ this._helpOption = this._helpOption ?? undefined; // preserve existing option
2461
+ } else {
2462
+ this._helpOption = null; // disable
2463
+ }
2464
+ return this;
2465
+ }
2466
+
2467
+ // Customise flags and description.
2468
+ flags = flags ?? '-h, --help';
2469
+ description = description ?? 'display help for command';
2470
+ this._helpOption = this.createOption(flags, description);
2471
+
2472
+ return this;
2473
+ }
2474
+
2475
+ /**
2476
+ * Lazy create help option.
2477
+ * Returns null if has been disabled with .helpOption(false).
2478
+ *
2479
+ * @returns {(Option | null)} the help option
2480
+ * @package
2481
+ */
2482
+ _getHelpOption() {
2483
+ // Lazy create help option on demand.
2484
+ if (this._helpOption === undefined) {
2485
+ this.helpOption(undefined, undefined);
2486
+ }
2487
+ return this._helpOption;
2488
+ }
2489
+
2490
+ /**
2491
+ * Supply your own option to use for the built-in help option.
2492
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2493
+ *
2494
+ * @param {Option} option
2495
+ * @return {Command} `this` command for chaining
2496
+ */
2497
+ addHelpOption(option) {
2498
+ this._helpOption = option;
2499
+ return this;
2500
+ }
2501
+
2502
+ /**
2503
+ * Output help information and exit.
2504
+ *
2505
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2506
+ *
2507
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2508
+ */
2509
+
2510
+ help(contextOptions) {
2511
+ this.outputHelp(contextOptions);
2512
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
2513
+ if (
2514
+ exitCode === 0 &&
2515
+ contextOptions &&
2516
+ typeof contextOptions !== 'function' &&
2517
+ contextOptions.error
2518
+ ) {
2519
+ exitCode = 1;
2520
+ }
2521
+ // message: do not have all displayed text available so only passing placeholder.
2522
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2523
+ }
2524
+
2525
+ /**
2526
+ * // Do a little typing to coordinate emit and listener for the help text events.
2527
+ * @typedef HelpTextEventContext
2528
+ * @type {object}
2529
+ * @property {boolean} error
2530
+ * @property {Command} command
2531
+ * @property {function} write
2532
+ */
2533
+
2534
+ /**
2535
+ * Add additional text to be displayed with the built-in help.
2536
+ *
2537
+ * Position is 'before' or 'after' to affect just this command,
2538
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2539
+ *
2540
+ * @param {string} position - before or after built-in help
2541
+ * @param {(string | Function)} text - string to add, or a function returning a string
2542
+ * @return {Command} `this` command for chaining
2543
+ */
2544
+
2545
+ addHelpText(position, text) {
2546
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2547
+ if (!allowedValues.includes(position)) {
2548
+ throw new Error(`Unexpected value for position to addHelpText.
2549
+ Expecting one of '${allowedValues.join("', '")}'`);
2550
+ }
2551
+
2552
+ const helpEvent = `${position}Help`;
2553
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
2554
+ let helpStr;
2555
+ if (typeof text === 'function') {
2556
+ helpStr = text({ error: context.error, command: context.command });
2557
+ } else {
2558
+ helpStr = text;
2559
+ }
2560
+ // Ignore falsy value when nothing to output.
2561
+ if (helpStr) {
2562
+ context.write(`${helpStr}\n`);
2563
+ }
2564
+ });
2565
+ return this;
2566
+ }
2567
+
2568
+ /**
2569
+ * Output help information if help flags specified
2570
+ *
2571
+ * @param {Array} args - array of options to search for help flags
2572
+ * @private
2573
+ */
2574
+
2575
+ _outputHelpIfRequested(args) {
2576
+ const helpOption = this._getHelpOption();
2577
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2578
+ if (helpRequested) {
2579
+ this.outputHelp();
2580
+ // (Do not have all displayed text available so only passing placeholder.)
2581
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2582
+ }
2583
+ }
2584
+ }
2585
+
2586
+ /**
2587
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2588
+ *
2589
+ * @param {string[]} args - array of arguments from node.execArgv
2590
+ * @returns {string[]}
2591
+ * @private
2592
+ */
2593
+
2594
+ function incrementNodeInspectorPort(args) {
2595
+ // Testing for these options:
2596
+ // --inspect[=[host:]port]
2597
+ // --inspect-brk[=[host:]port]
2598
+ // --inspect-port=[host:]port
2599
+ return args.map((arg) => {
2600
+ if (!arg.startsWith('--inspect')) {
2601
+ return arg;
2602
+ }
2603
+ let debugOption;
2604
+ let debugHost = '127.0.0.1';
2605
+ let debugPort = '9229';
2606
+ let match;
2607
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2608
+ // e.g. --inspect
2609
+ debugOption = match[1];
2610
+ } else if (
2611
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
2612
+ ) {
2613
+ debugOption = match[1];
2614
+ if (/^\d+$/.test(match[3])) {
2615
+ // e.g. --inspect=1234
2616
+ debugPort = match[3];
2617
+ } else {
2618
+ // e.g. --inspect=localhost
2619
+ debugHost = match[3];
2620
+ }
2621
+ } else if (
2622
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
2623
+ ) {
2624
+ // e.g. --inspect=localhost:1234
2625
+ debugOption = match[1];
2626
+ debugHost = match[3];
2627
+ debugPort = match[4];
2628
+ }
2629
+
2630
+ if (debugOption && debugPort !== '0') {
2631
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2632
+ }
2633
+ return arg;
2634
+ });
2635
+ }
2636
+
2637
+ /**
2638
+ * @returns {boolean | undefined}
2639
+ * @package
2640
+ */
2641
+ function useColor() {
2642
+ // Test for common conventions.
2643
+ // NB: the observed behaviour is in combination with how author adds color! For example:
2644
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
2645
+ // - we do test NO_COLOR, but Chalk does not
2646
+ //
2647
+ // References:
2648
+ // https://no-color.org
2649
+ // https://bixense.com/clicolors/
2650
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
2651
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
2652
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
2653
+
2654
+ if (
2655
+ process.env.NO_COLOR ||
2656
+ process.env.FORCE_COLOR === '0' ||
2657
+ process.env.FORCE_COLOR === 'false'
2658
+ )
2659
+ return false;
2660
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
2661
+ return true;
2662
+ return undefined;
2663
+ }
2664
+
2665
+ exports.Command = Command;
2666
+ exports.useColor = useColor; // exporting for tests