clawmini 0.0.8 → 0.0.9

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 (367) hide show
  1. package/.changeset/README.md +8 -0
  2. package/.changeset/config.json +14 -0
  3. package/.github/workflows/release.yml +49 -0
  4. package/CHANGELOG.md +36 -0
  5. package/README.md +5 -4
  6. package/dist/adapter-discord/index.d.mts.map +1 -1
  7. package/dist/adapter-discord/index.mjs +465 -282
  8. package/dist/adapter-discord/index.mjs.map +1 -1
  9. package/dist/adapter-google-chat/index.mjs +367 -243
  10. package/dist/adapter-google-chat/index.mjs.map +1 -1
  11. package/dist/cli/index.mjs +684 -24
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/cli/lite.mjs +43 -13
  14. package/dist/cli/lite.mjs.map +1 -1
  15. package/dist/cli/{propose-policy.mjs → manage-policies.mjs} +270 -47
  16. package/dist/cli/manage-policies.mjs.map +1 -0
  17. package/dist/cli/run-host.d.mts +1 -0
  18. package/dist/cli/run-host.mjs +3090 -0
  19. package/dist/cli/run-host.mjs.map +1 -0
  20. package/dist/config-CPFQIGdG.mjs +57 -0
  21. package/dist/config-CPFQIGdG.mjs.map +1 -0
  22. package/dist/config-Dvl-Pov4.mjs +76 -0
  23. package/dist/config-Dvl-Pov4.mjs.map +1 -0
  24. package/dist/daemon/index.d.mts.map +1 -1
  25. package/dist/daemon/index.mjs +970 -332
  26. package/dist/daemon/index.mjs.map +1 -1
  27. package/dist/supervisor-actions-CiW56eLi.mjs +843 -0
  28. package/dist/supervisor-actions-CiW56eLi.mjs.map +1 -0
  29. package/dist/turn-log-buffer-DRgW53gl.mjs +767 -0
  30. package/dist/turn-log-buffer-DRgW53gl.mjs.map +1 -0
  31. package/dist/web/_app/immutable/chunks/{Drm9vgeP.js → 3AZlWB6U.js} +1 -1
  32. package/dist/web/_app/immutable/chunks/BhRSsUCh.js +2 -0
  33. package/dist/web/_app/immutable/chunks/BiLeM2i1.js +1 -0
  34. package/{web/.svelte-kit/output/client/_app/immutable/chunks/CME08kGM.js → dist/web/_app/immutable/chunks/BmBj85Ll.js} +1 -1
  35. package/dist/web/_app/immutable/chunks/BrERcKAH.js +1 -0
  36. package/dist/web/_app/immutable/chunks/Bv9252RM.js +1 -0
  37. package/dist/web/_app/immutable/chunks/CIXNBPKi.js +1 -0
  38. package/dist/web/_app/immutable/chunks/DISKL3GN.js +2 -0
  39. package/dist/web/_app/immutable/chunks/{Zeh-C-mx.js → DcpaLzmX.js} +1 -1
  40. package/dist/web/_app/immutable/chunks/DnQ3vS13.js +1 -0
  41. package/dist/web/_app/immutable/chunks/KsloHTKS.js +1 -0
  42. package/{web/.svelte-kit/output/client/_app/immutable/chunks/Ck-be5J2.js → dist/web/_app/immutable/chunks/RsHsUj-8.js} +2 -2
  43. package/dist/web/_app/immutable/chunks/{vDehDcuJ.js → wpfV79dV.js} +1 -1
  44. package/dist/web/_app/immutable/entry/app.CIw1Qj0n.js +2 -0
  45. package/dist/web/_app/immutable/entry/start.Di0-Jhte.js +1 -0
  46. package/dist/web/_app/immutable/nodes/{0.CUGC2p-K.js → 0.DYyUA1au.js} +1 -1
  47. package/dist/web/_app/immutable/nodes/1.D-3QEMMZ.js +1 -0
  48. package/dist/web/_app/immutable/nodes/{2.BnwnD1Ki.js → 2.4olHnH7U.js} +1 -1
  49. package/{web/.svelte-kit/output/client/_app/immutable/nodes/3.0arZe_Uf.js → dist/web/_app/immutable/nodes/3.4w0bE-m2.js} +3 -3
  50. package/dist/web/_app/immutable/nodes/4.CZvjhVHt.js +60 -0
  51. package/dist/web/_app/immutable/nodes/{5.Bq2JzCEj.js → 5.DLbPVJY2.js} +1 -1
  52. package/dist/web/_app/version.json +1 -1
  53. package/dist/web/index.html +12 -12
  54. package/dist/workspace-oWmVh5mi.mjs +1001 -0
  55. package/dist/workspace-oWmVh5mi.mjs.map +1 -0
  56. package/docs/23_adapter_slash_autocomplete/development_log.md +19 -0
  57. package/docs/23_adapter_slash_autocomplete/notes.md +18 -0
  58. package/docs/23_adapter_slash_autocomplete/prd.md +46 -0
  59. package/docs/23_adapter_slash_autocomplete/questions.md +6 -0
  60. package/docs/23_adapter_slash_autocomplete/tickets.md +21 -0
  61. package/docs/24_subagent_job_policy_fixes/development_log.md +22 -0
  62. package/docs/24_subagent_job_policy_fixes/notes.md +28 -0
  63. package/docs/24_subagent_job_policy_fixes/prd.md +59 -0
  64. package/docs/24_subagent_job_policy_fixes/questions.md +3 -0
  65. package/docs/24_subagent_job_policy_fixes/tickets.md +49 -0
  66. package/docs/25_e2e_test_improvements/development_log.md +30 -0
  67. package/docs/25_e2e_test_improvements/notes.md +29 -0
  68. package/docs/25_e2e_test_improvements/prd.md +43 -0
  69. package/docs/25_e2e_test_improvements/questions.md +12 -0
  70. package/docs/25_e2e_test_improvements/tickets-2.md +22 -0
  71. package/docs/25_e2e_test_improvements/tickets.md +22 -0
  72. package/docs/25_policy_cwd/development_log.md +30 -0
  73. package/docs/25_policy_cwd/notes.md +28 -0
  74. package/docs/25_policy_cwd/prd.md +77 -0
  75. package/docs/25_policy_cwd/questions.md +6 -0
  76. package/docs/25_policy_cwd/tickets.md +77 -0
  77. package/docs/CLI_REFERENCE.md +3 -1
  78. package/docs/PHILOSOPHY.md +35 -0
  79. package/docs/adapter-visibility/SPEC.md +461 -0
  80. package/docs/adapter-visibility/SPEC_v2.md +202 -0
  81. package/docs/auto-update/SPEC.md +344 -0
  82. package/docs/backups/SPEC.md +296 -0
  83. package/docs/backups/clawmini.gitignore +69 -0
  84. package/docs/guides/assets/clawmini-avatar.png +0 -0
  85. package/docs/guides/backups.md +332 -0
  86. package/docs/guides/discord_adapter_setup.md +1 -1
  87. package/docs/guides/google_chat_adapter_setup.md +81 -0
  88. package/docs/unified-startup/SPEC.md +203 -0
  89. package/e2e/_helpers/test-environment.test.ts +49 -0
  90. package/e2e/_helpers/test-environment.ts +548 -0
  91. package/e2e/adapters/_google-chat-fixtures.ts +340 -0
  92. package/{src/cli/e2e → e2e/adapters}/adapter-discord.test.ts +22 -23
  93. package/e2e/adapters/adapter-google-chat-downtime.test.ts +157 -0
  94. package/e2e/adapters/adapter-google-chat-inbound.test.ts +697 -0
  95. package/e2e/adapters/adapter-google-chat-outbound.test.ts +297 -0
  96. package/e2e/adapters/adapter-google-chat-roundtrip.test.ts +56 -0
  97. package/e2e/adapters/adapter-google-chat-threads.test.ts +1078 -0
  98. package/e2e/agents/custom-api-env.test.ts +80 -0
  99. package/e2e/agents/export-lite-func.test.ts +104 -0
  100. package/e2e/agents/fallbacks.test.ts +124 -0
  101. package/e2e/agents/interrupt.test.ts +50 -0
  102. package/e2e/agents/no-reply-necessary.test.ts +57 -0
  103. package/e2e/agents/session-timeout-subagents.test.ts +76 -0
  104. package/e2e/agents/subagent-authorization.test.ts +246 -0
  105. package/e2e/agents/subagent-env.test.ts +49 -0
  106. package/e2e/agents/subagent-lifecycle.test.ts +782 -0
  107. package/e2e/agents/subagents-depth.test.ts +47 -0
  108. package/e2e/cli/agents.test.ts +176 -0
  109. package/e2e/cli/auto-update.test.ts +741 -0
  110. package/e2e/cli/basic.test.ts +44 -0
  111. package/{src/cli/e2e → e2e/cli}/export-lite.test.ts +16 -12
  112. package/e2e/cli/init-gitignore.test.ts +86 -0
  113. package/e2e/cli/init.test.ts +76 -0
  114. package/e2e/cli/messages.test.ts +363 -0
  115. package/e2e/cli/serve.test.ts +76 -0
  116. package/{src/cli/e2e → e2e/cli}/skills.test.ts +11 -10
  117. package/{src/cli/e2e → e2e/daemon}/daemon.test.ts +57 -195
  118. package/e2e/jobs/agent-jobs.test.ts +216 -0
  119. package/e2e/jobs/cron.test.ts +64 -0
  120. package/e2e/jobs/restart.test.ts +108 -0
  121. package/e2e/policies/approval-session.test.ts +69 -0
  122. package/e2e/policies/auto-create-policies-file.test.ts +35 -0
  123. package/e2e/policies/builtin-manage-policies.test.ts +184 -0
  124. package/e2e/policies/builtin-run-host.test.ts +180 -0
  125. package/e2e/policies/environment-policies.test.ts +177 -0
  126. package/e2e/policies/manage-policies.test.ts +566 -0
  127. package/e2e/policies/output-size.test.ts +98 -0
  128. package/e2e/policies/policies-context-cwd.test.ts +160 -0
  129. package/e2e/policies/relative-script-path.test.ts +60 -0
  130. package/e2e/policies/requests-show.test.ts +135 -0
  131. package/e2e/policies/requests.test.ts +208 -0
  132. package/e2e/policies/slash-policies.test.ts +308 -0
  133. package/e2e/policies/startup-cleanup.test.ts +48 -0
  134. package/e2e/routers/session-timeout.test.ts +106 -0
  135. package/e2e/routers/slash-model.test.ts +152 -0
  136. package/e2e/routers/slash-new.test.ts +50 -0
  137. package/e2e/routers/slash-restart-adapter.test.ts +96 -0
  138. package/e2e/routers/slash-restart.test.ts +114 -0
  139. package/e2e/routers/slash-shutdown.test.ts +55 -0
  140. package/e2e/routers/slash-stop.test.ts +232 -0
  141. package/e2e/routers/slash-upgrade.test.ts +88 -0
  142. package/{src/cli/e2e → e2e/sandbox}/environments.test.ts +14 -13
  143. package/eslint.config.js +6 -0
  144. package/napkin.md +1 -1
  145. package/package.json +8 -3
  146. package/src/adapter-discord/commands.test.ts +42 -0
  147. package/src/adapter-discord/commands.ts +33 -0
  148. package/src/adapter-discord/config.ts +12 -0
  149. package/src/adapter-discord/forwarder.test.ts +499 -21
  150. package/src/adapter-discord/forwarder.ts +343 -124
  151. package/src/adapter-discord/inbound-cache.test.ts +47 -0
  152. package/src/adapter-discord/inbound-cache.ts +37 -0
  153. package/src/adapter-discord/index.test.ts +67 -2
  154. package/src/adapter-discord/index.ts +84 -216
  155. package/src/adapter-discord/interactions.test.ts +54 -3
  156. package/src/adapter-discord/interactions.ts +97 -53
  157. package/src/adapter-discord/processMessage.ts +239 -0
  158. package/src/adapter-discord/state.ts +1 -0
  159. package/src/adapter-google-chat/auth.test.ts +9 -5
  160. package/src/adapter-google-chat/auth.ts +29 -23
  161. package/src/adapter-google-chat/cards.ts +7 -2
  162. package/src/adapter-google-chat/client.test.ts +37 -2
  163. package/src/adapter-google-chat/client.ts +138 -38
  164. package/src/adapter-google-chat/config.ts +19 -0
  165. package/src/adapter-google-chat/forwarder.test.ts +81 -56
  166. package/src/adapter-google-chat/forwarder.ts +394 -185
  167. package/src/adapter-google-chat/inbound-cache.test.ts +61 -0
  168. package/src/adapter-google-chat/inbound-cache.ts +36 -0
  169. package/src/adapter-google-chat/state.test.ts +1 -0
  170. package/src/adapter-google-chat/state.ts +9 -1
  171. package/src/adapter-google-chat/subscriptions.ts +8 -6
  172. package/src/cli/builtin-policies.ts +44 -0
  173. package/src/cli/commands/agents.ts +59 -5
  174. package/src/cli/commands/down.ts +54 -2
  175. package/src/cli/commands/environments.ts +8 -2
  176. package/src/cli/commands/init.ts +31 -0
  177. package/src/cli/commands/logs.ts +116 -0
  178. package/src/cli/commands/policies.ts +6 -4
  179. package/src/cli/commands/serve.test.ts +67 -0
  180. package/src/cli/commands/serve.ts +284 -0
  181. package/src/cli/commands/up.ts +122 -2
  182. package/src/cli/commands/web-api/agents.ts +3 -2
  183. package/src/cli/index.ts +4 -0
  184. package/src/cli/install-detection.test.ts +72 -0
  185. package/src/cli/install-detection.ts +48 -0
  186. package/src/cli/lite.ts +54 -22
  187. package/src/cli/manage-policies-utils.ts +104 -0
  188. package/src/cli/manage-policies.ts +291 -0
  189. package/src/cli/run-host.ts +45 -0
  190. package/src/cli/supervisor-actions.ts +267 -0
  191. package/src/cli/supervisor-control.test.ts +129 -0
  192. package/src/cli/supervisor-control.ts +155 -0
  193. package/src/cli/supervisor-pid.ts +68 -0
  194. package/src/cli/supervisor.ts +277 -0
  195. package/src/daemon/agent/agent-context.ts +11 -11
  196. package/src/daemon/agent/agent-session.ts +8 -1
  197. package/src/daemon/agent/chat-logger.test.ts +78 -9
  198. package/src/daemon/agent/chat-logger.ts +25 -5
  199. package/src/daemon/agent/turn-registry.test.ts +89 -0
  200. package/src/daemon/agent/turn-registry.ts +94 -0
  201. package/src/daemon/agent/types.ts +2 -0
  202. package/src/daemon/api/agent-policy-endpoints.ts +263 -0
  203. package/src/daemon/api/agent-router.ts +47 -126
  204. package/src/daemon/api/index.test.ts +1 -0
  205. package/src/daemon/api/policy-request.test.ts +7 -5
  206. package/src/daemon/api/router-utils.ts +6 -5
  207. package/src/daemon/api/subagent-router.ts +110 -74
  208. package/src/daemon/api/subagent-utils.test.ts +60 -0
  209. package/src/daemon/api/subagent-utils.ts +113 -87
  210. package/src/daemon/api/user-router.ts +34 -8
  211. package/src/daemon/auth.ts +1 -0
  212. package/src/daemon/cron.test.ts +62 -4
  213. package/src/daemon/cron.ts +42 -16
  214. package/src/daemon/events.ts +65 -0
  215. package/src/daemon/index.ts +24 -1
  216. package/src/daemon/message-interruption.test.ts +1 -0
  217. package/src/daemon/message-jobs.test.ts +1 -0
  218. package/src/daemon/message.ts +78 -14
  219. package/src/daemon/observation.test.ts +26 -18
  220. package/src/daemon/pending-replies.test.ts +112 -0
  221. package/src/daemon/pending-replies.ts +162 -0
  222. package/src/daemon/policy-request-service.ts +3 -1
  223. package/src/daemon/policy-utils.test.ts +66 -1
  224. package/src/daemon/policy-utils.ts +126 -1
  225. package/src/daemon/request-store.ts +31 -0
  226. package/src/daemon/routers/session-timeout.ts +4 -0
  227. package/src/daemon/routers/slash-model.test.ts +344 -0
  228. package/src/daemon/routers/slash-model.ts +207 -0
  229. package/src/daemon/routers/slash-policies.test.ts +38 -32
  230. package/src/daemon/routers/slash-policies.ts +84 -33
  231. package/src/daemon/routers/slash-restart.test.ts +69 -0
  232. package/src/daemon/routers/slash-restart.ts +36 -0
  233. package/src/daemon/routers/slash-shutdown.test.ts +50 -0
  234. package/src/daemon/routers/slash-shutdown.ts +28 -0
  235. package/src/daemon/routers/slash-upgrade.test.ts +116 -0
  236. package/src/daemon/routers/slash-upgrade.ts +76 -0
  237. package/src/daemon/routers/types.ts +7 -0
  238. package/src/daemon/routers.ts +16 -0
  239. package/src/shared/adapters/blockquote.test.ts +28 -0
  240. package/src/shared/adapters/blockquote.ts +20 -0
  241. package/src/shared/adapters/filtering.test.ts +224 -10
  242. package/src/shared/adapters/filtering.ts +95 -7
  243. package/src/shared/adapters/inbound-cache.test.ts +48 -0
  244. package/src/shared/adapters/inbound-cache.ts +54 -0
  245. package/src/shared/adapters/turn-log-buffer.ts +266 -0
  246. package/src/shared/adapters/turn-log.test.ts +389 -0
  247. package/src/shared/adapters/turn-log.ts +357 -0
  248. package/src/shared/agent-utils.ts +12 -5
  249. package/src/shared/chats.test.ts +4 -0
  250. package/src/shared/chats.ts +9 -0
  251. package/src/shared/config.ts +16 -1
  252. package/src/shared/lite.ts +76 -2
  253. package/src/shared/policies.ts +26 -0
  254. package/src/shared/template-manifest.ts +267 -0
  255. package/src/shared/utils/shell.ts +61 -0
  256. package/src/shared/version.ts +34 -0
  257. package/src/shared/workspace.test.ts +217 -0
  258. package/src/shared/workspace.ts +626 -48
  259. package/templates/environments/cladding/allowlist-domain.mjs +125 -0
  260. package/templates/environments/cladding/env.json +21 -1
  261. package/templates/environments/cladding/run-with-network.mjs +54 -0
  262. package/templates/environments/macos-proxy/allowlist-domain.mjs +95 -0
  263. package/templates/environments/macos-proxy/env.json +8 -1
  264. package/templates/environments/macos-proxy/proxy.mjs +0 -1
  265. package/templates/gemini/template.json +5 -0
  266. package/templates/gemini-claw/template.json +13 -0
  267. package/templates/skills/clawmini-requests/SKILL.md +69 -10
  268. package/templates/skills/run-host/SKILL.md +51 -0
  269. package/templates/skills/skill-creator/SKILL.md +4 -3
  270. package/templates/skills/skill-creator/scripts/validate.sh +52 -0
  271. package/tsdown.config.ts +10 -1
  272. package/vitest.config.ts +2 -2
  273. package/web/.svelte-kit/ambient.d.ts +292 -118
  274. package/web/.svelte-kit/generated/server/internal.js +1 -1
  275. package/web/.svelte-kit/output/client/.vite/manifest.json +126 -136
  276. package/web/.svelte-kit/output/client/_app/immutable/chunks/{Drm9vgeP.js → 3AZlWB6U.js} +1 -1
  277. package/web/.svelte-kit/output/client/_app/immutable/chunks/BhRSsUCh.js +2 -0
  278. package/web/.svelte-kit/output/client/_app/immutable/chunks/BiLeM2i1.js +1 -0
  279. package/{dist/web/_app/immutable/chunks/CME08kGM.js → web/.svelte-kit/output/client/_app/immutable/chunks/BmBj85Ll.js} +1 -1
  280. package/web/.svelte-kit/output/client/_app/immutable/chunks/BrERcKAH.js +1 -0
  281. package/web/.svelte-kit/output/client/_app/immutable/chunks/Bv9252RM.js +1 -0
  282. package/web/.svelte-kit/output/client/_app/immutable/chunks/CIXNBPKi.js +1 -0
  283. package/web/.svelte-kit/output/client/_app/immutable/chunks/DISKL3GN.js +2 -0
  284. package/web/.svelte-kit/output/client/_app/immutable/chunks/{Zeh-C-mx.js → DcpaLzmX.js} +1 -1
  285. package/web/.svelte-kit/output/client/_app/immutable/chunks/DnQ3vS13.js +1 -0
  286. package/web/.svelte-kit/output/client/_app/immutable/chunks/KsloHTKS.js +1 -0
  287. package/{dist/web/_app/immutable/chunks/Ck-be5J2.js → web/.svelte-kit/output/client/_app/immutable/chunks/RsHsUj-8.js} +2 -2
  288. package/web/.svelte-kit/output/client/_app/immutable/chunks/{vDehDcuJ.js → wpfV79dV.js} +1 -1
  289. package/web/.svelte-kit/output/client/_app/immutable/entry/app.CIw1Qj0n.js +2 -0
  290. package/web/.svelte-kit/output/client/_app/immutable/entry/start.Di0-Jhte.js +1 -0
  291. package/web/.svelte-kit/output/client/_app/immutable/nodes/{0.CUGC2p-K.js → 0.DYyUA1au.js} +1 -1
  292. package/web/.svelte-kit/output/client/_app/immutable/nodes/1.D-3QEMMZ.js +1 -0
  293. package/web/.svelte-kit/output/client/_app/immutable/nodes/{2.BnwnD1Ki.js → 2.4olHnH7U.js} +1 -1
  294. package/{dist/web/_app/immutable/nodes/3.0arZe_Uf.js → web/.svelte-kit/output/client/_app/immutable/nodes/3.4w0bE-m2.js} +3 -3
  295. package/web/.svelte-kit/output/client/_app/immutable/nodes/4.CZvjhVHt.js +60 -0
  296. package/web/.svelte-kit/output/client/_app/immutable/nodes/{5.Bq2JzCEj.js → 5.DLbPVJY2.js} +1 -1
  297. package/web/.svelte-kit/output/client/_app/version.json +1 -1
  298. package/web/.svelte-kit/output/server/.vite/manifest.json +12 -10
  299. package/web/.svelte-kit/output/server/chunks/Icon.js +1 -1
  300. package/web/.svelte-kit/output/server/chunks/client.js +1 -1
  301. package/web/.svelte-kit/output/server/chunks/exports.js +1 -1
  302. package/web/.svelte-kit/output/server/chunks/index-server.js +2 -1
  303. package/web/.svelte-kit/output/server/chunks/internal.js +1 -1
  304. package/web/.svelte-kit/output/server/chunks/render-context.js +77 -0
  305. package/web/.svelte-kit/output/server/chunks/root.js +739 -788
  306. package/web/.svelte-kit/output/server/chunks/shared.js +234 -21
  307. package/web/.svelte-kit/output/server/index.js +126 -90
  308. package/web/.svelte-kit/output/server/manifest-full.js +1 -1
  309. package/web/.svelte-kit/output/server/manifest.js +1 -1
  310. package/web/.svelte-kit/output/server/nodes/0.js +1 -1
  311. package/web/.svelte-kit/output/server/nodes/1.js +1 -1
  312. package/web/.svelte-kit/output/server/nodes/2.js +1 -1
  313. package/web/.svelte-kit/output/server/nodes/3.js +1 -1
  314. package/web/.svelte-kit/output/server/nodes/4.js +1 -1
  315. package/web/.svelte-kit/output/server/nodes/5.js +1 -1
  316. package/web/.svelte-kit/output/server/remote-entry.js +245 -81
  317. package/web/.svelte-kit/tsconfig.json +4 -1
  318. package/dist/cli/propose-policy.mjs.map +0 -1
  319. package/dist/lite-CBxOT1y5.mjs +0 -241
  320. package/dist/lite-CBxOT1y5.mjs.map +0 -1
  321. package/dist/routing-D8rTxtaV.mjs +0 -245
  322. package/dist/routing-D8rTxtaV.mjs.map +0 -1
  323. package/dist/web/_app/immutable/chunks/B6YN0Nuq.js +0 -1
  324. package/dist/web/_app/immutable/chunks/BmRlVmv6.js +0 -1
  325. package/dist/web/_app/immutable/chunks/CK9JZLaG.js +0 -2
  326. package/dist/web/_app/immutable/chunks/Ck3rYNON.js +0 -1
  327. package/dist/web/_app/immutable/chunks/D5iV40bG.js +0 -1
  328. package/dist/web/_app/immutable/chunks/DMtIqaiV.js +0 -2
  329. package/dist/web/_app/immutable/chunks/DhD271EB.js +0 -1
  330. package/dist/web/_app/immutable/chunks/DpuLqk8d.js +0 -1
  331. package/dist/web/_app/immutable/chunks/DsIToJCP.js +0 -1
  332. package/dist/web/_app/immutable/entry/app.BCSV3nrG.js +0 -2
  333. package/dist/web/_app/immutable/entry/start.D4eLEZUM.js +0 -1
  334. package/dist/web/_app/immutable/nodes/1.CGC_42IQ.js +0 -1
  335. package/dist/web/_app/immutable/nodes/4.ClM1bXLE.js +0 -60
  336. package/dist/workspace-BJmJBfKi.mjs +0 -456
  337. package/dist/workspace-BJmJBfKi.mjs.map +0 -1
  338. package/src/cli/e2e/agents.test.ts +0 -140
  339. package/src/cli/e2e/basic.test.ts +0 -43
  340. package/src/cli/e2e/cron.test.ts +0 -132
  341. package/src/cli/e2e/export-lite-func.test.ts +0 -206
  342. package/src/cli/e2e/fallbacks.test.ts +0 -175
  343. package/src/cli/e2e/init.test.ts +0 -77
  344. package/src/cli/e2e/messages.test.ts +0 -332
  345. package/src/cli/e2e/propose-policy.test.ts +0 -203
  346. package/src/cli/e2e/requests.test.ts +0 -180
  347. package/src/cli/e2e/session-timeout.test.ts +0 -192
  348. package/src/cli/e2e/slash-new.test.ts +0 -93
  349. package/src/cli/e2e/subagents.test.ts +0 -106
  350. package/src/cli/e2e/utils.ts +0 -66
  351. package/src/cli/propose-policy.ts +0 -91
  352. package/web/.svelte-kit/output/client/_app/immutable/chunks/B6YN0Nuq.js +0 -1
  353. package/web/.svelte-kit/output/client/_app/immutable/chunks/BmRlVmv6.js +0 -1
  354. package/web/.svelte-kit/output/client/_app/immutable/chunks/CK9JZLaG.js +0 -2
  355. package/web/.svelte-kit/output/client/_app/immutable/chunks/Ck3rYNON.js +0 -1
  356. package/web/.svelte-kit/output/client/_app/immutable/chunks/D5iV40bG.js +0 -1
  357. package/web/.svelte-kit/output/client/_app/immutable/chunks/DMtIqaiV.js +0 -2
  358. package/web/.svelte-kit/output/client/_app/immutable/chunks/DhD271EB.js +0 -1
  359. package/web/.svelte-kit/output/client/_app/immutable/chunks/DpuLqk8d.js +0 -1
  360. package/web/.svelte-kit/output/client/_app/immutable/chunks/DsIToJCP.js +0 -1
  361. package/web/.svelte-kit/output/client/_app/immutable/entry/app.BCSV3nrG.js +0 -2
  362. package/web/.svelte-kit/output/client/_app/immutable/entry/start.D4eLEZUM.js +0 -1
  363. package/web/.svelte-kit/output/client/_app/immutable/nodes/1.CGC_42IQ.js +0 -1
  364. package/web/.svelte-kit/output/client/_app/immutable/nodes/4.ClM1bXLE.js +0 -60
  365. package/web/.svelte-kit/output/server/chunks/false.js +0 -4
  366. /package/dist/cli/{propose-policy.d.mts → manage-policies.d.mts} +0 -0
  367. /package/{src/cli/e2e → e2e/_helpers}/global-setup.ts +0 -0
@@ -0,0 +1,3090 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { spawn } from "node:child_process";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ //#region \0rolldown/runtime.js
7
+ var __create = Object.create;
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __getProtoOf = Object.getPrototypeOf;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
+ key = keys[i];
18
+ if (!__hasOwnProp.call(to, key) && key !== except) {
19
+ __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ }
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
33
+
34
+ //#endregion
35
+ //#region node_modules/commander/lib/error.js
36
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
37
+ /**
38
+ * CommanderError class
39
+ */
40
+ var CommanderError = class extends Error {
41
+ /**
42
+ * Constructs the CommanderError class
43
+ * @param {number} exitCode suggested exit code which could be used with process.exit
44
+ * @param {string} code an id string representing the error
45
+ * @param {string} message human-readable description of the error
46
+ */
47
+ constructor(exitCode, code, message) {
48
+ super(message);
49
+ Error.captureStackTrace(this, this.constructor);
50
+ this.name = this.constructor.name;
51
+ this.code = code;
52
+ this.exitCode = exitCode;
53
+ this.nestedError = void 0;
54
+ }
55
+ };
56
+ /**
57
+ * InvalidArgumentError class
58
+ */
59
+ var InvalidArgumentError = class extends CommanderError {
60
+ /**
61
+ * Constructs the InvalidArgumentError class
62
+ * @param {string} [message] explanation of why argument is invalid
63
+ */
64
+ constructor(message) {
65
+ super(1, "commander.invalidArgument", message);
66
+ Error.captureStackTrace(this, this.constructor);
67
+ this.name = this.constructor.name;
68
+ }
69
+ };
70
+ exports.CommanderError = CommanderError;
71
+ exports.InvalidArgumentError = InvalidArgumentError;
72
+ }));
73
+
74
+ //#endregion
75
+ //#region node_modules/commander/lib/argument.js
76
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
77
+ const { InvalidArgumentError } = require_error();
78
+ var Argument = class {
79
+ /**
80
+ * Initialize a new command argument with the given name and description.
81
+ * The default is that the argument is required, and you can explicitly
82
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
83
+ *
84
+ * @param {string} name
85
+ * @param {string} [description]
86
+ */
87
+ constructor(name, description) {
88
+ this.description = description || "";
89
+ this.variadic = false;
90
+ this.parseArg = void 0;
91
+ this.defaultValue = void 0;
92
+ this.defaultValueDescription = void 0;
93
+ this.argChoices = void 0;
94
+ switch (name[0]) {
95
+ case "<":
96
+ this.required = true;
97
+ this._name = name.slice(1, -1);
98
+ break;
99
+ case "[":
100
+ this.required = false;
101
+ this._name = name.slice(1, -1);
102
+ break;
103
+ default:
104
+ this.required = true;
105
+ this._name = name;
106
+ break;
107
+ }
108
+ if (this._name.endsWith("...")) {
109
+ this.variadic = true;
110
+ this._name = this._name.slice(0, -3);
111
+ }
112
+ }
113
+ /**
114
+ * Return argument name.
115
+ *
116
+ * @return {string}
117
+ */
118
+ name() {
119
+ return this._name;
120
+ }
121
+ /**
122
+ * @package
123
+ */
124
+ _collectValue(value, previous) {
125
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
126
+ previous.push(value);
127
+ return previous;
128
+ }
129
+ /**
130
+ * Set the default value, and optionally supply the description to be displayed in the help.
131
+ *
132
+ * @param {*} value
133
+ * @param {string} [description]
134
+ * @return {Argument}
135
+ */
136
+ default(value, description) {
137
+ this.defaultValue = value;
138
+ this.defaultValueDescription = description;
139
+ return this;
140
+ }
141
+ /**
142
+ * Set the custom handler for processing CLI command arguments into argument values.
143
+ *
144
+ * @param {Function} [fn]
145
+ * @return {Argument}
146
+ */
147
+ argParser(fn) {
148
+ this.parseArg = fn;
149
+ return this;
150
+ }
151
+ /**
152
+ * Only allow argument value to be one of choices.
153
+ *
154
+ * @param {string[]} values
155
+ * @return {Argument}
156
+ */
157
+ choices(values) {
158
+ this.argChoices = values.slice();
159
+ this.parseArg = (arg, previous) => {
160
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
161
+ if (this.variadic) return this._collectValue(arg, previous);
162
+ return arg;
163
+ };
164
+ return this;
165
+ }
166
+ /**
167
+ * Make argument required.
168
+ *
169
+ * @returns {Argument}
170
+ */
171
+ argRequired() {
172
+ this.required = true;
173
+ return this;
174
+ }
175
+ /**
176
+ * Make argument optional.
177
+ *
178
+ * @returns {Argument}
179
+ */
180
+ argOptional() {
181
+ this.required = false;
182
+ return this;
183
+ }
184
+ };
185
+ /**
186
+ * Takes an argument and returns its human readable equivalent for help usage.
187
+ *
188
+ * @param {Argument} arg
189
+ * @return {string}
190
+ * @private
191
+ */
192
+ function humanReadableArgName(arg) {
193
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
194
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
195
+ }
196
+ exports.Argument = Argument;
197
+ exports.humanReadableArgName = humanReadableArgName;
198
+ }));
199
+
200
+ //#endregion
201
+ //#region node_modules/commander/lib/help.js
202
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
203
+ const { humanReadableArgName } = require_argument();
204
+ /**
205
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
206
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
207
+ * @typedef { import("./argument.js").Argument } Argument
208
+ * @typedef { import("./command.js").Command } Command
209
+ * @typedef { import("./option.js").Option } Option
210
+ */
211
+ var Help = class {
212
+ constructor() {
213
+ this.helpWidth = void 0;
214
+ this.minWidthToWrap = 40;
215
+ this.sortSubcommands = false;
216
+ this.sortOptions = false;
217
+ this.showGlobalOptions = false;
218
+ }
219
+ /**
220
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
221
+ * and just before calling `formatHelp()`.
222
+ *
223
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
224
+ *
225
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
226
+ */
227
+ prepareContext(contextOptions) {
228
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
229
+ }
230
+ /**
231
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
232
+ *
233
+ * @param {Command} cmd
234
+ * @returns {Command[]}
235
+ */
236
+ visibleCommands(cmd) {
237
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
238
+ const helpCommand = cmd._getHelpCommand();
239
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
240
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
241
+ return a.name().localeCompare(b.name());
242
+ });
243
+ return visibleCommands;
244
+ }
245
+ /**
246
+ * Compare options for sort.
247
+ *
248
+ * @param {Option} a
249
+ * @param {Option} b
250
+ * @returns {number}
251
+ */
252
+ compareOptions(a, b) {
253
+ const getSortKey = (option) => {
254
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
255
+ };
256
+ return getSortKey(a).localeCompare(getSortKey(b));
257
+ }
258
+ /**
259
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
260
+ *
261
+ * @param {Command} cmd
262
+ * @returns {Option[]}
263
+ */
264
+ visibleOptions(cmd) {
265
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
266
+ const helpOption = cmd._getHelpOption();
267
+ if (helpOption && !helpOption.hidden) {
268
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
269
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
270
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
271
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
272
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
273
+ }
274
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
275
+ return visibleOptions;
276
+ }
277
+ /**
278
+ * Get an array of the visible global options. (Not including help.)
279
+ *
280
+ * @param {Command} cmd
281
+ * @returns {Option[]}
282
+ */
283
+ visibleGlobalOptions(cmd) {
284
+ if (!this.showGlobalOptions) return [];
285
+ const globalOptions = [];
286
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
287
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
288
+ globalOptions.push(...visibleOptions);
289
+ }
290
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
291
+ return globalOptions;
292
+ }
293
+ /**
294
+ * Get an array of the arguments if any have a description.
295
+ *
296
+ * @param {Command} cmd
297
+ * @returns {Argument[]}
298
+ */
299
+ visibleArguments(cmd) {
300
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
301
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
302
+ });
303
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
304
+ return [];
305
+ }
306
+ /**
307
+ * Get the command term to show in the list of subcommands.
308
+ *
309
+ * @param {Command} cmd
310
+ * @returns {string}
311
+ */
312
+ subcommandTerm(cmd) {
313
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
314
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
315
+ }
316
+ /**
317
+ * Get the option term to show in the list of options.
318
+ *
319
+ * @param {Option} option
320
+ * @returns {string}
321
+ */
322
+ optionTerm(option) {
323
+ return option.flags;
324
+ }
325
+ /**
326
+ * Get the argument term to show in the list of arguments.
327
+ *
328
+ * @param {Argument} argument
329
+ * @returns {string}
330
+ */
331
+ argumentTerm(argument) {
332
+ return argument.name();
333
+ }
334
+ /**
335
+ * Get the longest command term length.
336
+ *
337
+ * @param {Command} cmd
338
+ * @param {Help} helper
339
+ * @returns {number}
340
+ */
341
+ longestSubcommandTermLength(cmd, helper) {
342
+ return helper.visibleCommands(cmd).reduce((max, command) => {
343
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
344
+ }, 0);
345
+ }
346
+ /**
347
+ * Get the longest option term length.
348
+ *
349
+ * @param {Command} cmd
350
+ * @param {Help} helper
351
+ * @returns {number}
352
+ */
353
+ longestOptionTermLength(cmd, helper) {
354
+ return helper.visibleOptions(cmd).reduce((max, option) => {
355
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
356
+ }, 0);
357
+ }
358
+ /**
359
+ * Get the longest global option term length.
360
+ *
361
+ * @param {Command} cmd
362
+ * @param {Help} helper
363
+ * @returns {number}
364
+ */
365
+ longestGlobalOptionTermLength(cmd, helper) {
366
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
367
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
368
+ }, 0);
369
+ }
370
+ /**
371
+ * Get the longest argument term length.
372
+ *
373
+ * @param {Command} cmd
374
+ * @param {Help} helper
375
+ * @returns {number}
376
+ */
377
+ longestArgumentTermLength(cmd, helper) {
378
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
379
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
380
+ }, 0);
381
+ }
382
+ /**
383
+ * Get the command usage to be displayed at the top of the built-in help.
384
+ *
385
+ * @param {Command} cmd
386
+ * @returns {string}
387
+ */
388
+ commandUsage(cmd) {
389
+ let cmdName = cmd._name;
390
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
391
+ let ancestorCmdNames = "";
392
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
393
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
394
+ }
395
+ /**
396
+ * Get the description for the command.
397
+ *
398
+ * @param {Command} cmd
399
+ * @returns {string}
400
+ */
401
+ commandDescription(cmd) {
402
+ return cmd.description();
403
+ }
404
+ /**
405
+ * Get the subcommand summary to show in the list of subcommands.
406
+ * (Fallback to description for backwards compatibility.)
407
+ *
408
+ * @param {Command} cmd
409
+ * @returns {string}
410
+ */
411
+ subcommandDescription(cmd) {
412
+ return cmd.summary() || cmd.description();
413
+ }
414
+ /**
415
+ * Get the option description to show in the list of options.
416
+ *
417
+ * @param {Option} option
418
+ * @return {string}
419
+ */
420
+ optionDescription(option) {
421
+ const extraInfo = [];
422
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
423
+ if (option.defaultValue !== void 0) {
424
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
425
+ }
426
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
427
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
428
+ if (extraInfo.length > 0) {
429
+ const extraDescription = `(${extraInfo.join(", ")})`;
430
+ if (option.description) return `${option.description} ${extraDescription}`;
431
+ return extraDescription;
432
+ }
433
+ return option.description;
434
+ }
435
+ /**
436
+ * Get the argument description to show in the list of arguments.
437
+ *
438
+ * @param {Argument} argument
439
+ * @return {string}
440
+ */
441
+ argumentDescription(argument) {
442
+ const extraInfo = [];
443
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
444
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
445
+ if (extraInfo.length > 0) {
446
+ const extraDescription = `(${extraInfo.join(", ")})`;
447
+ if (argument.description) return `${argument.description} ${extraDescription}`;
448
+ return extraDescription;
449
+ }
450
+ return argument.description;
451
+ }
452
+ /**
453
+ * Format a list of items, given a heading and an array of formatted items.
454
+ *
455
+ * @param {string} heading
456
+ * @param {string[]} items
457
+ * @param {Help} helper
458
+ * @returns string[]
459
+ */
460
+ formatItemList(heading, items, helper) {
461
+ if (items.length === 0) return [];
462
+ return [
463
+ helper.styleTitle(heading),
464
+ ...items,
465
+ ""
466
+ ];
467
+ }
468
+ /**
469
+ * Group items by their help group heading.
470
+ *
471
+ * @param {Command[] | Option[]} unsortedItems
472
+ * @param {Command[] | Option[]} visibleItems
473
+ * @param {Function} getGroup
474
+ * @returns {Map<string, Command[] | Option[]>}
475
+ */
476
+ groupItems(unsortedItems, visibleItems, getGroup) {
477
+ const result = /* @__PURE__ */ new Map();
478
+ unsortedItems.forEach((item) => {
479
+ const group = getGroup(item);
480
+ if (!result.has(group)) result.set(group, []);
481
+ });
482
+ visibleItems.forEach((item) => {
483
+ const group = getGroup(item);
484
+ if (!result.has(group)) result.set(group, []);
485
+ result.get(group).push(item);
486
+ });
487
+ return result;
488
+ }
489
+ /**
490
+ * Generate the built-in help text.
491
+ *
492
+ * @param {Command} cmd
493
+ * @param {Help} helper
494
+ * @returns {string}
495
+ */
496
+ formatHelp(cmd, helper) {
497
+ const termWidth = helper.padWidth(cmd, helper);
498
+ const helpWidth = helper.helpWidth ?? 80;
499
+ function callFormatItem(term, description) {
500
+ return helper.formatItem(term, termWidth, description, helper);
501
+ }
502
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
503
+ const commandDescription = helper.commandDescription(cmd);
504
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
505
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
506
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
507
+ });
508
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
509
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
510
+ const optionList = options.map((option) => {
511
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
512
+ });
513
+ output = output.concat(this.formatItemList(group, optionList, helper));
514
+ });
515
+ if (helper.showGlobalOptions) {
516
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
517
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
518
+ });
519
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
520
+ }
521
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
522
+ const commandList = commands.map((sub) => {
523
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
524
+ });
525
+ output = output.concat(this.formatItemList(group, commandList, helper));
526
+ });
527
+ return output.join("\n");
528
+ }
529
+ /**
530
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
531
+ *
532
+ * @param {string} str
533
+ * @returns {number}
534
+ */
535
+ displayWidth(str) {
536
+ return stripColor(str).length;
537
+ }
538
+ /**
539
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
540
+ *
541
+ * @param {string} str
542
+ * @returns {string}
543
+ */
544
+ styleTitle(str) {
545
+ return str;
546
+ }
547
+ styleUsage(str) {
548
+ return str.split(" ").map((word) => {
549
+ if (word === "[options]") return this.styleOptionText(word);
550
+ if (word === "[command]") return this.styleSubcommandText(word);
551
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
552
+ return this.styleCommandText(word);
553
+ }).join(" ");
554
+ }
555
+ styleCommandDescription(str) {
556
+ return this.styleDescriptionText(str);
557
+ }
558
+ styleOptionDescription(str) {
559
+ return this.styleDescriptionText(str);
560
+ }
561
+ styleSubcommandDescription(str) {
562
+ return this.styleDescriptionText(str);
563
+ }
564
+ styleArgumentDescription(str) {
565
+ return this.styleDescriptionText(str);
566
+ }
567
+ styleDescriptionText(str) {
568
+ return str;
569
+ }
570
+ styleOptionTerm(str) {
571
+ return this.styleOptionText(str);
572
+ }
573
+ styleSubcommandTerm(str) {
574
+ return str.split(" ").map((word) => {
575
+ if (word === "[options]") return this.styleOptionText(word);
576
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
577
+ return this.styleSubcommandText(word);
578
+ }).join(" ");
579
+ }
580
+ styleArgumentTerm(str) {
581
+ return this.styleArgumentText(str);
582
+ }
583
+ styleOptionText(str) {
584
+ return str;
585
+ }
586
+ styleArgumentText(str) {
587
+ return str;
588
+ }
589
+ styleSubcommandText(str) {
590
+ return str;
591
+ }
592
+ styleCommandText(str) {
593
+ return str;
594
+ }
595
+ /**
596
+ * Calculate the pad width from the maximum term length.
597
+ *
598
+ * @param {Command} cmd
599
+ * @param {Help} helper
600
+ * @returns {number}
601
+ */
602
+ padWidth(cmd, helper) {
603
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
604
+ }
605
+ /**
606
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
607
+ *
608
+ * @param {string} str
609
+ * @returns {boolean}
610
+ */
611
+ preformatted(str) {
612
+ return /\n[^\S\r\n]/.test(str);
613
+ }
614
+ /**
615
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
616
+ *
617
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
618
+ * TTT DDD DDDD
619
+ * DD DDD
620
+ *
621
+ * @param {string} term
622
+ * @param {number} termWidth
623
+ * @param {string} description
624
+ * @param {Help} helper
625
+ * @returns {string}
626
+ */
627
+ formatItem(term, termWidth, description, helper) {
628
+ const itemIndent = 2;
629
+ const itemIndentStr = " ".repeat(itemIndent);
630
+ if (!description) return itemIndentStr + term;
631
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
632
+ const spacerWidth = 2;
633
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
634
+ let formattedDescription;
635
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
636
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
637
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
638
+ }
639
+ /**
640
+ * Wrap a string at whitespace, preserving existing line breaks.
641
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
642
+ *
643
+ * @param {string} str
644
+ * @param {number} width
645
+ * @returns {string}
646
+ */
647
+ boxWrap(str, width) {
648
+ if (width < this.minWidthToWrap) return str;
649
+ const rawLines = str.split(/\r\n|\n/);
650
+ const chunkPattern = /[\s]*[^\s]+/g;
651
+ const wrappedLines = [];
652
+ rawLines.forEach((line) => {
653
+ const chunks = line.match(chunkPattern);
654
+ if (chunks === null) {
655
+ wrappedLines.push("");
656
+ return;
657
+ }
658
+ let sumChunks = [chunks.shift()];
659
+ let sumWidth = this.displayWidth(sumChunks[0]);
660
+ chunks.forEach((chunk) => {
661
+ const visibleWidth = this.displayWidth(chunk);
662
+ if (sumWidth + visibleWidth <= width) {
663
+ sumChunks.push(chunk);
664
+ sumWidth += visibleWidth;
665
+ return;
666
+ }
667
+ wrappedLines.push(sumChunks.join(""));
668
+ const nextChunk = chunk.trimStart();
669
+ sumChunks = [nextChunk];
670
+ sumWidth = this.displayWidth(nextChunk);
671
+ });
672
+ wrappedLines.push(sumChunks.join(""));
673
+ });
674
+ return wrappedLines.join("\n");
675
+ }
676
+ };
677
+ /**
678
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
679
+ *
680
+ * @param {string} str
681
+ * @returns {string}
682
+ * @package
683
+ */
684
+ function stripColor(str) {
685
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
686
+ }
687
+ exports.Help = Help;
688
+ exports.stripColor = stripColor;
689
+ }));
690
+
691
+ //#endregion
692
+ //#region node_modules/commander/lib/option.js
693
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
694
+ const { InvalidArgumentError } = require_error();
695
+ var Option = class {
696
+ /**
697
+ * Initialize a new `Option` with the given `flags` and `description`.
698
+ *
699
+ * @param {string} flags
700
+ * @param {string} [description]
701
+ */
702
+ constructor(flags, description) {
703
+ this.flags = flags;
704
+ this.description = description || "";
705
+ this.required = flags.includes("<");
706
+ this.optional = flags.includes("[");
707
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
708
+ this.mandatory = false;
709
+ const optionFlags = splitOptionFlags(flags);
710
+ this.short = optionFlags.shortFlag;
711
+ this.long = optionFlags.longFlag;
712
+ this.negate = false;
713
+ if (this.long) this.negate = this.long.startsWith("--no-");
714
+ this.defaultValue = void 0;
715
+ this.defaultValueDescription = void 0;
716
+ this.presetArg = void 0;
717
+ this.envVar = void 0;
718
+ this.parseArg = void 0;
719
+ this.hidden = false;
720
+ this.argChoices = void 0;
721
+ this.conflictsWith = [];
722
+ this.implied = void 0;
723
+ this.helpGroupHeading = void 0;
724
+ }
725
+ /**
726
+ * Set the default value, and optionally supply the description to be displayed in the help.
727
+ *
728
+ * @param {*} value
729
+ * @param {string} [description]
730
+ * @return {Option}
731
+ */
732
+ default(value, description) {
733
+ this.defaultValue = value;
734
+ this.defaultValueDescription = description;
735
+ return this;
736
+ }
737
+ /**
738
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
739
+ * The custom processing (parseArg) is called.
740
+ *
741
+ * @example
742
+ * new Option('--color').default('GREYSCALE').preset('RGB');
743
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
744
+ *
745
+ * @param {*} arg
746
+ * @return {Option}
747
+ */
748
+ preset(arg) {
749
+ this.presetArg = arg;
750
+ return this;
751
+ }
752
+ /**
753
+ * Add option name(s) that conflict with this option.
754
+ * An error will be displayed if conflicting options are found during parsing.
755
+ *
756
+ * @example
757
+ * new Option('--rgb').conflicts('cmyk');
758
+ * new Option('--js').conflicts(['ts', 'jsx']);
759
+ *
760
+ * @param {(string | string[])} names
761
+ * @return {Option}
762
+ */
763
+ conflicts(names) {
764
+ this.conflictsWith = this.conflictsWith.concat(names);
765
+ return this;
766
+ }
767
+ /**
768
+ * Specify implied option values for when this option is set and the implied options are not.
769
+ *
770
+ * The custom processing (parseArg) is not called on the implied values.
771
+ *
772
+ * @example
773
+ * program
774
+ * .addOption(new Option('--log', 'write logging information to file'))
775
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
776
+ *
777
+ * @param {object} impliedOptionValues
778
+ * @return {Option}
779
+ */
780
+ implies(impliedOptionValues) {
781
+ let newImplied = impliedOptionValues;
782
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
783
+ this.implied = Object.assign(this.implied || {}, newImplied);
784
+ return this;
785
+ }
786
+ /**
787
+ * Set environment variable to check for option value.
788
+ *
789
+ * An environment variable is only used if when processed the current option value is
790
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
791
+ *
792
+ * @param {string} name
793
+ * @return {Option}
794
+ */
795
+ env(name) {
796
+ this.envVar = name;
797
+ return this;
798
+ }
799
+ /**
800
+ * Set the custom handler for processing CLI option arguments into option values.
801
+ *
802
+ * @param {Function} [fn]
803
+ * @return {Option}
804
+ */
805
+ argParser(fn) {
806
+ this.parseArg = fn;
807
+ return this;
808
+ }
809
+ /**
810
+ * Whether the option is mandatory and must have a value after parsing.
811
+ *
812
+ * @param {boolean} [mandatory=true]
813
+ * @return {Option}
814
+ */
815
+ makeOptionMandatory(mandatory = true) {
816
+ this.mandatory = !!mandatory;
817
+ return this;
818
+ }
819
+ /**
820
+ * Hide option in help.
821
+ *
822
+ * @param {boolean} [hide=true]
823
+ * @return {Option}
824
+ */
825
+ hideHelp(hide = true) {
826
+ this.hidden = !!hide;
827
+ return this;
828
+ }
829
+ /**
830
+ * @package
831
+ */
832
+ _collectValue(value, previous) {
833
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
834
+ previous.push(value);
835
+ return previous;
836
+ }
837
+ /**
838
+ * Only allow option value to be one of choices.
839
+ *
840
+ * @param {string[]} values
841
+ * @return {Option}
842
+ */
843
+ choices(values) {
844
+ this.argChoices = values.slice();
845
+ this.parseArg = (arg, previous) => {
846
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
847
+ if (this.variadic) return this._collectValue(arg, previous);
848
+ return arg;
849
+ };
850
+ return this;
851
+ }
852
+ /**
853
+ * Return option name.
854
+ *
855
+ * @return {string}
856
+ */
857
+ name() {
858
+ if (this.long) return this.long.replace(/^--/, "");
859
+ return this.short.replace(/^-/, "");
860
+ }
861
+ /**
862
+ * Return option name, in a camelcase format that can be used
863
+ * as an object attribute key.
864
+ *
865
+ * @return {string}
866
+ */
867
+ attributeName() {
868
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
869
+ return camelcase(this.name());
870
+ }
871
+ /**
872
+ * Set the help group heading.
873
+ *
874
+ * @param {string} heading
875
+ * @return {Option}
876
+ */
877
+ helpGroup(heading) {
878
+ this.helpGroupHeading = heading;
879
+ return this;
880
+ }
881
+ /**
882
+ * Check if `arg` matches the short or long flag.
883
+ *
884
+ * @param {string} arg
885
+ * @return {boolean}
886
+ * @package
887
+ */
888
+ is(arg) {
889
+ return this.short === arg || this.long === arg;
890
+ }
891
+ /**
892
+ * Return whether a boolean option.
893
+ *
894
+ * Options are one of boolean, negated, required argument, or optional argument.
895
+ *
896
+ * @return {boolean}
897
+ * @package
898
+ */
899
+ isBoolean() {
900
+ return !this.required && !this.optional && !this.negate;
901
+ }
902
+ };
903
+ /**
904
+ * This class is to make it easier to work with dual options, without changing the existing
905
+ * implementation. We support separate dual options for separate positive and negative options,
906
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
907
+ * use cases, but is tricky for others where we want separate behaviours despite
908
+ * the single shared option value.
909
+ */
910
+ var DualOptions = class {
911
+ /**
912
+ * @param {Option[]} options
913
+ */
914
+ constructor(options) {
915
+ this.positiveOptions = /* @__PURE__ */ new Map();
916
+ this.negativeOptions = /* @__PURE__ */ new Map();
917
+ this.dualOptions = /* @__PURE__ */ new Set();
918
+ options.forEach((option) => {
919
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
920
+ else this.positiveOptions.set(option.attributeName(), option);
921
+ });
922
+ this.negativeOptions.forEach((value, key) => {
923
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
924
+ });
925
+ }
926
+ /**
927
+ * Did the value come from the option, and not from possible matching dual option?
928
+ *
929
+ * @param {*} value
930
+ * @param {Option} option
931
+ * @returns {boolean}
932
+ */
933
+ valueFromOption(value, option) {
934
+ const optionKey = option.attributeName();
935
+ if (!this.dualOptions.has(optionKey)) return true;
936
+ const preset = this.negativeOptions.get(optionKey).presetArg;
937
+ const negativeValue = preset !== void 0 ? preset : false;
938
+ return option.negate === (negativeValue === value);
939
+ }
940
+ };
941
+ /**
942
+ * Convert string from kebab-case to camelCase.
943
+ *
944
+ * @param {string} str
945
+ * @return {string}
946
+ * @private
947
+ */
948
+ function camelcase(str) {
949
+ return str.split("-").reduce((str, word) => {
950
+ return str + word[0].toUpperCase() + word.slice(1);
951
+ });
952
+ }
953
+ /**
954
+ * Split the short and long flag out of something like '-m,--mixed <value>'
955
+ *
956
+ * @private
957
+ */
958
+ function splitOptionFlags(flags) {
959
+ let shortFlag;
960
+ let longFlag;
961
+ const shortFlagExp = /^-[^-]$/;
962
+ const longFlagExp = /^--[^-]/;
963
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
964
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
965
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
966
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
967
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
968
+ shortFlag = longFlag;
969
+ longFlag = flagParts.shift();
970
+ }
971
+ if (flagParts[0].startsWith("-")) {
972
+ const unsupportedFlag = flagParts[0];
973
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
974
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
975
+ - a short flag is a single dash and a single character
976
+ - either use a single dash and a single character (for a short flag)
977
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
978
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
979
+ - too many short flags`);
980
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
981
+ - too many long flags`);
982
+ throw new Error(`${baseError}
983
+ - unrecognised flag format`);
984
+ }
985
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
986
+ return {
987
+ shortFlag,
988
+ longFlag
989
+ };
990
+ }
991
+ exports.Option = Option;
992
+ exports.DualOptions = DualOptions;
993
+ }));
994
+
995
+ //#endregion
996
+ //#region node_modules/commander/lib/suggestSimilar.js
997
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
998
+ const maxDistance = 3;
999
+ function editDistance(a, b) {
1000
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1001
+ const d = [];
1002
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1003
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1004
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1005
+ let cost = 1;
1006
+ if (a[i - 1] === b[j - 1]) cost = 0;
1007
+ else cost = 1;
1008
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1009
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1010
+ }
1011
+ return d[a.length][b.length];
1012
+ }
1013
+ /**
1014
+ * Find close matches, restricted to same number of edits.
1015
+ *
1016
+ * @param {string} word
1017
+ * @param {string[]} candidates
1018
+ * @returns {string}
1019
+ */
1020
+ function suggestSimilar(word, candidates) {
1021
+ if (!candidates || candidates.length === 0) return "";
1022
+ candidates = Array.from(new Set(candidates));
1023
+ const searchingOptions = word.startsWith("--");
1024
+ if (searchingOptions) {
1025
+ word = word.slice(2);
1026
+ candidates = candidates.map((candidate) => candidate.slice(2));
1027
+ }
1028
+ let similar = [];
1029
+ let bestDistance = maxDistance;
1030
+ const minSimilarity = .4;
1031
+ candidates.forEach((candidate) => {
1032
+ if (candidate.length <= 1) return;
1033
+ const distance = editDistance(word, candidate);
1034
+ const length = Math.max(word.length, candidate.length);
1035
+ if ((length - distance) / length > minSimilarity) {
1036
+ if (distance < bestDistance) {
1037
+ bestDistance = distance;
1038
+ similar = [candidate];
1039
+ } else if (distance === bestDistance) similar.push(candidate);
1040
+ }
1041
+ });
1042
+ similar.sort((a, b) => a.localeCompare(b));
1043
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1044
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1045
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1046
+ return "";
1047
+ }
1048
+ exports.suggestSimilar = suggestSimilar;
1049
+ }));
1050
+
1051
+ //#endregion
1052
+ //#region node_modules/commander/lib/command.js
1053
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1054
+ const EventEmitter = __require("node:events").EventEmitter;
1055
+ const childProcess = __require("node:child_process");
1056
+ const path = __require("node:path");
1057
+ const fs = __require("node:fs");
1058
+ const process$1 = __require("node:process");
1059
+ const { Argument, humanReadableArgName } = require_argument();
1060
+ const { CommanderError } = require_error();
1061
+ const { Help, stripColor } = require_help();
1062
+ const { Option, DualOptions } = require_option();
1063
+ const { suggestSimilar } = require_suggestSimilar();
1064
+ var Command = class Command extends EventEmitter {
1065
+ /**
1066
+ * Initialize a new `Command`.
1067
+ *
1068
+ * @param {string} [name]
1069
+ */
1070
+ constructor(name) {
1071
+ super();
1072
+ /** @type {Command[]} */
1073
+ this.commands = [];
1074
+ /** @type {Option[]} */
1075
+ this.options = [];
1076
+ this.parent = null;
1077
+ this._allowUnknownOption = false;
1078
+ this._allowExcessArguments = false;
1079
+ /** @type {Argument[]} */
1080
+ this.registeredArguments = [];
1081
+ this._args = this.registeredArguments;
1082
+ /** @type {string[]} */
1083
+ this.args = [];
1084
+ this.rawArgs = [];
1085
+ this.processedArgs = [];
1086
+ this._scriptPath = null;
1087
+ this._name = name || "";
1088
+ this._optionValues = {};
1089
+ this._optionValueSources = {};
1090
+ this._storeOptionsAsProperties = false;
1091
+ this._actionHandler = null;
1092
+ this._executableHandler = false;
1093
+ this._executableFile = null;
1094
+ this._executableDir = null;
1095
+ this._defaultCommandName = null;
1096
+ this._exitCallback = null;
1097
+ this._aliases = [];
1098
+ this._combineFlagAndOptionalValue = true;
1099
+ this._description = "";
1100
+ this._summary = "";
1101
+ this._argsDescription = void 0;
1102
+ this._enablePositionalOptions = false;
1103
+ this._passThroughOptions = false;
1104
+ this._lifeCycleHooks = {};
1105
+ /** @type {(boolean | string)} */
1106
+ this._showHelpAfterError = false;
1107
+ this._showSuggestionAfterError = true;
1108
+ this._savedState = null;
1109
+ this._outputConfiguration = {
1110
+ writeOut: (str) => process$1.stdout.write(str),
1111
+ writeErr: (str) => process$1.stderr.write(str),
1112
+ outputError: (str, write) => write(str),
1113
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1114
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1115
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1116
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1117
+ stripColor: (str) => stripColor(str)
1118
+ };
1119
+ this._hidden = false;
1120
+ /** @type {(Option | null | undefined)} */
1121
+ this._helpOption = void 0;
1122
+ this._addImplicitHelpCommand = void 0;
1123
+ /** @type {Command} */
1124
+ this._helpCommand = void 0;
1125
+ this._helpConfiguration = {};
1126
+ /** @type {string | undefined} */
1127
+ this._helpGroupHeading = void 0;
1128
+ /** @type {string | undefined} */
1129
+ this._defaultCommandGroup = void 0;
1130
+ /** @type {string | undefined} */
1131
+ this._defaultOptionGroup = void 0;
1132
+ }
1133
+ /**
1134
+ * Copy settings that are useful to have in common across root command and subcommands.
1135
+ *
1136
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1137
+ *
1138
+ * @param {Command} sourceCommand
1139
+ * @return {Command} `this` command for chaining
1140
+ */
1141
+ copyInheritedSettings(sourceCommand) {
1142
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1143
+ this._helpOption = sourceCommand._helpOption;
1144
+ this._helpCommand = sourceCommand._helpCommand;
1145
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1146
+ this._exitCallback = sourceCommand._exitCallback;
1147
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1148
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1149
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1150
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1151
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1152
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1153
+ return this;
1154
+ }
1155
+ /**
1156
+ * @returns {Command[]}
1157
+ * @private
1158
+ */
1159
+ _getCommandAndAncestors() {
1160
+ const result = [];
1161
+ for (let command = this; command; command = command.parent) result.push(command);
1162
+ return result;
1163
+ }
1164
+ /**
1165
+ * Define a command.
1166
+ *
1167
+ * There are two styles of command: pay attention to where to put the description.
1168
+ *
1169
+ * @example
1170
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1171
+ * program
1172
+ * .command('clone <source> [destination]')
1173
+ * .description('clone a repository into a newly created directory')
1174
+ * .action((source, destination) => {
1175
+ * console.log('clone command called');
1176
+ * });
1177
+ *
1178
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1179
+ * program
1180
+ * .command('start <service>', 'start named service')
1181
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1182
+ *
1183
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1184
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1185
+ * @param {object} [execOpts] - configuration options (for executable)
1186
+ * @return {Command} returns new command for action handler, or `this` for executable command
1187
+ */
1188
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1189
+ let desc = actionOptsOrExecDesc;
1190
+ let opts = execOpts;
1191
+ if (typeof desc === "object" && desc !== null) {
1192
+ opts = desc;
1193
+ desc = null;
1194
+ }
1195
+ opts = opts || {};
1196
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1197
+ const cmd = this.createCommand(name);
1198
+ if (desc) {
1199
+ cmd.description(desc);
1200
+ cmd._executableHandler = true;
1201
+ }
1202
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1203
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1204
+ cmd._executableFile = opts.executableFile || null;
1205
+ if (args) cmd.arguments(args);
1206
+ this._registerCommand(cmd);
1207
+ cmd.parent = this;
1208
+ cmd.copyInheritedSettings(this);
1209
+ if (desc) return this;
1210
+ return cmd;
1211
+ }
1212
+ /**
1213
+ * Factory routine to create a new unattached command.
1214
+ *
1215
+ * See .command() for creating an attached subcommand, which uses this routine to
1216
+ * create the command. You can override createCommand to customise subcommands.
1217
+ *
1218
+ * @param {string} [name]
1219
+ * @return {Command} new command
1220
+ */
1221
+ createCommand(name) {
1222
+ return new Command(name);
1223
+ }
1224
+ /**
1225
+ * You can customise the help with a subclass of Help by overriding createHelp,
1226
+ * or by overriding Help properties using configureHelp().
1227
+ *
1228
+ * @return {Help}
1229
+ */
1230
+ createHelp() {
1231
+ return Object.assign(new Help(), this.configureHelp());
1232
+ }
1233
+ /**
1234
+ * You can customise the help by overriding Help properties using configureHelp(),
1235
+ * or with a subclass of Help by overriding createHelp().
1236
+ *
1237
+ * @param {object} [configuration] - configuration options
1238
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1239
+ */
1240
+ configureHelp(configuration) {
1241
+ if (configuration === void 0) return this._helpConfiguration;
1242
+ this._helpConfiguration = configuration;
1243
+ return this;
1244
+ }
1245
+ /**
1246
+ * The default output goes to stdout and stderr. You can customise this for special
1247
+ * applications. You can also customise the display of errors by overriding outputError.
1248
+ *
1249
+ * The configuration properties are all functions:
1250
+ *
1251
+ * // change how output being written, defaults to stdout and stderr
1252
+ * writeOut(str)
1253
+ * writeErr(str)
1254
+ * // change how output being written for errors, defaults to writeErr
1255
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1256
+ * // specify width for wrapping help
1257
+ * getOutHelpWidth()
1258
+ * getErrHelpWidth()
1259
+ * // color support, currently only used with Help
1260
+ * getOutHasColors()
1261
+ * getErrHasColors()
1262
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1263
+ *
1264
+ * @param {object} [configuration] - configuration options
1265
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1266
+ */
1267
+ configureOutput(configuration) {
1268
+ if (configuration === void 0) return this._outputConfiguration;
1269
+ this._outputConfiguration = {
1270
+ ...this._outputConfiguration,
1271
+ ...configuration
1272
+ };
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Display the help or a custom message after an error occurs.
1277
+ *
1278
+ * @param {(boolean|string)} [displayHelp]
1279
+ * @return {Command} `this` command for chaining
1280
+ */
1281
+ showHelpAfterError(displayHelp = true) {
1282
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1283
+ this._showHelpAfterError = displayHelp;
1284
+ return this;
1285
+ }
1286
+ /**
1287
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1288
+ *
1289
+ * @param {boolean} [displaySuggestion]
1290
+ * @return {Command} `this` command for chaining
1291
+ */
1292
+ showSuggestionAfterError(displaySuggestion = true) {
1293
+ this._showSuggestionAfterError = !!displaySuggestion;
1294
+ return this;
1295
+ }
1296
+ /**
1297
+ * Add a prepared subcommand.
1298
+ *
1299
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1300
+ *
1301
+ * @param {Command} cmd - new subcommand
1302
+ * @param {object} [opts] - configuration options
1303
+ * @return {Command} `this` command for chaining
1304
+ */
1305
+ addCommand(cmd, opts) {
1306
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1307
+ - specify the name in Command constructor or using .name()`);
1308
+ opts = opts || {};
1309
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1310
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1311
+ this._registerCommand(cmd);
1312
+ cmd.parent = this;
1313
+ cmd._checkForBrokenPassThrough();
1314
+ return this;
1315
+ }
1316
+ /**
1317
+ * Factory routine to create a new unattached argument.
1318
+ *
1319
+ * See .argument() for creating an attached argument, which uses this routine to
1320
+ * create the argument. You can override createArgument to return a custom argument.
1321
+ *
1322
+ * @param {string} name
1323
+ * @param {string} [description]
1324
+ * @return {Argument} new argument
1325
+ */
1326
+ createArgument(name, description) {
1327
+ return new Argument(name, description);
1328
+ }
1329
+ /**
1330
+ * Define argument syntax for command.
1331
+ *
1332
+ * The default is that the argument is required, and you can explicitly
1333
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1334
+ *
1335
+ * @example
1336
+ * program.argument('<input-file>');
1337
+ * program.argument('[output-file]');
1338
+ *
1339
+ * @param {string} name
1340
+ * @param {string} [description]
1341
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1342
+ * @param {*} [defaultValue]
1343
+ * @return {Command} `this` command for chaining
1344
+ */
1345
+ argument(name, description, parseArg, defaultValue) {
1346
+ const argument = this.createArgument(name, description);
1347
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1348
+ else argument.default(parseArg);
1349
+ this.addArgument(argument);
1350
+ return this;
1351
+ }
1352
+ /**
1353
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1354
+ *
1355
+ * See also .argument().
1356
+ *
1357
+ * @example
1358
+ * program.arguments('<cmd> [env]');
1359
+ *
1360
+ * @param {string} names
1361
+ * @return {Command} `this` command for chaining
1362
+ */
1363
+ arguments(names) {
1364
+ names.trim().split(/ +/).forEach((detail) => {
1365
+ this.argument(detail);
1366
+ });
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Define argument syntax for command, adding a prepared argument.
1371
+ *
1372
+ * @param {Argument} argument
1373
+ * @return {Command} `this` command for chaining
1374
+ */
1375
+ addArgument(argument) {
1376
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1377
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1378
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1379
+ this.registeredArguments.push(argument);
1380
+ return this;
1381
+ }
1382
+ /**
1383
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1384
+ *
1385
+ * @example
1386
+ * program.helpCommand('help [cmd]');
1387
+ * program.helpCommand('help [cmd]', 'show help');
1388
+ * program.helpCommand(false); // suppress default help command
1389
+ * program.helpCommand(true); // add help command even if no subcommands
1390
+ *
1391
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1392
+ * @param {string} [description] - custom description
1393
+ * @return {Command} `this` command for chaining
1394
+ */
1395
+ helpCommand(enableOrNameAndArgs, description) {
1396
+ if (typeof enableOrNameAndArgs === "boolean") {
1397
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1398
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1399
+ return this;
1400
+ }
1401
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1402
+ const helpDescription = description ?? "display help for command";
1403
+ const helpCommand = this.createCommand(helpName);
1404
+ helpCommand.helpOption(false);
1405
+ if (helpArgs) helpCommand.arguments(helpArgs);
1406
+ if (helpDescription) helpCommand.description(helpDescription);
1407
+ this._addImplicitHelpCommand = true;
1408
+ this._helpCommand = helpCommand;
1409
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1410
+ return this;
1411
+ }
1412
+ /**
1413
+ * Add prepared custom help command.
1414
+ *
1415
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1416
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1417
+ * @return {Command} `this` command for chaining
1418
+ */
1419
+ addHelpCommand(helpCommand, deprecatedDescription) {
1420
+ if (typeof helpCommand !== "object") {
1421
+ this.helpCommand(helpCommand, deprecatedDescription);
1422
+ return this;
1423
+ }
1424
+ this._addImplicitHelpCommand = true;
1425
+ this._helpCommand = helpCommand;
1426
+ this._initCommandGroup(helpCommand);
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Lazy create help command.
1431
+ *
1432
+ * @return {(Command|null)}
1433
+ * @package
1434
+ */
1435
+ _getHelpCommand() {
1436
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1437
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1438
+ return this._helpCommand;
1439
+ }
1440
+ return null;
1441
+ }
1442
+ /**
1443
+ * Add hook for life cycle event.
1444
+ *
1445
+ * @param {string} event
1446
+ * @param {Function} listener
1447
+ * @return {Command} `this` command for chaining
1448
+ */
1449
+ hook(event, listener) {
1450
+ const allowedValues = [
1451
+ "preSubcommand",
1452
+ "preAction",
1453
+ "postAction"
1454
+ ];
1455
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1456
+ Expecting one of '${allowedValues.join("', '")}'`);
1457
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1458
+ else this._lifeCycleHooks[event] = [listener];
1459
+ return this;
1460
+ }
1461
+ /**
1462
+ * Register callback to use as replacement for calling process.exit.
1463
+ *
1464
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1465
+ * @return {Command} `this` command for chaining
1466
+ */
1467
+ exitOverride(fn) {
1468
+ if (fn) this._exitCallback = fn;
1469
+ else this._exitCallback = (err) => {
1470
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1471
+ };
1472
+ return this;
1473
+ }
1474
+ /**
1475
+ * Call process.exit, and _exitCallback if defined.
1476
+ *
1477
+ * @param {number} exitCode exit code for using with process.exit
1478
+ * @param {string} code an id string representing the error
1479
+ * @param {string} message human-readable description of the error
1480
+ * @return never
1481
+ * @private
1482
+ */
1483
+ _exit(exitCode, code, message) {
1484
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1485
+ process$1.exit(exitCode);
1486
+ }
1487
+ /**
1488
+ * Register callback `fn` for the command.
1489
+ *
1490
+ * @example
1491
+ * program
1492
+ * .command('serve')
1493
+ * .description('start service')
1494
+ * .action(function() {
1495
+ * // do work here
1496
+ * });
1497
+ *
1498
+ * @param {Function} fn
1499
+ * @return {Command} `this` command for chaining
1500
+ */
1501
+ action(fn) {
1502
+ const listener = (args) => {
1503
+ const expectedArgsCount = this.registeredArguments.length;
1504
+ const actionArgs = args.slice(0, expectedArgsCount);
1505
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1506
+ else actionArgs[expectedArgsCount] = this.opts();
1507
+ actionArgs.push(this);
1508
+ return fn.apply(this, actionArgs);
1509
+ };
1510
+ this._actionHandler = listener;
1511
+ return this;
1512
+ }
1513
+ /**
1514
+ * Factory routine to create a new unattached option.
1515
+ *
1516
+ * See .option() for creating an attached option, which uses this routine to
1517
+ * create the option. You can override createOption to return a custom option.
1518
+ *
1519
+ * @param {string} flags
1520
+ * @param {string} [description]
1521
+ * @return {Option} new option
1522
+ */
1523
+ createOption(flags, description) {
1524
+ return new Option(flags, description);
1525
+ }
1526
+ /**
1527
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1528
+ *
1529
+ * @param {(Option | Argument)} target
1530
+ * @param {string} value
1531
+ * @param {*} previous
1532
+ * @param {string} invalidArgumentMessage
1533
+ * @private
1534
+ */
1535
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1536
+ try {
1537
+ return target.parseArg(value, previous);
1538
+ } catch (err) {
1539
+ if (err.code === "commander.invalidArgument") {
1540
+ const message = `${invalidArgumentMessage} ${err.message}`;
1541
+ this.error(message, {
1542
+ exitCode: err.exitCode,
1543
+ code: err.code
1544
+ });
1545
+ }
1546
+ throw err;
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Check for option flag conflicts.
1551
+ * Register option if no conflicts found, or throw on conflict.
1552
+ *
1553
+ * @param {Option} option
1554
+ * @private
1555
+ */
1556
+ _registerOption(option) {
1557
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1558
+ if (matchingOption) {
1559
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1560
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1561
+ - already used by option '${matchingOption.flags}'`);
1562
+ }
1563
+ this._initOptionGroup(option);
1564
+ this.options.push(option);
1565
+ }
1566
+ /**
1567
+ * Check for command name and alias conflicts with existing commands.
1568
+ * Register command if no conflicts found, or throw on conflict.
1569
+ *
1570
+ * @param {Command} command
1571
+ * @private
1572
+ */
1573
+ _registerCommand(command) {
1574
+ const knownBy = (cmd) => {
1575
+ return [cmd.name()].concat(cmd.aliases());
1576
+ };
1577
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1578
+ if (alreadyUsed) {
1579
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1580
+ const newCmd = knownBy(command).join("|");
1581
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1582
+ }
1583
+ this._initCommandGroup(command);
1584
+ this.commands.push(command);
1585
+ }
1586
+ /**
1587
+ * Add an option.
1588
+ *
1589
+ * @param {Option} option
1590
+ * @return {Command} `this` command for chaining
1591
+ */
1592
+ addOption(option) {
1593
+ this._registerOption(option);
1594
+ const oname = option.name();
1595
+ const name = option.attributeName();
1596
+ if (option.negate) {
1597
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1598
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1599
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1600
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1601
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1602
+ const oldValue = this.getOptionValue(name);
1603
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1604
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1605
+ if (val == null) if (option.negate) val = false;
1606
+ else if (option.isBoolean() || option.optional) val = true;
1607
+ else val = "";
1608
+ this.setOptionValueWithSource(name, val, valueSource);
1609
+ };
1610
+ this.on("option:" + oname, (val) => {
1611
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1612
+ });
1613
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1614
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1615
+ });
1616
+ return this;
1617
+ }
1618
+ /**
1619
+ * Internal implementation shared by .option() and .requiredOption()
1620
+ *
1621
+ * @return {Command} `this` command for chaining
1622
+ * @private
1623
+ */
1624
+ _optionEx(config, flags, description, fn, defaultValue) {
1625
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1626
+ const option = this.createOption(flags, description);
1627
+ option.makeOptionMandatory(!!config.mandatory);
1628
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1629
+ else if (fn instanceof RegExp) {
1630
+ const regex = fn;
1631
+ fn = (val, def) => {
1632
+ const m = regex.exec(val);
1633
+ return m ? m[0] : def;
1634
+ };
1635
+ option.default(defaultValue).argParser(fn);
1636
+ } else option.default(fn);
1637
+ return this.addOption(option);
1638
+ }
1639
+ /**
1640
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1641
+ *
1642
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1643
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1644
+ *
1645
+ * See the README for more details, and see also addOption() and requiredOption().
1646
+ *
1647
+ * @example
1648
+ * program
1649
+ * .option('-p, --pepper', 'add pepper')
1650
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1651
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1652
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1653
+ *
1654
+ * @param {string} flags
1655
+ * @param {string} [description]
1656
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1657
+ * @param {*} [defaultValue]
1658
+ * @return {Command} `this` command for chaining
1659
+ */
1660
+ option(flags, description, parseArg, defaultValue) {
1661
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1662
+ }
1663
+ /**
1664
+ * Add a required option which must have a value after parsing. This usually means
1665
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1666
+ *
1667
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1668
+ *
1669
+ * @param {string} flags
1670
+ * @param {string} [description]
1671
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1672
+ * @param {*} [defaultValue]
1673
+ * @return {Command} `this` command for chaining
1674
+ */
1675
+ requiredOption(flags, description, parseArg, defaultValue) {
1676
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1677
+ }
1678
+ /**
1679
+ * Alter parsing of short flags with optional values.
1680
+ *
1681
+ * @example
1682
+ * // for `.option('-f,--flag [value]'):
1683
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1684
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1685
+ *
1686
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1687
+ * @return {Command} `this` command for chaining
1688
+ */
1689
+ combineFlagAndOptionalValue(combine = true) {
1690
+ this._combineFlagAndOptionalValue = !!combine;
1691
+ return this;
1692
+ }
1693
+ /**
1694
+ * Allow unknown options on the command line.
1695
+ *
1696
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1697
+ * @return {Command} `this` command for chaining
1698
+ */
1699
+ allowUnknownOption(allowUnknown = true) {
1700
+ this._allowUnknownOption = !!allowUnknown;
1701
+ return this;
1702
+ }
1703
+ /**
1704
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1705
+ *
1706
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1707
+ * @return {Command} `this` command for chaining
1708
+ */
1709
+ allowExcessArguments(allowExcess = true) {
1710
+ this._allowExcessArguments = !!allowExcess;
1711
+ return this;
1712
+ }
1713
+ /**
1714
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1715
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1716
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1717
+ *
1718
+ * @param {boolean} [positional]
1719
+ * @return {Command} `this` command for chaining
1720
+ */
1721
+ enablePositionalOptions(positional = true) {
1722
+ this._enablePositionalOptions = !!positional;
1723
+ return this;
1724
+ }
1725
+ /**
1726
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1727
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1728
+ * positional options to have been enabled on the program (parent commands).
1729
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1730
+ *
1731
+ * @param {boolean} [passThrough] for unknown options.
1732
+ * @return {Command} `this` command for chaining
1733
+ */
1734
+ passThroughOptions(passThrough = true) {
1735
+ this._passThroughOptions = !!passThrough;
1736
+ this._checkForBrokenPassThrough();
1737
+ return this;
1738
+ }
1739
+ /**
1740
+ * @private
1741
+ */
1742
+ _checkForBrokenPassThrough() {
1743
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1744
+ }
1745
+ /**
1746
+ * Whether to store option values as properties on command object,
1747
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1748
+ *
1749
+ * @param {boolean} [storeAsProperties=true]
1750
+ * @return {Command} `this` command for chaining
1751
+ */
1752
+ storeOptionsAsProperties(storeAsProperties = true) {
1753
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1754
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1755
+ this._storeOptionsAsProperties = !!storeAsProperties;
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Retrieve option value.
1760
+ *
1761
+ * @param {string} key
1762
+ * @return {object} value
1763
+ */
1764
+ getOptionValue(key) {
1765
+ if (this._storeOptionsAsProperties) return this[key];
1766
+ return this._optionValues[key];
1767
+ }
1768
+ /**
1769
+ * Store option value.
1770
+ *
1771
+ * @param {string} key
1772
+ * @param {object} value
1773
+ * @return {Command} `this` command for chaining
1774
+ */
1775
+ setOptionValue(key, value) {
1776
+ return this.setOptionValueWithSource(key, value, void 0);
1777
+ }
1778
+ /**
1779
+ * Store option value and where the value came from.
1780
+ *
1781
+ * @param {string} key
1782
+ * @param {object} value
1783
+ * @param {string} source - expected values are default/config/env/cli/implied
1784
+ * @return {Command} `this` command for chaining
1785
+ */
1786
+ setOptionValueWithSource(key, value, source) {
1787
+ if (this._storeOptionsAsProperties) this[key] = value;
1788
+ else this._optionValues[key] = value;
1789
+ this._optionValueSources[key] = source;
1790
+ return this;
1791
+ }
1792
+ /**
1793
+ * Get source of option value.
1794
+ * Expected values are default | config | env | cli | implied
1795
+ *
1796
+ * @param {string} key
1797
+ * @return {string}
1798
+ */
1799
+ getOptionValueSource(key) {
1800
+ return this._optionValueSources[key];
1801
+ }
1802
+ /**
1803
+ * Get source of option value. See also .optsWithGlobals().
1804
+ * Expected values are default | config | env | cli | implied
1805
+ *
1806
+ * @param {string} key
1807
+ * @return {string}
1808
+ */
1809
+ getOptionValueSourceWithGlobals(key) {
1810
+ let source;
1811
+ this._getCommandAndAncestors().forEach((cmd) => {
1812
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1813
+ });
1814
+ return source;
1815
+ }
1816
+ /**
1817
+ * Get user arguments from implied or explicit arguments.
1818
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1819
+ *
1820
+ * @private
1821
+ */
1822
+ _prepareUserArgs(argv, parseOptions) {
1823
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1824
+ parseOptions = parseOptions || {};
1825
+ if (argv === void 0 && parseOptions.from === void 0) {
1826
+ if (process$1.versions?.electron) parseOptions.from = "electron";
1827
+ const execArgv = process$1.execArgv ?? [];
1828
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1829
+ }
1830
+ if (argv === void 0) argv = process$1.argv;
1831
+ this.rawArgs = argv.slice();
1832
+ let userArgs;
1833
+ switch (parseOptions.from) {
1834
+ case void 0:
1835
+ case "node":
1836
+ this._scriptPath = argv[1];
1837
+ userArgs = argv.slice(2);
1838
+ break;
1839
+ case "electron":
1840
+ if (process$1.defaultApp) {
1841
+ this._scriptPath = argv[1];
1842
+ userArgs = argv.slice(2);
1843
+ } else userArgs = argv.slice(1);
1844
+ break;
1845
+ case "user":
1846
+ userArgs = argv.slice(0);
1847
+ break;
1848
+ case "eval":
1849
+ userArgs = argv.slice(1);
1850
+ break;
1851
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1852
+ }
1853
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1854
+ this._name = this._name || "program";
1855
+ return userArgs;
1856
+ }
1857
+ /**
1858
+ * Parse `argv`, setting options and invoking commands when defined.
1859
+ *
1860
+ * Use parseAsync instead of parse if any of your action handlers are async.
1861
+ *
1862
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1863
+ *
1864
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1865
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1866
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1867
+ * - `'user'`: just user arguments
1868
+ *
1869
+ * @example
1870
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1871
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1872
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1873
+ *
1874
+ * @param {string[]} [argv] - optional, defaults to process.argv
1875
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1876
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1877
+ * @return {Command} `this` command for chaining
1878
+ */
1879
+ parse(argv, parseOptions) {
1880
+ this._prepareForParse();
1881
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1882
+ this._parseCommand([], userArgs);
1883
+ return this;
1884
+ }
1885
+ /**
1886
+ * Parse `argv`, setting options and invoking commands when defined.
1887
+ *
1888
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1889
+ *
1890
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1891
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1892
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1893
+ * - `'user'`: just user arguments
1894
+ *
1895
+ * @example
1896
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1897
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1898
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1899
+ *
1900
+ * @param {string[]} [argv]
1901
+ * @param {object} [parseOptions]
1902
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1903
+ * @return {Promise}
1904
+ */
1905
+ async parseAsync(argv, parseOptions) {
1906
+ this._prepareForParse();
1907
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1908
+ await this._parseCommand([], userArgs);
1909
+ return this;
1910
+ }
1911
+ _prepareForParse() {
1912
+ if (this._savedState === null) this.saveStateBeforeParse();
1913
+ else this.restoreStateBeforeParse();
1914
+ }
1915
+ /**
1916
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1917
+ * Not usually called directly, but available for subclasses to save their custom state.
1918
+ *
1919
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1920
+ */
1921
+ saveStateBeforeParse() {
1922
+ this._savedState = {
1923
+ _name: this._name,
1924
+ _optionValues: { ...this._optionValues },
1925
+ _optionValueSources: { ...this._optionValueSources }
1926
+ };
1927
+ }
1928
+ /**
1929
+ * Restore state before parse for calls after the first.
1930
+ * Not usually called directly, but available for subclasses to save their custom state.
1931
+ *
1932
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1933
+ */
1934
+ restoreStateBeforeParse() {
1935
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1936
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1937
+ this._name = this._savedState._name;
1938
+ this._scriptPath = null;
1939
+ this.rawArgs = [];
1940
+ this._optionValues = { ...this._savedState._optionValues };
1941
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1942
+ this.args = [];
1943
+ this.processedArgs = [];
1944
+ }
1945
+ /**
1946
+ * Throw if expected executable is missing. Add lots of help for author.
1947
+ *
1948
+ * @param {string} executableFile
1949
+ * @param {string} executableDir
1950
+ * @param {string} subcommandName
1951
+ */
1952
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1953
+ if (fs.existsSync(executableFile)) return;
1954
+ const executableMissing = `'${executableFile}' does not exist
1955
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1956
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1957
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1958
+ throw new Error(executableMissing);
1959
+ }
1960
+ /**
1961
+ * Execute a sub-command executable.
1962
+ *
1963
+ * @private
1964
+ */
1965
+ _executeSubCommand(subcommand, args) {
1966
+ args = args.slice();
1967
+ let launchWithNode = false;
1968
+ const sourceExt = [
1969
+ ".js",
1970
+ ".ts",
1971
+ ".tsx",
1972
+ ".mjs",
1973
+ ".cjs"
1974
+ ];
1975
+ function findFile(baseDir, baseName) {
1976
+ const localBin = path.resolve(baseDir, baseName);
1977
+ if (fs.existsSync(localBin)) return localBin;
1978
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1979
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1980
+ if (foundExt) return `${localBin}${foundExt}`;
1981
+ }
1982
+ this._checkForMissingMandatoryOptions();
1983
+ this._checkForConflictingOptions();
1984
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1985
+ let executableDir = this._executableDir || "";
1986
+ if (this._scriptPath) {
1987
+ let resolvedScriptPath;
1988
+ try {
1989
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1990
+ } catch {
1991
+ resolvedScriptPath = this._scriptPath;
1992
+ }
1993
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1994
+ }
1995
+ if (executableDir) {
1996
+ let localFile = findFile(executableDir, executableFile);
1997
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1998
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1999
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2000
+ }
2001
+ executableFile = localFile || executableFile;
2002
+ }
2003
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2004
+ let proc;
2005
+ if (process$1.platform !== "win32") if (launchWithNode) {
2006
+ args.unshift(executableFile);
2007
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2008
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
2009
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2010
+ else {
2011
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2012
+ args.unshift(executableFile);
2013
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2014
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
2015
+ }
2016
+ if (!proc.killed) [
2017
+ "SIGUSR1",
2018
+ "SIGUSR2",
2019
+ "SIGTERM",
2020
+ "SIGINT",
2021
+ "SIGHUP"
2022
+ ].forEach((signal) => {
2023
+ process$1.on(signal, () => {
2024
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2025
+ });
2026
+ });
2027
+ const exitCallback = this._exitCallback;
2028
+ proc.on("close", (code) => {
2029
+ code = code ?? 1;
2030
+ if (!exitCallback) process$1.exit(code);
2031
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2032
+ });
2033
+ proc.on("error", (err) => {
2034
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2035
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2036
+ if (!exitCallback) process$1.exit(1);
2037
+ else {
2038
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2039
+ wrappedError.nestedError = err;
2040
+ exitCallback(wrappedError);
2041
+ }
2042
+ });
2043
+ this.runningCommand = proc;
2044
+ }
2045
+ /**
2046
+ * @private
2047
+ */
2048
+ _dispatchSubcommand(commandName, operands, unknown) {
2049
+ const subCommand = this._findCommand(commandName);
2050
+ if (!subCommand) this.help({ error: true });
2051
+ subCommand._prepareForParse();
2052
+ let promiseChain;
2053
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2054
+ promiseChain = this._chainOrCall(promiseChain, () => {
2055
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2056
+ else return subCommand._parseCommand(operands, unknown);
2057
+ });
2058
+ return promiseChain;
2059
+ }
2060
+ /**
2061
+ * Invoke help directly if possible, or dispatch if necessary.
2062
+ * e.g. help foo
2063
+ *
2064
+ * @private
2065
+ */
2066
+ _dispatchHelpCommand(subcommandName) {
2067
+ if (!subcommandName) this.help();
2068
+ const subCommand = this._findCommand(subcommandName);
2069
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2070
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2071
+ }
2072
+ /**
2073
+ * Check this.args against expected this.registeredArguments.
2074
+ *
2075
+ * @private
2076
+ */
2077
+ _checkNumberOfArguments() {
2078
+ this.registeredArguments.forEach((arg, i) => {
2079
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2080
+ });
2081
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2082
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2083
+ }
2084
+ /**
2085
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2086
+ *
2087
+ * @private
2088
+ */
2089
+ _processArguments() {
2090
+ const myParseArg = (argument, value, previous) => {
2091
+ let parsedValue = value;
2092
+ if (value !== null && argument.parseArg) {
2093
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2094
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2095
+ }
2096
+ return parsedValue;
2097
+ };
2098
+ this._checkNumberOfArguments();
2099
+ const processedArgs = [];
2100
+ this.registeredArguments.forEach((declaredArg, index) => {
2101
+ let value = declaredArg.defaultValue;
2102
+ if (declaredArg.variadic) {
2103
+ if (index < this.args.length) {
2104
+ value = this.args.slice(index);
2105
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2106
+ return myParseArg(declaredArg, v, processed);
2107
+ }, declaredArg.defaultValue);
2108
+ } else if (value === void 0) value = [];
2109
+ } else if (index < this.args.length) {
2110
+ value = this.args[index];
2111
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2112
+ }
2113
+ processedArgs[index] = value;
2114
+ });
2115
+ this.processedArgs = processedArgs;
2116
+ }
2117
+ /**
2118
+ * Once we have a promise we chain, but call synchronously until then.
2119
+ *
2120
+ * @param {(Promise|undefined)} promise
2121
+ * @param {Function} fn
2122
+ * @return {(Promise|undefined)}
2123
+ * @private
2124
+ */
2125
+ _chainOrCall(promise, fn) {
2126
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2127
+ return fn();
2128
+ }
2129
+ /**
2130
+ *
2131
+ * @param {(Promise|undefined)} promise
2132
+ * @param {string} event
2133
+ * @return {(Promise|undefined)}
2134
+ * @private
2135
+ */
2136
+ _chainOrCallHooks(promise, event) {
2137
+ let result = promise;
2138
+ const hooks = [];
2139
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2140
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2141
+ hooks.push({
2142
+ hookedCommand,
2143
+ callback
2144
+ });
2145
+ });
2146
+ });
2147
+ if (event === "postAction") hooks.reverse();
2148
+ hooks.forEach((hookDetail) => {
2149
+ result = this._chainOrCall(result, () => {
2150
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2151
+ });
2152
+ });
2153
+ return result;
2154
+ }
2155
+ /**
2156
+ *
2157
+ * @param {(Promise|undefined)} promise
2158
+ * @param {Command} subCommand
2159
+ * @param {string} event
2160
+ * @return {(Promise|undefined)}
2161
+ * @private
2162
+ */
2163
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2164
+ let result = promise;
2165
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2166
+ result = this._chainOrCall(result, () => {
2167
+ return hook(this, subCommand);
2168
+ });
2169
+ });
2170
+ return result;
2171
+ }
2172
+ /**
2173
+ * Process arguments in context of this command.
2174
+ * Returns action result, in case it is a promise.
2175
+ *
2176
+ * @private
2177
+ */
2178
+ _parseCommand(operands, unknown) {
2179
+ const parsed = this.parseOptions(unknown);
2180
+ this._parseOptionsEnv();
2181
+ this._parseOptionsImplied();
2182
+ operands = operands.concat(parsed.operands);
2183
+ unknown = parsed.unknown;
2184
+ this.args = operands.concat(unknown);
2185
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2186
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2187
+ if (this._defaultCommandName) {
2188
+ this._outputHelpIfRequested(unknown);
2189
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2190
+ }
2191
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2192
+ this._outputHelpIfRequested(parsed.unknown);
2193
+ this._checkForMissingMandatoryOptions();
2194
+ this._checkForConflictingOptions();
2195
+ const checkForUnknownOptions = () => {
2196
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2197
+ };
2198
+ const commandEvent = `command:${this.name()}`;
2199
+ if (this._actionHandler) {
2200
+ checkForUnknownOptions();
2201
+ this._processArguments();
2202
+ let promiseChain;
2203
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2204
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2205
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2206
+ this.parent.emit(commandEvent, operands, unknown);
2207
+ });
2208
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2209
+ return promiseChain;
2210
+ }
2211
+ if (this.parent?.listenerCount(commandEvent)) {
2212
+ checkForUnknownOptions();
2213
+ this._processArguments();
2214
+ this.parent.emit(commandEvent, operands, unknown);
2215
+ } else if (operands.length) {
2216
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2217
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2218
+ else if (this.commands.length) this.unknownCommand();
2219
+ else {
2220
+ checkForUnknownOptions();
2221
+ this._processArguments();
2222
+ }
2223
+ } else if (this.commands.length) {
2224
+ checkForUnknownOptions();
2225
+ this.help({ error: true });
2226
+ } else {
2227
+ checkForUnknownOptions();
2228
+ this._processArguments();
2229
+ }
2230
+ }
2231
+ /**
2232
+ * Find matching command.
2233
+ *
2234
+ * @private
2235
+ * @return {Command | undefined}
2236
+ */
2237
+ _findCommand(name) {
2238
+ if (!name) return void 0;
2239
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2240
+ }
2241
+ /**
2242
+ * Return an option matching `arg` if any.
2243
+ *
2244
+ * @param {string} arg
2245
+ * @return {Option}
2246
+ * @package
2247
+ */
2248
+ _findOption(arg) {
2249
+ return this.options.find((option) => option.is(arg));
2250
+ }
2251
+ /**
2252
+ * Display an error message if a mandatory option does not have a value.
2253
+ * Called after checking for help flags in leaf subcommand.
2254
+ *
2255
+ * @private
2256
+ */
2257
+ _checkForMissingMandatoryOptions() {
2258
+ this._getCommandAndAncestors().forEach((cmd) => {
2259
+ cmd.options.forEach((anOption) => {
2260
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2261
+ });
2262
+ });
2263
+ }
2264
+ /**
2265
+ * Display an error message if conflicting options are used together in this.
2266
+ *
2267
+ * @private
2268
+ */
2269
+ _checkForConflictingLocalOptions() {
2270
+ const definedNonDefaultOptions = this.options.filter((option) => {
2271
+ const optionKey = option.attributeName();
2272
+ if (this.getOptionValue(optionKey) === void 0) return false;
2273
+ return this.getOptionValueSource(optionKey) !== "default";
2274
+ });
2275
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2276
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2277
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2278
+ });
2279
+ }
2280
+ /**
2281
+ * Display an error message if conflicting options are used together.
2282
+ * Called after checking for help flags in leaf subcommand.
2283
+ *
2284
+ * @private
2285
+ */
2286
+ _checkForConflictingOptions() {
2287
+ this._getCommandAndAncestors().forEach((cmd) => {
2288
+ cmd._checkForConflictingLocalOptions();
2289
+ });
2290
+ }
2291
+ /**
2292
+ * Parse options from `argv` removing known options,
2293
+ * and return argv split into operands and unknown arguments.
2294
+ *
2295
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2296
+ *
2297
+ * Examples:
2298
+ *
2299
+ * argv => operands, unknown
2300
+ * --known kkk op => [op], []
2301
+ * op --known kkk => [op], []
2302
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2303
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2304
+ *
2305
+ * @param {string[]} args
2306
+ * @return {{operands: string[], unknown: string[]}}
2307
+ */
2308
+ parseOptions(args) {
2309
+ const operands = [];
2310
+ const unknown = [];
2311
+ let dest = operands;
2312
+ function maybeOption(arg) {
2313
+ return arg.length > 1 && arg[0] === "-";
2314
+ }
2315
+ const negativeNumberArg = (arg) => {
2316
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2317
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2318
+ };
2319
+ let activeVariadicOption = null;
2320
+ let activeGroup = null;
2321
+ let i = 0;
2322
+ while (i < args.length || activeGroup) {
2323
+ const arg = activeGroup ?? args[i++];
2324
+ activeGroup = null;
2325
+ if (arg === "--") {
2326
+ if (dest === unknown) dest.push(arg);
2327
+ dest.push(...args.slice(i));
2328
+ break;
2329
+ }
2330
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2331
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2332
+ continue;
2333
+ }
2334
+ activeVariadicOption = null;
2335
+ if (maybeOption(arg)) {
2336
+ const option = this._findOption(arg);
2337
+ if (option) {
2338
+ if (option.required) {
2339
+ const value = args[i++];
2340
+ if (value === void 0) this.optionMissingArgument(option);
2341
+ this.emit(`option:${option.name()}`, value);
2342
+ } else if (option.optional) {
2343
+ let value = null;
2344
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2345
+ this.emit(`option:${option.name()}`, value);
2346
+ } else this.emit(`option:${option.name()}`);
2347
+ activeVariadicOption = option.variadic ? option : null;
2348
+ continue;
2349
+ }
2350
+ }
2351
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2352
+ const option = this._findOption(`-${arg[1]}`);
2353
+ if (option) {
2354
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2355
+ else {
2356
+ this.emit(`option:${option.name()}`);
2357
+ activeGroup = `-${arg.slice(2)}`;
2358
+ }
2359
+ continue;
2360
+ }
2361
+ }
2362
+ if (/^--[^=]+=/.test(arg)) {
2363
+ const index = arg.indexOf("=");
2364
+ const option = this._findOption(arg.slice(0, index));
2365
+ if (option && (option.required || option.optional)) {
2366
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2367
+ continue;
2368
+ }
2369
+ }
2370
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2371
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2372
+ if (this._findCommand(arg)) {
2373
+ operands.push(arg);
2374
+ unknown.push(...args.slice(i));
2375
+ break;
2376
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2377
+ operands.push(arg, ...args.slice(i));
2378
+ break;
2379
+ } else if (this._defaultCommandName) {
2380
+ unknown.push(arg, ...args.slice(i));
2381
+ break;
2382
+ }
2383
+ }
2384
+ if (this._passThroughOptions) {
2385
+ dest.push(arg, ...args.slice(i));
2386
+ break;
2387
+ }
2388
+ dest.push(arg);
2389
+ }
2390
+ return {
2391
+ operands,
2392
+ unknown
2393
+ };
2394
+ }
2395
+ /**
2396
+ * Return an object containing local option values as key-value pairs.
2397
+ *
2398
+ * @return {object}
2399
+ */
2400
+ opts() {
2401
+ if (this._storeOptionsAsProperties) {
2402
+ const result = {};
2403
+ const len = this.options.length;
2404
+ for (let i = 0; i < len; i++) {
2405
+ const key = this.options[i].attributeName();
2406
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2407
+ }
2408
+ return result;
2409
+ }
2410
+ return this._optionValues;
2411
+ }
2412
+ /**
2413
+ * Return an object containing merged local and global option values as key-value pairs.
2414
+ *
2415
+ * @return {object}
2416
+ */
2417
+ optsWithGlobals() {
2418
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2419
+ }
2420
+ /**
2421
+ * Display error message and exit (or call exitOverride).
2422
+ *
2423
+ * @param {string} message
2424
+ * @param {object} [errorOptions]
2425
+ * @param {string} [errorOptions.code] - an id string representing the error
2426
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2427
+ */
2428
+ error(message, errorOptions) {
2429
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2430
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2431
+ else if (this._showHelpAfterError) {
2432
+ this._outputConfiguration.writeErr("\n");
2433
+ this.outputHelp({ error: true });
2434
+ }
2435
+ const config = errorOptions || {};
2436
+ const exitCode = config.exitCode || 1;
2437
+ const code = config.code || "commander.error";
2438
+ this._exit(exitCode, code, message);
2439
+ }
2440
+ /**
2441
+ * Apply any option related environment variables, if option does
2442
+ * not have a value from cli or client code.
2443
+ *
2444
+ * @private
2445
+ */
2446
+ _parseOptionsEnv() {
2447
+ this.options.forEach((option) => {
2448
+ if (option.envVar && option.envVar in process$1.env) {
2449
+ const optionKey = option.attributeName();
2450
+ if (this.getOptionValue(optionKey) === void 0 || [
2451
+ "default",
2452
+ "config",
2453
+ "env"
2454
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2455
+ else this.emit(`optionEnv:${option.name()}`);
2456
+ }
2457
+ });
2458
+ }
2459
+ /**
2460
+ * Apply any implied option values, if option is undefined or default value.
2461
+ *
2462
+ * @private
2463
+ */
2464
+ _parseOptionsImplied() {
2465
+ const dualHelper = new DualOptions(this.options);
2466
+ const hasCustomOptionValue = (optionKey) => {
2467
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2468
+ };
2469
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2470
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2471
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2472
+ });
2473
+ });
2474
+ }
2475
+ /**
2476
+ * Argument `name` is missing.
2477
+ *
2478
+ * @param {string} name
2479
+ * @private
2480
+ */
2481
+ missingArgument(name) {
2482
+ const message = `error: missing required argument '${name}'`;
2483
+ this.error(message, { code: "commander.missingArgument" });
2484
+ }
2485
+ /**
2486
+ * `Option` is missing an argument.
2487
+ *
2488
+ * @param {Option} option
2489
+ * @private
2490
+ */
2491
+ optionMissingArgument(option) {
2492
+ const message = `error: option '${option.flags}' argument missing`;
2493
+ this.error(message, { code: "commander.optionMissingArgument" });
2494
+ }
2495
+ /**
2496
+ * `Option` does not have a value, and is a mandatory option.
2497
+ *
2498
+ * @param {Option} option
2499
+ * @private
2500
+ */
2501
+ missingMandatoryOptionValue(option) {
2502
+ const message = `error: required option '${option.flags}' not specified`;
2503
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2504
+ }
2505
+ /**
2506
+ * `Option` conflicts with another option.
2507
+ *
2508
+ * @param {Option} option
2509
+ * @param {Option} conflictingOption
2510
+ * @private
2511
+ */
2512
+ _conflictingOption(option, conflictingOption) {
2513
+ const findBestOptionFromValue = (option) => {
2514
+ const optionKey = option.attributeName();
2515
+ const optionValue = this.getOptionValue(optionKey);
2516
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2517
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2518
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2519
+ return positiveOption || option;
2520
+ };
2521
+ const getErrorMessage = (option) => {
2522
+ const bestOption = findBestOptionFromValue(option);
2523
+ const optionKey = bestOption.attributeName();
2524
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2525
+ return `option '${bestOption.flags}'`;
2526
+ };
2527
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2528
+ this.error(message, { code: "commander.conflictingOption" });
2529
+ }
2530
+ /**
2531
+ * Unknown option `flag`.
2532
+ *
2533
+ * @param {string} flag
2534
+ * @private
2535
+ */
2536
+ unknownOption(flag) {
2537
+ if (this._allowUnknownOption) return;
2538
+ let suggestion = "";
2539
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2540
+ let candidateFlags = [];
2541
+ let command = this;
2542
+ do {
2543
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2544
+ candidateFlags = candidateFlags.concat(moreFlags);
2545
+ command = command.parent;
2546
+ } while (command && !command._enablePositionalOptions);
2547
+ suggestion = suggestSimilar(flag, candidateFlags);
2548
+ }
2549
+ const message = `error: unknown option '${flag}'${suggestion}`;
2550
+ this.error(message, { code: "commander.unknownOption" });
2551
+ }
2552
+ /**
2553
+ * Excess arguments, more than expected.
2554
+ *
2555
+ * @param {string[]} receivedArgs
2556
+ * @private
2557
+ */
2558
+ _excessArguments(receivedArgs) {
2559
+ if (this._allowExcessArguments) return;
2560
+ const expected = this.registeredArguments.length;
2561
+ const s = expected === 1 ? "" : "s";
2562
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2563
+ this.error(message, { code: "commander.excessArguments" });
2564
+ }
2565
+ /**
2566
+ * Unknown command.
2567
+ *
2568
+ * @private
2569
+ */
2570
+ unknownCommand() {
2571
+ const unknownName = this.args[0];
2572
+ let suggestion = "";
2573
+ if (this._showSuggestionAfterError) {
2574
+ const candidateNames = [];
2575
+ this.createHelp().visibleCommands(this).forEach((command) => {
2576
+ candidateNames.push(command.name());
2577
+ if (command.alias()) candidateNames.push(command.alias());
2578
+ });
2579
+ suggestion = suggestSimilar(unknownName, candidateNames);
2580
+ }
2581
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2582
+ this.error(message, { code: "commander.unknownCommand" });
2583
+ }
2584
+ /**
2585
+ * Get or set the program version.
2586
+ *
2587
+ * This method auto-registers the "-V, --version" option which will print the version number.
2588
+ *
2589
+ * You can optionally supply the flags and description to override the defaults.
2590
+ *
2591
+ * @param {string} [str]
2592
+ * @param {string} [flags]
2593
+ * @param {string} [description]
2594
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2595
+ */
2596
+ version(str, flags, description) {
2597
+ if (str === void 0) return this._version;
2598
+ this._version = str;
2599
+ flags = flags || "-V, --version";
2600
+ description = description || "output the version number";
2601
+ const versionOption = this.createOption(flags, description);
2602
+ this._versionOptionName = versionOption.attributeName();
2603
+ this._registerOption(versionOption);
2604
+ this.on("option:" + versionOption.name(), () => {
2605
+ this._outputConfiguration.writeOut(`${str}\n`);
2606
+ this._exit(0, "commander.version", str);
2607
+ });
2608
+ return this;
2609
+ }
2610
+ /**
2611
+ * Set the description.
2612
+ *
2613
+ * @param {string} [str]
2614
+ * @param {object} [argsDescription]
2615
+ * @return {(string|Command)}
2616
+ */
2617
+ description(str, argsDescription) {
2618
+ if (str === void 0 && argsDescription === void 0) return this._description;
2619
+ this._description = str;
2620
+ if (argsDescription) this._argsDescription = argsDescription;
2621
+ return this;
2622
+ }
2623
+ /**
2624
+ * Set the summary. Used when listed as subcommand of parent.
2625
+ *
2626
+ * @param {string} [str]
2627
+ * @return {(string|Command)}
2628
+ */
2629
+ summary(str) {
2630
+ if (str === void 0) return this._summary;
2631
+ this._summary = str;
2632
+ return this;
2633
+ }
2634
+ /**
2635
+ * Set an alias for the command.
2636
+ *
2637
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2638
+ *
2639
+ * @param {string} [alias]
2640
+ * @return {(string|Command)}
2641
+ */
2642
+ alias(alias) {
2643
+ if (alias === void 0) return this._aliases[0];
2644
+ /** @type {Command} */
2645
+ let command = this;
2646
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2647
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2648
+ const matchingCommand = this.parent?._findCommand(alias);
2649
+ if (matchingCommand) {
2650
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2651
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2652
+ }
2653
+ command._aliases.push(alias);
2654
+ return this;
2655
+ }
2656
+ /**
2657
+ * Set aliases for the command.
2658
+ *
2659
+ * Only the first alias is shown in the auto-generated help.
2660
+ *
2661
+ * @param {string[]} [aliases]
2662
+ * @return {(string[]|Command)}
2663
+ */
2664
+ aliases(aliases) {
2665
+ if (aliases === void 0) return this._aliases;
2666
+ aliases.forEach((alias) => this.alias(alias));
2667
+ return this;
2668
+ }
2669
+ /**
2670
+ * Set / get the command usage `str`.
2671
+ *
2672
+ * @param {string} [str]
2673
+ * @return {(string|Command)}
2674
+ */
2675
+ usage(str) {
2676
+ if (str === void 0) {
2677
+ if (this._usage) return this._usage;
2678
+ const args = this.registeredArguments.map((arg) => {
2679
+ return humanReadableArgName(arg);
2680
+ });
2681
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2682
+ }
2683
+ this._usage = str;
2684
+ return this;
2685
+ }
2686
+ /**
2687
+ * Get or set the name of the command.
2688
+ *
2689
+ * @param {string} [str]
2690
+ * @return {(string|Command)}
2691
+ */
2692
+ name(str) {
2693
+ if (str === void 0) return this._name;
2694
+ this._name = str;
2695
+ return this;
2696
+ }
2697
+ /**
2698
+ * Set/get the help group heading for this subcommand in parent command's help.
2699
+ *
2700
+ * @param {string} [heading]
2701
+ * @return {Command | string}
2702
+ */
2703
+ helpGroup(heading) {
2704
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2705
+ this._helpGroupHeading = heading;
2706
+ return this;
2707
+ }
2708
+ /**
2709
+ * Set/get the default help group heading for subcommands added to this command.
2710
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2711
+ *
2712
+ * @example
2713
+ * program.commandsGroup('Development Commands:);
2714
+ * program.command('watch')...
2715
+ * program.command('lint')...
2716
+ * ...
2717
+ *
2718
+ * @param {string} [heading]
2719
+ * @returns {Command | string}
2720
+ */
2721
+ commandsGroup(heading) {
2722
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2723
+ this._defaultCommandGroup = heading;
2724
+ return this;
2725
+ }
2726
+ /**
2727
+ * Set/get the default help group heading for options added to this command.
2728
+ * (This does not override a group set directly on the option using .helpGroup().)
2729
+ *
2730
+ * @example
2731
+ * program
2732
+ * .optionsGroup('Development Options:')
2733
+ * .option('-d, --debug', 'output extra debugging')
2734
+ * .option('-p, --profile', 'output profiling information')
2735
+ *
2736
+ * @param {string} [heading]
2737
+ * @returns {Command | string}
2738
+ */
2739
+ optionsGroup(heading) {
2740
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2741
+ this._defaultOptionGroup = heading;
2742
+ return this;
2743
+ }
2744
+ /**
2745
+ * @param {Option} option
2746
+ * @private
2747
+ */
2748
+ _initOptionGroup(option) {
2749
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2750
+ }
2751
+ /**
2752
+ * @param {Command} cmd
2753
+ * @private
2754
+ */
2755
+ _initCommandGroup(cmd) {
2756
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2757
+ }
2758
+ /**
2759
+ * Set the name of the command from script filename, such as process.argv[1],
2760
+ * or require.main.filename, or __filename.
2761
+ *
2762
+ * (Used internally and public although not documented in README.)
2763
+ *
2764
+ * @example
2765
+ * program.nameFromFilename(require.main.filename);
2766
+ *
2767
+ * @param {string} filename
2768
+ * @return {Command}
2769
+ */
2770
+ nameFromFilename(filename) {
2771
+ this._name = path.basename(filename, path.extname(filename));
2772
+ return this;
2773
+ }
2774
+ /**
2775
+ * Get or set the directory for searching for executable subcommands of this command.
2776
+ *
2777
+ * @example
2778
+ * program.executableDir(__dirname);
2779
+ * // or
2780
+ * program.executableDir('subcommands');
2781
+ *
2782
+ * @param {string} [path]
2783
+ * @return {(string|null|Command)}
2784
+ */
2785
+ executableDir(path) {
2786
+ if (path === void 0) return this._executableDir;
2787
+ this._executableDir = path;
2788
+ return this;
2789
+ }
2790
+ /**
2791
+ * Return program help documentation.
2792
+ *
2793
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2794
+ * @return {string}
2795
+ */
2796
+ helpInformation(contextOptions) {
2797
+ const helper = this.createHelp();
2798
+ const context = this._getOutputContext(contextOptions);
2799
+ helper.prepareContext({
2800
+ error: context.error,
2801
+ helpWidth: context.helpWidth,
2802
+ outputHasColors: context.hasColors
2803
+ });
2804
+ const text = helper.formatHelp(this, helper);
2805
+ if (context.hasColors) return text;
2806
+ return this._outputConfiguration.stripColor(text);
2807
+ }
2808
+ /**
2809
+ * @typedef HelpContext
2810
+ * @type {object}
2811
+ * @property {boolean} error
2812
+ * @property {number} helpWidth
2813
+ * @property {boolean} hasColors
2814
+ * @property {function} write - includes stripColor if needed
2815
+ *
2816
+ * @returns {HelpContext}
2817
+ * @private
2818
+ */
2819
+ _getOutputContext(contextOptions) {
2820
+ contextOptions = contextOptions || {};
2821
+ const error = !!contextOptions.error;
2822
+ let baseWrite;
2823
+ let hasColors;
2824
+ let helpWidth;
2825
+ if (error) {
2826
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2827
+ hasColors = this._outputConfiguration.getErrHasColors();
2828
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2829
+ } else {
2830
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2831
+ hasColors = this._outputConfiguration.getOutHasColors();
2832
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2833
+ }
2834
+ const write = (str) => {
2835
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2836
+ return baseWrite(str);
2837
+ };
2838
+ return {
2839
+ error,
2840
+ write,
2841
+ hasColors,
2842
+ helpWidth
2843
+ };
2844
+ }
2845
+ /**
2846
+ * Output help information for this command.
2847
+ *
2848
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2849
+ *
2850
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2851
+ */
2852
+ outputHelp(contextOptions) {
2853
+ let deprecatedCallback;
2854
+ if (typeof contextOptions === "function") {
2855
+ deprecatedCallback = contextOptions;
2856
+ contextOptions = void 0;
2857
+ }
2858
+ const outputContext = this._getOutputContext(contextOptions);
2859
+ /** @type {HelpTextEventContext} */
2860
+ const eventContext = {
2861
+ error: outputContext.error,
2862
+ write: outputContext.write,
2863
+ command: this
2864
+ };
2865
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2866
+ this.emit("beforeHelp", eventContext);
2867
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2868
+ if (deprecatedCallback) {
2869
+ helpInformation = deprecatedCallback(helpInformation);
2870
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2871
+ }
2872
+ outputContext.write(helpInformation);
2873
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2874
+ this.emit("afterHelp", eventContext);
2875
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2876
+ }
2877
+ /**
2878
+ * You can pass in flags and a description to customise the built-in help option.
2879
+ * Pass in false to disable the built-in help option.
2880
+ *
2881
+ * @example
2882
+ * program.helpOption('-?, --help' 'show help'); // customise
2883
+ * program.helpOption(false); // disable
2884
+ *
2885
+ * @param {(string | boolean)} flags
2886
+ * @param {string} [description]
2887
+ * @return {Command} `this` command for chaining
2888
+ */
2889
+ helpOption(flags, description) {
2890
+ if (typeof flags === "boolean") {
2891
+ if (flags) {
2892
+ if (this._helpOption === null) this._helpOption = void 0;
2893
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2894
+ } else this._helpOption = null;
2895
+ return this;
2896
+ }
2897
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2898
+ if (flags || description) this._initOptionGroup(this._helpOption);
2899
+ return this;
2900
+ }
2901
+ /**
2902
+ * Lazy create help option.
2903
+ * Returns null if has been disabled with .helpOption(false).
2904
+ *
2905
+ * @returns {(Option | null)} the help option
2906
+ * @package
2907
+ */
2908
+ _getHelpOption() {
2909
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2910
+ return this._helpOption;
2911
+ }
2912
+ /**
2913
+ * Supply your own option to use for the built-in help option.
2914
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2915
+ *
2916
+ * @param {Option} option
2917
+ * @return {Command} `this` command for chaining
2918
+ */
2919
+ addHelpOption(option) {
2920
+ this._helpOption = option;
2921
+ this._initOptionGroup(option);
2922
+ return this;
2923
+ }
2924
+ /**
2925
+ * Output help information and exit.
2926
+ *
2927
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2928
+ *
2929
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2930
+ */
2931
+ help(contextOptions) {
2932
+ this.outputHelp(contextOptions);
2933
+ let exitCode = Number(process$1.exitCode ?? 0);
2934
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2935
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2936
+ }
2937
+ /**
2938
+ * // Do a little typing to coordinate emit and listener for the help text events.
2939
+ * @typedef HelpTextEventContext
2940
+ * @type {object}
2941
+ * @property {boolean} error
2942
+ * @property {Command} command
2943
+ * @property {function} write
2944
+ */
2945
+ /**
2946
+ * Add additional text to be displayed with the built-in help.
2947
+ *
2948
+ * Position is 'before' or 'after' to affect just this command,
2949
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2950
+ *
2951
+ * @param {string} position - before or after built-in help
2952
+ * @param {(string | Function)} text - string to add, or a function returning a string
2953
+ * @return {Command} `this` command for chaining
2954
+ */
2955
+ addHelpText(position, text) {
2956
+ const allowedValues = [
2957
+ "beforeAll",
2958
+ "before",
2959
+ "after",
2960
+ "afterAll"
2961
+ ];
2962
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2963
+ Expecting one of '${allowedValues.join("', '")}'`);
2964
+ const helpEvent = `${position}Help`;
2965
+ this.on(helpEvent, (context) => {
2966
+ let helpStr;
2967
+ if (typeof text === "function") helpStr = text({
2968
+ error: context.error,
2969
+ command: context.command
2970
+ });
2971
+ else helpStr = text;
2972
+ if (helpStr) context.write(`${helpStr}\n`);
2973
+ });
2974
+ return this;
2975
+ }
2976
+ /**
2977
+ * Output help information if help flags specified
2978
+ *
2979
+ * @param {Array} args - array of options to search for help flags
2980
+ * @private
2981
+ */
2982
+ _outputHelpIfRequested(args) {
2983
+ const helpOption = this._getHelpOption();
2984
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2985
+ this.outputHelp();
2986
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2987
+ }
2988
+ }
2989
+ };
2990
+ /**
2991
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2992
+ *
2993
+ * @param {string[]} args - array of arguments from node.execArgv
2994
+ * @returns {string[]}
2995
+ * @private
2996
+ */
2997
+ function incrementNodeInspectorPort(args) {
2998
+ return args.map((arg) => {
2999
+ if (!arg.startsWith("--inspect")) return arg;
3000
+ let debugOption;
3001
+ let debugHost = "127.0.0.1";
3002
+ let debugPort = "9229";
3003
+ let match;
3004
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3005
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3006
+ debugOption = match[1];
3007
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3008
+ else debugHost = match[3];
3009
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3010
+ debugOption = match[1];
3011
+ debugHost = match[3];
3012
+ debugPort = match[4];
3013
+ }
3014
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3015
+ return arg;
3016
+ });
3017
+ }
3018
+ /**
3019
+ * @returns {boolean | undefined}
3020
+ * @package
3021
+ */
3022
+ function useColor() {
3023
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
3024
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
3025
+ }
3026
+ exports.Command = Command;
3027
+ exports.useColor = useColor;
3028
+ }));
3029
+
3030
+ //#endregion
3031
+ //#region node_modules/commander/index.js
3032
+ var require_commander = /* @__PURE__ */ __commonJSMin(((exports) => {
3033
+ const { Argument } = require_argument();
3034
+ const { Command } = require_command();
3035
+ const { CommanderError, InvalidArgumentError } = require_error();
3036
+ const { Help } = require_help();
3037
+ const { Option } = require_option();
3038
+ exports.program = new Command();
3039
+ exports.createCommand = (name) => new Command(name);
3040
+ exports.createOption = (flags, description) => new Option(flags, description);
3041
+ exports.createArgument = (name, description) => new Argument(name, description);
3042
+ /**
3043
+ * Expose classes
3044
+ */
3045
+ exports.Command = Command;
3046
+ exports.Option = Option;
3047
+ exports.Argument = Argument;
3048
+ exports.Help = Help;
3049
+ exports.CommanderError = CommanderError;
3050
+ exports.InvalidArgumentError = InvalidArgumentError;
3051
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3052
+ }));
3053
+
3054
+ //#endregion
3055
+ //#region node_modules/commander/esm.mjs
3056
+ var import_commander = /* @__PURE__ */ __toESM(require_commander(), 1);
3057
+ const { program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = import_commander.default;
3058
+
3059
+ //#endregion
3060
+ //#region src/cli/run-host.ts
3061
+ const runHostCmd = new Command("run-host");
3062
+ runHostCmd.description("Run an arbitrary shell command on the host via `sh -c`.").requiredOption("--command <command_string>", "The shell command to execute. Supports pipes, redirection, &&, ||, etc.").addHelpText("after", `
3063
+ Examples:
3064
+ 1. Run a simple command:
3065
+ clawmini-lite request run-host -- --command "ls -la"
3066
+
3067
+ 2. Run a command with pipes and redirection:
3068
+ clawmini-lite request run-host -- --command "cat file.txt | grep error > errors.log"
3069
+
3070
+ 3. Chain commands:
3071
+ clawmini-lite request run-host -- --command "npm install && npm test"
3072
+ `).action((options) => {
3073
+ const child = spawn("sh", ["-c", options.command], { stdio: [
3074
+ "ignore",
3075
+ "inherit",
3076
+ "inherit"
3077
+ ] });
3078
+ child.on("close", (code) => {
3079
+ process.exit(code ?? 1);
3080
+ });
3081
+ child.on("error", (err) => {
3082
+ console.error(`Failed to execute command: ${err.message}`);
3083
+ process.exit(1);
3084
+ });
3085
+ });
3086
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) runHostCmd.parse(process.argv);
3087
+
3088
+ //#endregion
3089
+ export { };
3090
+ //# sourceMappingURL=run-host.mjs.map