@rocket.chat/houston 0.27.0-next.3 → 2.1.8

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 (293) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -194
  284. package/dist/outputCI.js +0 -59
  285. package/src/bin.js +0 -4
  286. package/src/cli.ts +0 -25
  287. package/src/commands/createBranch.ts +0 -28
  288. package/src/outputCI.ts +0 -12
  289. package/src-old/logs.js +0 -323
  290. package/src-old/md.js +0 -191
  291. package/src-old/release-table.js +0 -60
  292. package/src-old/set-version.js +0 -614
  293. package/src-old/utils.js +0 -15
@@ -0,0 +1,861 @@
1
+ "use strict";
2
+ /**
3
+ * The single boundary through which Houston launches operating-system processes.
4
+ *
5
+ * This is deliberately a mechanism, not a policy layer. A non-zero exit and a
6
+ * signal are returned as process facts. Spawn and timeout failures are typed only
7
+ * enough for an adapter to preserve their cause; Docker, Kubernetes, TLS, and the
8
+ * CLI remain responsible for translating those facts into their distinct public
9
+ * contracts.
10
+ *
11
+ * Every command is an argv tuple and `shell` is always false. Text decoding is
12
+ * opt-in: output is bytes unless text is requested. Only `startDetached` calls `unref()`;
13
+ * using a process group for safe cancellation does not make an ordinary child outlive
14
+ * Houston.
15
+ *
16
+ * It is also where a Ctrl-C reaches what Houston is waiting on (see "CTRL-C" below): a
17
+ * child is the one wait every command has, and the lock and HTTP seams register theirs
18
+ * here because this is the only module below all of them.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.POPEN_SIGINT_WAIT_MS = exports.Interrupted = exports.ProcessTimeout = exports.SpawnFailure = void 0;
22
+ exports.stoppable = stoppable;
23
+ exports.unstoppable = unstoppable;
24
+ exports.interruptibly = interruptibly;
25
+ exports.interruptPoint = interruptPoint;
26
+ exports.sleep = sleep;
27
+ exports.unwindsOnInterrupt = unwindsOnInterrupt;
28
+ exports.cleanup = cleanup;
29
+ exports.interruptRaised = interruptRaised;
30
+ exports.interruptSettled = interruptSettled;
31
+ exports.interrupt = interrupt;
32
+ exports.resetInterruptForTest = resetInterruptForTest;
33
+ exports.capture = capture;
34
+ exports.stream = stream;
35
+ exports.inherit = inherit;
36
+ exports.startDetached = startDetached;
37
+ const node_async_hooks_1 = require("node:async_hooks");
38
+ const node_child_process_1 = require("node:child_process");
39
+ const node_util_1 = require("node:util");
40
+ /** A launch failure with the original Node error retained as `cause`. */
41
+ class SpawnFailure extends Error {
42
+ constructor(argv, cause) {
43
+ super(`could not spawn ${JSON.stringify(argv[0])}`, { cause });
44
+ this.name = 'SpawnFailure';
45
+ this.argv = [...argv];
46
+ this.cause = cause;
47
+ Object.setPrototypeOf(this, new.target.prototype);
48
+ }
49
+ }
50
+ exports.SpawnFailure = SpawnFailure;
51
+ /** A timeout with any output produced before cancellation attached. */
52
+ class ProcessTimeout extends Error {
53
+ constructor(argv, timeoutMs, result) {
54
+ super(`${JSON.stringify(argv[0])} timed out after ${timeoutMs} ms`);
55
+ this.name = 'ProcessTimeout';
56
+ this.argv = [...argv];
57
+ this.timeoutMs = timeoutMs;
58
+ this.result = result;
59
+ Object.setPrototypeOf(this, new.target.prototype);
60
+ }
61
+ }
62
+ exports.ProcessTimeout = ProcessTimeout;
63
+ // ------------------------------------------------------------------------------- CTRL-C
64
+ /**
65
+ * The Ctrl-C interrupt, raised where Houston was waiting when Ctrl-C arrived.
66
+ *
67
+ * NOT an `Error` a command should report. It is raised at the wait the command was in,
68
+ * every `finally` and every `cleanup` on the stack runs as it unwinds, and the CLI turns
69
+ * it into a silent exit 130. An ordinary-failure handler must not catch it -- a `catch`
70
+ * here does, so a `catch` that is such a handler rethrows it
71
+ * (`if (error instanceof Interrupted) throw error`).
72
+ */
73
+ class Interrupted extends Error {
74
+ constructor() {
75
+ super('');
76
+ this.name = 'Interrupted';
77
+ Object.setPrototypeOf(this, new.target.prototype);
78
+ }
79
+ }
80
+ exports.Interrupted = Interrupted;
81
+ /**
82
+ * How long a child that was being waited on when the interrupt arrived is given to end on
83
+ * its own, on the assumption that it also received the ^C, before it is SIGKILLed and the
84
+ * interrupt resumes. MEASURED against an earlier release with SIGINT sent to its pid alone,
85
+ * so the child never saw it: `logs --follow` and `down`, each waiting on a `sleep 30`,
86
+ * exited 0.31 s after the signal, with the child killed.
87
+ */
88
+ exports.POPEN_SIGINT_WAIT_MS = 250;
89
+ /**
90
+ * How long an unwind may run outside every `cleanup` before it is answered as a plain exit.
91
+ *
92
+ * Unwinding is the rejection reaching the command's own `finally` and `catch` blocks: the
93
+ * child's 250 ms above, and then JavaScript and awaits that have already settled. Two
94
+ * seconds is that with room to spare. A `cleanup` is a `finally` doing real work --
95
+ * `backup` starting Rocket.Chat again and waiting for it to serve, up to five minutes --
96
+ * and that has never had a bound, so this puts none on it: the clock stops while one
97
+ * runs. What the bound catches is an unwind this build cannot finish -- a wait nobody
98
+ * registered, which a Ctrl-C does not reach -- and a second Ctrl-C catches the rest, as it
99
+ * always has.
100
+ */
101
+ const UNWIND_BOUND_MS = 2000;
102
+ const frames = new node_async_hooks_1.AsyncLocalStorage();
103
+ /**
104
+ * The stop signal of the job this call chain belongs to: `serve`'s Stop button.
105
+ *
106
+ * The Ctrl-C machinery here is the whole process's. A GUI job is one of many in `serve`, and
107
+ * the only way to end one that was stuck -- a create waiting ten minutes on a port-forward it
108
+ * could not see -- was to kill the server, while its lock held up every other operation on
109
+ * that workspace. So a job carries its own signal. Aborted, every wait in that job that a
110
+ * Ctrl-C could reach rejects with Interrupted, a child stopped first; so does every wait it
111
+ * starts afterwards, so a catch that swallows one cannot carry the job on; and the other
112
+ * jobs never notice. Waits inside `cleanup` still run to the end.
113
+ */
114
+ const stops = new node_async_hooks_1.AsyncLocalStorage();
115
+ /** Run `body` as a job that aborting `signal` stops (see `stops`). */
116
+ function stoppable(signal, body) {
117
+ return stops.run(signal, body);
118
+ }
119
+ /**
120
+ * Run `body` outside any job's stop scope: for work SHARED between jobs, such as a probe
121
+ * memoised for the whole process. Started inside a job that is then stopped, its answer
122
+ * would be "refused" for every job that awaits it, for as long as the process runs.
123
+ */
124
+ function unstoppable(body) {
125
+ return stops.exit(body);
126
+ }
127
+ /** This chain's stop signal -- none inside cleanup, which runs to the end regardless. */
128
+ function stopSignal() {
129
+ return frames.getStore()?.cleanup != null ? undefined : stops.getStore();
130
+ }
131
+ const waiting = new Set();
132
+ /** Waits taken over and still in their grace: calling one ends the grace now. */
133
+ const inGrace = new Set();
134
+ const cleanups = new Set();
135
+ const stopping = [];
136
+ let unwinding = 0;
137
+ let lastCleanup = 0;
138
+ let state = { mode: 'idle' };
139
+ let endProcess = null;
140
+ let bound;
141
+ function exitNow() {
142
+ const end = endProcess;
143
+ endProcess = null;
144
+ if (bound !== undefined)
145
+ clearTimeout(bound);
146
+ end?.();
147
+ }
148
+ function armBound() {
149
+ if (bound !== undefined)
150
+ clearTimeout(bound);
151
+ const check = () => {
152
+ const cleaning = [...cleanups].some((one) => !one.interrupted);
153
+ if (cleaning || performance.now() - lastCleanup < UNWIND_BOUND_MS) {
154
+ bound = setTimeout(check, UNWIND_BOUND_MS);
155
+ return;
156
+ }
157
+ exitNow();
158
+ };
159
+ bound = setTimeout(check, UNWIND_BOUND_MS);
160
+ }
161
+ /**
162
+ * What a wait about to START does once a Ctrl-C has been answered: `run` in a `cleanup`,
163
+ * `raise` if it is the first wait of an unwind that nothing pending had taken the interrupt
164
+ * for, and otherwise `hold` -- never start, never settle -- because the process is ending.
165
+ *
166
+ * A wait that starts AFTER the Interrupted was raised, outside any cleanup, is code
167
+ * that must never run: something caught the interrupt as if it were an ordinary failure
168
+ * and carried on (a TypeScript `catch` meant as an ordinary-failure handler). Carrying on
169
+ * with it would start the next child, send the next request, print the next line -- so the
170
+ * process ends there.
171
+ */
172
+ function gate() {
173
+ if (state.mode === 'idle')
174
+ return 'run';
175
+ if (state.mode === 'exit')
176
+ return 'hold';
177
+ const frame = frames.getStore();
178
+ if (frame?.cleanup != null && !frame.cleanup.interrupted)
179
+ return 'run';
180
+ if (frame?.unwinds === true && !state.delivered) {
181
+ state.delivered = true;
182
+ return 'raise';
183
+ }
184
+ exitNow();
185
+ return 'hold';
186
+ }
187
+ /**
188
+ * A wait Ctrl-C can reach. `start` begins the work and says how to `stop` it; `graceMs` is
189
+ * how long the work may take to end on its own first (`POPEN_SIGINT_WAIT_MS` for a child).
190
+ *
191
+ * Taken over by an interrupt, the wait never settles with the work's own result: inside
192
+ * `unwindsOnInterrupt` it rejects with an Interrupted once the work is stopped, and
193
+ * outside it stays pending while the process ends. A child that exits inside the grace
194
+ * is still an interrupt, whatever the child did.
195
+ */
196
+ function interruptibly(start, graceMs = 0) {
197
+ const gated = gate();
198
+ if (gated === 'raise')
199
+ return Promise.reject(new Interrupted());
200
+ if (gated === 'hold')
201
+ return new Promise(() => undefined);
202
+ const signal = stopSignal();
203
+ if (signal?.aborted === true)
204
+ return Promise.reject(new Interrupted());
205
+ const { done, stop } = start();
206
+ const frame = frames.getStore();
207
+ return new Promise((resolve, reject) => {
208
+ let taken = false;
209
+ const entry = {
210
+ unwinds: frame?.unwinds === true,
211
+ take: async (raise) => {
212
+ taken = true;
213
+ if (graceMs > 0) {
214
+ // A LATER Ctrl-C lands inside this grace: the child is killed and the unwind goes
215
+ // on. So the grace can be cut short (`interrupt`), rather than the second Ctrl-C
216
+ // finding nothing pending and ending the process with nothing unwound.
217
+ let timer;
218
+ let hurry = () => undefined;
219
+ await Promise.race([
220
+ done.then(() => undefined, () => undefined),
221
+ new Promise((resolve) => {
222
+ timer = setTimeout(resolve, graceMs);
223
+ hurry = resolve;
224
+ inGrace.add(hurry);
225
+ }),
226
+ ]);
227
+ clearTimeout(timer);
228
+ inGrace.delete(hurry);
229
+ }
230
+ stop();
231
+ if (raise)
232
+ reject(new Interrupted());
233
+ },
234
+ };
235
+ // Its job stopped: this wait alone is taken over, as a Ctrl-C would take it.
236
+ const stopped = () => {
237
+ if (waiting.delete(entry))
238
+ void entry.take(true);
239
+ };
240
+ waiting.add(entry);
241
+ signal?.addEventListener('abort', stopped, { once: true });
242
+ done.then((value) => {
243
+ waiting.delete(entry);
244
+ signal?.removeEventListener('abort', stopped);
245
+ if (!taken)
246
+ resolve(value);
247
+ }, (error) => {
248
+ waiting.delete(entry);
249
+ signal?.removeEventListener('abort', stopped);
250
+ if (!taken)
251
+ reject(error);
252
+ });
253
+ });
254
+ }
255
+ /**
256
+ * Where a pending interrupt is raised in work that waits on nothing a Ctrl-C reaches --
257
+ * packing a bundle -- this is the wait.
258
+ */
259
+ function interruptPoint() {
260
+ return interruptibly(() => ({ done: Promise.resolve(), stop: () => undefined }));
261
+ }
262
+ /** A sleep, which a Ctrl-C interrupts. */
263
+ function sleep(ms) {
264
+ return interruptibly(() => {
265
+ let timer;
266
+ const done = new Promise((resolve) => {
267
+ timer = setTimeout(resolve, ms);
268
+ });
269
+ return { done, stop: () => clearTimeout(timer) };
270
+ });
271
+ }
272
+ /**
273
+ * Run `body` so that a Ctrl-C UNWINDS it: the waits inside reject with `Interrupted`,
274
+ * and the `finally` and `catch` blocks around them run on the way out.
275
+ *
276
+ * Outside every such body a Ctrl-C ends the process once what it waits on is stopped, with
277
+ * nothing unwound (`interrupt`). That is the default on purpose. Every TypeScript `catch`
278
+ * catches an Interrupted, and the ordinary-failure handlers they stand for must not:
279
+ * raised into a path that has not been read for that, the interrupt is swallowed and the
280
+ * command carries on -- `ready`'s restart count answers 0 and it prints one more
281
+ * `still booting` line. So an unwind is asked for where a cleanup is, around a body whose
282
+ * catches have been read.
283
+ */
284
+ async function unwindsOnInterrupt(body) {
285
+ unwinding += 1;
286
+ try {
287
+ return await frames.run({ unwinds: true, cleanup: null }, body);
288
+ }
289
+ finally {
290
+ unwinding -= 1;
291
+ }
292
+ }
293
+ /**
294
+ * Run `fn` as cleanup: to completion, whether or not an Interrupted is unwinding
295
+ * through it. Its waits start normally after the interrupt, and a Ctrl-C while it runs
296
+ * raises inside it.
297
+ */
298
+ async function cleanup(fn) {
299
+ const parent = frames.getStore();
300
+ const running = { interrupted: false };
301
+ cleanups.add(running);
302
+ try {
303
+ return await frames.run({ unwinds: parent?.unwinds === true, cleanup: running }, fn);
304
+ }
305
+ finally {
306
+ cleanups.delete(running);
307
+ lastCleanup = performance.now();
308
+ }
309
+ }
310
+ /** Whether a Ctrl-C has been answered by `interrupt` in this process. */
311
+ function interruptRaised() {
312
+ return state.mode !== 'idle';
313
+ }
314
+ /** Resolves once every wait the interrupt took over has had its work stopped. */
315
+ async function interruptSettled() {
316
+ await Promise.allSettled(stopping);
317
+ }
318
+ /**
319
+ * The CLI's Ctrl-C: `runMain`'s SIGINT listener calls this, with how to end the process.
320
+ *
321
+ * Inside `unwindsOnInterrupt`, the waits there raise Interrupted and the command
322
+ * unwinds; `end` is called only if the unwind cannot finish (`UNWIND_BOUND_MS`), if it
323
+ * resumes the command instead (`gate`), or at a second Ctrl-C with nothing left to raise
324
+ * in. Anywhere else, every pending wait has its work stopped -- a child after its grace
325
+ * (`POPEN_SIGINT_WAIT_MS`), then SIGKILLed -- and then `end` is called. A Ctrl-C while an
326
+ * earlier one's grace runs ends the grace: the child is killed there and then.
327
+ */
328
+ function interrupt(end) {
329
+ // Whatever an earlier Ctrl-C left in its grace is killed now, and goes on as it would have.
330
+ const hurried = [...inGrace];
331
+ inGrace.clear();
332
+ for (const hurry of hurried)
333
+ hurry();
334
+ if (state.mode === 'exit')
335
+ return;
336
+ endProcess = end;
337
+ const first = state.mode === 'idle';
338
+ if (first)
339
+ state = unwinding > 0 ? { mode: 'raise', delivered: false } : { mode: 'exit' };
340
+ const raising = state.mode === 'raise' ? state : null;
341
+ for (const running of cleanups)
342
+ running.interrupted = true;
343
+ const taken = [...waiting];
344
+ waiting.clear();
345
+ if (raising === null) {
346
+ // Nothing to stop: end now, in this handler.
347
+ if (taken.length === 0) {
348
+ exitNow();
349
+ return;
350
+ }
351
+ const stopped = taken.map((one) => one.take(false));
352
+ stopping.push(...stopped);
353
+ void Promise.allSettled(stopped).then(exitNow);
354
+ return;
355
+ }
356
+ if (!first && hurried.length === 0 && !taken.some((one) => one.unwinds)) {
357
+ exitNow();
358
+ return;
359
+ }
360
+ for (const one of taken) {
361
+ if (one.unwinds)
362
+ raising.delivered = true;
363
+ stopping.push(one.take(one.unwinds));
364
+ }
365
+ armBound();
366
+ }
367
+ /** Forget an interrupt, for a test that raised one in its own process. */
368
+ function resetInterruptForTest() {
369
+ if (bound !== undefined)
370
+ clearTimeout(bound);
371
+ bound = undefined;
372
+ state = { mode: 'idle' };
373
+ endProcess = null;
374
+ waiting.clear();
375
+ inGrace.clear();
376
+ cleanups.clear();
377
+ stopping.length = 0;
378
+ unwinding = 0;
379
+ lastCleanup = 0;
380
+ }
381
+ /**
382
+ * How long the death of a child killed by SIGINT is held back before it is reported.
383
+ *
384
+ * A terminal's Ctrl-C signals its whole foreground process group at once, so the child
385
+ * and Houston are interrupted by the same keypress and Houston's SIGINT is sent before the
386
+ * child can die of its own. The interrupt must be answered first, and the command
387
+ * interrupted whatever the child's status says, as it always has been. Node does not keep
388
+ * that order: the signal and the child's exit both wait for the event loop, and the exit
389
+ * can be handed to JS first. MEASURED on a pty,
390
+ * `logs --name <ws> --follow` waiting on a docker whose `compose logs` was `sleep 30`,
391
+ * Ctrl-C typed: in 14 of 300 runs (two loops at once; 1 of 100 alone) the child's `close`
392
+ * reached JS 1.2 to 2.3 ms before Houston's own SIGINT -- in the same turn of the loop in
393
+ * 13, 407 turns later in one. `logs` then returned 0, since it discards compose's code,
394
+ * and `runMain` wrote an `end` record of 0 and removed its handler before the interrupt
395
+ * got there: exit 0, every one of the 14. An earlier release gave 130 and an `end` of 130
396
+ * in every run.
397
+ *
398
+ * Held, the interrupt that came with the child's death is answered first, by `runMain`
399
+ * or by a command's own listener: 300 of 300 runs then exited 130 with an `end` of 130, 4
400
+ * of them in the late order. The result is unchanged; only
401
+ * when it is reported moves. A child killed on its own, with no interrupt for Houston,
402
+ * is reported this much later and otherwise as before -- `logs` still exits 0, as it
403
+ * always has. Not held: a child this seam signalled itself, and a child in its own
404
+ * process group (`processGroup`), which a terminal's Ctrl-C does not reach.
405
+ */
406
+ const INTERRUPT_GRACE_MS = 100;
407
+ /**
408
+ * Node cannot map a child's stderr to that same child's newly-created stdout pipe.
409
+ * A tiny Node relay supplies one real descriptor to both fds without using a shell.
410
+ * The control fd reports an inner spawn error separately from user output.
411
+ */
412
+ const MERGE_RELAY = String.raw `
413
+ const fs = require('node:fs');
414
+ const { spawn } = require('node:child_process');
415
+ const { Socket } = require('node:net');
416
+ let failed = false;
417
+ let finished = false;
418
+ let controlStream;
419
+ const child = spawn(process.argv[1], process.argv.slice(2), {
420
+ shell: false,
421
+ stdio: ['inherit', process.stdout, process.stdout],
422
+ });
423
+ child.once('error', error => {
424
+ failed = true;
425
+ controlStream.destroy();
426
+ fs.writeSync(3, JSON.stringify({
427
+ name: error.name,
428
+ message: error.message,
429
+ code: error.code,
430
+ errno: error.errno,
431
+ syscall: error.syscall,
432
+ path: error.path,
433
+ }));
434
+ process.exit(127);
435
+ });
436
+ child.once('exit', (code, signal) => {
437
+ if (failed) return;
438
+ finished = true;
439
+ controlStream.destroy();
440
+ if (signal) process.kill(process.pid, signal);
441
+ else process.exit(code === null ? 1 : code);
442
+ });
443
+ let control = '';
444
+ controlStream = new Socket({ fd: 4, readable: true, writable: false })
445
+ .setEncoding('utf8')
446
+ .on('data', chunk => {
447
+ control += chunk;
448
+ let newline;
449
+ while ((newline = control.indexOf('\n')) !== -1) {
450
+ const raw = control.slice(0, newline);
451
+ control = control.slice(newline + 1);
452
+ const signal = /^\d+$/.test(raw) ? Number(raw) : raw;
453
+ child.kill(signal);
454
+ }
455
+ })
456
+ .on('end', () => {
457
+ if (!failed && !finished) child.kill('SIGKILL');
458
+ });
459
+ `;
460
+ function command(argv) {
461
+ if (argv.length === 0 || argv[0].length === 0)
462
+ throw new TypeError('argv must name an executable');
463
+ return { file: argv[0], args: argv.slice(1), frozen: Object.freeze([...argv]) };
464
+ }
465
+ function decode(chunks, encoding) {
466
+ const joined = Buffer.concat(chunks);
467
+ return encoding === null ? joined : new node_util_1.TextDecoder('utf-8', { fatal: true }).decode(joined);
468
+ }
469
+ function signalChild(child, signal, processGroup) {
470
+ if (child.pid === undefined)
471
+ return;
472
+ if (processGroup && process.platform !== 'win32') {
473
+ try {
474
+ process.kill(-child.pid, signal);
475
+ return;
476
+ }
477
+ catch (error) {
478
+ if (error.code !== 'ESRCH')
479
+ throw error;
480
+ }
481
+ }
482
+ child.kill(signal);
483
+ }
484
+ function signalManagedChild(child, signal, processGroup, mergeRelayControl) {
485
+ if (mergeRelayControl !== null && (!processGroup || process.platform === 'win32')) {
486
+ if (!mergeRelayControl.destroyed && mergeRelayControl.writable) {
487
+ try {
488
+ mergeRelayControl.write(`${signal}\n`);
489
+ }
490
+ catch {
491
+ mergeRelayControl.destroy();
492
+ }
493
+ }
494
+ return;
495
+ }
496
+ signalChild(child, signal, processGroup);
497
+ }
498
+ /**
499
+ * A child Houston waits on: a Ctrl-C gives it `POPEN_SIGINT_WAIT_MS` to exit on its own,
500
+ * then SIGKILLs it (see `interruptibly`). Unless its caller answers the
501
+ * interrupt itself (`interrupt: 'caller'`).
502
+ */
503
+ function runMode(argv, mode, options) {
504
+ if (options.interrupt === 'caller')
505
+ return launch(argv, mode, options).done;
506
+ return interruptibly(() => launch(argv, mode, options), exports.POPEN_SIGINT_WAIT_MS);
507
+ }
508
+ /** No child was started, so there is nothing for an interrupt to stop. */
509
+ function notLaunched(error) {
510
+ return { done: Promise.reject(error), stop: () => undefined };
511
+ }
512
+ function launch(argv, mode, options) {
513
+ const resolved = command(argv);
514
+ const processGroup = options.processGroup ?? false;
515
+ const encoding = 'encoding' in options ? (options.encoding ?? null) : null;
516
+ const mergeStderr = 'mergeStderr' in options && options.mergeStderr === true;
517
+ const ioOptions = mode === 'inherit' ? null : options;
518
+ if (ioOptions?.input !== undefined && ioOptions.stdin !== undefined) {
519
+ return notLaunched(new TypeError('input and stdin are mutually exclusive'));
520
+ }
521
+ if (mergeStderr && mode === 'stream' && options.stderrSink !== undefined) {
522
+ return notLaunched(new TypeError('stderrSink cannot be used when mergeStderr is true'));
523
+ }
524
+ if (options.timeoutMs !== undefined &&
525
+ (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 0)) {
526
+ return notLaunched(new RangeError('timeoutMs must be a finite non-negative number'));
527
+ }
528
+ const stdoutChunks = [];
529
+ const stderrChunks = [];
530
+ const mergedChunks = [];
531
+ const mergedThroughRelay = mergeStderr && mode !== 'inherit';
532
+ const stdinMode = ioOptions?.input !== undefined ||
533
+ (ioOptions?.stdin !== undefined && typeof ioOptions.stdin !== 'string')
534
+ ? 'pipe'
535
+ : (ioOptions?.stdin ?? 'inherit');
536
+ let child;
537
+ try {
538
+ child = (0, node_child_process_1.spawn)(mergedThroughRelay ? process.execPath : resolved.file, mergedThroughRelay
539
+ ? ['-e', MERGE_RELAY, '--', resolved.file, ...resolved.args]
540
+ : resolved.args, {
541
+ ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
542
+ ...(options.env !== undefined ? { env: options.env } : {}),
543
+ detached: processGroup,
544
+ shell: false,
545
+ stdio: mode === 'inherit'
546
+ ? options.stdoutToStderr === true
547
+ ? ['inherit', 2, 'inherit']
548
+ : 'inherit'
549
+ : mergedThroughRelay
550
+ ? [stdinMode, 'pipe', 'ignore', 'pipe', 'pipe']
551
+ : [stdinMode, 'pipe', 'pipe'],
552
+ });
553
+ }
554
+ catch (error) {
555
+ return notLaunched(new SpawnFailure(resolved.frozen, error));
556
+ }
557
+ let stop = () => undefined;
558
+ const done = new Promise((resolve, reject) => {
559
+ let settled = false;
560
+ let timedOut = false;
561
+ // Whether this seam sent the child a signal itself, and whether a death by SIGINT is
562
+ // being held back (see INTERRUPT_GRACE_MS).
563
+ let signalled = false;
564
+ let holding = false;
565
+ let timer;
566
+ let closed = null;
567
+ let pendingSinkWrites = 0;
568
+ const mergeControl = [];
569
+ const mergeRelayControl = mergedThroughRelay ? child.stdio[4] : null;
570
+ if (mergedThroughRelay) {
571
+ child.stdio[3]?.on('data', (chunk) => {
572
+ mergeControl.push(Buffer.from(chunk));
573
+ });
574
+ }
575
+ const stdoutDecoder = mode === 'stream' && encoding !== null ? new node_util_1.TextDecoder('utf-8', { fatal: true }) : null;
576
+ const stderrDecoder = mode === 'stream' && encoding !== null ? new node_util_1.TextDecoder('utf-8', { fatal: true }) : null;
577
+ const streamOptions = mode === 'stream' ? options : null;
578
+ const finishStream = (decoder, callback) => {
579
+ if (decoder === null || callback === undefined)
580
+ return;
581
+ try {
582
+ const tail = decoder.decode();
583
+ if (tail.length > 0) {
584
+ callback(tail);
585
+ }
586
+ }
587
+ catch (error) {
588
+ fail(error);
589
+ }
590
+ };
591
+ const cleanup = (keepSinkErrorListener) => {
592
+ if (timer !== undefined)
593
+ clearTimeout(timer);
594
+ options.abortSignal?.removeEventListener('abort', abort);
595
+ if (ioOptions?.stdin !== undefined && typeof ioOptions.stdin !== 'string') {
596
+ ioOptions.stdin.removeListener('error', fail);
597
+ if (child.stdin !== null)
598
+ ioOptions.stdin.unpipe(child.stdin);
599
+ }
600
+ if (streamOptions?.stdoutSink !== keepSinkErrorListener) {
601
+ streamOptions?.stdoutSink?.removeListener('error', fail);
602
+ }
603
+ if (streamOptions?.stderrSink !== keepSinkErrorListener) {
604
+ streamOptions?.stderrSink?.removeListener('error', fail);
605
+ }
606
+ };
607
+ const controlError = (error) => {
608
+ // The relay is gone -- killed with the child it relays for, by the same terminal
609
+ // Ctrl-C -- so there is nothing left to signal, as ESRCH is nothing for a direct child
610
+ // (`signalChild`). Its death reaches `close` like any other. Rejecting here turned a
611
+ // signal sent to a dead relay into the command's error: Kubernetes `logs`, Ctrl-C'd on
612
+ // a terminal, terminates kubectl, as it always has, and wrote a JS stack of
613
+ // `read ECONNRESET` instead of exiting 254.
614
+ if (error.code === 'EPIPE' || error.code === 'ECONNRESET') {
615
+ mergeRelayControl?.destroy();
616
+ return;
617
+ }
618
+ if (settled)
619
+ return;
620
+ settled = true;
621
+ cleanup();
622
+ mergeRelayControl?.destroy();
623
+ reject(error);
624
+ };
625
+ mergeRelayControl?.once('error', controlError);
626
+ const abort = () => {
627
+ signalled = true;
628
+ try {
629
+ signalManagedChild(child, options.abortKillSignal ?? 'SIGTERM', processGroup, mergeRelayControl);
630
+ }
631
+ catch (error) {
632
+ fail(error);
633
+ }
634
+ };
635
+ const fail = (error, possibleLateSinkError) => {
636
+ if (settled)
637
+ return;
638
+ settled = true;
639
+ cleanup(possibleLateSinkError);
640
+ if (possibleLateSinkError !== undefined) {
641
+ // Writable implementations may both pass the error to the write callback
642
+ // and emit it just afterward. Keep the once-listener for that turn so the
643
+ // duplicate cannot become uncaught, then remove it if no event arrives.
644
+ setImmediate(() => possibleLateSinkError.removeListener('error', fail));
645
+ }
646
+ try {
647
+ signalManagedChild(child, 'SIGKILL', processGroup, mergeRelayControl);
648
+ }
649
+ catch {
650
+ // Preserve the initiating error; the cancellation failure is secondary.
651
+ }
652
+ reject(error);
653
+ };
654
+ const complete = () => {
655
+ if (settled || closed === null || pendingSinkWrites > 0 || holding)
656
+ return;
657
+ if (mergeControl.length > 0) {
658
+ let record;
659
+ try {
660
+ const fields = JSON.parse(Buffer.concat(mergeControl).toString('utf8'));
661
+ record = Object.assign(new Error(String(fields.message ?? 'spawn failed')), fields);
662
+ }
663
+ catch (error) {
664
+ record = Object.assign(new Error('merge relay did not report a valid spawn error'), {
665
+ cause: error,
666
+ });
667
+ }
668
+ fail(new SpawnFailure(resolved.frozen, record));
669
+ return;
670
+ }
671
+ const captured = mode === 'capture';
672
+ let result;
673
+ try {
674
+ result = {
675
+ argv: resolved.frozen,
676
+ exitCode: closed.exitCode,
677
+ signal: closed.exitSignal,
678
+ stdout: captured ? decode(mergeStderr ? mergedChunks : stdoutChunks, encoding) : null,
679
+ stderr: captured && !mergeStderr ? decode(stderrChunks, encoding) : null,
680
+ };
681
+ }
682
+ catch (error) {
683
+ fail(error);
684
+ return;
685
+ }
686
+ settled = true;
687
+ cleanup();
688
+ if (timedOut && options.timeoutMs !== undefined) {
689
+ reject(new ProcessTimeout(resolved.frozen, options.timeoutMs, result));
690
+ }
691
+ else {
692
+ resolve(result);
693
+ }
694
+ };
695
+ const writeSink = (sink, source, chunk) => {
696
+ pendingSinkWrites += 1;
697
+ source.pause();
698
+ try {
699
+ sink.write(chunk, (error) => {
700
+ pendingSinkWrites -= 1;
701
+ if (error != null) {
702
+ fail(error, sink);
703
+ return;
704
+ }
705
+ source.resume();
706
+ complete();
707
+ });
708
+ }
709
+ catch (error) {
710
+ pendingSinkWrites -= 1;
711
+ fail(error);
712
+ }
713
+ };
714
+ child.once('error', (cause) => {
715
+ fail(new SpawnFailure(resolved.frozen, cause));
716
+ });
717
+ if (mode !== 'inherit') {
718
+ // RETAINED ONLY WHEN CAPTURED. The merged copy was kept in every mode, so a `stream`
719
+ // with `mergeStderr` -- Kubernetes `logs -f` is one -- held all the output it had
720
+ // delivered, for a result that is `null` outside capture mode.
721
+ child.stdout?.on('data', (chunk) => {
722
+ const copy = Buffer.from(chunk);
723
+ if (mode === 'capture')
724
+ (mergeStderr ? mergedChunks : stdoutChunks).push(copy);
725
+ if (streamOptions?.onStdout !== undefined) {
726
+ try {
727
+ streamOptions.onStdout(stdoutDecoder === null ? copy : stdoutDecoder.decode(copy, { stream: true }));
728
+ }
729
+ catch (error) {
730
+ fail(error);
731
+ }
732
+ }
733
+ if (streamOptions?.stdoutSink !== undefined && child.stdout !== null) {
734
+ writeSink(streamOptions.stdoutSink, child.stdout, copy);
735
+ }
736
+ });
737
+ child.stderr?.on('data', (chunk) => {
738
+ const copy = Buffer.from(chunk);
739
+ if (mode === 'capture')
740
+ (mergeStderr ? mergedChunks : stderrChunks).push(copy);
741
+ const callback = mergeStderr ? streamOptions?.onStdout : streamOptions?.onStderr;
742
+ if (callback !== undefined) {
743
+ try {
744
+ callback(stderrDecoder === null ? copy : stderrDecoder.decode(copy, { stream: true }));
745
+ }
746
+ catch (error) {
747
+ fail(error);
748
+ }
749
+ }
750
+ const sink = mergeStderr ? streamOptions?.stdoutSink : streamOptions?.stderrSink;
751
+ if (sink !== undefined && child.stderr !== null)
752
+ writeSink(sink, child.stderr, copy);
753
+ });
754
+ if (streamOptions?.stdoutSink !== undefined) {
755
+ streamOptions.stdoutSink.once('error', fail);
756
+ }
757
+ if (!mergeStderr && streamOptions?.stderrSink !== undefined) {
758
+ streamOptions.stderrSink.once('error', fail);
759
+ }
760
+ child.stdout?.once('end', () => finishStream(stdoutDecoder, streamOptions?.onStdout));
761
+ child.stderr?.once('end', () => finishStream(stderrDecoder, mergeStderr ? streamOptions?.onStdout : streamOptions?.onStderr));
762
+ child.stdin?.on('error', (error) => {
763
+ // A broken pipe when the child exits before consuming all its input is suppressed,
764
+ // as it always has been, which also avoids an unhandled EventEmitter error.
765
+ if (error.code !== 'EPIPE' && error.code !== 'ERR_STREAM_DESTROYED')
766
+ fail(error);
767
+ });
768
+ if (ioOptions?.stdin !== undefined &&
769
+ typeof ioOptions.stdin !== 'string' &&
770
+ child.stdin !== null) {
771
+ ioOptions.stdin.once('error', fail);
772
+ ioOptions.stdin.pipe(child.stdin);
773
+ }
774
+ else {
775
+ child.stdin?.end(ioOptions?.input);
776
+ }
777
+ }
778
+ options.abortSignal?.addEventListener('abort', abort, { once: true });
779
+ if (options.abortSignal?.aborted === true)
780
+ abort();
781
+ if (options.timeoutMs !== undefined) {
782
+ timer = setTimeout(() => {
783
+ timedOut = true;
784
+ signalled = true;
785
+ try {
786
+ signalManagedChild(child, options.timeoutSignal ?? 'SIGKILL', processGroup, mergeRelayControl);
787
+ }
788
+ catch (error) {
789
+ fail(error);
790
+ }
791
+ }, options.timeoutMs);
792
+ }
793
+ child.once('close', (exitCode, exitSignal) => {
794
+ closed = { exitCode, exitSignal };
795
+ if (exitSignal === 'SIGINT' && !signalled && !processGroup) {
796
+ // The child is gone, so nothing is left to time out: the grace must not become a
797
+ // ProcessTimeout for a child that finished inside its deadline.
798
+ if (timer !== undefined)
799
+ clearTimeout(timer);
800
+ holding = true;
801
+ setTimeout(() => {
802
+ holding = false;
803
+ complete();
804
+ }, INTERRUPT_GRACE_MS);
805
+ return;
806
+ }
807
+ complete();
808
+ });
809
+ // A Ctrl-C's `run` answer: SIGKILL the child and raise (see `interruptibly`).
810
+ stop = () => fail(new Interrupted());
811
+ });
812
+ return { done, stop };
813
+ }
814
+ /** Run to completion while retaining stdout and stderr separately by default. */
815
+ function capture(argv, options = {}) {
816
+ return runMode(argv, 'capture', options);
817
+ }
818
+ /** Deliver stdout/stderr as they arrive without retaining an unbounded copy. */
819
+ function stream(argv, options = {}) {
820
+ return runMode(argv, 'stream', options);
821
+ }
822
+ /** Run with the parent's stdin/stdout/stderr, including its TTY identity. */
823
+ function inherit(argv, options = {}) {
824
+ return runMode(argv, 'inherit', options);
825
+ }
826
+ /**
827
+ * Start a child that intentionally outlives this command.
828
+ *
829
+ * Detached children cannot safely retain Houston's pipes: a referenced pipe would
830
+ * keep the launching command alive. The returned PID is the cleanup handle.
831
+ */
832
+ function startDetached(argv, options = {}) {
833
+ const resolved = command(argv);
834
+ let child;
835
+ try {
836
+ child = (0, node_child_process_1.spawn)(resolved.file, resolved.args, {
837
+ ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
838
+ ...(options.env !== undefined ? { env: options.env } : {}),
839
+ detached: true,
840
+ shell: false,
841
+ stdio: 'ignore',
842
+ });
843
+ }
844
+ catch (error) {
845
+ return Promise.reject(new SpawnFailure(resolved.frozen, error));
846
+ }
847
+ return new Promise((resolve, reject) => {
848
+ child.once('error', (cause) => {
849
+ reject(new SpawnFailure(resolved.frozen, cause));
850
+ });
851
+ child.once('spawn', () => {
852
+ const pid = child.pid;
853
+ if (pid === undefined) {
854
+ reject(new Error('spawned child has no pid'));
855
+ return;
856
+ }
857
+ child.unref();
858
+ resolve({ argv: resolved.frozen, pid });
859
+ });
860
+ });
861
+ }