dsh-pstack 0.2.0-beta.1 → 0.2.0-beta.3

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 (261) hide show
  1. package/LICENSE +2 -3
  2. package/README.md +135 -84
  3. package/README.zh.md +185 -0
  4. package/cordis.patch.yml +97 -27
  5. package/dist/host-contract-CUPSpeNk.d.mts +22 -0
  6. package/dist/index.d.mts +49 -238
  7. package/dist/index.mjs +250 -123
  8. package/dist/models.d.mts +44 -0
  9. package/dist/models.mjs +201 -0
  10. package/dist/paths-BT77khwm.mjs +48 -0
  11. package/dist/pstack/LICENSE +21 -0
  12. package/dist/pstack/README.md +291 -0
  13. package/dist/pstack/agents/poteto-agent.md +9 -0
  14. package/{assets → dist/pstack}/docs/guide/01-setup.md +13 -11
  15. package/{assets → dist/pstack}/docs/guide/02-poteto-mode.md +4 -4
  16. package/{assets → dist/pstack}/docs/guide/04-design.md +4 -4
  17. package/{assets → dist/pstack}/docs/guide/05-build-and-clean.md +2 -2
  18. package/{assets → dist/pstack}/docs/guide/06-verify-and-ship.md +13 -3
  19. package/{assets → dist/pstack}/docs/guide/07-overnight.md +15 -13
  20. package/{assets → dist/pstack}/docs/guide/09-make-it-yours.md +6 -2
  21. package/{assets → dist/pstack}/docs/guide/10-recipes-and-pitfalls.md +7 -5
  22. package/{assets → dist/pstack}/docs/guide/README.md +1 -1
  23. package/dist/pstack/docs/harness/dsh.md +98 -0
  24. package/{assets → dist/pstack}/skills/architect/SKILL.md +12 -12
  25. package/dist/pstack/skills/arena/SKILL.md +50 -0
  26. package/{assets → dist/pstack}/skills/automate-me/SKILL.md +14 -14
  27. package/{assets → dist/pstack}/skills/benchmark-checklist/SKILL.md +1 -1
  28. package/{assets → dist/pstack}/skills/blast-radius/SKILL.md +4 -6
  29. package/{assets → dist/pstack}/skills/correct/SKILL.md +1 -1
  30. package/{assets → dist/pstack}/skills/create-formal-verification-skill/SKILL.md +4 -2
  31. package/{assets → dist/pstack}/skills/create-verification-skill/SKILL.md +5 -5
  32. package/dist/pstack/skills/figure-it-out/SKILL.md +54 -0
  33. package/dist/pstack/skills/how/SKILL.md +38 -0
  34. package/{assets → dist/pstack}/skills/in-your-own-words/SKILL.md +1 -1
  35. package/dist/pstack/skills/interrogate/SKILL.md +33 -0
  36. package/{assets → dist/pstack}/skills/ketchup/SKILL.md +3 -5
  37. package/dist/pstack/skills/ketchup-video/SKILL.md +29 -0
  38. package/{assets → dist/pstack}/skills/maintain-formal-verification-skill/SKILL.md +1 -1
  39. package/{assets → dist/pstack}/skills/maintain-verification-skill/SKILL.md +3 -3
  40. package/dist/pstack/skills/make-bot-ui/SKILL.md +117 -0
  41. package/dist/pstack/skills/no-comments/SKILL.md +26 -0
  42. package/{assets → dist/pstack}/skills/poteto-help/SKILL.md +34 -31
  43. package/{assets → dist/pstack}/skills/poteto-help/references/prompting.md +1 -1
  44. package/{assets → dist/pstack}/skills/poteto-help/references/recipes.md +3 -3
  45. package/{assets → dist/pstack}/skills/poteto-mode/SKILL.md +20 -19
  46. package/dist/pstack/skills/poteto-mode/playbooks/authoring-a-skill.md +12 -0
  47. package/dist/pstack/skills/poteto-mode/playbooks/autonomous-run.md +13 -0
  48. package/dist/pstack/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  49. package/dist/pstack/skills/poteto-mode/playbooks/autopilot-stack.md +8 -0
  50. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/babysit.md +4 -4
  51. package/dist/pstack/skills/poteto-mode/playbooks/bug-fix.md +15 -0
  52. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/eval.md +3 -3
  53. package/dist/pstack/skills/poteto-mode/playbooks/feature.md +21 -0
  54. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/hillclimb.md +3 -3
  55. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/investigation.md +2 -2
  56. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/multi-phase-plan.md +23 -23
  57. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/opening-a-pr.md +6 -6
  58. package/dist/pstack/skills/poteto-mode/playbooks/orchestrate.md +25 -0
  59. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/pause-safely.md +2 -2
  60. package/dist/pstack/skills/poteto-mode/playbooks/perf-issue.md +25 -0
  61. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/prototype.md +4 -4
  62. package/dist/pstack/skills/poteto-mode/playbooks/refactoring.md +16 -0
  63. package/dist/pstack/skills/poteto-mode/playbooks/runtime-forensics.md +11 -0
  64. package/dist/pstack/skills/poteto-mode/playbooks/session-pickup.md +11 -0
  65. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/shipping.md +2 -2
  66. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/trace-forensics.md +2 -2
  67. package/dist/pstack/skills/poteto-mode/playbooks/visual-parity.md +11 -0
  68. package/dist/pstack/skills/poteto-mode/playbooks/worktree-cleanup.md +12 -0
  69. package/{assets → dist/pstack}/skills/poteto-mode/scripts/check-plan.mjs +6 -8
  70. package/dist/pstack/skills/poteto-mode/scripts/check-plan.test.mjs +128 -0
  71. package/{assets/skills/poteto-mode/scripts/check-plan.test.mjs → dist/pstack/skills/poteto-mode/scripts/expect.mjs} +12 -101
  72. package/dist/pstack/skills/poteto-mode/scripts/support.mjs +93 -0
  73. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/cli.mjs +123 -0
  74. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +217 -0
  75. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.mjs +119 -0
  76. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/github.mjs +626 -0
  77. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/github.test.mjs +521 -0
  78. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/policy.mjs +657 -0
  79. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +523 -0
  80. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/render.mjs +106 -0
  81. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/types.mjs +9 -0
  82. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +5 -0
  83. package/{assets → dist/pstack}/skills/poteto-mode/scripts/worktree-audit.mjs +15 -22
  84. package/dist/pstack/skills/poteto-mode/scripts/worktree-audit.test.mjs +134 -0
  85. package/{assets → dist/pstack}/skills/principle-attack-the-premise/SKILL.md +1 -1
  86. package/{assets → dist/pstack}/skills/principle-boundary-discipline/SKILL.md +1 -1
  87. package/{assets → dist/pstack}/skills/principle-encode-lessons-in-structure/SKILL.md +1 -1
  88. package/{assets → dist/pstack}/skills/principle-exhaust-the-design-space/SKILL.md +1 -1
  89. package/{assets → dist/pstack}/skills/principle-experience-first/SKILL.md +1 -1
  90. package/{assets → dist/pstack}/skills/principle-explain-the-number/SKILL.md +3 -2
  91. package/{assets → dist/pstack}/skills/principle-fix-root-causes/SKILL.md +1 -1
  92. package/{assets → dist/pstack}/skills/principle-laziness-protocol/SKILL.md +1 -1
  93. package/{assets → dist/pstack}/skills/principle-make-operations-idempotent/SKILL.md +1 -1
  94. package/{assets → dist/pstack}/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +1 -1
  95. package/{assets → dist/pstack}/skills/principle-minimize-reader-load/SKILL.md +1 -1
  96. package/{assets → dist/pstack}/skills/principle-model-the-domain/SKILL.md +1 -1
  97. package/{assets → dist/pstack}/skills/principle-never-block-on-the-human/SKILL.md +1 -1
  98. package/{assets → dist/pstack}/skills/principle-outcome-oriented-execution/SKILL.md +1 -1
  99. package/{assets → dist/pstack}/skills/principle-prove-it-works/SKILL.md +2 -2
  100. package/{assets → dist/pstack}/skills/principle-redesign-from-first-principles/SKILL.md +1 -1
  101. package/{assets → dist/pstack}/skills/principle-separate-before-serializing-shared-state/SKILL.md +1 -1
  102. package/{assets → dist/pstack}/skills/principle-sequence-verifiable-units/SKILL.md +1 -1
  103. package/{assets → dist/pstack}/skills/principle-subtract-before-you-add/SKILL.md +1 -1
  104. package/{assets → dist/pstack}/skills/principle-test-behavior-not-implementation/SKILL.md +1 -1
  105. package/{assets → dist/pstack}/skills/principle-type-system-discipline/SKILL.md +1 -1
  106. package/dist/pstack/skills/recall/SKILL.md +37 -0
  107. package/dist/pstack/skills/reflect/SKILL.md +71 -0
  108. package/{assets → dist/pstack}/skills/reflect/references/divergent-reviewer.md +4 -4
  109. package/{assets → dist/pstack}/skills/reflect/references/judgment-reviewer.md +2 -2
  110. package/{assets → dist/pstack}/skills/reflect/references/synthesizer.md +5 -5
  111. package/{assets → dist/pstack}/skills/reflect/references/tooling-reviewer.md +2 -2
  112. package/dist/pstack/skills/setup-pstack/SKILL.md +80 -0
  113. package/{assets → dist/pstack}/skills/sharpen/SKILL.md +1 -1
  114. package/{assets → dist/pstack}/skills/show-me-your-work/SKILL.md +8 -8
  115. package/{assets → dist/pstack}/skills/show-me-your-work/scripts/log.mjs +1 -3
  116. package/dist/pstack/skills/show-me-your-work/scripts/log.test.mjs +56 -0
  117. package/dist/pstack/skills/statechart/SKILL.md +82 -0
  118. package/dist/pstack/skills/statechart/references/render.md +93 -0
  119. package/dist/pstack/skills/statechart/scripts/backends/cfg.mjs +31 -0
  120. package/dist/pstack/skills/statechart/scripts/backends/mermaid.mjs +186 -0
  121. package/dist/pstack/skills/statechart/scripts/backends/plain-text.mjs +62 -0
  122. package/dist/pstack/skills/statechart/scripts/backends/report.mjs +84 -0
  123. package/dist/pstack/skills/statechart/scripts/frontends/config.mjs +268 -0
  124. package/dist/pstack/skills/statechart/scripts/frontends/dot.mjs +67 -0
  125. package/dist/pstack/skills/statechart/scripts/frontends/marks.mjs +94 -0
  126. package/dist/pstack/skills/statechart/scripts/frontends/messages.mjs +48 -0
  127. package/dist/pstack/skills/statechart/scripts/frontends/spec.mjs +101 -0
  128. package/dist/pstack/skills/statechart/scripts/frontends/trace.mjs +39 -0
  129. package/dist/pstack/skills/statechart/scripts/frontends/value.mjs +180 -0
  130. package/dist/pstack/skills/statechart/scripts/frontends/verdict.mjs +40 -0
  131. package/dist/pstack/skills/statechart/scripts/frontends/view.mjs +99 -0
  132. package/dist/pstack/skills/statechart/scripts/ir.mjs +277 -0
  133. package/dist/pstack/skills/statechart/scripts/passes/annotate.mjs +92 -0
  134. package/dist/pstack/skills/statechart/scripts/passes/label.mjs +210 -0
  135. package/dist/pstack/skills/statechart/scripts/passes/lift.mjs +84 -0
  136. package/dist/pstack/skills/statechart/scripts/passes/loop-check.mjs +47 -0
  137. package/dist/pstack/skills/statechart/scripts/passes/paths.mjs +72 -0
  138. package/dist/pstack/skills/statechart/scripts/passes/reach.mjs +135 -0
  139. package/dist/pstack/skills/statechart/scripts/passes/region-check.mjs +82 -0
  140. package/dist/pstack/skills/statechart/scripts/passes/regions.mjs +268 -0
  141. package/dist/pstack/skills/statechart/scripts/pipeline.mjs +72 -0
  142. package/dist/pstack/skills/statechart/scripts/run.mjs +440 -0
  143. package/dist/pstack/skills/statechart/scripts/statechart.mjs +155 -0
  144. package/dist/pstack/skills/statechart/scripts/statechart.test.mjs +198 -0
  145. package/dist/pstack/skills/statechart/scripts/worker.mjs +31 -0
  146. package/dist/pstack/skills/swarm/SKILL.md +43 -0
  147. package/{assets → dist/pstack}/skills/tdd/SKILL.md +1 -1
  148. package/{assets → dist/pstack}/skills/teach/SKILL.md +2 -2
  149. package/{assets → dist/pstack}/skills/technical-writing/SKILL.md +1 -1
  150. package/{assets → dist/pstack}/skills/typescript-best-practices/SKILL.md +3 -6
  151. package/{assets → dist/pstack}/skills/why/SKILL.md +8 -8
  152. package/dist/script.d.mts +9 -111
  153. package/dist/script.mjs +32 -329
  154. package/dist/skill.d.mts +38 -0
  155. package/dist/skill.mjs +183 -0
  156. package/dist/skills/authored/decision-audit/SKILL.md +99 -0
  157. package/dist/skills/authored/decision-audit/SKILL.zh.md +99 -0
  158. package/dist/skills/authored/decision-audit/references/recover-commit.md +17 -0
  159. package/dist/skills/authored/decision-audit/references/recover-commit.zh.md +17 -0
  160. package/dist/skills/authored/decision-write/SKILL.md +131 -0
  161. package/dist/skills/authored/decision-write/SKILL.zh.md +131 -0
  162. package/dist/skills/authored/decision-write/references/land.md +48 -0
  163. package/dist/skills/authored/decision-write/references/land.zh.md +48 -0
  164. package/dist/skills/authored/setup-project-docs/SKILL.md +58 -0
  165. package/dist/skills/authored/setup-project-docs/SKILL.zh.md +58 -0
  166. package/dist/skills/authored/setup-project-docs/references/decision-conventions.md +11 -0
  167. package/dist/skills/authored/setup-project-docs/references/decision-conventions.zh.md +11 -0
  168. package/dist/skills/vendored/retro/SKILL.md +44 -0
  169. package/dist/skills/vendored/retro/agents/openai.yaml +5 -0
  170. package/dist/skills/vendored/writing-for-agents/SKILL-MECHANICS.md +22 -0
  171. package/dist/skills/vendored/writing-for-agents/SKILL.md +81 -0
  172. package/dist/skills/vendored/writing-for-agents/agents/openai.yaml +3 -0
  173. package/dist/subagent.d.mts +56 -193
  174. package/dist/subagent.mjs +443 -741
  175. package/locale/en.json +3 -2
  176. package/locale/zh.json +3 -2
  177. package/package.json +63 -66
  178. package/assets/agents/poteto-agent.md +0 -8
  179. package/assets/docs/harness/dsh.md +0 -60
  180. package/assets/docs/pstack-models.example.md +0 -54
  181. package/assets/skills/arena/SKILL.md +0 -50
  182. package/assets/skills/figure-it-out/SKILL.md +0 -54
  183. package/assets/skills/how/SKILL.md +0 -38
  184. package/assets/skills/interrogate/SKILL.md +0 -71
  185. package/assets/skills/interrogate/references/code-quality-review.md +0 -47
  186. package/assets/skills/interrogate/references/lead-judgment.md +0 -39
  187. package/assets/skills/interrogate/references/reviewer-prompt.md +0 -62
  188. package/assets/skills/interrogate/references/rubric.md +0 -77
  189. package/assets/skills/no-comments/SKILL.md +0 -26
  190. package/assets/skills/poteto-mode/playbooks/authoring-a-skill.md +0 -12
  191. package/assets/skills/poteto-mode/playbooks/autonomous-run.md +0 -15
  192. package/assets/skills/poteto-mode/playbooks/autopilot-full.md +0 -25
  193. package/assets/skills/poteto-mode/playbooks/autopilot-stack.md +0 -12
  194. package/assets/skills/poteto-mode/playbooks/bug-fix.md +0 -15
  195. package/assets/skills/poteto-mode/playbooks/feature.md +0 -21
  196. package/assets/skills/poteto-mode/playbooks/orchestrate.md +0 -112
  197. package/assets/skills/poteto-mode/playbooks/perf-issue.md +0 -25
  198. package/assets/skills/poteto-mode/playbooks/refactoring.md +0 -16
  199. package/assets/skills/poteto-mode/playbooks/runtime-forensics.md +0 -11
  200. package/assets/skills/poteto-mode/playbooks/session-pickup.md +0 -11
  201. package/assets/skills/poteto-mode/playbooks/visual-parity.md +0 -11
  202. package/assets/skills/poteto-mode/playbooks/worktree-cleanup.md +0 -20
  203. package/assets/skills/poteto-mode/scripts/orch/orch.mjs +0 -4282
  204. package/assets/skills/poteto-mode/scripts/orch/orch.test.mjs +0 -2042
  205. package/assets/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +0 -5101
  206. package/assets/skills/poteto-mode/scripts/watch-pr/github.test.mjs +0 -1177
  207. package/assets/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +0 -1441
  208. package/assets/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +0 -4601
  209. package/assets/skills/recall/SKILL.md +0 -37
  210. package/assets/skills/reflect/SKILL.md +0 -69
  211. package/assets/skills/setup-pstack/SKILL.md +0 -67
  212. package/assets/skills/swarm/SKILL.md +0 -43
  213. package/dist/frontmatter-BQX3ekwP.mjs +0 -229
  214. package/dist/frontmatter-BQX3ekwP.mjs.map +0 -1
  215. package/dist/history.d.mts +0 -429
  216. package/dist/history.mjs +0 -1129
  217. package/dist/history.mjs.map +0 -1
  218. package/dist/host-contract-o47JH_r8.d.mts +0 -527
  219. package/dist/index.mjs.map +0 -1
  220. package/dist/paths-D_JlVmBk.mjs +0 -42
  221. package/dist/paths-D_JlVmBk.mjs.map +0 -1
  222. package/dist/script.mjs.map +0 -1
  223. package/dist/subagent.mjs.map +0 -1
  224. /package/{static/icon.png → assets/logo.png} +0 -0
  225. /package/{assets → dist/pstack}/agents/comment-sicko.md +0 -0
  226. /package/{assets → dist/pstack}/docs/guide/03-understand.md +0 -0
  227. /package/{assets → dist/pstack}/docs/guide/08-principles.md +0 -0
  228. /package/{assets → dist/pstack}/docs/guide/images/design.jpg +0 -0
  229. /package/{assets → dist/pstack}/docs/guide/images/overnight.jpg +0 -0
  230. /package/{assets → dist/pstack}/docs/guide/images/recipes.jpg +0 -0
  231. /package/{assets → dist/pstack}/docs/guide/images/router.jpg +0 -0
  232. /package/{assets → dist/pstack}/docs/guide/images/understanding.jpg +0 -0
  233. /package/{assets → dist/pstack}/docs/guide/images/verification.jpg +0 -0
  234. /package/{assets → dist/pstack}/skills/architect/references/design-red-flags.md +0 -0
  235. /package/{assets → dist/pstack}/skills/architect/references/rationale-template.md +0 -0
  236. /package/{assets → dist/pstack}/skills/architect/references/runner-prompt.md +0 -0
  237. /package/{assets → dist/pstack}/skills/bro/SKILL.md +0 -0
  238. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/README.md +0 -0
  239. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/create-note.md +0 -0
  240. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/search.md +0 -0
  241. /package/{assets → dist/pstack}/skills/how/references/explainer-prompt.md +0 -0
  242. /package/{assets → dist/pstack}/skills/how/references/explorer-prompt.md +0 -0
  243. /package/{assets → dist/pstack}/skills/poteto-mode/references/bugbot-triage.md +0 -0
  244. /package/{assets → dist/pstack}/skills/principle-build-the-lever/SKILL.md +0 -0
  245. /package/{assets → dist/pstack}/skills/principle-foundational-thinking/SKILL.md +0 -0
  246. /package/{assets → dist/pstack}/skills/principle-guard-the-context-window/SKILL.md +0 -0
  247. /package/{assets → dist/pstack}/skills/show-me-your-work/references/decision-log-template.tsv +0 -0
  248. /package/{assets → dist/pstack}/skills/typescript-best-practices/references/patterns.md +0 -0
  249. /package/{assets → dist/pstack}/skills/unslop/SKILL.md +0 -0
  250. /package/{assets → dist/pstack}/skills/why/references/epistemics.md +0 -0
  251. /package/{assets → dist/pstack}/skills/why/references/investigator-prompt.md +0 -0
  252. /package/{assets → dist/pstack}/skills/why/references/source-playbook.md +0 -0
  253. /package/{assets → dist/pstack}/skills/why/references/sources/code-archaeology.md +0 -0
  254. /package/{assets → dist/pstack}/skills/why/references/sources/databricks.md +0 -0
  255. /package/{assets → dist/pstack}/skills/why/references/sources/datadog.md +0 -0
  256. /package/{assets → dist/pstack}/skills/why/references/sources/incident-postmortem.md +0 -0
  257. /package/{assets → dist/pstack}/skills/why/references/sources/linear.md +0 -0
  258. /package/{assets → dist/pstack}/skills/why/references/sources/notion.md +0 -0
  259. /package/{assets → dist/pstack}/skills/why/references/sources/sentry.md +0 -0
  260. /package/{assets → dist/pstack}/skills/why/references/sources/slack.md +0 -0
  261. /package/{assets → dist/pstack}/skills/why/references/synthesizer-prompt.md +0 -0
@@ -1,4282 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- import { execFileSync } from "node:child_process";
4
- import { randomUUID } from "node:crypto";
5
- import { access, mkdir, open, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
6
- import { basename, dirname, join, resolve } from "node:path";
7
- //#region \0rolldown/runtime.js
8
- var __create = Object.create;
9
- var __defProp = Object.defineProperty;
10
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
- var __getOwnPropNames = Object.getOwnPropertyNames;
12
- var __getProtoOf = Object.getPrototypeOf;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __esmMin = (fn, res, err) => () => {
15
- if (err) throw err[0];
16
- try {
17
- return fn && (res = fn(fn = 0)), res;
18
- } catch (e) {
19
- throw err = [e], e;
20
- }
21
- };
22
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
23
- var __exportAll = (all, no_symbols) => {
24
- let target = {};
25
- for (var name in all) __defProp(target, name, {
26
- get: all[name],
27
- enumerable: true
28
- });
29
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
30
- return target;
31
- };
32
- var __copyProps = (to, from, except, desc) => {
33
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
34
- key = keys[i];
35
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
36
- get: ((k) => from[k]).bind(null, key),
37
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
38
- });
39
- }
40
- return to;
41
- };
42
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
43
- value: mod,
44
- enumerable: true
45
- }) : target, mod));
46
- var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
47
- //#endregion
48
- //#region .runtime-sources/skills/poteto-mode/scripts/orch/store.ts
49
- const UNIT_HEADER = "id track state branch pr sha brief";
50
- const LEDGER_HEADER = "pr sha verdict evidence verifier ts";
51
- const LOCK_FILE = ".orch.lock";
52
- var UserError = class extends Error {};
53
- var UsageError = class extends UserError {};
54
- var NotFoundError = class extends UserError {
55
- output;
56
- constructor(message, output) {
57
- super(message);
58
- this.output = output;
59
- }
60
- };
61
- function errorCode(error) {
62
- if (error !== null && typeof error === "object" && "code" in error && typeof error.code === "string") return error.code;
63
- return null;
64
- }
65
- function errorMessage(error) {
66
- return error instanceof Error ? error.message : String(error);
67
- }
68
- function isRecord(value) {
69
- return value !== null && typeof value === "object" && !Array.isArray(value);
70
- }
71
- function isUnknownArray(value) {
72
- return Array.isArray(value);
73
- }
74
- function verdictOrNull(value) {
75
- switch (value) {
76
- case "live-ui-verified":
77
- case "unit-test-verified":
78
- case "type-check-only":
79
- case "verifier-blocked":
80
- case "verifier-failed": return value;
81
- default: return null;
82
- }
83
- }
84
- function frontierPrStateOrNull(value) {
85
- switch (value) {
86
- case "OPEN":
87
- case "MERGED":
88
- case "CLOSED": return value;
89
- default: return null;
90
- }
91
- }
92
- function parseVerdict(value) {
93
- const verdict = verdictOrNull(value);
94
- if (verdict === null) throw new UserError("verdict must be live-ui-verified, unit-test-verified, type-check-only, verifier-blocked, or verifier-failed");
95
- return verdict;
96
- }
97
- function cleanCell(value) {
98
- const cleaned = value.replace(/[\t\n\r]/g, " ");
99
- return /^[=+\-@]/.test(cleaned) ? `'${cleaned}` : cleaned;
100
- }
101
- function requiredCell(value, label) {
102
- const cleaned = cleanCell(value);
103
- if (cleaned.trim().length === 0) throw new UserError(`${label} must not be empty`);
104
- return cleaned;
105
- }
106
- function requiredLine(value, label) {
107
- const cleaned = value.replace(/[\n\r]/g, " ").trim();
108
- if (cleaned.length === 0) throw new UserError(`${label} must not be empty`);
109
- return cleaned;
110
- }
111
- function positiveInteger$1(value, label) {
112
- if (!Number.isSafeInteger(value) || value < 1) throw new UserError(`${label} must be a positive integer`);
113
- return value;
114
- }
115
- async function exists(path) {
116
- try {
117
- await access(path);
118
- return true;
119
- } catch (error) {
120
- if (errorCode(error) === "ENOENT") return false;
121
- throw error;
122
- }
123
- }
124
- async function atomicWrite(path, contents) {
125
- const temporary = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
126
- try {
127
- await writeFile(temporary, contents, { flag: "wx" });
128
- await rename(temporary, path);
129
- } finally {
130
- await rm(temporary, { force: true });
131
- }
132
- }
133
- async function writeIfMissing(path, contents) {
134
- if (!await exists(path)) await atomicWrite(path, contents);
135
- }
136
- async function requiredFile(path) {
137
- try {
138
- return await readFile(path, "utf8");
139
- } catch (error) {
140
- if (errorCode(error) === "ENOENT") throw new UserError(`store is not initialized at ${dirname(path)}; run orch init`);
141
- throw error;
142
- }
143
- }
144
- function holderIsDead(holder) {
145
- const pid = Number.parseInt(holder, 10);
146
- if (!Number.isSafeInteger(pid) || pid <= 0 || String(pid) !== holder) return false;
147
- try {
148
- process.kill(pid, 0);
149
- return false;
150
- } catch (error) {
151
- return errorCode(error) === "ESRCH";
152
- }
153
- }
154
- async function acquireLock(store, options) {
155
- const path = join(store, LOCK_FILE);
156
- const pid = String(process.pid);
157
- const create = async () => {
158
- const handle = await open(path, "wx");
159
- await handle.writeFile(`${pid}\n`);
160
- await handle.close();
161
- };
162
- const takeOver = async () => {
163
- await unlink(path);
164
- try {
165
- await create();
166
- } catch (retryError) {
167
- if (errorCode(retryError) === "EEXIST") throw new UserError(`store lock held by pid ${(await readFile(path, "utf8")).trim() || "unknown"}`);
168
- throw retryError;
169
- }
170
- };
171
- try {
172
- await create();
173
- } catch (error) {
174
- if (errorCode(error) !== "EEXIST") throw error;
175
- let holder = "unknown";
176
- try {
177
- holder = (await readFile(path, "utf8")).trim() || "unknown";
178
- } catch {
179
- holder = "unknown";
180
- }
181
- if (holderIsDead(holder)) {
182
- options.onStaleLock?.(holder);
183
- await takeOver();
184
- } else if (options.force) {
185
- options.onLockStolen?.(holder);
186
- await takeOver();
187
- } else throw new UserError(`store lock held by pid ${holder}`);
188
- }
189
- return async () => {
190
- try {
191
- if ((await readFile(path, "utf8")).trim() === pid) await unlink(path);
192
- } catch (error) {
193
- if (errorCode(error) !== "ENOENT") throw error;
194
- }
195
- };
196
- }
197
- async function readTsv(path, header, width) {
198
- const lines = (await requiredFile(path)).replace(/\r/g, "").split("\n");
199
- if (lines.shift() !== header) throw new UserError(`${basename(path)} has an invalid header`);
200
- return lines.filter((value) => value.length > 0).map((value) => {
201
- const cells = value.split(" ");
202
- if (cells.length !== width) throw new UserError(`${basename(path)} has a malformed row`);
203
- return cells;
204
- });
205
- }
206
- async function writeTsv(path, header, rows) {
207
- const body = rows.map((row) => row.map(cleanCell).join(" ")).join("\n");
208
- await atomicWrite(path, `${header}\n${body}${body.length > 0 ? "\n" : ""}`);
209
- }
210
- async function readUnits(store) {
211
- return (await readTsv(join(store, "units.tsv"), UNIT_HEADER, 7)).map((row) => ({
212
- id: row[0] ?? "",
213
- track: row[1] ?? "",
214
- state: row[2] ?? "",
215
- branch: row[3] ?? "",
216
- pr: row[4] ?? "",
217
- sha: row[5] ?? "",
218
- brief: row[6] ?? ""
219
- }));
220
- }
221
- function unitCells(unit) {
222
- return [
223
- unit.id,
224
- unit.track,
225
- unit.state,
226
- unit.branch,
227
- unit.pr,
228
- unit.sha,
229
- unit.brief
230
- ];
231
- }
232
- async function saveUnits(store, rows) {
233
- await writeTsv(join(store, "units.tsv"), UNIT_HEADER, rows.map(unitCells));
234
- }
235
- async function readLedger(store) {
236
- return (await readTsv(join(store, "ledger.tsv"), LEDGER_HEADER, 6)).map((row) => {
237
- const rawVerdict = row[2] ?? "";
238
- const verdict = verdictOrNull(rawVerdict);
239
- if (verdict === null) throw new UserError(`ledger.tsv has invalid verdict ${rawVerdict}`);
240
- return {
241
- pr: row[0] ?? "",
242
- sha: row[1] ?? "",
243
- verdict,
244
- evidence: row[3] ?? "",
245
- verifier: row[4] ?? "",
246
- ts: row[5] ?? ""
247
- };
248
- });
249
- }
250
- function ledgerCells(row) {
251
- return [
252
- row.pr,
253
- row.sha,
254
- row.verdict,
255
- row.evidence,
256
- row.verifier,
257
- row.ts
258
- ];
259
- }
260
- async function saveLedger(store, rows) {
261
- await writeTsv(join(store, "ledger.tsv"), LEDGER_HEADER, rows.map(ledgerCells));
262
- }
263
- function pointerCells(pointer) {
264
- return [
265
- pointer.ts,
266
- pointer.agent,
267
- pointer.unit,
268
- pointer.status,
269
- pointer.report
270
- ];
271
- }
272
- async function readPointers(directory) {
273
- let entries;
274
- try {
275
- entries = await readdir(directory, { withFileTypes: true });
276
- } catch (error) {
277
- if (errorCode(error) === "ENOENT") throw new UserError(`store is not initialized at ${dirname(directory)}; run orch init`);
278
- throw error;
279
- }
280
- const result = [];
281
- const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".tsv")).sort((left, right) => left.name.localeCompare(right.name));
282
- for (const entry of files) {
283
- const raw = (await readFile(join(directory, entry.name), "utf8")).replace(/\r?\n$/, "");
284
- const row = raw.split(" ");
285
- if (/[\r\n]/.test(raw) || row.length !== 5) throw new UserError(`inbox pointer ${entry.name} is malformed`);
286
- result.push({
287
- ts: row[0] ?? "",
288
- agent: row[1] ?? "",
289
- unit: row[2] ?? "",
290
- status: row[3] ?? "",
291
- report: row[4] ?? ""
292
- });
293
- }
294
- return result;
295
- }
296
- function renderGates(rows) {
297
- if (rows.length === 0) return "";
298
- return `# Gates\n\n${rows.map((gate) => {
299
- const answer = gate.kind === "resolved" ? `\n- Answer: ${gate.answer}` : "";
300
- return `## ${gate.id}
301
-
302
- - Status: ${gate.kind}
303
- - Question: ${gate.question}
304
- - Options: ${gate.options}
305
- - Default: ${gate.defaultAnswer}${answer}`;
306
- }).join("\n\n")}\n`;
307
- }
308
- async function readGates(store) {
309
- const raw = (await requiredFile(join(store, "gates.md"))).replace(/\r/g, "").trim();
310
- if (raw.length === 0) return [];
311
- if (!raw.startsWith("# Gates\n\n## ")) throw new UserError("gates.md has an invalid heading");
312
- const result = [];
313
- for (const block of raw.slice(12).split("\n\n## ")) {
314
- const lines = block.split("\n").filter((value) => value.length > 0);
315
- const id = lines.shift() ?? "";
316
- const fields = /* @__PURE__ */ new Map();
317
- for (const value of lines) {
318
- const match = /^- ([^:]+): (.*)$/.exec(value);
319
- if (match === null) throw new UserError(`gates.md has a malformed gate ${id}`);
320
- fields.set(match[1] ?? "", match[2] ?? "");
321
- }
322
- const status = fields.get("Status");
323
- const question = fields.get("Question");
324
- const options = fields.get("Options");
325
- const defaultAnswer = fields.get("Default");
326
- if (id.length === 0 || question === void 0 || options === void 0 || defaultAnswer === void 0) throw new UserError(`gates.md has a malformed gate ${id}`);
327
- if (status === "open") result.push({
328
- kind: "open",
329
- id,
330
- question,
331
- options,
332
- defaultAnswer
333
- });
334
- else if (status === "resolved" && fields.has("Answer")) result.push({
335
- kind: "resolved",
336
- id,
337
- question,
338
- options,
339
- defaultAnswer,
340
- answer: fields.get("Answer") ?? ""
341
- });
342
- else throw new UserError(`gates.md has invalid status ${status ?? ""}`);
343
- }
344
- if (new Set(result.map((gate) => gate.id)).size !== result.length) throw new UserError("gates.md has duplicate gate ids");
345
- return result;
346
- }
347
- function parseFrontier(raw) {
348
- let value;
349
- try {
350
- value = JSON.parse(raw);
351
- } catch {
352
- throw new UserError("frontier.json is not valid JSON");
353
- }
354
- if (!isRecord(value)) throw new UserError("frontier.json must contain an object");
355
- if (Object.keys(value).length === 0) return {
356
- generation: 0,
357
- prs: [],
358
- lowestUnmerged: null
359
- };
360
- if (typeof value.generation !== "number" || !Number.isSafeInteger(value.generation) || value.generation < 0 || !isUnknownArray(value.prs) || !(value.lowestUnmerged === null || typeof value.lowestUnmerged === "number" && Number.isSafeInteger(value.lowestUnmerged))) throw new UserError("frontier.json has an invalid shape");
361
- const prs = [];
362
- for (const row of value.prs) {
363
- const state = isRecord(row) ? frontierPrStateOrNull(row.state) : null;
364
- if (!isRecord(row) || typeof row.pr !== "number" || !Number.isSafeInteger(row.pr) || row.pr < 1 || typeof row.branches !== "string" || row.branches.length === 0 || typeof row.sha !== "string" || state === null) throw new UserError("frontier.json has an invalid PR row");
365
- prs.push({
366
- pr: row.pr,
367
- branches: row.branches,
368
- sha: row.sha,
369
- state
370
- });
371
- }
372
- return {
373
- generation: value.generation,
374
- prs,
375
- lowestUnmerged: value.lowestUnmerged
376
- };
377
- }
378
- async function readFrontier(store) {
379
- return parseFrontier(await requiredFile(join(store, "frontier.json")));
380
- }
381
- async function readStanding(store) {
382
- const raw = (await requiredFile(join(store, "preferences.md"))).replace(/\r/g, "");
383
- if (raw.trim().length === 0) return [];
384
- const result = [];
385
- for (const value of raw.split("\n").filter((item) => item.length > 0)) {
386
- const match = /^([1-9]\d*)\. (.+)$/.exec(value);
387
- const number = Number(match?.[1] ?? 0);
388
- if (match === null || number !== result.length + 1) throw new UserError("preferences.md has malformed numbering");
389
- result.push({
390
- number,
391
- line: match[2] ?? ""
392
- });
393
- }
394
- return result;
395
- }
396
- function countValues(values) {
397
- const result = {};
398
- for (const value of values) result[value] = (result[value] ?? 0) + 1;
399
- return Object.fromEntries(Object.entries(result).sort(([left], [right]) => left.localeCompare(right)));
400
- }
401
- function summarize(unitRows, ledgerRows, currentFrontier, gateRows) {
402
- return {
403
- unitStates: countValues(unitRows.map((unit) => unit.state)),
404
- ledgerVerdicts: countValues(ledgerRows.map((row) => row.verdict)),
405
- frontierGeneration: currentFrontier.generation,
406
- openGateIds: gateRows.filter((gate) => gate.kind === "open").map((gate) => gate.id).sort()
407
- };
408
- }
409
- function countRecord(value) {
410
- if (!isRecord(value)) return null;
411
- const result = {};
412
- for (const [name, count] of Object.entries(value)) {
413
- if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) return null;
414
- result[name] = count;
415
- }
416
- return result;
417
- }
418
- function previousSummary(raw) {
419
- const match = /<!-- orch-summary (.+) -->/.exec(raw);
420
- if (match === null) return null;
421
- let value;
422
- try {
423
- value = JSON.parse(match[1] ?? "");
424
- } catch {
425
- return null;
426
- }
427
- if (!isRecord(value) || typeof value.frontierGeneration !== "number" || !isUnknownArray(value.openGateIds)) return null;
428
- const unitStates = countRecord(value.unitStates);
429
- const ledgerVerdicts = countRecord(value.ledgerVerdicts);
430
- const openGateIds = value.openGateIds.filter((item) => typeof item === "string");
431
- if (unitStates === null || ledgerVerdicts === null || openGateIds.length !== value.openGateIds.length) return null;
432
- return {
433
- unitStates,
434
- ledgerVerdicts,
435
- frontierGeneration: value.frontierGeneration,
436
- openGateIds
437
- };
438
- }
439
- function changed(before, after) {
440
- if (before === null) return "first render";
441
- const result = [];
442
- const groups = [{
443
- label: "units",
444
- oldCounts: before.unitStates,
445
- newCounts: after.unitStates
446
- }, {
447
- label: "ledger",
448
- oldCounts: before.ledgerVerdicts,
449
- newCounts: after.ledgerVerdicts
450
- }];
451
- for (const { label, oldCounts, newCounts } of groups) {
452
- const names = [.../* @__PURE__ */ new Set([...Object.keys(oldCounts), ...Object.keys(newCounts)])].sort();
453
- for (const name of names) {
454
- const oldCount = oldCounts[name] ?? 0;
455
- const newCount = newCounts[name] ?? 0;
456
- if (oldCount !== newCount) result.push(`${label} ${name} ${oldCount}->${newCount}`);
457
- }
458
- }
459
- if (before.frontierGeneration !== after.frontierGeneration) result.push(`frontier generation ${before.frontierGeneration}->${after.frontierGeneration}`);
460
- if (before.openGateIds.join("\0") !== after.openGateIds.join("\0")) result.push(`open gates ${before.openGateIds.length}->${after.openGateIds.length}`);
461
- return result.length === 0 ? "no derived changes" : result.join("; ");
462
- }
463
- function markdown(value) {
464
- return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
465
- }
466
- function table(headers, rows) {
467
- if (rows.length === 0) return "(none)";
468
- return [
469
- `| ${headers.join(" | ")} |`,
470
- `| ${headers.map(() => "---").join(" | ")} |`,
471
- ...rows.map((row) => `| ${row.map(markdown).join(" | ")} |`)
472
- ].join("\n");
473
- }
474
- function statusMarkdown(unitRows, ledgerRows, currentFrontier, gateRows, currentSummary) {
475
- return `# Orchestrate status
476
-
477
- Generated: ${(/* @__PURE__ */ new Date()).toISOString()}
478
-
479
- ## Units
480
-
481
- States: ${countLine$1(currentSummary.unitStates)}
482
-
483
- ${table([
484
- "ID",
485
- "Track",
486
- "State",
487
- "Branch",
488
- "PR",
489
- "SHA",
490
- "Brief"
491
- ], unitRows.map(unitCells))}
492
-
493
- ## Verification ledger
494
-
495
- Verdicts: ${countLine$1(currentSummary.ledgerVerdicts)}
496
-
497
- ${table([
498
- "PR",
499
- "SHA",
500
- "Verdict",
501
- "Evidence",
502
- "Verifier",
503
- "Timestamp"
504
- ], ledgerRows.map(ledgerCells))}
505
-
506
- ## Frontier
507
-
508
- Generation: ${currentFrontier.generation}
509
- Lowest unmerged: ${currentFrontier.lowestUnmerged ?? "none"}
510
-
511
- ${table([
512
- "Branch",
513
- "PR",
514
- "SHA",
515
- "State"
516
- ], currentFrontier.prs.map((row) => [
517
- row.branches,
518
- String(row.pr),
519
- row.sha,
520
- row.state
521
- ]))}
522
-
523
- ## Gates
524
-
525
- ${table([
526
- "ID",
527
- "Status",
528
- "Question",
529
- "Options",
530
- "Default",
531
- "Answer"
532
- ], gateRows.map((gate) => [
533
- gate.id,
534
- gate.kind,
535
- gate.question,
536
- gate.options,
537
- gate.defaultAnswer,
538
- gate.kind === "resolved" ? gate.answer : ""
539
- ]))}
540
-
541
- <!-- orch-summary ${JSON.stringify(currentSummary)} -->
542
- `;
543
- }
544
- function countLine$1(value) {
545
- const entries = Object.entries(value);
546
- return entries.length === 0 ? "none" : entries.map(([name, count]) => `${name}=${count}`).join(", ");
547
- }
548
- const FORGE_PULL_REQUEST_QUERIES = {
549
- gh: {
550
- stateField: "state",
551
- headField: "headRefName",
552
- baseField: "baseRefName",
553
- states: /* @__PURE__ */ new Map([
554
- ["OPEN", "OPEN"],
555
- ["MERGED", "MERGED"],
556
- ["CLOSED", "CLOSED"]
557
- ])
558
- },
559
- origin: {
560
- stateField: "status",
561
- headField: "headRef",
562
- baseField: "baseRef",
563
- states: /* @__PURE__ */ new Map([
564
- ["open", "OPEN"],
565
- ["draft", "OPEN"],
566
- ["merged", "MERGED"],
567
- ["closed", "CLOSED"]
568
- ])
569
- }
570
- };
571
- function parseForge(value) {
572
- if (value === "gh" || value === "origin") return value;
573
- throw new UserError("forge must be gh or origin");
574
- }
575
- function runTool({ command, args, repo }) {
576
- try {
577
- return execFileSync(command, args, {
578
- cwd: repo,
579
- encoding: "utf8",
580
- env: process.env,
581
- stdio: [
582
- "ignore",
583
- "pipe",
584
- "pipe"
585
- ]
586
- });
587
- } catch (error) {
588
- throw new UserError(`${command} ${args.join(" ")} failed: ${errorMessage(error)}`);
589
- }
590
- }
591
- function listPullRequests({ filter, branch, forge, repo }) {
592
- const query = FORGE_PULL_REQUEST_QUERIES[forge];
593
- const command = `${forge} pr list ${filter} ${branch}`;
594
- const raw = runTool({
595
- command: forge,
596
- args: [
597
- "pr",
598
- "list",
599
- filter,
600
- branch,
601
- "--state",
602
- "all",
603
- "--json",
604
- [
605
- "number",
606
- query.stateField,
607
- query.headField,
608
- query.baseField
609
- ].join(",")
610
- ],
611
- repo
612
- });
613
- let value;
614
- try {
615
- value = JSON.parse(raw);
616
- } catch {
617
- throw new UserError(`${command} output is not valid JSON`);
618
- }
619
- if (!isUnknownArray(value)) throw new UserError(`${command} output is not a JSON array`);
620
- return value.map((row) => {
621
- const status = isRecord(row) ? row[query.stateField] : void 0;
622
- const state = typeof status === "string" ? query.states.get(status) ?? null : null;
623
- const head = isRecord(row) ? row[query.headField] : void 0;
624
- const base = isRecord(row) ? row[query.baseField] : void 0;
625
- if (!isRecord(row) || typeof row.number !== "number" || !Number.isSafeInteger(row.number) || row.number < 1 || state === null || typeof head !== "string" || head.length === 0 || typeof base !== "string" || base.length === 0) throw new UserError(`${command} output has an invalid PR row`);
626
- return {
627
- pr: row.number,
628
- state,
629
- branch: head,
630
- base
631
- };
632
- });
633
- }
634
- function branchPullRequest({ branch, forge, repo }) {
635
- const rows = listPullRequests({
636
- filter: "--head",
637
- branch,
638
- forge,
639
- repo
640
- });
641
- const row = rows[0];
642
- if (row === void 0) throw new UserError(`branch ${branch} has no pull request; open one with ${forge} pr create, or resolve the frontier from a branch whose chain is fully submitted`);
643
- if (rows.length > 1) throw new UserError(`branch ${branch} has multiple pull requests (${rows.map((item) => `#${item.pr}`).join(", ")}); close the stale ones first`);
644
- return row;
645
- }
646
- function openChildren({ branch, forge, repo }) {
647
- return listPullRequests({
648
- filter: "--base",
649
- branch,
650
- forge,
651
- repo
652
- }).filter((row) => row.state === "OPEN");
653
- }
654
- function runGit({ args, repo }) {
655
- return runTool({
656
- command: "git",
657
- args,
658
- repo
659
- }).trim();
660
- }
661
- function branchSha({ branch, repo }) {
662
- const sha = runGit({
663
- args: ["rev-parse", branch],
664
- repo
665
- });
666
- if (!/^[0-9a-f]{40,64}$/i.test(sha)) throw new UserError(`git rev-parse ${branch} returned an invalid SHA`);
667
- return sha;
668
- }
669
- function currentBranch(repo) {
670
- return runGit({
671
- args: [
672
- "symbolic-ref",
673
- "--short",
674
- "HEAD"
675
- ],
676
- repo
677
- });
678
- }
679
- function trunkBranch(repo) {
680
- try {
681
- return runGit({
682
- args: [
683
- "symbolic-ref",
684
- "--short",
685
- "refs/remotes/origin/HEAD"
686
- ],
687
- repo
688
- }).replace(/^origin\//, "");
689
- } catch {
690
- return "main";
691
- }
692
- }
693
- function resolveFrontier(repo, forge) {
694
- const trunk = trunkBranch(repo);
695
- const current = currentBranch(repo);
696
- if (current === trunk) return [];
697
- const seen = /* @__PURE__ */ new Set([current]);
698
- let bottom = branchPullRequest({
699
- branch: current,
700
- forge,
701
- repo
702
- });
703
- const chain = [bottom];
704
- while (bottom.base !== trunk) {
705
- if (seen.has(bottom.base)) throw new UserError(`pull request base chain loops at branch ${bottom.base}`);
706
- seen.add(bottom.base);
707
- bottom = branchPullRequest({
708
- branch: bottom.base,
709
- forge,
710
- repo
711
- });
712
- chain.unshift(bottom);
713
- }
714
- let tip = current;
715
- for (;;) {
716
- const children = openChildren({
717
- branch: tip,
718
- forge,
719
- repo
720
- });
721
- const child = children[0];
722
- if (child === void 0) break;
723
- if (children.length > 1) throw new UserError(`stack is not linear: branches ${children.map((row) => row.branch).join(", ")} all target ${tip}`);
724
- if (seen.has(child.branch)) throw new UserError(`pull request base chain loops at branch ${child.branch}`);
725
- seen.add(child.branch);
726
- chain.push(child);
727
- tip = child.branch;
728
- }
729
- if (new Set(chain.map((row) => row.pr)).size !== chain.length) throw new UserError("pull request base chain contains duplicate pull requests");
730
- return chain.map((row) => ({
731
- pr: row.pr,
732
- branches: row.branch,
733
- sha: branchSha({
734
- branch: row.branch,
735
- repo
736
- }),
737
- state: row.state
738
- }));
739
- }
740
- function validateFrontierPin({ actual, expected }) {
741
- if (actual.length === expected.length && actual.every((pr, index) => pr === expected[index])) return;
742
- const actualSet = new Set(actual);
743
- const expectedSet = new Set(expected);
744
- const missing = expected.filter((pr) => !actualSet.has(pr));
745
- const extra = actual.filter((pr) => !expectedSet.has(pr));
746
- const drift = [];
747
- if (missing.length > 0) drift.push(`missing from resolved chain: ${missing.join(",")}`);
748
- if (extra.length > 0) drift.push(`extra in resolved chain: ${extra.join(",")}`);
749
- if (missing.length === 0 && extra.length === 0) drift.push(`order differs: expected ${expected.join(",")}; resolved ${actual.join(",")}`);
750
- throw new UserError(`frontier pin mismatch: ${drift.join("; ")}`);
751
- }
752
- function openStore(directory, options = {}) {
753
- const store = resolve(directory);
754
- let closed = false;
755
- let releaseLock = null;
756
- let lockRequest = null;
757
- const ensureOpen = () => {
758
- if (closed) throw new UserError("store is closed");
759
- };
760
- const ensureLock = async () => {
761
- ensureOpen();
762
- if (releaseLock !== null) return;
763
- if (lockRequest === null) lockRequest = acquireLock(store, options).then((release) => {
764
- releaseLock = release;
765
- });
766
- try {
767
- await lockRequest;
768
- } catch (error) {
769
- lockRequest = null;
770
- throw error;
771
- }
772
- };
773
- const beginWrite = async () => {
774
- ensureOpen();
775
- if (!await exists(store)) throw new UserError(`store is not initialized at ${store}; run orch init`);
776
- await ensureLock();
777
- };
778
- return {
779
- units: {
780
- add: async (params) => {
781
- await beginWrite();
782
- const row = {
783
- id: requiredCell(params.id, "unit id"),
784
- track: requiredCell(params.track, "track"),
785
- state: "pending",
786
- branch: "",
787
- pr: "",
788
- sha: "",
789
- brief: params.brief === void 0 ? "" : requiredCell(params.brief, "brief")
790
- };
791
- const rows = [...await readUnits(store)];
792
- if (rows.some((unit) => unit.id === row.id)) throw new UserError(`unit ${row.id} already exists`);
793
- rows.push(row);
794
- await saveUnits(store, rows);
795
- return row;
796
- },
797
- set: async (params) => {
798
- await beginWrite();
799
- const id = requiredCell(params.id, "unit id");
800
- const state = requiredCell(params.state, "state");
801
- const rows = [...await readUnits(store)];
802
- const index = rows.findIndex((unit) => unit.id === id);
803
- const old = rows[index];
804
- if (index < 0 || old === void 0) throw new NotFoundError(`unit ${id} not found`);
805
- const row = {
806
- ...old,
807
- state,
808
- branch: params.branch === void 0 ? old.branch : requiredCell(params.branch, "branch"),
809
- pr: params.pr === void 0 ? old.pr : String(positiveInteger$1(params.pr, "PR")),
810
- sha: params.sha === void 0 ? old.sha : requiredCell(params.sha, "SHA")
811
- };
812
- rows[index] = row;
813
- await saveUnits(store, rows);
814
- return row;
815
- },
816
- get: async (id) => {
817
- ensureOpen();
818
- const cleanId = requiredCell(id, "unit id");
819
- const row = (await readUnits(store)).find((unit) => unit.id === cleanId);
820
- if (row === void 0) throw new NotFoundError(`unit ${cleanId} not found`);
821
- return row;
822
- },
823
- list: async (params = {}) => {
824
- ensureOpen();
825
- const state = params.state === void 0 ? void 0 : requiredCell(params.state, "state");
826
- const track = params.track === void 0 ? void 0 : requiredCell(params.track, "track");
827
- return (await readUnits(store)).filter((unit) => (state === void 0 || unit.state === state) && (track === void 0 || unit.track === track));
828
- },
829
- counts: async () => {
830
- ensureOpen();
831
- return countValues((await readUnits(store)).map((unit) => unit.state));
832
- }
833
- },
834
- ledger: {
835
- record: async (params) => {
836
- await beginWrite();
837
- const verdict = parseVerdict(params.verdict);
838
- const row = {
839
- pr: String(positiveInteger$1(params.pr, "PR")),
840
- sha: requiredCell(params.sha, "SHA"),
841
- verdict,
842
- evidence: requiredCell(params.evidence, "evidence"),
843
- verifier: params.verifier === void 0 ? "" : requiredCell(params.verifier, "verifier"),
844
- ts: (/* @__PURE__ */ new Date()).toISOString()
845
- };
846
- const rows = [...await readLedger(store)];
847
- const index = rows.findIndex((old) => old.pr === row.pr && old.sha === row.sha);
848
- if (index < 0) rows.push(row);
849
- else rows[index] = row;
850
- await saveLedger(store, rows);
851
- return row;
852
- },
853
- check: async (params) => {
854
- ensureOpen();
855
- const pr = String(positiveInteger$1(params.pr, "PR"));
856
- const sha = requiredCell(params.sha, "SHA");
857
- const row = (await readLedger(store)).find((value) => value.pr === pr && value.sha === sha);
858
- if (row === void 0) throw new NotFoundError("NOT-VERIFIED", {
859
- compact: "NOT-VERIFIED",
860
- json: {
861
- pr,
862
- sha,
863
- verdict: "NOT-VERIFIED"
864
- }
865
- });
866
- return row;
867
- },
868
- summary: async () => {
869
- ensureOpen();
870
- return countValues((await readLedger(store)).map((row) => row.verdict));
871
- }
872
- },
873
- inbox: {
874
- push: async (params) => {
875
- await beginWrite();
876
- const pointer = {
877
- ts: (/* @__PURE__ */ new Date()).toISOString(),
878
- agent: requiredCell(params.agent, "agent"),
879
- unit: requiredCell(params.unit, "unit"),
880
- status: requiredCell(params.status, "status"),
881
- report: params.report === void 0 ? "" : requiredCell(params.report, "report")
882
- };
883
- const inbox = join(store, "inbox");
884
- if (!await exists(inbox)) throw new UserError(`store is not initialized at ${store}; run orch init`);
885
- const filename = `${pointer.ts.replace(/[:.]/g, "-")}-${process.pid}-${randomUUID()}.tsv`;
886
- const contents = `${pointerCells(pointer).map(cleanCell).join(" ")}\n`;
887
- await atomicWrite(join(inbox, filename), contents);
888
- return {
889
- pointer,
890
- filename
891
- };
892
- },
893
- drain: async () => {
894
- await beginWrite();
895
- const inbox = join(store, "inbox");
896
- const rows = await readPointers(inbox);
897
- const drained = join(store, `.inbox-drain-${process.pid}-${randomUUID()}`);
898
- await rename(inbox, drained);
899
- try {
900
- await mkdir(inbox);
901
- } catch (error) {
902
- await rename(drained, inbox);
903
- throw error;
904
- }
905
- await rm(drained, {
906
- recursive: true,
907
- force: true
908
- });
909
- return rows;
910
- },
911
- peek: async () => {
912
- ensureOpen();
913
- return readPointers(join(store, "inbox"));
914
- },
915
- count: async () => {
916
- ensureOpen();
917
- return (await readPointers(join(store, "inbox"))).length;
918
- }
919
- },
920
- gates: {
921
- park: async (params) => {
922
- await beginWrite();
923
- const gate = {
924
- kind: "open",
925
- id: requiredLine(params.id, "gate id"),
926
- question: requiredLine(params.question, "question"),
927
- options: requiredLine(params.options, "options"),
928
- defaultAnswer: requiredLine(params.defaultAnswer, "default")
929
- };
930
- const rows = [...await readGates(store)];
931
- const index = rows.findIndex((old) => old.id === gate.id);
932
- if (index < 0) rows.push(gate);
933
- else rows[index] = gate;
934
- await atomicWrite(join(store, "gates.md"), renderGates(rows));
935
- return gate;
936
- },
937
- list: async () => {
938
- ensureOpen();
939
- return (await readGates(store)).filter((gate) => gate.kind === "open");
940
- },
941
- resolve: async (params) => {
942
- await beginWrite();
943
- const id = requiredLine(params.id, "gate id");
944
- const rows = [...await readGates(store)];
945
- const index = rows.findIndex((gate) => gate.id === id);
946
- const old = rows[index];
947
- if (index < 0 || old === void 0) throw new NotFoundError(`gate ${id} not found`);
948
- const gate = {
949
- kind: "resolved",
950
- id: old.id,
951
- question: old.question,
952
- options: old.options,
953
- defaultAnswer: old.defaultAnswer,
954
- answer: requiredLine(params.answer, "answer")
955
- };
956
- rows[index] = gate;
957
- await atomicWrite(join(store, "gates.md"), renderGates(rows));
958
- return gate;
959
- }
960
- },
961
- frontier: {
962
- set: async (params) => {
963
- await beginWrite();
964
- const repo = resolve(requiredLine(params.repo, "repo directory"));
965
- const forge = parseForge(params.forge ?? "gh");
966
- const pin = params.prs === void 0 ? void 0 : params.prs.map((pr) => positiveInteger$1(pr, "PR"));
967
- if (pin !== void 0 && new Set(pin).size !== pin.length) throw new UserError("--prs must not contain duplicates");
968
- const old = await readFrontier(store);
969
- const prs = resolveFrontier(repo, forge);
970
- if (pin !== void 0) validateFrontierPin({
971
- actual: prs.map((row) => row.pr),
972
- expected: pin
973
- });
974
- const value = {
975
- generation: old.generation + 1,
976
- prs,
977
- lowestUnmerged: prs.find((row) => row.state === "OPEN")?.pr ?? null
978
- };
979
- await atomicWrite(join(store, "frontier.json"), `${JSON.stringify(value, null, 2)}\n`);
980
- return value;
981
- },
982
- show: async () => {
983
- ensureOpen();
984
- return readFrontier(store);
985
- }
986
- },
987
- standing: {
988
- show: async () => {
989
- ensureOpen();
990
- return readStanding(store);
991
- },
992
- add: async (params) => {
993
- await beginWrite();
994
- const rows = [...await readStanding(store)];
995
- const item = {
996
- number: rows.length + 1,
997
- line: requiredLine(params.line, "standing order")
998
- };
999
- rows.push(item);
1000
- await atomicWrite(join(store, "preferences.md"), `${rows.map((row) => `${row.number}. ${row.line}`).join("\n")}\n`);
1001
- return item;
1002
- }
1003
- },
1004
- status: { render: async () => {
1005
- await beginWrite();
1006
- const unitRows = await readUnits(store);
1007
- const ledgerRows = await readLedger(store);
1008
- const currentFrontier = await readFrontier(store);
1009
- const gateRows = await readGates(store);
1010
- const currentSummary = summarize(unitRows, ledgerRows, currentFrontier, gateRows);
1011
- const path = join(store, "status.md");
1012
- const change = changed(await exists(path) ? previousSummary(await readFile(path, "utf8")) : null, currentSummary);
1013
- await atomicWrite(path, statusMarkdown(unitRows, ledgerRows, currentFrontier, gateRows, currentSummary));
1014
- return {
1015
- units: unitRows,
1016
- ledger: ledgerRows,
1017
- frontier: currentFrontier,
1018
- gates: gateRows,
1019
- summary: currentSummary,
1020
- changed: change
1021
- };
1022
- } },
1023
- init: async () => {
1024
- ensureOpen();
1025
- await mkdir(store, { recursive: true });
1026
- await ensureLock();
1027
- await writeIfMissing(join(store, "units.tsv"), `${UNIT_HEADER}\n`);
1028
- await writeIfMissing(join(store, "ledger.tsv"), `${LEDGER_HEADER}\n`);
1029
- await mkdir(join(store, "inbox"), { recursive: true });
1030
- await writeIfMissing(join(store, "gates.md"), "");
1031
- await writeIfMissing(join(store, "preferences.md"), "");
1032
- await writeIfMissing(join(store, "frontier.json"), "{}\n");
1033
- return { store };
1034
- },
1035
- close: async () => {
1036
- if (closed) return;
1037
- if (lockRequest !== null) try {
1038
- await lockRequest;
1039
- } catch {}
1040
- const release = releaseLock;
1041
- releaseLock = null;
1042
- closed = true;
1043
- if (release !== null) await release();
1044
- }
1045
- };
1046
- }
1047
- //#endregion
1048
- //#region vendor/commander/lib/error.js
1049
- var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
1050
- /**
1051
- * CommanderError class
1052
- */
1053
- var CommanderError = class extends Error {
1054
- /**
1055
- * Constructs the CommanderError class
1056
- * @param {number} exitCode suggested exit code which could be used with process.exit
1057
- * @param {string} code an id string representing the error
1058
- * @param {string} message human-readable description of the error
1059
- */
1060
- constructor(exitCode, code, message) {
1061
- super(message);
1062
- Error.captureStackTrace(this, this.constructor);
1063
- this.name = this.constructor.name;
1064
- this.code = code;
1065
- this.exitCode = exitCode;
1066
- this.nestedError = void 0;
1067
- }
1068
- };
1069
- /**
1070
- * InvalidArgumentError class
1071
- */
1072
- var InvalidArgumentError = class extends CommanderError {
1073
- /**
1074
- * Constructs the InvalidArgumentError class
1075
- * @param {string} [message] explanation of why argument is invalid
1076
- */
1077
- constructor(message) {
1078
- super(1, "commander.invalidArgument", message);
1079
- Error.captureStackTrace(this, this.constructor);
1080
- this.name = this.constructor.name;
1081
- }
1082
- };
1083
- exports.CommanderError = CommanderError;
1084
- exports.InvalidArgumentError = InvalidArgumentError;
1085
- }));
1086
- //#endregion
1087
- //#region vendor/commander/lib/argument.js
1088
- var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
1089
- const { InvalidArgumentError } = require_error();
1090
- var Argument = class {
1091
- /**
1092
- * Initialize a new command argument with the given name and description.
1093
- * The default is that the argument is required, and you can explicitly
1094
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1095
- *
1096
- * @param {string} name
1097
- * @param {string} [description]
1098
- */
1099
- constructor(name, description) {
1100
- this.description = description || "";
1101
- this.variadic = false;
1102
- this.parseArg = void 0;
1103
- this.defaultValue = void 0;
1104
- this.defaultValueDescription = void 0;
1105
- this.argChoices = void 0;
1106
- switch (name[0]) {
1107
- case "<":
1108
- this.required = true;
1109
- this._name = name.slice(1, -1);
1110
- break;
1111
- case "[":
1112
- this.required = false;
1113
- this._name = name.slice(1, -1);
1114
- break;
1115
- default:
1116
- this.required = true;
1117
- this._name = name;
1118
- }
1119
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
1120
- this.variadic = true;
1121
- this._name = this._name.slice(0, -3);
1122
- }
1123
- }
1124
- /**
1125
- * Return argument name.
1126
- *
1127
- * @return {string}
1128
- */
1129
- name() {
1130
- return this._name;
1131
- }
1132
- /**
1133
- * @package
1134
- */
1135
- _concatValue(value, previous) {
1136
- if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
1137
- return previous.concat(value);
1138
- }
1139
- /**
1140
- * Set the default value, and optionally supply the description to be displayed in the help.
1141
- *
1142
- * @param {*} value
1143
- * @param {string} [description]
1144
- * @return {Argument}
1145
- */
1146
- default(value, description) {
1147
- this.defaultValue = value;
1148
- this.defaultValueDescription = description;
1149
- return this;
1150
- }
1151
- /**
1152
- * Set the custom handler for processing CLI command arguments into argument values.
1153
- *
1154
- * @param {Function} [fn]
1155
- * @return {Argument}
1156
- */
1157
- argParser(fn) {
1158
- this.parseArg = fn;
1159
- return this;
1160
- }
1161
- /**
1162
- * Only allow argument value to be one of choices.
1163
- *
1164
- * @param {string[]} values
1165
- * @return {Argument}
1166
- */
1167
- choices(values) {
1168
- this.argChoices = values.slice();
1169
- this.parseArg = (arg, previous) => {
1170
- if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
1171
- if (this.variadic) return this._concatValue(arg, previous);
1172
- return arg;
1173
- };
1174
- return this;
1175
- }
1176
- /**
1177
- * Make argument required.
1178
- *
1179
- * @returns {Argument}
1180
- */
1181
- argRequired() {
1182
- this.required = true;
1183
- return this;
1184
- }
1185
- /**
1186
- * Make argument optional.
1187
- *
1188
- * @returns {Argument}
1189
- */
1190
- argOptional() {
1191
- this.required = false;
1192
- return this;
1193
- }
1194
- };
1195
- /**
1196
- * Takes an argument and returns its human readable equivalent for help usage.
1197
- *
1198
- * @param {Argument} arg
1199
- * @return {string}
1200
- * @private
1201
- */
1202
- function humanReadableArgName(arg) {
1203
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
1204
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
1205
- }
1206
- exports.Argument = Argument;
1207
- exports.humanReadableArgName = humanReadableArgName;
1208
- }));
1209
- //#endregion
1210
- //#region vendor/commander/lib/help.js
1211
- var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
1212
- const { humanReadableArgName } = require_argument();
1213
- /**
1214
- * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
1215
- * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
1216
- * @typedef { import("./argument.js").Argument } Argument
1217
- * @typedef { import("./command.js").Command } Command
1218
- * @typedef { import("./option.js").Option } Option
1219
- */
1220
- var Help = class {
1221
- constructor() {
1222
- this.helpWidth = void 0;
1223
- this.minWidthToWrap = 40;
1224
- this.sortSubcommands = false;
1225
- this.sortOptions = false;
1226
- this.showGlobalOptions = false;
1227
- }
1228
- /**
1229
- * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
1230
- * and just before calling `formatHelp()`.
1231
- *
1232
- * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
1233
- *
1234
- * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
1235
- */
1236
- prepareContext(contextOptions) {
1237
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
1238
- }
1239
- /**
1240
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
1241
- *
1242
- * @param {Command} cmd
1243
- * @returns {Command[]}
1244
- */
1245
- visibleCommands(cmd) {
1246
- const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
1247
- const helpCommand = cmd._getHelpCommand();
1248
- if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
1249
- if (this.sortSubcommands) visibleCommands.sort((a, b) => {
1250
- return a.name().localeCompare(b.name());
1251
- });
1252
- return visibleCommands;
1253
- }
1254
- /**
1255
- * Compare options for sort.
1256
- *
1257
- * @param {Option} a
1258
- * @param {Option} b
1259
- * @returns {number}
1260
- */
1261
- compareOptions(a, b) {
1262
- const getSortKey = (option) => {
1263
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
1264
- };
1265
- return getSortKey(a).localeCompare(getSortKey(b));
1266
- }
1267
- /**
1268
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
1269
- *
1270
- * @param {Command} cmd
1271
- * @returns {Option[]}
1272
- */
1273
- visibleOptions(cmd) {
1274
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
1275
- const helpOption = cmd._getHelpOption();
1276
- if (helpOption && !helpOption.hidden) {
1277
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
1278
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
1279
- if (!removeShort && !removeLong) visibleOptions.push(helpOption);
1280
- else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
1281
- else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
1282
- }
1283
- if (this.sortOptions) visibleOptions.sort(this.compareOptions);
1284
- return visibleOptions;
1285
- }
1286
- /**
1287
- * Get an array of the visible global options. (Not including help.)
1288
- *
1289
- * @param {Command} cmd
1290
- * @returns {Option[]}
1291
- */
1292
- visibleGlobalOptions(cmd) {
1293
- if (!this.showGlobalOptions) return [];
1294
- const globalOptions = [];
1295
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1296
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
1297
- globalOptions.push(...visibleOptions);
1298
- }
1299
- if (this.sortOptions) globalOptions.sort(this.compareOptions);
1300
- return globalOptions;
1301
- }
1302
- /**
1303
- * Get an array of the arguments if any have a description.
1304
- *
1305
- * @param {Command} cmd
1306
- * @returns {Argument[]}
1307
- */
1308
- visibleArguments(cmd) {
1309
- if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
1310
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
1311
- });
1312
- if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
1313
- return [];
1314
- }
1315
- /**
1316
- * Get the command term to show in the list of subcommands.
1317
- *
1318
- * @param {Command} cmd
1319
- * @returns {string}
1320
- */
1321
- subcommandTerm(cmd) {
1322
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
1323
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
1324
- }
1325
- /**
1326
- * Get the option term to show in the list of options.
1327
- *
1328
- * @param {Option} option
1329
- * @returns {string}
1330
- */
1331
- optionTerm(option) {
1332
- return option.flags;
1333
- }
1334
- /**
1335
- * Get the argument term to show in the list of arguments.
1336
- *
1337
- * @param {Argument} argument
1338
- * @returns {string}
1339
- */
1340
- argumentTerm(argument) {
1341
- return argument.name();
1342
- }
1343
- /**
1344
- * Get the longest command term length.
1345
- *
1346
- * @param {Command} cmd
1347
- * @param {Help} helper
1348
- * @returns {number}
1349
- */
1350
- longestSubcommandTermLength(cmd, helper) {
1351
- return helper.visibleCommands(cmd).reduce((max, command) => {
1352
- return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
1353
- }, 0);
1354
- }
1355
- /**
1356
- * Get the longest option term length.
1357
- *
1358
- * @param {Command} cmd
1359
- * @param {Help} helper
1360
- * @returns {number}
1361
- */
1362
- longestOptionTermLength(cmd, helper) {
1363
- return helper.visibleOptions(cmd).reduce((max, option) => {
1364
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1365
- }, 0);
1366
- }
1367
- /**
1368
- * Get the longest global option term length.
1369
- *
1370
- * @param {Command} cmd
1371
- * @param {Help} helper
1372
- * @returns {number}
1373
- */
1374
- longestGlobalOptionTermLength(cmd, helper) {
1375
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
1376
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1377
- }, 0);
1378
- }
1379
- /**
1380
- * Get the longest argument term length.
1381
- *
1382
- * @param {Command} cmd
1383
- * @param {Help} helper
1384
- * @returns {number}
1385
- */
1386
- longestArgumentTermLength(cmd, helper) {
1387
- return helper.visibleArguments(cmd).reduce((max, argument) => {
1388
- return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
1389
- }, 0);
1390
- }
1391
- /**
1392
- * Get the command usage to be displayed at the top of the built-in help.
1393
- *
1394
- * @param {Command} cmd
1395
- * @returns {string}
1396
- */
1397
- commandUsage(cmd) {
1398
- let cmdName = cmd._name;
1399
- if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
1400
- let ancestorCmdNames = "";
1401
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
1402
- return ancestorCmdNames + cmdName + " " + cmd.usage();
1403
- }
1404
- /**
1405
- * Get the description for the command.
1406
- *
1407
- * @param {Command} cmd
1408
- * @returns {string}
1409
- */
1410
- commandDescription(cmd) {
1411
- return cmd.description();
1412
- }
1413
- /**
1414
- * Get the subcommand summary to show in the list of subcommands.
1415
- * (Fallback to description for backwards compatibility.)
1416
- *
1417
- * @param {Command} cmd
1418
- * @returns {string}
1419
- */
1420
- subcommandDescription(cmd) {
1421
- return cmd.summary() || cmd.description();
1422
- }
1423
- /**
1424
- * Get the option description to show in the list of options.
1425
- *
1426
- * @param {Option} option
1427
- * @return {string}
1428
- */
1429
- optionDescription(option) {
1430
- const extraInfo = [];
1431
- if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1432
- if (option.defaultValue !== void 0) {
1433
- if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
1434
- }
1435
- if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
1436
- if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
1437
- if (extraInfo.length > 0) {
1438
- const extraDescription = `(${extraInfo.join(", ")})`;
1439
- if (option.description) return `${option.description} ${extraDescription}`;
1440
- return extraDescription;
1441
- }
1442
- return option.description;
1443
- }
1444
- /**
1445
- * Get the argument description to show in the list of arguments.
1446
- *
1447
- * @param {Argument} argument
1448
- * @return {string}
1449
- */
1450
- argumentDescription(argument) {
1451
- const extraInfo = [];
1452
- if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1453
- if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
1454
- if (extraInfo.length > 0) {
1455
- const extraDescription = `(${extraInfo.join(", ")})`;
1456
- if (argument.description) return `${argument.description} ${extraDescription}`;
1457
- return extraDescription;
1458
- }
1459
- return argument.description;
1460
- }
1461
- /**
1462
- * Format a list of items, given a heading and an array of formatted items.
1463
- *
1464
- * @param {string} heading
1465
- * @param {string[]} items
1466
- * @param {Help} helper
1467
- * @returns string[]
1468
- */
1469
- formatItemList(heading, items, helper) {
1470
- if (items.length === 0) return [];
1471
- return [
1472
- helper.styleTitle(heading),
1473
- ...items,
1474
- ""
1475
- ];
1476
- }
1477
- /**
1478
- * Group items by their help group heading.
1479
- *
1480
- * @param {Command[] | Option[]} unsortedItems
1481
- * @param {Command[] | Option[]} visibleItems
1482
- * @param {Function} getGroup
1483
- * @returns {Map<string, Command[] | Option[]>}
1484
- */
1485
- groupItems(unsortedItems, visibleItems, getGroup) {
1486
- const result = /* @__PURE__ */ new Map();
1487
- unsortedItems.forEach((item) => {
1488
- const group = getGroup(item);
1489
- if (!result.has(group)) result.set(group, []);
1490
- });
1491
- visibleItems.forEach((item) => {
1492
- const group = getGroup(item);
1493
- if (!result.has(group)) result.set(group, []);
1494
- result.get(group).push(item);
1495
- });
1496
- return result;
1497
- }
1498
- /**
1499
- * Generate the built-in help text.
1500
- *
1501
- * @param {Command} cmd
1502
- * @param {Help} helper
1503
- * @returns {string}
1504
- */
1505
- formatHelp(cmd, helper) {
1506
- const termWidth = helper.padWidth(cmd, helper);
1507
- const helpWidth = helper.helpWidth ?? 80;
1508
- function callFormatItem(term, description) {
1509
- return helper.formatItem(term, termWidth, description, helper);
1510
- }
1511
- let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
1512
- const commandDescription = helper.commandDescription(cmd);
1513
- if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
1514
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
1515
- return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
1516
- });
1517
- output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
1518
- this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
1519
- const optionList = options.map((option) => {
1520
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
1521
- });
1522
- output = output.concat(this.formatItemList(group, optionList, helper));
1523
- });
1524
- if (helper.showGlobalOptions) {
1525
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
1526
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
1527
- });
1528
- output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
1529
- }
1530
- this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
1531
- const commandList = commands.map((sub) => {
1532
- return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
1533
- });
1534
- output = output.concat(this.formatItemList(group, commandList, helper));
1535
- });
1536
- return output.join("\n");
1537
- }
1538
- /**
1539
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
1540
- *
1541
- * @param {string} str
1542
- * @returns {number}
1543
- */
1544
- displayWidth(str) {
1545
- return stripColor(str).length;
1546
- }
1547
- /**
1548
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
1549
- *
1550
- * @param {string} str
1551
- * @returns {string}
1552
- */
1553
- styleTitle(str) {
1554
- return str;
1555
- }
1556
- styleUsage(str) {
1557
- return str.split(" ").map((word) => {
1558
- if (word === "[options]") return this.styleOptionText(word);
1559
- if (word === "[command]") return this.styleSubcommandText(word);
1560
- if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
1561
- return this.styleCommandText(word);
1562
- }).join(" ");
1563
- }
1564
- styleCommandDescription(str) {
1565
- return this.styleDescriptionText(str);
1566
- }
1567
- styleOptionDescription(str) {
1568
- return this.styleDescriptionText(str);
1569
- }
1570
- styleSubcommandDescription(str) {
1571
- return this.styleDescriptionText(str);
1572
- }
1573
- styleArgumentDescription(str) {
1574
- return this.styleDescriptionText(str);
1575
- }
1576
- styleDescriptionText(str) {
1577
- return str;
1578
- }
1579
- styleOptionTerm(str) {
1580
- return this.styleOptionText(str);
1581
- }
1582
- styleSubcommandTerm(str) {
1583
- return str.split(" ").map((word) => {
1584
- if (word === "[options]") return this.styleOptionText(word);
1585
- if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
1586
- return this.styleSubcommandText(word);
1587
- }).join(" ");
1588
- }
1589
- styleArgumentTerm(str) {
1590
- return this.styleArgumentText(str);
1591
- }
1592
- styleOptionText(str) {
1593
- return str;
1594
- }
1595
- styleArgumentText(str) {
1596
- return str;
1597
- }
1598
- styleSubcommandText(str) {
1599
- return str;
1600
- }
1601
- styleCommandText(str) {
1602
- return str;
1603
- }
1604
- /**
1605
- * Calculate the pad width from the maximum term length.
1606
- *
1607
- * @param {Command} cmd
1608
- * @param {Help} helper
1609
- * @returns {number}
1610
- */
1611
- padWidth(cmd, helper) {
1612
- return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
1613
- }
1614
- /**
1615
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
1616
- *
1617
- * @param {string} str
1618
- * @returns {boolean}
1619
- */
1620
- preformatted(str) {
1621
- return /\n[^\S\r\n]/.test(str);
1622
- }
1623
- /**
1624
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
1625
- *
1626
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
1627
- * TTT DDD DDDD
1628
- * DD DDD
1629
- *
1630
- * @param {string} term
1631
- * @param {number} termWidth
1632
- * @param {string} description
1633
- * @param {Help} helper
1634
- * @returns {string}
1635
- */
1636
- formatItem(term, termWidth, description, helper) {
1637
- const itemIndent = 2;
1638
- const itemIndentStr = " ".repeat(itemIndent);
1639
- if (!description) return itemIndentStr + term;
1640
- const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
1641
- const spacerWidth = 2;
1642
- const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
1643
- let formattedDescription;
1644
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
1645
- else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
1646
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
1647
- }
1648
- /**
1649
- * Wrap a string at whitespace, preserving existing line breaks.
1650
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
1651
- *
1652
- * @param {string} str
1653
- * @param {number} width
1654
- * @returns {string}
1655
- */
1656
- boxWrap(str, width) {
1657
- if (width < this.minWidthToWrap) return str;
1658
- const rawLines = str.split(/\r\n|\n/);
1659
- const chunkPattern = /[\s]*[^\s]+/g;
1660
- const wrappedLines = [];
1661
- rawLines.forEach((line) => {
1662
- const chunks = line.match(chunkPattern);
1663
- if (chunks === null) {
1664
- wrappedLines.push("");
1665
- return;
1666
- }
1667
- let sumChunks = [chunks.shift()];
1668
- let sumWidth = this.displayWidth(sumChunks[0]);
1669
- chunks.forEach((chunk) => {
1670
- const visibleWidth = this.displayWidth(chunk);
1671
- if (sumWidth + visibleWidth <= width) {
1672
- sumChunks.push(chunk);
1673
- sumWidth += visibleWidth;
1674
- return;
1675
- }
1676
- wrappedLines.push(sumChunks.join(""));
1677
- const nextChunk = chunk.trimStart();
1678
- sumChunks = [nextChunk];
1679
- sumWidth = this.displayWidth(nextChunk);
1680
- });
1681
- wrappedLines.push(sumChunks.join(""));
1682
- });
1683
- return wrappedLines.join("\n");
1684
- }
1685
- };
1686
- /**
1687
- * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
1688
- *
1689
- * @param {string} str
1690
- * @returns {string}
1691
- * @package
1692
- */
1693
- function stripColor(str) {
1694
- return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
1695
- }
1696
- exports.Help = Help;
1697
- exports.stripColor = stripColor;
1698
- }));
1699
- //#endregion
1700
- //#region vendor/commander/lib/option.js
1701
- var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
1702
- const { InvalidArgumentError } = require_error();
1703
- var Option = class {
1704
- /**
1705
- * Initialize a new `Option` with the given `flags` and `description`.
1706
- *
1707
- * @param {string} flags
1708
- * @param {string} [description]
1709
- */
1710
- constructor(flags, description) {
1711
- this.flags = flags;
1712
- this.description = description || "";
1713
- this.required = flags.includes("<");
1714
- this.optional = flags.includes("[");
1715
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1716
- this.mandatory = false;
1717
- const optionFlags = splitOptionFlags(flags);
1718
- this.short = optionFlags.shortFlag;
1719
- this.long = optionFlags.longFlag;
1720
- this.negate = false;
1721
- if (this.long) this.negate = this.long.startsWith("--no-");
1722
- this.defaultValue = void 0;
1723
- this.defaultValueDescription = void 0;
1724
- this.presetArg = void 0;
1725
- this.envVar = void 0;
1726
- this.parseArg = void 0;
1727
- this.hidden = false;
1728
- this.argChoices = void 0;
1729
- this.conflictsWith = [];
1730
- this.implied = void 0;
1731
- this.helpGroupHeading = void 0;
1732
- }
1733
- /**
1734
- * Set the default value, and optionally supply the description to be displayed in the help.
1735
- *
1736
- * @param {*} value
1737
- * @param {string} [description]
1738
- * @return {Option}
1739
- */
1740
- default(value, description) {
1741
- this.defaultValue = value;
1742
- this.defaultValueDescription = description;
1743
- return this;
1744
- }
1745
- /**
1746
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1747
- * The custom processing (parseArg) is called.
1748
- *
1749
- * @example
1750
- * new Option('--color').default('GREYSCALE').preset('RGB');
1751
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1752
- *
1753
- * @param {*} arg
1754
- * @return {Option}
1755
- */
1756
- preset(arg) {
1757
- this.presetArg = arg;
1758
- return this;
1759
- }
1760
- /**
1761
- * Add option name(s) that conflict with this option.
1762
- * An error will be displayed if conflicting options are found during parsing.
1763
- *
1764
- * @example
1765
- * new Option('--rgb').conflicts('cmyk');
1766
- * new Option('--js').conflicts(['ts', 'jsx']);
1767
- *
1768
- * @param {(string | string[])} names
1769
- * @return {Option}
1770
- */
1771
- conflicts(names) {
1772
- this.conflictsWith = this.conflictsWith.concat(names);
1773
- return this;
1774
- }
1775
- /**
1776
- * Specify implied option values for when this option is set and the implied options are not.
1777
- *
1778
- * The custom processing (parseArg) is not called on the implied values.
1779
- *
1780
- * @example
1781
- * program
1782
- * .addOption(new Option('--log', 'write logging information to file'))
1783
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1784
- *
1785
- * @param {object} impliedOptionValues
1786
- * @return {Option}
1787
- */
1788
- implies(impliedOptionValues) {
1789
- let newImplied = impliedOptionValues;
1790
- if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
1791
- this.implied = Object.assign(this.implied || {}, newImplied);
1792
- return this;
1793
- }
1794
- /**
1795
- * Set environment variable to check for option value.
1796
- *
1797
- * An environment variable is only used if when processed the current option value is
1798
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1799
- *
1800
- * @param {string} name
1801
- * @return {Option}
1802
- */
1803
- env(name) {
1804
- this.envVar = name;
1805
- return this;
1806
- }
1807
- /**
1808
- * Set the custom handler for processing CLI option arguments into option values.
1809
- *
1810
- * @param {Function} [fn]
1811
- * @return {Option}
1812
- */
1813
- argParser(fn) {
1814
- this.parseArg = fn;
1815
- return this;
1816
- }
1817
- /**
1818
- * Whether the option is mandatory and must have a value after parsing.
1819
- *
1820
- * @param {boolean} [mandatory=true]
1821
- * @return {Option}
1822
- */
1823
- makeOptionMandatory(mandatory = true) {
1824
- this.mandatory = !!mandatory;
1825
- return this;
1826
- }
1827
- /**
1828
- * Hide option in help.
1829
- *
1830
- * @param {boolean} [hide=true]
1831
- * @return {Option}
1832
- */
1833
- hideHelp(hide = true) {
1834
- this.hidden = !!hide;
1835
- return this;
1836
- }
1837
- /**
1838
- * @package
1839
- */
1840
- _concatValue(value, previous) {
1841
- if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
1842
- return previous.concat(value);
1843
- }
1844
- /**
1845
- * Only allow option value to be one of choices.
1846
- *
1847
- * @param {string[]} values
1848
- * @return {Option}
1849
- */
1850
- choices(values) {
1851
- this.argChoices = values.slice();
1852
- this.parseArg = (arg, previous) => {
1853
- if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
1854
- if (this.variadic) return this._concatValue(arg, previous);
1855
- return arg;
1856
- };
1857
- return this;
1858
- }
1859
- /**
1860
- * Return option name.
1861
- *
1862
- * @return {string}
1863
- */
1864
- name() {
1865
- if (this.long) return this.long.replace(/^--/, "");
1866
- return this.short.replace(/^-/, "");
1867
- }
1868
- /**
1869
- * Return option name, in a camelcase format that can be used
1870
- * as an object attribute key.
1871
- *
1872
- * @return {string}
1873
- */
1874
- attributeName() {
1875
- if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
1876
- return camelcase(this.name());
1877
- }
1878
- /**
1879
- * Set the help group heading.
1880
- *
1881
- * @param {string} heading
1882
- * @return {Option}
1883
- */
1884
- helpGroup(heading) {
1885
- this.helpGroupHeading = heading;
1886
- return this;
1887
- }
1888
- /**
1889
- * Check if `arg` matches the short or long flag.
1890
- *
1891
- * @param {string} arg
1892
- * @return {boolean}
1893
- * @package
1894
- */
1895
- is(arg) {
1896
- return this.short === arg || this.long === arg;
1897
- }
1898
- /**
1899
- * Return whether a boolean option.
1900
- *
1901
- * Options are one of boolean, negated, required argument, or optional argument.
1902
- *
1903
- * @return {boolean}
1904
- * @package
1905
- */
1906
- isBoolean() {
1907
- return !this.required && !this.optional && !this.negate;
1908
- }
1909
- };
1910
- /**
1911
- * This class is to make it easier to work with dual options, without changing the existing
1912
- * implementation. We support separate dual options for separate positive and negative options,
1913
- * like `--build` and `--no-build`, which share a single option value. This works nicely for some
1914
- * use cases, but is tricky for others where we want separate behaviours despite
1915
- * the single shared option value.
1916
- */
1917
- var DualOptions = class {
1918
- /**
1919
- * @param {Option[]} options
1920
- */
1921
- constructor(options) {
1922
- this.positiveOptions = /* @__PURE__ */ new Map();
1923
- this.negativeOptions = /* @__PURE__ */ new Map();
1924
- this.dualOptions = /* @__PURE__ */ new Set();
1925
- options.forEach((option) => {
1926
- if (option.negate) this.negativeOptions.set(option.attributeName(), option);
1927
- else this.positiveOptions.set(option.attributeName(), option);
1928
- });
1929
- this.negativeOptions.forEach((value, key) => {
1930
- if (this.positiveOptions.has(key)) this.dualOptions.add(key);
1931
- });
1932
- }
1933
- /**
1934
- * Did the value come from the option, and not from possible matching dual option?
1935
- *
1936
- * @param {*} value
1937
- * @param {Option} option
1938
- * @returns {boolean}
1939
- */
1940
- valueFromOption(value, option) {
1941
- const optionKey = option.attributeName();
1942
- if (!this.dualOptions.has(optionKey)) return true;
1943
- const preset = this.negativeOptions.get(optionKey).presetArg;
1944
- const negativeValue = preset !== void 0 ? preset : false;
1945
- return option.negate === (negativeValue === value);
1946
- }
1947
- };
1948
- /**
1949
- * Convert string from kebab-case to camelCase.
1950
- *
1951
- * @param {string} str
1952
- * @return {string}
1953
- * @private
1954
- */
1955
- function camelcase(str) {
1956
- return str.split("-").reduce((str, word) => {
1957
- return str + word[0].toUpperCase() + word.slice(1);
1958
- });
1959
- }
1960
- /**
1961
- * Split the short and long flag out of something like '-m,--mixed <value>'
1962
- *
1963
- * @private
1964
- */
1965
- function splitOptionFlags(flags) {
1966
- let shortFlag;
1967
- let longFlag;
1968
- const shortFlagExp = /^-[^-]$/;
1969
- const longFlagExp = /^--[^-]/;
1970
- const flagParts = flags.split(/[ |,]+/).concat("guard");
1971
- if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1972
- if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1973
- if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1974
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
1975
- shortFlag = longFlag;
1976
- longFlag = flagParts.shift();
1977
- }
1978
- if (flagParts[0].startsWith("-")) {
1979
- const unsupportedFlag = flagParts[0];
1980
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1981
- if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
1982
- - a short flag is a single dash and a single character
1983
- - either use a single dash and a single character (for a short flag)
1984
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
1985
- if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1986
- - too many short flags`);
1987
- if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1988
- - too many long flags`);
1989
- throw new Error(`${baseError}
1990
- - unrecognised flag format`);
1991
- }
1992
- if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
1993
- return {
1994
- shortFlag,
1995
- longFlag
1996
- };
1997
- }
1998
- exports.Option = Option;
1999
- exports.DualOptions = DualOptions;
2000
- }));
2001
- //#endregion
2002
- //#region vendor/commander/lib/suggestSimilar.js
2003
- var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
2004
- const maxDistance = 3;
2005
- function editDistance(a, b) {
2006
- if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
2007
- const d = [];
2008
- for (let i = 0; i <= a.length; i++) d[i] = [i];
2009
- for (let j = 0; j <= b.length; j++) d[0][j] = j;
2010
- for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
2011
- let cost = 1;
2012
- if (a[i - 1] === b[j - 1]) cost = 0;
2013
- else cost = 1;
2014
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
2015
- 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);
2016
- }
2017
- return d[a.length][b.length];
2018
- }
2019
- /**
2020
- * Find close matches, restricted to same number of edits.
2021
- *
2022
- * @param {string} word
2023
- * @param {string[]} candidates
2024
- * @returns {string}
2025
- */
2026
- function suggestSimilar(word, candidates) {
2027
- if (!candidates || candidates.length === 0) return "";
2028
- candidates = Array.from(new Set(candidates));
2029
- const searchingOptions = word.startsWith("--");
2030
- if (searchingOptions) {
2031
- word = word.slice(2);
2032
- candidates = candidates.map((candidate) => candidate.slice(2));
2033
- }
2034
- let similar = [];
2035
- let bestDistance = maxDistance;
2036
- const minSimilarity = .4;
2037
- candidates.forEach((candidate) => {
2038
- if (candidate.length <= 1) return;
2039
- const distance = editDistance(word, candidate);
2040
- const length = Math.max(word.length, candidate.length);
2041
- if ((length - distance) / length > minSimilarity) {
2042
- if (distance < bestDistance) {
2043
- bestDistance = distance;
2044
- similar = [candidate];
2045
- } else if (distance === bestDistance) similar.push(candidate);
2046
- }
2047
- });
2048
- similar.sort((a, b) => a.localeCompare(b));
2049
- if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
2050
- if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
2051
- if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
2052
- return "";
2053
- }
2054
- exports.suggestSimilar = suggestSimilar;
2055
- }));
2056
- //#endregion
2057
- //#region vendor/commander/lib/command.js
2058
- var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
2059
- const EventEmitter = __require("node:events").EventEmitter;
2060
- const childProcess = __require("node:child_process");
2061
- const path = __require("node:path");
2062
- const fs = __require("node:fs");
2063
- const process = __require("node:process");
2064
- const { Argument, humanReadableArgName } = require_argument();
2065
- const { CommanderError } = require_error();
2066
- const { Help, stripColor } = require_help();
2067
- const { Option, DualOptions } = require_option();
2068
- const { suggestSimilar } = require_suggestSimilar();
2069
- var Command = class Command extends EventEmitter {
2070
- /**
2071
- * Initialize a new `Command`.
2072
- *
2073
- * @param {string} [name]
2074
- */
2075
- constructor(name) {
2076
- super();
2077
- /** @type {Command[]} */
2078
- this.commands = [];
2079
- /** @type {Option[]} */
2080
- this.options = [];
2081
- this.parent = null;
2082
- this._allowUnknownOption = false;
2083
- this._allowExcessArguments = false;
2084
- /** @type {Argument[]} */
2085
- this.registeredArguments = [];
2086
- this._args = this.registeredArguments;
2087
- /** @type {string[]} */
2088
- this.args = [];
2089
- this.rawArgs = [];
2090
- this.processedArgs = [];
2091
- this._scriptPath = null;
2092
- this._name = name || "";
2093
- this._optionValues = {};
2094
- this._optionValueSources = {};
2095
- this._storeOptionsAsProperties = false;
2096
- this._actionHandler = null;
2097
- this._executableHandler = false;
2098
- this._executableFile = null;
2099
- this._executableDir = null;
2100
- this._defaultCommandName = null;
2101
- this._exitCallback = null;
2102
- this._aliases = [];
2103
- this._combineFlagAndOptionalValue = true;
2104
- this._description = "";
2105
- this._summary = "";
2106
- this._argsDescription = void 0;
2107
- this._enablePositionalOptions = false;
2108
- this._passThroughOptions = false;
2109
- this._lifeCycleHooks = {};
2110
- /** @type {(boolean | string)} */
2111
- this._showHelpAfterError = false;
2112
- this._showSuggestionAfterError = true;
2113
- this._savedState = null;
2114
- this._outputConfiguration = {
2115
- writeOut: (str) => process.stdout.write(str),
2116
- writeErr: (str) => process.stderr.write(str),
2117
- outputError: (str, write) => write(str),
2118
- getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
2119
- getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
2120
- getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
2121
- getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
2122
- stripColor: (str) => stripColor(str)
2123
- };
2124
- this._hidden = false;
2125
- /** @type {(Option | null | undefined)} */
2126
- this._helpOption = void 0;
2127
- this._addImplicitHelpCommand = void 0;
2128
- /** @type {Command} */
2129
- this._helpCommand = void 0;
2130
- this._helpConfiguration = {};
2131
- /** @type {string | undefined} */
2132
- this._helpGroupHeading = void 0;
2133
- /** @type {string | undefined} */
2134
- this._defaultCommandGroup = void 0;
2135
- /** @type {string | undefined} */
2136
- this._defaultOptionGroup = void 0;
2137
- }
2138
- /**
2139
- * Copy settings that are useful to have in common across root command and subcommands.
2140
- *
2141
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
2142
- *
2143
- * @param {Command} sourceCommand
2144
- * @return {Command} `this` command for chaining
2145
- */
2146
- copyInheritedSettings(sourceCommand) {
2147
- this._outputConfiguration = sourceCommand._outputConfiguration;
2148
- this._helpOption = sourceCommand._helpOption;
2149
- this._helpCommand = sourceCommand._helpCommand;
2150
- this._helpConfiguration = sourceCommand._helpConfiguration;
2151
- this._exitCallback = sourceCommand._exitCallback;
2152
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
2153
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
2154
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
2155
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
2156
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
2157
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
2158
- return this;
2159
- }
2160
- /**
2161
- * @returns {Command[]}
2162
- * @private
2163
- */
2164
- _getCommandAndAncestors() {
2165
- const result = [];
2166
- for (let command = this; command; command = command.parent) result.push(command);
2167
- return result;
2168
- }
2169
- /**
2170
- * Define a command.
2171
- *
2172
- * There are two styles of command: pay attention to where to put the description.
2173
- *
2174
- * @example
2175
- * // Command implemented using action handler (description is supplied separately to `.command`)
2176
- * program
2177
- * .command('clone <source> [destination]')
2178
- * .description('clone a repository into a newly created directory')
2179
- * .action((source, destination) => {
2180
- * console.log('clone command called');
2181
- * });
2182
- *
2183
- * // Command implemented using separate executable file (description is second parameter to `.command`)
2184
- * program
2185
- * .command('start <service>', 'start named service')
2186
- * .command('stop [service]', 'stop named service, or all if no name supplied');
2187
- *
2188
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
2189
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
2190
- * @param {object} [execOpts] - configuration options (for executable)
2191
- * @return {Command} returns new command for action handler, or `this` for executable command
2192
- */
2193
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
2194
- let desc = actionOptsOrExecDesc;
2195
- let opts = execOpts;
2196
- if (typeof desc === "object" && desc !== null) {
2197
- opts = desc;
2198
- desc = null;
2199
- }
2200
- opts = opts || {};
2201
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
2202
- const cmd = this.createCommand(name);
2203
- if (desc) {
2204
- cmd.description(desc);
2205
- cmd._executableHandler = true;
2206
- }
2207
- if (opts.isDefault) this._defaultCommandName = cmd._name;
2208
- cmd._hidden = !!(opts.noHelp || opts.hidden);
2209
- cmd._executableFile = opts.executableFile || null;
2210
- if (args) cmd.arguments(args);
2211
- this._registerCommand(cmd);
2212
- cmd.parent = this;
2213
- cmd.copyInheritedSettings(this);
2214
- if (desc) return this;
2215
- return cmd;
2216
- }
2217
- /**
2218
- * Factory routine to create a new unattached command.
2219
- *
2220
- * See .command() for creating an attached subcommand, which uses this routine to
2221
- * create the command. You can override createCommand to customise subcommands.
2222
- *
2223
- * @param {string} [name]
2224
- * @return {Command} new command
2225
- */
2226
- createCommand(name) {
2227
- return new Command(name);
2228
- }
2229
- /**
2230
- * You can customise the help with a subclass of Help by overriding createHelp,
2231
- * or by overriding Help properties using configureHelp().
2232
- *
2233
- * @return {Help}
2234
- */
2235
- createHelp() {
2236
- return Object.assign(new Help(), this.configureHelp());
2237
- }
2238
- /**
2239
- * You can customise the help by overriding Help properties using configureHelp(),
2240
- * or with a subclass of Help by overriding createHelp().
2241
- *
2242
- * @param {object} [configuration] - configuration options
2243
- * @return {(Command | object)} `this` command for chaining, or stored configuration
2244
- */
2245
- configureHelp(configuration) {
2246
- if (configuration === void 0) return this._helpConfiguration;
2247
- this._helpConfiguration = configuration;
2248
- return this;
2249
- }
2250
- /**
2251
- * The default output goes to stdout and stderr. You can customise this for special
2252
- * applications. You can also customise the display of errors by overriding outputError.
2253
- *
2254
- * The configuration properties are all functions:
2255
- *
2256
- * // change how output being written, defaults to stdout and stderr
2257
- * writeOut(str)
2258
- * writeErr(str)
2259
- * // change how output being written for errors, defaults to writeErr
2260
- * outputError(str, write) // used for displaying errors and not used for displaying help
2261
- * // specify width for wrapping help
2262
- * getOutHelpWidth()
2263
- * getErrHelpWidth()
2264
- * // color support, currently only used with Help
2265
- * getOutHasColors()
2266
- * getErrHasColors()
2267
- * stripColor() // used to remove ANSI escape codes if output does not have colors
2268
- *
2269
- * @param {object} [configuration] - configuration options
2270
- * @return {(Command | object)} `this` command for chaining, or stored configuration
2271
- */
2272
- configureOutput(configuration) {
2273
- if (configuration === void 0) return this._outputConfiguration;
2274
- this._outputConfiguration = Object.assign({}, this._outputConfiguration, configuration);
2275
- return this;
2276
- }
2277
- /**
2278
- * Display the help or a custom message after an error occurs.
2279
- *
2280
- * @param {(boolean|string)} [displayHelp]
2281
- * @return {Command} `this` command for chaining
2282
- */
2283
- showHelpAfterError(displayHelp = true) {
2284
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
2285
- this._showHelpAfterError = displayHelp;
2286
- return this;
2287
- }
2288
- /**
2289
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
2290
- *
2291
- * @param {boolean} [displaySuggestion]
2292
- * @return {Command} `this` command for chaining
2293
- */
2294
- showSuggestionAfterError(displaySuggestion = true) {
2295
- this._showSuggestionAfterError = !!displaySuggestion;
2296
- return this;
2297
- }
2298
- /**
2299
- * Add a prepared subcommand.
2300
- *
2301
- * See .command() for creating an attached subcommand which inherits settings from its parent.
2302
- *
2303
- * @param {Command} cmd - new subcommand
2304
- * @param {object} [opts] - configuration options
2305
- * @return {Command} `this` command for chaining
2306
- */
2307
- addCommand(cmd, opts) {
2308
- if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
2309
- - specify the name in Command constructor or using .name()`);
2310
- opts = opts || {};
2311
- if (opts.isDefault) this._defaultCommandName = cmd._name;
2312
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
2313
- this._registerCommand(cmd);
2314
- cmd.parent = this;
2315
- cmd._checkForBrokenPassThrough();
2316
- return this;
2317
- }
2318
- /**
2319
- * Factory routine to create a new unattached argument.
2320
- *
2321
- * See .argument() for creating an attached argument, which uses this routine to
2322
- * create the argument. You can override createArgument to return a custom argument.
2323
- *
2324
- * @param {string} name
2325
- * @param {string} [description]
2326
- * @return {Argument} new argument
2327
- */
2328
- createArgument(name, description) {
2329
- return new Argument(name, description);
2330
- }
2331
- /**
2332
- * Define argument syntax for command.
2333
- *
2334
- * The default is that the argument is required, and you can explicitly
2335
- * indicate this with <> around the name. Put [] around the name for an optional argument.
2336
- *
2337
- * @example
2338
- * program.argument('<input-file>');
2339
- * program.argument('[output-file]');
2340
- *
2341
- * @param {string} name
2342
- * @param {string} [description]
2343
- * @param {(Function|*)} [parseArg] - custom argument processing function or default value
2344
- * @param {*} [defaultValue]
2345
- * @return {Command} `this` command for chaining
2346
- */
2347
- argument(name, description, parseArg, defaultValue) {
2348
- const argument = this.createArgument(name, description);
2349
- if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
2350
- else argument.default(parseArg);
2351
- this.addArgument(argument);
2352
- return this;
2353
- }
2354
- /**
2355
- * Define argument syntax for command, adding multiple at once (without descriptions).
2356
- *
2357
- * See also .argument().
2358
- *
2359
- * @example
2360
- * program.arguments('<cmd> [env]');
2361
- *
2362
- * @param {string} names
2363
- * @return {Command} `this` command for chaining
2364
- */
2365
- arguments(names) {
2366
- names.trim().split(/ +/).forEach((detail) => {
2367
- this.argument(detail);
2368
- });
2369
- return this;
2370
- }
2371
- /**
2372
- * Define argument syntax for command, adding a prepared argument.
2373
- *
2374
- * @param {Argument} argument
2375
- * @return {Command} `this` command for chaining
2376
- */
2377
- addArgument(argument) {
2378
- const previousArgument = this.registeredArguments.slice(-1)[0];
2379
- if (previousArgument && previousArgument.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
2380
- 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()}'`);
2381
- this.registeredArguments.push(argument);
2382
- return this;
2383
- }
2384
- /**
2385
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
2386
- *
2387
- * @example
2388
- * program.helpCommand('help [cmd]');
2389
- * program.helpCommand('help [cmd]', 'show help');
2390
- * program.helpCommand(false); // suppress default help command
2391
- * program.helpCommand(true); // add help command even if no subcommands
2392
- *
2393
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
2394
- * @param {string} [description] - custom description
2395
- * @return {Command} `this` command for chaining
2396
- */
2397
- helpCommand(enableOrNameAndArgs, description) {
2398
- if (typeof enableOrNameAndArgs === "boolean") {
2399
- this._addImplicitHelpCommand = enableOrNameAndArgs;
2400
- if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
2401
- return this;
2402
- }
2403
- const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
2404
- const helpDescription = description ?? "display help for command";
2405
- const helpCommand = this.createCommand(helpName);
2406
- helpCommand.helpOption(false);
2407
- if (helpArgs) helpCommand.arguments(helpArgs);
2408
- if (helpDescription) helpCommand.description(helpDescription);
2409
- this._addImplicitHelpCommand = true;
2410
- this._helpCommand = helpCommand;
2411
- if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
2412
- return this;
2413
- }
2414
- /**
2415
- * Add prepared custom help command.
2416
- *
2417
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
2418
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
2419
- * @return {Command} `this` command for chaining
2420
- */
2421
- addHelpCommand(helpCommand, deprecatedDescription) {
2422
- if (typeof helpCommand !== "object") {
2423
- this.helpCommand(helpCommand, deprecatedDescription);
2424
- return this;
2425
- }
2426
- this._addImplicitHelpCommand = true;
2427
- this._helpCommand = helpCommand;
2428
- this._initCommandGroup(helpCommand);
2429
- return this;
2430
- }
2431
- /**
2432
- * Lazy create help command.
2433
- *
2434
- * @return {(Command|null)}
2435
- * @package
2436
- */
2437
- _getHelpCommand() {
2438
- if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
2439
- if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
2440
- return this._helpCommand;
2441
- }
2442
- return null;
2443
- }
2444
- /**
2445
- * Add hook for life cycle event.
2446
- *
2447
- * @param {string} event
2448
- * @param {Function} listener
2449
- * @return {Command} `this` command for chaining
2450
- */
2451
- hook(event, listener) {
2452
- const allowedValues = [
2453
- "preSubcommand",
2454
- "preAction",
2455
- "postAction"
2456
- ];
2457
- if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
2458
- Expecting one of '${allowedValues.join("', '")}'`);
2459
- if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
2460
- else this._lifeCycleHooks[event] = [listener];
2461
- return this;
2462
- }
2463
- /**
2464
- * Register callback to use as replacement for calling process.exit.
2465
- *
2466
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
2467
- * @return {Command} `this` command for chaining
2468
- */
2469
- exitOverride(fn) {
2470
- if (fn) this._exitCallback = fn;
2471
- else this._exitCallback = (err) => {
2472
- if (err.code !== "commander.executeSubCommandAsync") throw err;
2473
- };
2474
- return this;
2475
- }
2476
- /**
2477
- * Call process.exit, and _exitCallback if defined.
2478
- *
2479
- * @param {number} exitCode exit code for using with process.exit
2480
- * @param {string} code an id string representing the error
2481
- * @param {string} message human-readable description of the error
2482
- * @return never
2483
- * @private
2484
- */
2485
- _exit(exitCode, code, message) {
2486
- if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
2487
- process.exit(exitCode);
2488
- }
2489
- /**
2490
- * Register callback `fn` for the command.
2491
- *
2492
- * @example
2493
- * program
2494
- * .command('serve')
2495
- * .description('start service')
2496
- * .action(function() {
2497
- * // do work here
2498
- * });
2499
- *
2500
- * @param {Function} fn
2501
- * @return {Command} `this` command for chaining
2502
- */
2503
- action(fn) {
2504
- const listener = (args) => {
2505
- const expectedArgsCount = this.registeredArguments.length;
2506
- const actionArgs = args.slice(0, expectedArgsCount);
2507
- if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
2508
- else actionArgs[expectedArgsCount] = this.opts();
2509
- actionArgs.push(this);
2510
- return fn.apply(this, actionArgs);
2511
- };
2512
- this._actionHandler = listener;
2513
- return this;
2514
- }
2515
- /**
2516
- * Factory routine to create a new unattached option.
2517
- *
2518
- * See .option() for creating an attached option, which uses this routine to
2519
- * create the option. You can override createOption to return a custom option.
2520
- *
2521
- * @param {string} flags
2522
- * @param {string} [description]
2523
- * @return {Option} new option
2524
- */
2525
- createOption(flags, description) {
2526
- return new Option(flags, description);
2527
- }
2528
- /**
2529
- * Wrap parseArgs to catch 'commander.invalidArgument'.
2530
- *
2531
- * @param {(Option | Argument)} target
2532
- * @param {string} value
2533
- * @param {*} previous
2534
- * @param {string} invalidArgumentMessage
2535
- * @private
2536
- */
2537
- _callParseArg(target, value, previous, invalidArgumentMessage) {
2538
- try {
2539
- return target.parseArg(value, previous);
2540
- } catch (err) {
2541
- if (err.code === "commander.invalidArgument") {
2542
- const message = `${invalidArgumentMessage} ${err.message}`;
2543
- this.error(message, {
2544
- exitCode: err.exitCode,
2545
- code: err.code
2546
- });
2547
- }
2548
- throw err;
2549
- }
2550
- }
2551
- /**
2552
- * Check for option flag conflicts.
2553
- * Register option if no conflicts found, or throw on conflict.
2554
- *
2555
- * @param {Option} option
2556
- * @private
2557
- */
2558
- _registerOption(option) {
2559
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
2560
- if (matchingOption) {
2561
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
2562
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2563
- - already used by option '${matchingOption.flags}'`);
2564
- }
2565
- this._initOptionGroup(option);
2566
- this.options.push(option);
2567
- }
2568
- /**
2569
- * Check for command name and alias conflicts with existing commands.
2570
- * Register command if no conflicts found, or throw on conflict.
2571
- *
2572
- * @param {Command} command
2573
- * @private
2574
- */
2575
- _registerCommand(command) {
2576
- const knownBy = (cmd) => {
2577
- return [cmd.name()].concat(cmd.aliases());
2578
- };
2579
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
2580
- if (alreadyUsed) {
2581
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
2582
- const newCmd = knownBy(command).join("|");
2583
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
2584
- }
2585
- this._initCommandGroup(command);
2586
- this.commands.push(command);
2587
- }
2588
- /**
2589
- * Add an option.
2590
- *
2591
- * @param {Option} option
2592
- * @return {Command} `this` command for chaining
2593
- */
2594
- addOption(option) {
2595
- this._registerOption(option);
2596
- const oname = option.name();
2597
- const name = option.attributeName();
2598
- if (option.negate) {
2599
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
2600
- if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
2601
- } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
2602
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2603
- if (val == null && option.presetArg !== void 0) val = option.presetArg;
2604
- const oldValue = this.getOptionValue(name);
2605
- if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
2606
- else if (val !== null && option.variadic) val = option._concatValue(val, oldValue);
2607
- if (val == null) {
2608
- if (option.negate) val = false;
2609
- else if (option.isBoolean() || option.optional) val = true;
2610
- else val = "";
2611
- }
2612
- this.setOptionValueWithSource(name, val, valueSource);
2613
- };
2614
- this.on("option:" + oname, (val) => {
2615
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
2616
- handleOptionValue(val, invalidValueMessage, "cli");
2617
- });
2618
- if (option.envVar) this.on("optionEnv:" + oname, (val) => {
2619
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
2620
- handleOptionValue(val, invalidValueMessage, "env");
2621
- });
2622
- return this;
2623
- }
2624
- /**
2625
- * Internal implementation shared by .option() and .requiredOption()
2626
- *
2627
- * @return {Command} `this` command for chaining
2628
- * @private
2629
- */
2630
- _optionEx(config, flags, description, fn, defaultValue) {
2631
- if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
2632
- const option = this.createOption(flags, description);
2633
- option.makeOptionMandatory(!!config.mandatory);
2634
- if (typeof fn === "function") option.default(defaultValue).argParser(fn);
2635
- else if (fn instanceof RegExp) {
2636
- const regex = fn;
2637
- fn = (val, def) => {
2638
- const m = regex.exec(val);
2639
- return m ? m[0] : def;
2640
- };
2641
- option.default(defaultValue).argParser(fn);
2642
- } else option.default(fn);
2643
- return this.addOption(option);
2644
- }
2645
- /**
2646
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2647
- *
2648
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2649
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2650
- *
2651
- * See the README for more details, and see also addOption() and requiredOption().
2652
- *
2653
- * @example
2654
- * program
2655
- * .option('-p, --pepper', 'add pepper')
2656
- * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2657
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2658
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2659
- *
2660
- * @param {string} flags
2661
- * @param {string} [description]
2662
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
2663
- * @param {*} [defaultValue]
2664
- * @return {Command} `this` command for chaining
2665
- */
2666
- option(flags, description, parseArg, defaultValue) {
2667
- return this._optionEx({}, flags, description, parseArg, defaultValue);
2668
- }
2669
- /**
2670
- * Add a required option which must have a value after parsing. This usually means
2671
- * the option must be specified on the command line. (Otherwise the same as .option().)
2672
- *
2673
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2674
- *
2675
- * @param {string} flags
2676
- * @param {string} [description]
2677
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
2678
- * @param {*} [defaultValue]
2679
- * @return {Command} `this` command for chaining
2680
- */
2681
- requiredOption(flags, description, parseArg, defaultValue) {
2682
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
2683
- }
2684
- /**
2685
- * Alter parsing of short flags with optional values.
2686
- *
2687
- * @example
2688
- * // for `.option('-f,--flag [value]'):
2689
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2690
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2691
- *
2692
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2693
- * @return {Command} `this` command for chaining
2694
- */
2695
- combineFlagAndOptionalValue(combine = true) {
2696
- this._combineFlagAndOptionalValue = !!combine;
2697
- return this;
2698
- }
2699
- /**
2700
- * Allow unknown options on the command line.
2701
- *
2702
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2703
- * @return {Command} `this` command for chaining
2704
- */
2705
- allowUnknownOption(allowUnknown = true) {
2706
- this._allowUnknownOption = !!allowUnknown;
2707
- return this;
2708
- }
2709
- /**
2710
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2711
- *
2712
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2713
- * @return {Command} `this` command for chaining
2714
- */
2715
- allowExcessArguments(allowExcess = true) {
2716
- this._allowExcessArguments = !!allowExcess;
2717
- return this;
2718
- }
2719
- /**
2720
- * Enable positional options. Positional means global options are specified before subcommands which lets
2721
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2722
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
2723
- *
2724
- * @param {boolean} [positional]
2725
- * @return {Command} `this` command for chaining
2726
- */
2727
- enablePositionalOptions(positional = true) {
2728
- this._enablePositionalOptions = !!positional;
2729
- return this;
2730
- }
2731
- /**
2732
- * Pass through options that come after command-arguments rather than treat them as command-options,
2733
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2734
- * positional options to have been enabled on the program (parent commands).
2735
- * The default behaviour is non-positional and options may appear before or after command-arguments.
2736
- *
2737
- * @param {boolean} [passThrough] for unknown options.
2738
- * @return {Command} `this` command for chaining
2739
- */
2740
- passThroughOptions(passThrough = true) {
2741
- this._passThroughOptions = !!passThrough;
2742
- this._checkForBrokenPassThrough();
2743
- return this;
2744
- }
2745
- /**
2746
- * @private
2747
- */
2748
- _checkForBrokenPassThrough() {
2749
- 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)`);
2750
- }
2751
- /**
2752
- * Whether to store option values as properties on command object,
2753
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
2754
- *
2755
- * @param {boolean} [storeAsProperties=true]
2756
- * @return {Command} `this` command for chaining
2757
- */
2758
- storeOptionsAsProperties(storeAsProperties = true) {
2759
- if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
2760
- if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
2761
- this._storeOptionsAsProperties = !!storeAsProperties;
2762
- return this;
2763
- }
2764
- /**
2765
- * Retrieve option value.
2766
- *
2767
- * @param {string} key
2768
- * @return {object} value
2769
- */
2770
- getOptionValue(key) {
2771
- if (this._storeOptionsAsProperties) return this[key];
2772
- return this._optionValues[key];
2773
- }
2774
- /**
2775
- * Store option value.
2776
- *
2777
- * @param {string} key
2778
- * @param {object} value
2779
- * @return {Command} `this` command for chaining
2780
- */
2781
- setOptionValue(key, value) {
2782
- return this.setOptionValueWithSource(key, value, void 0);
2783
- }
2784
- /**
2785
- * Store option value and where the value came from.
2786
- *
2787
- * @param {string} key
2788
- * @param {object} value
2789
- * @param {string} source - expected values are default/config/env/cli/implied
2790
- * @return {Command} `this` command for chaining
2791
- */
2792
- setOptionValueWithSource(key, value, source) {
2793
- if (this._storeOptionsAsProperties) this[key] = value;
2794
- else this._optionValues[key] = value;
2795
- this._optionValueSources[key] = source;
2796
- return this;
2797
- }
2798
- /**
2799
- * Get source of option value.
2800
- * Expected values are default | config | env | cli | implied
2801
- *
2802
- * @param {string} key
2803
- * @return {string}
2804
- */
2805
- getOptionValueSource(key) {
2806
- return this._optionValueSources[key];
2807
- }
2808
- /**
2809
- * Get source of option value. See also .optsWithGlobals().
2810
- * Expected values are default | config | env | cli | implied
2811
- *
2812
- * @param {string} key
2813
- * @return {string}
2814
- */
2815
- getOptionValueSourceWithGlobals(key) {
2816
- let source;
2817
- this._getCommandAndAncestors().forEach((cmd) => {
2818
- if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
2819
- });
2820
- return source;
2821
- }
2822
- /**
2823
- * Get user arguments from implied or explicit arguments.
2824
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2825
- *
2826
- * @private
2827
- */
2828
- _prepareUserArgs(argv, parseOptions) {
2829
- if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
2830
- parseOptions = parseOptions || {};
2831
- if (argv === void 0 && parseOptions.from === void 0) {
2832
- if (process.versions?.electron) parseOptions.from = "electron";
2833
- const execArgv = process.execArgv ?? [];
2834
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
2835
- }
2836
- if (argv === void 0) argv = process.argv;
2837
- this.rawArgs = argv.slice();
2838
- let userArgs;
2839
- switch (parseOptions.from) {
2840
- case void 0:
2841
- case "node":
2842
- this._scriptPath = argv[1];
2843
- userArgs = argv.slice(2);
2844
- break;
2845
- case "electron":
2846
- if (process.defaultApp) {
2847
- this._scriptPath = argv[1];
2848
- userArgs = argv.slice(2);
2849
- } else userArgs = argv.slice(1);
2850
- break;
2851
- case "user":
2852
- userArgs = argv.slice(0);
2853
- break;
2854
- case "eval":
2855
- userArgs = argv.slice(1);
2856
- break;
2857
- default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2858
- }
2859
- if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
2860
- this._name = this._name || "program";
2861
- return userArgs;
2862
- }
2863
- /**
2864
- * Parse `argv`, setting options and invoking commands when defined.
2865
- *
2866
- * Use parseAsync instead of parse if any of your action handlers are async.
2867
- *
2868
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2869
- *
2870
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2871
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2872
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2873
- * - `'user'`: just user arguments
2874
- *
2875
- * @example
2876
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
2877
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2878
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2879
- *
2880
- * @param {string[]} [argv] - optional, defaults to process.argv
2881
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2882
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2883
- * @return {Command} `this` command for chaining
2884
- */
2885
- parse(argv, parseOptions) {
2886
- this._prepareForParse();
2887
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2888
- this._parseCommand([], userArgs);
2889
- return this;
2890
- }
2891
- /**
2892
- * Parse `argv`, setting options and invoking commands when defined.
2893
- *
2894
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2895
- *
2896
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2897
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2898
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2899
- * - `'user'`: just user arguments
2900
- *
2901
- * @example
2902
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2903
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2904
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2905
- *
2906
- * @param {string[]} [argv]
2907
- * @param {object} [parseOptions]
2908
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2909
- * @return {Promise}
2910
- */
2911
- async parseAsync(argv, parseOptions) {
2912
- this._prepareForParse();
2913
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2914
- await this._parseCommand([], userArgs);
2915
- return this;
2916
- }
2917
- _prepareForParse() {
2918
- if (this._savedState === null) this.saveStateBeforeParse();
2919
- else this.restoreStateBeforeParse();
2920
- }
2921
- /**
2922
- * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2923
- * Not usually called directly, but available for subclasses to save their custom state.
2924
- *
2925
- * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2926
- */
2927
- saveStateBeforeParse() {
2928
- this._savedState = {
2929
- _name: this._name,
2930
- _optionValues: { ...this._optionValues },
2931
- _optionValueSources: { ...this._optionValueSources }
2932
- };
2933
- }
2934
- /**
2935
- * Restore state before parse for calls after the first.
2936
- * Not usually called directly, but available for subclasses to save their custom state.
2937
- *
2938
- * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2939
- */
2940
- restoreStateBeforeParse() {
2941
- if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2942
- - either make a new Command for each call to parse, or stop storing options as properties`);
2943
- this._name = this._savedState._name;
2944
- this._scriptPath = null;
2945
- this.rawArgs = [];
2946
- this._optionValues = { ...this._savedState._optionValues };
2947
- this._optionValueSources = { ...this._savedState._optionValueSources };
2948
- this.args = [];
2949
- this.processedArgs = [];
2950
- }
2951
- /**
2952
- * Throw if expected executable is missing. Add lots of help for author.
2953
- *
2954
- * @param {string} executableFile
2955
- * @param {string} executableDir
2956
- * @param {string} subcommandName
2957
- */
2958
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2959
- if (fs.existsSync(executableFile)) return;
2960
- const executableMissing = `'${executableFile}' does not exist
2961
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2962
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2963
- - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
2964
- throw new Error(executableMissing);
2965
- }
2966
- /**
2967
- * Execute a sub-command executable.
2968
- *
2969
- * @private
2970
- */
2971
- _executeSubCommand(subcommand, args) {
2972
- args = args.slice();
2973
- let launchWithNode = false;
2974
- const sourceExt = [
2975
- ".js",
2976
- ".ts",
2977
- ".tsx",
2978
- ".mjs",
2979
- ".cjs"
2980
- ];
2981
- function findFile(baseDir, baseName) {
2982
- const localBin = path.resolve(baseDir, baseName);
2983
- if (fs.existsSync(localBin)) return localBin;
2984
- if (sourceExt.includes(path.extname(baseName))) return void 0;
2985
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
2986
- if (foundExt) return `${localBin}${foundExt}`;
2987
- }
2988
- this._checkForMissingMandatoryOptions();
2989
- this._checkForConflictingOptions();
2990
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2991
- let executableDir = this._executableDir || "";
2992
- if (this._scriptPath) {
2993
- let resolvedScriptPath;
2994
- try {
2995
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
2996
- } catch {
2997
- resolvedScriptPath = this._scriptPath;
2998
- }
2999
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
3000
- }
3001
- if (executableDir) {
3002
- let localFile = findFile(executableDir, executableFile);
3003
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
3004
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
3005
- if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
3006
- }
3007
- executableFile = localFile || executableFile;
3008
- }
3009
- launchWithNode = sourceExt.includes(path.extname(executableFile));
3010
- let proc;
3011
- if (process.platform !== "win32") {
3012
- if (launchWithNode) {
3013
- args.unshift(executableFile);
3014
- args = incrementNodeInspectorPort(process.execArgv).concat(args);
3015
- proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
3016
- } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
3017
- } else {
3018
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
3019
- args.unshift(executableFile);
3020
- args = incrementNodeInspectorPort(process.execArgv).concat(args);
3021
- proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
3022
- }
3023
- if (!proc.killed) [
3024
- "SIGUSR1",
3025
- "SIGUSR2",
3026
- "SIGTERM",
3027
- "SIGINT",
3028
- "SIGHUP"
3029
- ].forEach((signal) => {
3030
- process.on(signal, () => {
3031
- if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
3032
- });
3033
- });
3034
- const exitCallback = this._exitCallback;
3035
- proc.on("close", (code) => {
3036
- code = code ?? 1;
3037
- if (!exitCallback) process.exit(code);
3038
- else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
3039
- });
3040
- proc.on("error", (err) => {
3041
- if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
3042
- else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
3043
- if (!exitCallback) process.exit(1);
3044
- else {
3045
- const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
3046
- wrappedError.nestedError = err;
3047
- exitCallback(wrappedError);
3048
- }
3049
- });
3050
- this.runningCommand = proc;
3051
- }
3052
- /**
3053
- * @private
3054
- */
3055
- _dispatchSubcommand(commandName, operands, unknown) {
3056
- const subCommand = this._findCommand(commandName);
3057
- if (!subCommand) this.help({ error: true });
3058
- subCommand._prepareForParse();
3059
- let promiseChain;
3060
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
3061
- promiseChain = this._chainOrCall(promiseChain, () => {
3062
- if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
3063
- else return subCommand._parseCommand(operands, unknown);
3064
- });
3065
- return promiseChain;
3066
- }
3067
- /**
3068
- * Invoke help directly if possible, or dispatch if necessary.
3069
- * e.g. help foo
3070
- *
3071
- * @private
3072
- */
3073
- _dispatchHelpCommand(subcommandName) {
3074
- if (!subcommandName) this.help();
3075
- const subCommand = this._findCommand(subcommandName);
3076
- if (subCommand && !subCommand._executableHandler) subCommand.help();
3077
- return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
3078
- }
3079
- /**
3080
- * Check this.args against expected this.registeredArguments.
3081
- *
3082
- * @private
3083
- */
3084
- _checkNumberOfArguments() {
3085
- this.registeredArguments.forEach((arg, i) => {
3086
- if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
3087
- });
3088
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
3089
- if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
3090
- }
3091
- /**
3092
- * Process this.args using this.registeredArguments and save as this.processedArgs!
3093
- *
3094
- * @private
3095
- */
3096
- _processArguments() {
3097
- const myParseArg = (argument, value, previous) => {
3098
- let parsedValue = value;
3099
- if (value !== null && argument.parseArg) {
3100
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
3101
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
3102
- }
3103
- return parsedValue;
3104
- };
3105
- this._checkNumberOfArguments();
3106
- const processedArgs = [];
3107
- this.registeredArguments.forEach((declaredArg, index) => {
3108
- let value = declaredArg.defaultValue;
3109
- if (declaredArg.variadic) {
3110
- if (index < this.args.length) {
3111
- value = this.args.slice(index);
3112
- if (declaredArg.parseArg) value = value.reduce((processed, v) => {
3113
- return myParseArg(declaredArg, v, processed);
3114
- }, declaredArg.defaultValue);
3115
- } else if (value === void 0) value = [];
3116
- } else if (index < this.args.length) {
3117
- value = this.args[index];
3118
- if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
3119
- }
3120
- processedArgs[index] = value;
3121
- });
3122
- this.processedArgs = processedArgs;
3123
- }
3124
- /**
3125
- * Once we have a promise we chain, but call synchronously until then.
3126
- *
3127
- * @param {(Promise|undefined)} promise
3128
- * @param {Function} fn
3129
- * @return {(Promise|undefined)}
3130
- * @private
3131
- */
3132
- _chainOrCall(promise, fn) {
3133
- if (promise && promise.then && typeof promise.then === "function") return promise.then(() => fn());
3134
- return fn();
3135
- }
3136
- /**
3137
- *
3138
- * @param {(Promise|undefined)} promise
3139
- * @param {string} event
3140
- * @return {(Promise|undefined)}
3141
- * @private
3142
- */
3143
- _chainOrCallHooks(promise, event) {
3144
- let result = promise;
3145
- const hooks = [];
3146
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
3147
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
3148
- hooks.push({
3149
- hookedCommand,
3150
- callback
3151
- });
3152
- });
3153
- });
3154
- if (event === "postAction") hooks.reverse();
3155
- hooks.forEach((hookDetail) => {
3156
- result = this._chainOrCall(result, () => {
3157
- return hookDetail.callback(hookDetail.hookedCommand, this);
3158
- });
3159
- });
3160
- return result;
3161
- }
3162
- /**
3163
- *
3164
- * @param {(Promise|undefined)} promise
3165
- * @param {Command} subCommand
3166
- * @param {string} event
3167
- * @return {(Promise|undefined)}
3168
- * @private
3169
- */
3170
- _chainOrCallSubCommandHook(promise, subCommand, event) {
3171
- let result = promise;
3172
- if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
3173
- result = this._chainOrCall(result, () => {
3174
- return hook(this, subCommand);
3175
- });
3176
- });
3177
- return result;
3178
- }
3179
- /**
3180
- * Process arguments in context of this command.
3181
- * Returns action result, in case it is a promise.
3182
- *
3183
- * @private
3184
- */
3185
- _parseCommand(operands, unknown) {
3186
- const parsed = this.parseOptions(unknown);
3187
- this._parseOptionsEnv();
3188
- this._parseOptionsImplied();
3189
- operands = operands.concat(parsed.operands);
3190
- unknown = parsed.unknown;
3191
- this.args = operands.concat(unknown);
3192
- if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
3193
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
3194
- if (this._defaultCommandName) {
3195
- this._outputHelpIfRequested(unknown);
3196
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
3197
- }
3198
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
3199
- this._outputHelpIfRequested(parsed.unknown);
3200
- this._checkForMissingMandatoryOptions();
3201
- this._checkForConflictingOptions();
3202
- const checkForUnknownOptions = () => {
3203
- if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
3204
- };
3205
- const commandEvent = `command:${this.name()}`;
3206
- if (this._actionHandler) {
3207
- checkForUnknownOptions();
3208
- this._processArguments();
3209
- let promiseChain;
3210
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
3211
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
3212
- if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
3213
- this.parent.emit(commandEvent, operands, unknown);
3214
- });
3215
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
3216
- return promiseChain;
3217
- }
3218
- if (this.parent && this.parent.listenerCount(commandEvent)) {
3219
- checkForUnknownOptions();
3220
- this._processArguments();
3221
- this.parent.emit(commandEvent, operands, unknown);
3222
- } else if (operands.length) {
3223
- if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
3224
- if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
3225
- else if (this.commands.length) this.unknownCommand();
3226
- else {
3227
- checkForUnknownOptions();
3228
- this._processArguments();
3229
- }
3230
- } else if (this.commands.length) {
3231
- checkForUnknownOptions();
3232
- this.help({ error: true });
3233
- } else {
3234
- checkForUnknownOptions();
3235
- this._processArguments();
3236
- }
3237
- }
3238
- /**
3239
- * Find matching command.
3240
- *
3241
- * @private
3242
- * @return {Command | undefined}
3243
- */
3244
- _findCommand(name) {
3245
- if (!name) return void 0;
3246
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
3247
- }
3248
- /**
3249
- * Return an option matching `arg` if any.
3250
- *
3251
- * @param {string} arg
3252
- * @return {Option}
3253
- * @package
3254
- */
3255
- _findOption(arg) {
3256
- return this.options.find((option) => option.is(arg));
3257
- }
3258
- /**
3259
- * Display an error message if a mandatory option does not have a value.
3260
- * Called after checking for help flags in leaf subcommand.
3261
- *
3262
- * @private
3263
- */
3264
- _checkForMissingMandatoryOptions() {
3265
- this._getCommandAndAncestors().forEach((cmd) => {
3266
- cmd.options.forEach((anOption) => {
3267
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
3268
- });
3269
- });
3270
- }
3271
- /**
3272
- * Display an error message if conflicting options are used together in this.
3273
- *
3274
- * @private
3275
- */
3276
- _checkForConflictingLocalOptions() {
3277
- const definedNonDefaultOptions = this.options.filter((option) => {
3278
- const optionKey = option.attributeName();
3279
- if (this.getOptionValue(optionKey) === void 0) return false;
3280
- return this.getOptionValueSource(optionKey) !== "default";
3281
- });
3282
- definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
3283
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
3284
- if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
3285
- });
3286
- }
3287
- /**
3288
- * Display an error message if conflicting options are used together.
3289
- * Called after checking for help flags in leaf subcommand.
3290
- *
3291
- * @private
3292
- */
3293
- _checkForConflictingOptions() {
3294
- this._getCommandAndAncestors().forEach((cmd) => {
3295
- cmd._checkForConflictingLocalOptions();
3296
- });
3297
- }
3298
- /**
3299
- * Parse options from `argv` removing known options,
3300
- * and return argv split into operands and unknown arguments.
3301
- *
3302
- * Side effects: modifies command by storing options. Does not reset state if called again.
3303
- *
3304
- * Examples:
3305
- *
3306
- * argv => operands, unknown
3307
- * --known kkk op => [op], []
3308
- * op --known kkk => [op], []
3309
- * sub --unknown uuu op => [sub], [--unknown uuu op]
3310
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
3311
- *
3312
- * @param {string[]} argv
3313
- * @return {{operands: string[], unknown: string[]}}
3314
- */
3315
- parseOptions(argv) {
3316
- const operands = [];
3317
- const unknown = [];
3318
- let dest = operands;
3319
- const args = argv.slice();
3320
- function maybeOption(arg) {
3321
- return arg.length > 1 && arg[0] === "-";
3322
- }
3323
- const negativeNumberArg = (arg) => {
3324
- if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;
3325
- return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
3326
- };
3327
- let activeVariadicOption = null;
3328
- while (args.length) {
3329
- const arg = args.shift();
3330
- if (arg === "--") {
3331
- if (dest === unknown) dest.push(arg);
3332
- dest.push(...args);
3333
- break;
3334
- }
3335
- if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
3336
- this.emit(`option:${activeVariadicOption.name()}`, arg);
3337
- continue;
3338
- }
3339
- activeVariadicOption = null;
3340
- if (maybeOption(arg)) {
3341
- const option = this._findOption(arg);
3342
- if (option) {
3343
- if (option.required) {
3344
- const value = args.shift();
3345
- if (value === void 0) this.optionMissingArgument(option);
3346
- this.emit(`option:${option.name()}`, value);
3347
- } else if (option.optional) {
3348
- let value = null;
3349
- if (args.length > 0 && (!maybeOption(args[0]) || negativeNumberArg(args[0]))) value = args.shift();
3350
- this.emit(`option:${option.name()}`, value);
3351
- } else this.emit(`option:${option.name()}`);
3352
- activeVariadicOption = option.variadic ? option : null;
3353
- continue;
3354
- }
3355
- }
3356
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
3357
- const option = this._findOption(`-${arg[1]}`);
3358
- if (option) {
3359
- if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
3360
- else {
3361
- this.emit(`option:${option.name()}`);
3362
- args.unshift(`-${arg.slice(2)}`);
3363
- }
3364
- continue;
3365
- }
3366
- }
3367
- if (/^--[^=]+=/.test(arg)) {
3368
- const index = arg.indexOf("=");
3369
- const option = this._findOption(arg.slice(0, index));
3370
- if (option && (option.required || option.optional)) {
3371
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
3372
- continue;
3373
- }
3374
- }
3375
- if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
3376
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
3377
- if (this._findCommand(arg)) {
3378
- operands.push(arg);
3379
- if (args.length > 0) unknown.push(...args);
3380
- break;
3381
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
3382
- operands.push(arg);
3383
- if (args.length > 0) operands.push(...args);
3384
- break;
3385
- } else if (this._defaultCommandName) {
3386
- unknown.push(arg);
3387
- if (args.length > 0) unknown.push(...args);
3388
- break;
3389
- }
3390
- }
3391
- if (this._passThroughOptions) {
3392
- dest.push(arg);
3393
- if (args.length > 0) dest.push(...args);
3394
- break;
3395
- }
3396
- dest.push(arg);
3397
- }
3398
- return {
3399
- operands,
3400
- unknown
3401
- };
3402
- }
3403
- /**
3404
- * Return an object containing local option values as key-value pairs.
3405
- *
3406
- * @return {object}
3407
- */
3408
- opts() {
3409
- if (this._storeOptionsAsProperties) {
3410
- const result = {};
3411
- const len = this.options.length;
3412
- for (let i = 0; i < len; i++) {
3413
- const key = this.options[i].attributeName();
3414
- result[key] = key === this._versionOptionName ? this._version : this[key];
3415
- }
3416
- return result;
3417
- }
3418
- return this._optionValues;
3419
- }
3420
- /**
3421
- * Return an object containing merged local and global option values as key-value pairs.
3422
- *
3423
- * @return {object}
3424
- */
3425
- optsWithGlobals() {
3426
- return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
3427
- }
3428
- /**
3429
- * Display error message and exit (or call exitOverride).
3430
- *
3431
- * @param {string} message
3432
- * @param {object} [errorOptions]
3433
- * @param {string} [errorOptions.code] - an id string representing the error
3434
- * @param {number} [errorOptions.exitCode] - used with process.exit
3435
- */
3436
- error(message, errorOptions) {
3437
- this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
3438
- if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
3439
- else if (this._showHelpAfterError) {
3440
- this._outputConfiguration.writeErr("\n");
3441
- this.outputHelp({ error: true });
3442
- }
3443
- const config = errorOptions || {};
3444
- const exitCode = config.exitCode || 1;
3445
- const code = config.code || "commander.error";
3446
- this._exit(exitCode, code, message);
3447
- }
3448
- /**
3449
- * Apply any option related environment variables, if option does
3450
- * not have a value from cli or client code.
3451
- *
3452
- * @private
3453
- */
3454
- _parseOptionsEnv() {
3455
- this.options.forEach((option) => {
3456
- if (option.envVar && option.envVar in process.env) {
3457
- const optionKey = option.attributeName();
3458
- if (this.getOptionValue(optionKey) === void 0 || [
3459
- "default",
3460
- "config",
3461
- "env"
3462
- ].includes(this.getOptionValueSource(optionKey))) {
3463
- if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
3464
- else this.emit(`optionEnv:${option.name()}`);
3465
- }
3466
- }
3467
- });
3468
- }
3469
- /**
3470
- * Apply any implied option values, if option is undefined or default value.
3471
- *
3472
- * @private
3473
- */
3474
- _parseOptionsImplied() {
3475
- const dualHelper = new DualOptions(this.options);
3476
- const hasCustomOptionValue = (optionKey) => {
3477
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3478
- };
3479
- this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
3480
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3481
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
3482
- });
3483
- });
3484
- }
3485
- /**
3486
- * Argument `name` is missing.
3487
- *
3488
- * @param {string} name
3489
- * @private
3490
- */
3491
- missingArgument(name) {
3492
- const message = `error: missing required argument '${name}'`;
3493
- this.error(message, { code: "commander.missingArgument" });
3494
- }
3495
- /**
3496
- * `Option` is missing an argument.
3497
- *
3498
- * @param {Option} option
3499
- * @private
3500
- */
3501
- optionMissingArgument(option) {
3502
- const message = `error: option '${option.flags}' argument missing`;
3503
- this.error(message, { code: "commander.optionMissingArgument" });
3504
- }
3505
- /**
3506
- * `Option` does not have a value, and is a mandatory option.
3507
- *
3508
- * @param {Option} option
3509
- * @private
3510
- */
3511
- missingMandatoryOptionValue(option) {
3512
- const message = `error: required option '${option.flags}' not specified`;
3513
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
3514
- }
3515
- /**
3516
- * `Option` conflicts with another option.
3517
- *
3518
- * @param {Option} option
3519
- * @param {Option} conflictingOption
3520
- * @private
3521
- */
3522
- _conflictingOption(option, conflictingOption) {
3523
- const findBestOptionFromValue = (option) => {
3524
- const optionKey = option.attributeName();
3525
- const optionValue = this.getOptionValue(optionKey);
3526
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
3527
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
3528
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
3529
- return positiveOption || option;
3530
- };
3531
- const getErrorMessage = (option) => {
3532
- const bestOption = findBestOptionFromValue(option);
3533
- const optionKey = bestOption.attributeName();
3534
- if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
3535
- return `option '${bestOption.flags}'`;
3536
- };
3537
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3538
- this.error(message, { code: "commander.conflictingOption" });
3539
- }
3540
- /**
3541
- * Unknown option `flag`.
3542
- *
3543
- * @param {string} flag
3544
- * @private
3545
- */
3546
- unknownOption(flag) {
3547
- if (this._allowUnknownOption) return;
3548
- let suggestion = "";
3549
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
3550
- let candidateFlags = [];
3551
- let command = this;
3552
- do {
3553
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
3554
- candidateFlags = candidateFlags.concat(moreFlags);
3555
- command = command.parent;
3556
- } while (command && !command._enablePositionalOptions);
3557
- suggestion = suggestSimilar(flag, candidateFlags);
3558
- }
3559
- const message = `error: unknown option '${flag}'${suggestion}`;
3560
- this.error(message, { code: "commander.unknownOption" });
3561
- }
3562
- /**
3563
- * Excess arguments, more than expected.
3564
- *
3565
- * @param {string[]} receivedArgs
3566
- * @private
3567
- */
3568
- _excessArguments(receivedArgs) {
3569
- if (this._allowExcessArguments) return;
3570
- const expected = this.registeredArguments.length;
3571
- const s = expected === 1 ? "" : "s";
3572
- const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3573
- this.error(message, { code: "commander.excessArguments" });
3574
- }
3575
- /**
3576
- * Unknown command.
3577
- *
3578
- * @private
3579
- */
3580
- unknownCommand() {
3581
- const unknownName = this.args[0];
3582
- let suggestion = "";
3583
- if (this._showSuggestionAfterError) {
3584
- const candidateNames = [];
3585
- this.createHelp().visibleCommands(this).forEach((command) => {
3586
- candidateNames.push(command.name());
3587
- if (command.alias()) candidateNames.push(command.alias());
3588
- });
3589
- suggestion = suggestSimilar(unknownName, candidateNames);
3590
- }
3591
- const message = `error: unknown command '${unknownName}'${suggestion}`;
3592
- this.error(message, { code: "commander.unknownCommand" });
3593
- }
3594
- /**
3595
- * Get or set the program version.
3596
- *
3597
- * This method auto-registers the "-V, --version" option which will print the version number.
3598
- *
3599
- * You can optionally supply the flags and description to override the defaults.
3600
- *
3601
- * @param {string} [str]
3602
- * @param {string} [flags]
3603
- * @param {string} [description]
3604
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3605
- */
3606
- version(str, flags, description) {
3607
- if (str === void 0) return this._version;
3608
- this._version = str;
3609
- flags = flags || "-V, --version";
3610
- description = description || "output the version number";
3611
- const versionOption = this.createOption(flags, description);
3612
- this._versionOptionName = versionOption.attributeName();
3613
- this._registerOption(versionOption);
3614
- this.on("option:" + versionOption.name(), () => {
3615
- this._outputConfiguration.writeOut(`${str}\n`);
3616
- this._exit(0, "commander.version", str);
3617
- });
3618
- return this;
3619
- }
3620
- /**
3621
- * Set the description.
3622
- *
3623
- * @param {string} [str]
3624
- * @param {object} [argsDescription]
3625
- * @return {(string|Command)}
3626
- */
3627
- description(str, argsDescription) {
3628
- if (str === void 0 && argsDescription === void 0) return this._description;
3629
- this._description = str;
3630
- if (argsDescription) this._argsDescription = argsDescription;
3631
- return this;
3632
- }
3633
- /**
3634
- * Set the summary. Used when listed as subcommand of parent.
3635
- *
3636
- * @param {string} [str]
3637
- * @return {(string|Command)}
3638
- */
3639
- summary(str) {
3640
- if (str === void 0) return this._summary;
3641
- this._summary = str;
3642
- return this;
3643
- }
3644
- /**
3645
- * Set an alias for the command.
3646
- *
3647
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3648
- *
3649
- * @param {string} [alias]
3650
- * @return {(string|Command)}
3651
- */
3652
- alias(alias) {
3653
- if (alias === void 0) return this._aliases[0];
3654
- /** @type {Command} */
3655
- let command = this;
3656
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
3657
- if (alias === command._name) throw new Error("Command alias can't be the same as its name");
3658
- const matchingCommand = this.parent?._findCommand(alias);
3659
- if (matchingCommand) {
3660
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3661
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
3662
- }
3663
- command._aliases.push(alias);
3664
- return this;
3665
- }
3666
- /**
3667
- * Set aliases for the command.
3668
- *
3669
- * Only the first alias is shown in the auto-generated help.
3670
- *
3671
- * @param {string[]} [aliases]
3672
- * @return {(string[]|Command)}
3673
- */
3674
- aliases(aliases) {
3675
- if (aliases === void 0) return this._aliases;
3676
- aliases.forEach((alias) => this.alias(alias));
3677
- return this;
3678
- }
3679
- /**
3680
- * Set / get the command usage `str`.
3681
- *
3682
- * @param {string} [str]
3683
- * @return {(string|Command)}
3684
- */
3685
- usage(str) {
3686
- if (str === void 0) {
3687
- if (this._usage) return this._usage;
3688
- const args = this.registeredArguments.map((arg) => {
3689
- return humanReadableArgName(arg);
3690
- });
3691
- return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
3692
- }
3693
- this._usage = str;
3694
- return this;
3695
- }
3696
- /**
3697
- * Get or set the name of the command.
3698
- *
3699
- * @param {string} [str]
3700
- * @return {(string|Command)}
3701
- */
3702
- name(str) {
3703
- if (str === void 0) return this._name;
3704
- this._name = str;
3705
- return this;
3706
- }
3707
- /**
3708
- * Set/get the help group heading for this subcommand in parent command's help.
3709
- *
3710
- * @param {string} [heading]
3711
- * @return {Command | string}
3712
- */
3713
- helpGroup(heading) {
3714
- if (heading === void 0) return this._helpGroupHeading ?? "";
3715
- this._helpGroupHeading = heading;
3716
- return this;
3717
- }
3718
- /**
3719
- * Set/get the default help group heading for subcommands added to this command.
3720
- * (This does not override a group set directly on the subcommand using .helpGroup().)
3721
- *
3722
- * @example
3723
- * program.commandsGroup('Development Commands:);
3724
- * program.command('watch')...
3725
- * program.command('lint')...
3726
- * ...
3727
- *
3728
- * @param {string} [heading]
3729
- * @returns {Command | string}
3730
- */
3731
- commandsGroup(heading) {
3732
- if (heading === void 0) return this._defaultCommandGroup ?? "";
3733
- this._defaultCommandGroup = heading;
3734
- return this;
3735
- }
3736
- /**
3737
- * Set/get the default help group heading for options added to this command.
3738
- * (This does not override a group set directly on the option using .helpGroup().)
3739
- *
3740
- * @example
3741
- * program
3742
- * .optionsGroup('Development Options:')
3743
- * .option('-d, --debug', 'output extra debugging')
3744
- * .option('-p, --profile', 'output profiling information')
3745
- *
3746
- * @param {string} [heading]
3747
- * @returns {Command | string}
3748
- */
3749
- optionsGroup(heading) {
3750
- if (heading === void 0) return this._defaultOptionGroup ?? "";
3751
- this._defaultOptionGroup = heading;
3752
- return this;
3753
- }
3754
- /**
3755
- * @param {Option} option
3756
- * @private
3757
- */
3758
- _initOptionGroup(option) {
3759
- if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
3760
- }
3761
- /**
3762
- * @param {Command} cmd
3763
- * @private
3764
- */
3765
- _initCommandGroup(cmd) {
3766
- if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
3767
- }
3768
- /**
3769
- * Set the name of the command from script filename, such as process.argv[1],
3770
- * or require.main.filename, or __filename.
3771
- *
3772
- * (Used internally and public although not documented in README.)
3773
- *
3774
- * @example
3775
- * program.nameFromFilename(require.main.filename);
3776
- *
3777
- * @param {string} filename
3778
- * @return {Command}
3779
- */
3780
- nameFromFilename(filename) {
3781
- this._name = path.basename(filename, path.extname(filename));
3782
- return this;
3783
- }
3784
- /**
3785
- * Get or set the directory for searching for executable subcommands of this command.
3786
- *
3787
- * @example
3788
- * program.executableDir(__dirname);
3789
- * // or
3790
- * program.executableDir('subcommands');
3791
- *
3792
- * @param {string} [path]
3793
- * @return {(string|null|Command)}
3794
- */
3795
- executableDir(path) {
3796
- if (path === void 0) return this._executableDir;
3797
- this._executableDir = path;
3798
- return this;
3799
- }
3800
- /**
3801
- * Return program help documentation.
3802
- *
3803
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3804
- * @return {string}
3805
- */
3806
- helpInformation(contextOptions) {
3807
- const helper = this.createHelp();
3808
- const context = this._getOutputContext(contextOptions);
3809
- helper.prepareContext({
3810
- error: context.error,
3811
- helpWidth: context.helpWidth,
3812
- outputHasColors: context.hasColors
3813
- });
3814
- const text = helper.formatHelp(this, helper);
3815
- if (context.hasColors) return text;
3816
- return this._outputConfiguration.stripColor(text);
3817
- }
3818
- /**
3819
- * @typedef HelpContext
3820
- * @type {object}
3821
- * @property {boolean} error
3822
- * @property {number} helpWidth
3823
- * @property {boolean} hasColors
3824
- * @property {function} write - includes stripColor if needed
3825
- *
3826
- * @returns {HelpContext}
3827
- * @private
3828
- */
3829
- _getOutputContext(contextOptions) {
3830
- contextOptions = contextOptions || {};
3831
- const error = !!contextOptions.error;
3832
- let baseWrite;
3833
- let hasColors;
3834
- let helpWidth;
3835
- if (error) {
3836
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
3837
- hasColors = this._outputConfiguration.getErrHasColors();
3838
- helpWidth = this._outputConfiguration.getErrHelpWidth();
3839
- } else {
3840
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3841
- hasColors = this._outputConfiguration.getOutHasColors();
3842
- helpWidth = this._outputConfiguration.getOutHelpWidth();
3843
- }
3844
- const write = (str) => {
3845
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3846
- return baseWrite(str);
3847
- };
3848
- return {
3849
- error,
3850
- write,
3851
- hasColors,
3852
- helpWidth
3853
- };
3854
- }
3855
- /**
3856
- * Output help information for this command.
3857
- *
3858
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3859
- *
3860
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3861
- */
3862
- outputHelp(contextOptions) {
3863
- let deprecatedCallback;
3864
- if (typeof contextOptions === "function") {
3865
- deprecatedCallback = contextOptions;
3866
- contextOptions = void 0;
3867
- }
3868
- const outputContext = this._getOutputContext(contextOptions);
3869
- /** @type {HelpTextEventContext} */
3870
- const eventContext = {
3871
- error: outputContext.error,
3872
- write: outputContext.write,
3873
- command: this
3874
- };
3875
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3876
- this.emit("beforeHelp", eventContext);
3877
- let helpInformation = this.helpInformation({ error: outputContext.error });
3878
- if (deprecatedCallback) {
3879
- helpInformation = deprecatedCallback(helpInformation);
3880
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
3881
- }
3882
- outputContext.write(helpInformation);
3883
- if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
3884
- this.emit("afterHelp", eventContext);
3885
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
3886
- }
3887
- /**
3888
- * You can pass in flags and a description to customise the built-in help option.
3889
- * Pass in false to disable the built-in help option.
3890
- *
3891
- * @example
3892
- * program.helpOption('-?, --help' 'show help'); // customise
3893
- * program.helpOption(false); // disable
3894
- *
3895
- * @param {(string | boolean)} flags
3896
- * @param {string} [description]
3897
- * @return {Command} `this` command for chaining
3898
- */
3899
- helpOption(flags, description) {
3900
- if (typeof flags === "boolean") {
3901
- if (flags) {
3902
- if (this._helpOption === null) this._helpOption = void 0;
3903
- if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
3904
- } else this._helpOption = null;
3905
- return this;
3906
- }
3907
- this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
3908
- if (flags || description) this._initOptionGroup(this._helpOption);
3909
- return this;
3910
- }
3911
- /**
3912
- * Lazy create help option.
3913
- * Returns null if has been disabled with .helpOption(false).
3914
- *
3915
- * @returns {(Option | null)} the help option
3916
- * @package
3917
- */
3918
- _getHelpOption() {
3919
- if (this._helpOption === void 0) this.helpOption(void 0, void 0);
3920
- return this._helpOption;
3921
- }
3922
- /**
3923
- * Supply your own option to use for the built-in help option.
3924
- * This is an alternative to using helpOption() to customise the flags and description etc.
3925
- *
3926
- * @param {Option} option
3927
- * @return {Command} `this` command for chaining
3928
- */
3929
- addHelpOption(option) {
3930
- this._helpOption = option;
3931
- this._initOptionGroup(option);
3932
- return this;
3933
- }
3934
- /**
3935
- * Output help information and exit.
3936
- *
3937
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3938
- *
3939
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3940
- */
3941
- help(contextOptions) {
3942
- this.outputHelp(contextOptions);
3943
- let exitCode = Number(process.exitCode ?? 0);
3944
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
3945
- this._exit(exitCode, "commander.help", "(outputHelp)");
3946
- }
3947
- /**
3948
- * // Do a little typing to coordinate emit and listener for the help text events.
3949
- * @typedef HelpTextEventContext
3950
- * @type {object}
3951
- * @property {boolean} error
3952
- * @property {Command} command
3953
- * @property {function} write
3954
- */
3955
- /**
3956
- * Add additional text to be displayed with the built-in help.
3957
- *
3958
- * Position is 'before' or 'after' to affect just this command,
3959
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3960
- *
3961
- * @param {string} position - before or after built-in help
3962
- * @param {(string | Function)} text - string to add, or a function returning a string
3963
- * @return {Command} `this` command for chaining
3964
- */
3965
- addHelpText(position, text) {
3966
- const allowedValues = [
3967
- "beforeAll",
3968
- "before",
3969
- "after",
3970
- "afterAll"
3971
- ];
3972
- if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
3973
- Expecting one of '${allowedValues.join("', '")}'`);
3974
- const helpEvent = `${position}Help`;
3975
- this.on(helpEvent, (context) => {
3976
- let helpStr;
3977
- if (typeof text === "function") helpStr = text({
3978
- error: context.error,
3979
- command: context.command
3980
- });
3981
- else helpStr = text;
3982
- if (helpStr) context.write(`${helpStr}\n`);
3983
- });
3984
- return this;
3985
- }
3986
- /**
3987
- * Output help information if help flags specified
3988
- *
3989
- * @param {Array} args - array of options to search for help flags
3990
- * @private
3991
- */
3992
- _outputHelpIfRequested(args) {
3993
- const helpOption = this._getHelpOption();
3994
- if (helpOption && args.find((arg) => helpOption.is(arg))) {
3995
- this.outputHelp();
3996
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3997
- }
3998
- }
3999
- };
4000
- /**
4001
- * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
4002
- *
4003
- * @param {string[]} args - array of arguments from node.execArgv
4004
- * @returns {string[]}
4005
- * @private
4006
- */
4007
- function incrementNodeInspectorPort(args) {
4008
- return args.map((arg) => {
4009
- if (!arg.startsWith("--inspect")) return arg;
4010
- let debugOption;
4011
- let debugHost = "127.0.0.1";
4012
- let debugPort = "9229";
4013
- let match;
4014
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
4015
- else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
4016
- debugOption = match[1];
4017
- if (/^\d+$/.test(match[3])) debugPort = match[3];
4018
- else debugHost = match[3];
4019
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
4020
- debugOption = match[1];
4021
- debugHost = match[3];
4022
- debugPort = match[4];
4023
- }
4024
- if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
4025
- return arg;
4026
- });
4027
- }
4028
- /**
4029
- * @returns {boolean | undefined}
4030
- * @package
4031
- */
4032
- function useColor() {
4033
- if (process.env.NO_COLOR || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") return false;
4034
- if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== void 0) return true;
4035
- }
4036
- exports.Command = Command;
4037
- exports.useColor = useColor;
4038
- }));
4039
- //#endregion
4040
- //#region vendor/commander/index.js
4041
- var require_commander = /* @__PURE__ */ __commonJSMin(((exports) => {
4042
- const { Argument } = require_argument();
4043
- const { Command } = require_command();
4044
- const { CommanderError, InvalidArgumentError } = require_error();
4045
- const { Help } = require_help();
4046
- const { Option } = require_option();
4047
- exports.program = new Command();
4048
- exports.createCommand = (name) => new Command(name);
4049
- exports.createOption = (flags, description) => new Option(flags, description);
4050
- exports.createArgument = (name, description) => new Argument(name, description);
4051
- /**
4052
- * Expose classes
4053
- */
4054
- exports.Command = Command;
4055
- exports.Option = Option;
4056
- exports.Argument = Argument;
4057
- exports.Help = Help;
4058
- exports.CommanderError = CommanderError;
4059
- exports.InvalidArgumentError = InvalidArgumentError;
4060
- exports.InvalidOptionArgumentError = InvalidArgumentError;
4061
- }));
4062
- //#endregion
4063
- //#region vendor/commander/esm.mjs
4064
- var esm_exports = /* @__PURE__ */ __exportAll({
4065
- Argument: () => Argument,
4066
- Command: () => Command,
4067
- CommanderError: () => CommanderError$1,
4068
- Help: () => Help,
4069
- InvalidArgumentError: () => InvalidArgumentError$1,
4070
- InvalidOptionArgumentError: () => InvalidOptionArgumentError,
4071
- Option: () => Option$1,
4072
- createArgument: () => createArgument,
4073
- createCommand: () => createCommand,
4074
- createOption: () => createOption,
4075
- program: () => program
4076
- });
4077
- var import_commander, program, createCommand, createArgument, createOption, CommanderError$1, InvalidArgumentError$1, InvalidOptionArgumentError, Command, Argument, Option$1, Help;
4078
- var init_esm = __esmMin((() => {
4079
- import_commander = /* @__PURE__ */ __toESM(require_commander(), 1);
4080
- ({program, createCommand, createArgument, createOption, CommanderError: CommanderError$1, InvalidArgumentError: InvalidArgumentError$1, InvalidOptionArgumentError, Command, Argument, Option: Option$1, Help} = import_commander.default);
4081
- }));
4082
- //#endregion
4083
- //#region .runtime-sources/skills/poteto-mode/scripts/orch/orch.ts
4084
- const { Command: CommanderCommand, CommanderError, InvalidArgumentError, Option } = await Promise.resolve().then(() => (init_esm(), esm_exports));
4085
- const DISPLAY_LIMIT = 4;
4086
- function message(error) {
4087
- return error instanceof Error ? error.message : String(error);
4088
- }
4089
- function positiveInteger(value) {
4090
- const parsed = Number(value);
4091
- if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(parsed)) throw new InvalidArgumentError("must be a positive integer");
4092
- return parsed;
4093
- }
4094
- function prList(value) {
4095
- const parts = value.split(",");
4096
- if (parts.some((part) => part.length === 0)) throw new InvalidArgumentError("requires a comma-separated PR list");
4097
- return parts.map(positiveInteger);
4098
- }
4099
- function countLine(value) {
4100
- const entries = Object.entries(value);
4101
- return entries.length === 0 ? "none" : entries.map(([name, count]) => `${name}=${count}`).join(", ");
4102
- }
4103
- function unitLine(unit) {
4104
- return [
4105
- unit.id,
4106
- unit.track,
4107
- unit.state,
4108
- unit.branch,
4109
- unit.pr,
4110
- unit.sha,
4111
- unit.brief
4112
- ].join(" ");
4113
- }
4114
- function pointerLine(pointer) {
4115
- return [
4116
- pointer.ts,
4117
- pointer.agent,
4118
- pointer.unit,
4119
- pointer.status,
4120
- pointer.report
4121
- ].join(" ");
4122
- }
4123
- function gateLine(gate) {
4124
- return [
4125
- gate.id,
4126
- gate.question,
4127
- gate.options,
4128
- gate.defaultAnswer
4129
- ].join(" ");
4130
- }
4131
- function compactRows(rows, format, empty, limit = DISPLAY_LIMIT) {
4132
- if (rows.length === 0) return empty;
4133
- const lines = (limit === null ? rows : rows.slice(0, limit)).map(format);
4134
- if (limit !== null && rows.length > limit) lines.push(`... ${rows.length - limit} more; use --json`);
4135
- return lines.join("\n");
4136
- }
4137
- function frontierLine(value) {
4138
- const prs = value.prs.length === 0 ? "none" : value.prs.map((row) => `${row.branches}#${row.pr}@${row.sha}:${row.state}`).join(",");
4139
- return `generation=${value.generation} prs=${prs} lowest-unmerged=${value.lowestUnmerged ?? "none"}`;
4140
- }
4141
- function statusLines(report) {
4142
- const visible = report.summary.openGateIds.slice(0, DISPLAY_LIMIT);
4143
- const more = report.summary.openGateIds.length > DISPLAY_LIMIT ? `,+${report.summary.openGateIds.length - DISPLAY_LIMIT} more` : "";
4144
- return [
4145
- `counts: units=${report.units.length}; states=${countLine(report.summary.unitStates)}; ledger=${countLine(report.summary.ledgerVerdicts)}`,
4146
- `changed: ${report.changed}`,
4147
- `gates open: ${report.summary.openGateIds.length}${visible.length > 0 ? `; ids=${visible.join(",")}${more}` : ""}`
4148
- ].join("\n");
4149
- }
4150
- function emit(io, json, value, compact, jsonValue = (result) => result) {
4151
- const rendered = json ? JSON.stringify(jsonValue(value), null, 2) : compact(value);
4152
- io.stdout(rendered.endsWith("\n") ? rendered : `${rendered}\n`);
4153
- }
4154
- function storeDirectory(program) {
4155
- const value = program.opts().store;
4156
- if (value === void 0 || value.trim().length === 0) throw new UsageError("set --store <dir> or ORCH_STORE");
4157
- return value;
4158
- }
4159
- function frontierRepo(options) {
4160
- const value = options.repo;
4161
- if (value === void 0 || value.trim().length === 0) throw new UsageError("set --repo <dir> or ORCH_REPO");
4162
- return value;
4163
- }
4164
- async function runStore(program, io, operation, compact, jsonValue) {
4165
- const options = program.opts();
4166
- const store = openStore(storeDirectory(program), {
4167
- force: options.force,
4168
- onLockStolen: (holder) => io.stderr(`stealing store lock held by pid ${holder}\n`),
4169
- onStaleLock: (holder) => io.stderr(`replacing stale store lock (pid ${holder} is dead)\n`)
4170
- });
4171
- try {
4172
- const result = await operation(store);
4173
- emit(io, options.json, result, compact, jsonValue);
4174
- } finally {
4175
- await store.close();
4176
- }
4177
- }
4178
- function leaf(parent, name, description) {
4179
- return parent.command(name).description(description).allowExcessArguments(false);
4180
- }
4181
- function requireSubcommand(program) {
4182
- storeDirectory(program);
4183
- throw new UsageError("a valid command is required");
4184
- }
4185
- function createProgram(io) {
4186
- const program = new CommanderCommand("orch").description("Plain-file orchestrate bookkeeping").usage("[--store <dir>] [--json] [--force] <command>").configureOutput({
4187
- writeOut: io.stdout,
4188
- writeErr: io.stderr
4189
- }).exitOverride().showHelpAfterError().allowExcessArguments(false).addOption(new Option("--store <dir>", "store directory (or ORCH_STORE)").env("ORCH_STORE")).option("--json", "print complete rows as JSON", false).option("--force", "steal an existing store lock", false);
4190
- leaf(program, "init", "initialize the store").action(() => runStore(program, io, (store) => store.init(), (result) => `initialized ${result.store}`));
4191
- const unit = program.command("unit").description("manage work units").action(() => requireSubcommand(program));
4192
- leaf(unit, "add <id>", "add a unit").requiredOption("--track <track>", "unit track").option("--brief <path>", "brief path").action((id, options) => runStore(program, io, (store) => store.units.add({
4193
- id,
4194
- track: options.track,
4195
- brief: options.brief
4196
- }), unitLine));
4197
- leaf(unit, "set <id>", "update a unit").requiredOption("--state <state>", "unit state").option("--branch <branch>", "branch name").option("--pr <number>", "pull request number", positiveInteger).option("--sha <sha>", "commit SHA").action((id, options) => runStore(program, io, (store) => store.units.set({
4198
- id,
4199
- state: options.state,
4200
- branch: options.branch,
4201
- pr: options.pr,
4202
- sha: options.sha
4203
- }), unitLine));
4204
- leaf(unit, "get <id>", "get a unit").action((id) => runStore(program, io, (store) => store.units.get(id), unitLine));
4205
- leaf(unit, "list", "list units").option("--state <state>", "filter by state").option("--track <track>", "filter by track").action((options) => runStore(program, io, (store) => store.units.list(options), (rows) => compactRows(rows, unitLine, "(no units)")));
4206
- leaf(unit, "counts", "count units by state").action(() => runStore(program, io, (store) => store.units.counts(), countLine));
4207
- const ledger = program.command("ledger").description("manage verification records").action(() => requireSubcommand(program));
4208
- leaf(ledger, "record", "record a verification verdict").argument("<pr>", "pull request number", positiveInteger).argument("<sha>", "commit SHA").argument("<verdict>", "verification verdict", parseVerdict).requiredOption("--evidence <path>", "evidence path").option("--verifier <name>", "verifier name").action((pr, sha, verdict, options) => runStore(program, io, (store) => store.ledger.record({
4209
- pr,
4210
- sha,
4211
- verdict,
4212
- evidence: options.evidence,
4213
- verifier: options.verifier
4214
- }), (row) => `${row.pr}\t${row.sha}\t${row.verdict}`));
4215
- leaf(ledger, "check", "check a verification verdict").argument("<pr>", "pull request number", positiveInteger).argument("<sha>", "commit SHA").action((pr, sha) => runStore(program, io, (store) => store.ledger.check({
4216
- pr,
4217
- sha
4218
- }), (row) => row.verdict));
4219
- leaf(ledger, "summary", "count verification verdicts").action(() => runStore(program, io, (store) => store.ledger.summary(), countLine));
4220
- const inbox = program.command("inbox").description("manage agent pointers").action(() => requireSubcommand(program));
4221
- leaf(inbox, "push <agent> <unit> <status>", "push an inbox pointer").option("--report <path>", "report path").action((agent, unitId, status, options) => runStore(program, io, (store) => store.inbox.push({
4222
- agent,
4223
- unit: unitId,
4224
- status,
4225
- report: options.report
4226
- }), (result) => `${result.pointer.unit}\t${result.pointer.status}\t${result.filename}`, (result) => result.pointer));
4227
- leaf(inbox, "drain", "drain inbox pointers").option("--peek", "read without draining", false).action((options) => runStore(program, io, (store) => options.peek ? store.inbox.peek() : store.inbox.drain(), (rows) => compactRows(rows, pointerLine, "(empty)", null)));
4228
- leaf(inbox, "count", "count inbox pointers").action(() => runStore(program, io, (store) => store.inbox.count(), String, (count) => ({ count })));
4229
- const gate = program.command("gate").description("manage decision gates").action(() => requireSubcommand(program));
4230
- leaf(gate, "park <id>", "park a decision gate").requiredOption("--question <question>", "gate question").requiredOption("--options <options>", "gate options").requiredOption("--default <answer>", "default answer").action((id, options) => runStore(program, io, (store) => store.gates.park({
4231
- id,
4232
- question: options.question,
4233
- options: options.options,
4234
- defaultAnswer: options.default
4235
- }), (result) => `${result.id}\topen`));
4236
- leaf(gate, "list", "list open decision gates").action(() => runStore(program, io, (store) => store.gates.list(), (rows) => compactRows(rows, gateLine, "(no open gates)")));
4237
- leaf(gate, "resolve <id>", "resolve a decision gate").requiredOption("--answer <answer>", "chosen answer").action((id, options) => runStore(program, io, (store) => store.gates.resolve({
4238
- id,
4239
- answer: options.answer
4240
- }), (result) => `${result.id}\tresolved\t${result.answer}`));
4241
- const frontier = program.command("frontier").description("manage the stack frontier").action(() => requireSubcommand(program));
4242
- leaf(frontier, "set", "resolve the pull request base chain and set the frontier").addOption(new Option("--repo <dir>", "repository directory (or ORCH_REPO)").env("ORCH_REPO")).addOption(new Option("--forge <forge>", "pull request forge").choices(["gh", "origin"]).default("gh")).option("--prs <n,...>", "optional expected pull request order pin", prList).action((options) => runStore(program, io, (store) => store.frontier.set({
4243
- repo: frontierRepo(options),
4244
- forge: options.forge,
4245
- prs: options.prs
4246
- }), frontierLine));
4247
- leaf(frontier, "show", "show the frontier").action(() => runStore(program, io, (store) => store.frontier.show(), frontierLine));
4248
- leaf(program, "status", "render status.md and print a summary").action(() => runStore(program, io, (store) => store.status.render(), statusLines));
4249
- const standing = program.command("standing").description("manage standing orders").action(() => requireSubcommand(program));
4250
- leaf(standing, "show", "show standing orders").action(() => runStore(program, io, (store) => store.standing.show(), (rows) => compactRows(rows, (item) => `${item.number}. ${item.line}`, "(no standing orders)")));
4251
- leaf(standing, "add <line>", "add a standing order").action((line) => runStore(program, io, (store) => store.standing.add({ line }), (item) => `${item.number}. ${item.line}`));
4252
- program.action(() => requireSubcommand(program));
4253
- return program;
4254
- }
4255
- function handleError(error, program, io) {
4256
- if (error instanceof CommanderError) return error.exitCode === 0 ? 0 : 1;
4257
- const json = program.opts().json;
4258
- if (error instanceof NotFoundError) {
4259
- const output = error.output;
4260
- if (output === void 0) io.stderr(`error: ${error.message}\n`);
4261
- else emit(io, json, output.json, () => output.compact);
4262
- return 2;
4263
- }
4264
- io.stderr(`error: ${message(error)}\n`);
4265
- if (error instanceof UsageError) io.stderr(program.helpInformation());
4266
- return 1;
4267
- }
4268
- async function main(argv, io = {
4269
- stdout: (value) => process.stdout.write(value),
4270
- stderr: (value) => process.stderr.write(value)
4271
- }) {
4272
- const program = createProgram(io);
4273
- try {
4274
- await program.parseAsync(argv, { from: "user" });
4275
- return 0;
4276
- } catch (error) {
4277
- return handleError(error, program, io);
4278
- }
4279
- }
4280
- if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
4281
- //#endregion
4282
- export { main };