hacksh 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -128,9 +128,9 @@ const copy = defineCommand({
128
128
  z.string().meta({ title: "FILES", description: "Input files" }),
129
129
  ),
130
130
  }),
131
- run({ args }) {
131
+ run({ args, output }) {
132
132
  const [destination, ...files] = args.positionals; // [string, ...string[]]
133
- return { destination, files };
133
+ output.json({ destination, files });
134
134
  },
135
135
  });
136
136
  ```
@@ -486,8 +486,9 @@ holding the exact text, including the newline `println` adds, or
486
486
  pretty stdout, except that terminal control sequences are removed as in every JSON string. `json`
487
487
  values are normalized like log properties.
488
488
 
489
- hacksh never prints a `run` return value; it is returned to `runCommand` callers only.
490
- `runMain` reports thrown `HackshError` instances on stderr and rethrows other exceptions.
489
+ `run` return values are exit codes, never command output. Use `output` for data, or keep reusable
490
+ domain functions separate from the handler. `runMain` reports thrown `HackshError` instances on
491
+ stderr and rethrows other exceptions.
491
492
  Output that was written before a failure stays written. Like logger calls,
492
493
  `output` calls do not need to be awaited and are drained before execution finishes. Writing to
493
494
  `process.stdout` or `console.log` directly bypasses the printer, the output mode, and any `stdout`
@@ -606,7 +607,7 @@ produces `input-error` with the original error as `cause`.
606
607
  Explicit option types take the whole item type, for example
607
608
  `SelectOptions<{ value: "staging" | "production"; priority: number }>`.
608
609
 
609
- Prompts are allowed only when the resolved mode is interactive: pretty output outside CI with TTY
610
+ Input prompts are allowed only when the resolved mode is interactive: pretty output outside CI with TTY
610
611
  stdin and stdout. JSON, CI, and non-TTY invocations throw `HackshPromptError` immediately even if a
611
612
  default is available. Its `reason` and `prompt` fields identify why input failed and the prompt's
612
613
  `kind`, `message`, and select/autocomplete `choices`. Reasons distinguish `non-interactive`, `cancelled`,
@@ -626,8 +627,63 @@ Physical rows are calculated from explicit newlines, ANSI-free Unicode display w
626
627
  `stdout.columns`, including terminal wrapping. When a custom output writer does not expose a
627
628
  positive `columns` value, the renderer conservatively counts explicit lines only.
628
629
 
630
+ ### Waiting for work
631
+
632
+ Use `prompt.wait` to display a spinner in the left rail while a callback runs:
633
+
634
+ ```ts
635
+ const data = await prompt.wait(() => fetchData(), { message: "Fetching data" });
636
+ ```
637
+
638
+ The message is optional and defaults to `待機中`. The callback may return a value or a
639
+ promise; `wait` infers and returns its result, and propagates its thrown error unchanged.
640
+ The spinner animates only in interactive pretty mode. Non-TTY and CI invocations still
641
+ run the callback: pretty output prints a static message, while JSON emits `active` and
642
+ `closed` prompt events with `kind: "wait"`, without animation frames.
643
+
644
+ Logger and output events remain visible during the wait. On success or failure, the
645
+ animated row is replaced by the plain rail; `wait` does not print a success message.
646
+ With `unicode: false`, the spinner and rail use ASCII. Only one prompt or wait may be
647
+ active per invocation. Nested waits, input prompts, and terminal-owning external
648
+ commands are rejected with `overlapping`; captured `exec` calls remain available.
649
+
650
+ Wait does not read stdin or enable raw mode. An invocation abort stops the animation
651
+ and closes the display, but still awaits the callback and retains the terminal lock
652
+ until it settles. Pass the command context's `signal` to cancellable work. If the
653
+ callback rejects, its error takes precedence; otherwise an aborted wait rejects with
654
+ `HackshPromptError` (`aborted`). Printer failures similarly close the display and
655
+ reject with `printer-error` once the callback settles.
656
+
657
+ Custom printers receive `WaitPromptState` through ordinary prompt events. `frame` is
658
+ present for animated waits (including their closing event), and absent for static
659
+ waits.
660
+
629
661
  ### Cancellation and exit status
630
662
 
663
+ Handlers return `number | void | Promise<number | void>`. A returned integer from 0 through 255
664
+ is the exit code; `undefined` (including a handler with no return) means 0. Other values, including
665
+ fractions, `NaN`, infinities, out-of-range numbers, and non-numbers, cause a `TypeError`.
666
+ `runCommand` always returns `Promise<number>`: it resolves to the selected handler's exit code,
667
+ or 0 for help, version, or execution without a handler, and propagates thrown errors unchanged.
668
+ It does not print return values or exit the process.
669
+
670
+ ```ts
671
+ const health = defineCommand({
672
+ name: "health",
673
+ async run({ signal }) {
674
+ const response = await fetch("https://example.com/health", { signal });
675
+ return response.ok ? 0 : 2;
676
+ },
677
+ });
678
+
679
+ const exitCode = await runCommand(health, []); // number
680
+ ```
681
+
682
+ `runMain` drains output before applying the returned exit code. For 0 it sets
683
+ `process.exitCode = 0` and lets the process finish naturally; for a nonzero code it calls
684
+ `process.exit(code)`. Returning a nonzero code does not report an error or call `onError`.
685
+ Invalid returns reject with `TypeError`, without CLI error reporting or a forced exit.
686
+
631
687
  Every `run` context has a `signal`, an `AbortSignal` for that invocation. `exec` calls and prompts
632
688
  already follow it; pass it to `fetch` and other APIs that accept one. Cancellation is cooperative:
633
689
  hacksh does not stop code that ignores the signal.
@@ -658,9 +714,10 @@ output is drained and the process exits with 130 for `SIGINT` or 143 for `SIGTER
658
714
  exceptions and output failures still reject instead of being converted to a signal exit.
659
715
  A second signal while the invocation is pending exits immediately with that signal's status.
660
716
 
661
- Throw `HackshExitError(exitCode, message?)` to choose the exit status, an integer from 0 to 255.
717
+ Alternatively, throw `HackshExitError(exitCode, message?)` to choose an exit status from 0 to 255.
662
718
  `runMain` prints a non-empty message as an ordinary CLI error and prints nothing when the message
663
- is omitted; `onError` still receives the error. `runCommand` rethrows it unchanged.
719
+ is omitted; `onError` still receives the error. This error path calls `process.exit` even for 0.
720
+ `runCommand` rejects with the error unchanged.
664
721
  Other `HackshError` instances exit with 1, or 130 for a cancelled prompt.
665
722
 
666
723
  ## Output formats
@@ -734,14 +791,15 @@ the semantic events that the command emits.
734
791
 
735
792
  ### Entry points
736
793
 
737
- `defineCommand` preserves the handler's exact return type. Handlers are ordinary functions that
738
- return values or `void`, synchronously or asynchronously. `runCommand(command, argv, options)`
739
- returns a promise of the awaited result, unioned with results from every possible routed
740
- descendant and `undefined` for help/version. Routing-only commands add no handler result.
794
+ `defineCommand` accepts handlers returning `number | void | Promise<number | void>`; it does not
795
+ infer arbitrary result types. `CommandDef<S, Children>` describes the argument schema and child
796
+ commands, without a result type parameter. `runCommand(command, argv, options)` returns
797
+ `Promise<number>`: an integer exit code from 0 through 255, with `undefined`, help, version, and
798
+ execution without a handler normalized to 0. Invalid return values reject with `TypeError`.
741
799
  Thrown exceptions, argument errors, and output failures reject the promise. `runCommand` never
742
800
  exits or automatically prints a return value or error.
743
801
 
744
- `runMain(command)` reads `process.argv`, discards return values, and only handles thrown
802
+ `runMain(command)` reads `process.argv`, applies the returned exit code, and only handles thrown
745
803
  `HackshError` instances as normal CLI failures. Other exceptions reject without automatic error
746
804
  display, `onError`, or process exit. Pending output is drained and signal listeners are removed
747
805
  on both success and rejection. Output failures also reject, including while reporting a CLI
@@ -805,12 +863,13 @@ function loadUser(id: string) {
805
863
 
806
864
  const schema = z.object({ id: z.string() });
807
865
 
808
- function run({ args }: CommandContext<typeof schema>) {
866
+ function run({ args, output }: CommandContext<typeof schema>) {
809
867
  try {
810
- return loadUser(args.id);
868
+ output.json(loadUser(args.id));
811
869
  } catch (error) {
812
870
  if (error instanceof NotFoundError) {
813
- return { id: error.id, displayName: "Guest" };
871
+ output.json({ id: error.id, displayName: "Guest" });
872
+ return;
814
873
  }
815
874
  throw error;
816
875
  }
@@ -91,7 +91,7 @@ declare class HackshValidationError extends HackshUsageError {
91
91
  readonly issues: ReadonlyArray<HackshIssue>;
92
92
  constructor(command: AnyCommandDef, issues: ReadonlyArray<HackshIssue>);
93
93
  }
94
- type PromptKind = "select" | "autocomplete" | "confirm" | "text";
94
+ type PromptKind = "select" | "autocomplete" | "confirm" | "text" | "wait";
95
95
  type HackshPromptErrorReason = "non-interactive" | "cancelled" | "aborted" | "eof" | "overlapping" | "invalid-options" | "input-error" | "printer-error";
96
96
  interface PromptErrorDetails {
97
97
  kind: PromptKind;
@@ -285,7 +285,12 @@ interface AutocompletePromptState extends PromptStateBase {
285
285
  choices: readonly PromptChoiceState[];
286
286
  value?: string;
287
287
  }
288
- type PromptState = SelectPromptState | ConfirmPromptState | TextPromptState | AutocompletePromptState;
288
+ /** Waiting for callback completion; frame is present only for animated output. */
289
+ interface WaitPromptState extends PromptStateBase {
290
+ kind: "wait";
291
+ frame?: number;
292
+ }
293
+ type PromptState = SelectPromptState | ConfirmPromptState | TextPromptState | AutocompletePromptState | WaitPromptState;
289
294
  interface PromptPrintEvent {
290
295
  type: "prompt";
291
296
  prompt: PromptState;
@@ -380,11 +385,15 @@ interface TextOptions {
380
385
  placeholder?: string;
381
386
  validate?(value: string): string | undefined;
382
387
  }
388
+ interface WaitOptions {
389
+ message?: string;
390
+ }
383
391
  interface Prompter {
384
392
  select<const TItem extends SelectOption<string>>(options: SelectOptions<TItem>): Promise<TItem["value"]>;
385
393
  autocomplete<const TItem extends SelectOption<string>>(options: AutocompleteOptions<TItem>): Promise<TItem["value"]>;
386
394
  confirm(options: ConfirmOptions): Promise<boolean>;
387
395
  text(options: TextOptions): Promise<string>;
396
+ wait<T>(work: () => T | Promise<T>, options?: WaitOptions): Promise<T>;
388
397
  }
389
398
  //#endregion
390
399
  //#region src/schema.d.ts
@@ -417,7 +426,7 @@ interface CommandContext<S extends ArgsSchema> {
417
426
  exec: Exec;
418
427
  signal: AbortSignal;
419
428
  }
420
- interface CommandDef<S extends ArgsSchema = EmptyArgs, R = unknown, Children extends Record<string, AnyCommandDef> = Record<string, AnyCommandDef>> {
429
+ interface CommandDef<S extends ArgsSchema = EmptyArgs, Children extends Record<string, AnyCommandDef> = Record<string, AnyCommandDef>> {
421
430
  name?: string;
422
431
  version?: string;
423
432
  description?: string;
@@ -426,10 +435,10 @@ interface CommandDef<S extends ArgsSchema = EmptyArgs, R = unknown, Children ext
426
435
  allowUnknownArgs?: boolean;
427
436
  args?: S;
428
437
  subCommands?: Children;
429
- run?(context: CommandContext<S>): R;
438
+ run?(context: CommandContext<S>): number | void | Promise<number | void>;
430
439
  }
431
440
  type AnyCommandDef = CommandDef<ArgsSchema>;
432
- declare function defineCommand<S extends ArgsSchema = EmptyArgs, R = never, Children extends Record<string, AnyCommandDef> = {}>(def: CommandDef<S, R, Children>): NoInfer<CommandDef<S, R, Children>>;
441
+ declare function defineCommand<S extends ArgsSchema = EmptyArgs, Children extends Record<string, AnyCommandDef> = {}>(def: CommandDef<S, Children>): NoInfer<CommandDef<S, Children>>;
433
442
  //#endregion
434
- export { Logger as $, PromptStatus as A, resolveOutputMode as B, OutputWriter as C, PromptChoiceState as D, Printer as E, TerminalOutput as F, UsageSummary as G, UsageArgumentSummary as H, TextPromptState as I, summarizeUsage as J, renderUsage as K, UsagePrintEvent as L, SelectPromptState as M, StreamColors as N, PromptPrintEvent as O, TerminalInput as P, LogRecord as Q, VersionPrintEvent as R, OutputPrintEvent as S, PrintStream as T, UsageCommandSummary as U, ShowUsageOptions as V, UsageOptionSummary as W, LogLevel as X, LogKind as Y, LogProperties as Z, JsonPrinterOptions as _, ExecOptions as _t, ArgsSchema as a, HackshIssue as at, OutputMode as b, ExecSkipped as bt, Prompter as c, HackshUsageError as ct, TextOptions as d, PromptKind as dt, HackshError as et, Output as f, ValidationIssueSummary as ft, ExecPrintEvent as g, ExecFailureReason as gt, ErrorPrintEvent as h, ExecFailure as ht, defineCommand as i, HackshExitError as it, ResolveOutputModeOptions as j, PromptState as k, SelectOption as l, HackshValidationError as lt, ConfirmPromptState as m, ExecCommand as mt, CommandContext as n, HackshErrorSummary as nt, AutocompleteOptions as o, HackshPromptError as ot, AutocompletePromptState as p, Exec as pt, showUsage as q, CommandDef as r, HackshExecError as rt, ConfirmOptions as s, HackshPromptErrorReason as st, AnyCommandDef as t, HackshErrorKind as tt, SelectOptions as u, PromptErrorDetails as ut, LogPrintEvent as v, ExecResult as vt, PrintEvent as w, OutputPreference as x, ExecSuccess as xt, OutputFormat as y, ExecReturn as yt, createJsonPrinter as z };
435
- //# sourceMappingURL=command-Czf4qXhe.d.ts.map
443
+ export { LogProperties as $, PromptState as A, WaitPromptState as B, OutputPrintEvent as C, ExecSuccess as Ct, Printer as D, PrintStream as E, TerminalInput as F, UsageCommandSummary as G, resolveOutputMode as H, TerminalOutput as I, renderUsage as J, UsageOptionSummary as K, TextPromptState as L, ResolveOutputModeOptions as M, SelectPromptState as N, PromptChoiceState as O, StreamColors as P, LogLevel as Q, UsagePrintEvent as R, OutputPreference as S, ExecSkipped as St, PrintEvent as T, ShowUsageOptions as U, createJsonPrinter as V, UsageArgumentSummary as W, summarizeUsage as X, showUsage as Y, LogKind as Z, ExecPrintEvent as _, ExecFailure as _t, ArgsSchema as a, HackshExecError as at, OutputFormat as b, ExecResult as bt, Prompter as c, HackshPromptError as ct, TextOptions as d, HackshValidationError as dt, LogRecord as et, WaitOptions as f, PromptErrorDetails as ft, ErrorPrintEvent as g, ExecCommand as gt, ConfirmPromptState as h, Exec as ht, defineCommand as i, HackshErrorSummary as it, PromptStatus as j, PromptPrintEvent as k, SelectOption as l, HackshPromptErrorReason as lt, AutocompletePromptState as m, ValidationIssueSummary as mt, CommandContext as n, HackshError as nt, AutocompleteOptions as o, HackshExitError as ot, Output as p, PromptKind as pt, UsageSummary as q, CommandDef as r, HackshErrorKind as rt, ConfirmOptions as s, HackshIssue as st, AnyCommandDef as t, Logger as tt, SelectOptions as u, HackshUsageError as ut, JsonPrinterOptions as v, ExecFailureReason as vt, OutputWriter as w, OutputMode as x, ExecReturn as xt, LogPrintEvent as y, ExecOptions as yt, VersionPrintEvent as z };
444
+ //# sourceMappingURL=command-EDfoT1KJ.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as Logger, E as Printer, F as TerminalOutput, J as summarizeUsage, K as renderUsage, P as TerminalInput, V as ShowUsageOptions, _t as ExecOptions, a as ArgsSchema, at as HackshIssue, bt as ExecSkipped, c as Prompter, ct as HackshUsageError, d as TextOptions, dt as PromptKind, et as HackshError, f as Output, gt as ExecFailureReason, ht as ExecFailure, i as defineCommand, it as HackshExitError, l as SelectOption, lt as HackshValidationError, mt as ExecCommand, n as CommandContext, o as AutocompleteOptions, ot as HackshPromptError, pt as Exec, q as showUsage, r as CommandDef, rt as HackshExecError, s as ConfirmOptions, st as HackshPromptErrorReason, t as AnyCommandDef, u as SelectOptions, ut as PromptErrorDetails, vt as ExecResult, x as OutputPreference, xt as ExecSuccess, yt as ExecReturn } from "./command-Czf4qXhe.js";
1
+ import { Ct as ExecSuccess, D as Printer, F as TerminalInput, I as TerminalOutput, J as renderUsage, S as OutputPreference, St as ExecSkipped, U as ShowUsageOptions, X as summarizeUsage, Y as showUsage, _t as ExecFailure, a as ArgsSchema, at as HackshExecError, bt as ExecResult, c as Prompter, ct as HackshPromptError, d as TextOptions, dt as HackshValidationError, f as WaitOptions, ft as PromptErrorDetails, gt as ExecCommand, ht as Exec, i as defineCommand, l as SelectOption, lt as HackshPromptErrorReason, n as CommandContext, nt as HackshError, o as AutocompleteOptions, ot as HackshExitError, p as Output, pt as PromptKind, r as CommandDef, s as ConfirmOptions, st as HackshIssue, t as AnyCommandDef, tt as Logger, u as SelectOptions, ut as HackshUsageError, vt as ExecFailureReason, xt as ExecReturn, yt as ExecOptions } from "./command-EDfoT1KJ.js";
2
2
  import { output } from "zod/v4/core";
3
3
  //#region src/parser.d.ts
4
4
  /**
@@ -25,13 +25,7 @@ interface RunCommandOptions extends OutputOptions {
25
25
  printer?: Printer;
26
26
  signal?: AbortSignal;
27
27
  }
28
- type HandlerResult<C> = C extends {
29
- run?: infer Handler;
30
- } ? Handler extends ((...args: never[]) => infer R) ? Awaited<R> : never : never;
31
- type CommandResult<C> = HandlerResult<C> | (C extends {
32
- subCommands?: infer Children;
33
- } ? Children extends Record<string, AnyCommandDef> ? string extends keyof Children ? unknown : CommandResult<Children[keyof Children]> : never : never);
34
- declare function runCommand<C extends AnyCommandDef>(root: C, argv: string[], options?: RunCommandOptions): Promise<CommandResult<C> | undefined>;
28
+ declare function runCommand(root: AnyCommandDef, argv: string[], options?: RunCommandOptions): Promise<number>;
35
29
  interface RunMainOptions extends OutputOptions {
36
30
  onError?: (error: HackshError) => void | Promise<void>;
37
31
  argv?: string[];
@@ -39,5 +33,5 @@ interface RunMainOptions extends OutputOptions {
39
33
  }
40
34
  declare function runMain<S extends ArgsSchema>(command: CommandDef<S>, options?: RunMainOptions): Promise<void>;
41
35
  //#endregion
42
- export { type AutocompleteOptions, type CommandContext, type CommandDef, type ConfirmOptions, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecResult, type ExecReturn, type ExecSkipped, type ExecSuccess, HackshError, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type Logger, type Output, type OutputOptions, type PromptErrorDetails, type PromptKind, type Prompter, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type ShowUsageOptions, type TextOptions, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage, summarizeUsage };
36
+ export { type AutocompleteOptions, type CommandContext, type CommandDef, type ConfirmOptions, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecResult, type ExecReturn, type ExecSkipped, type ExecSuccess, HackshError, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type Logger, type Output, type OutputOptions, type PromptErrorDetails, type PromptKind, type Prompter, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type ShowUsageOptions, type TextOptions, type WaitOptions, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage, summarizeUsage };
43
37
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createExec, c as HackshExitError, d as HackshValidationError, f as summarizeError, i as resolveOutputMode, l as HackshPromptError, n as createJsonPrinter, o as HackshError, p as summarizeErrors, r as createPrintQueue, s as HackshExecError, t as createPrettyPrinter, u as HackshUsageError } from "./pretty-BjzGnVLM.js";
1
+ import { a as createExec, c as HackshExitError, d as HackshValidationError, f as summarizeError, i as resolveOutputMode, l as HackshPromptError, n as createJsonPrinter, o as HackshError, p as summarizeErrors, r as createPrintQueue, s as HackshExecError, t as createPrettyPrinter, u as HackshUsageError } from "./pretty-BykhfUqM.js";
2
2
  import { globalRegistry, safeParseAsync } from "zod/v4/core";
3
3
  import { parseArgs as parseArgs$1 } from "node:util";
4
4
  import { readFile, realpath } from "node:fs/promises";
@@ -834,6 +834,78 @@ var PromptController = class {
834
834
  this.#terminal.release();
835
835
  }
836
836
  }
837
+ async wait(work, options) {
838
+ const message = options?.message === void 0 ? "待機中" : options.message;
839
+ const prompt = details$1("wait", message);
840
+ validateMessage("wait", message);
841
+ if (typeof work !== "function") throw promptError("invalid-options", prompt, "Wait work must be a function");
842
+ if (this.#signal.aborted) throw promptError("aborted", prompt, "Prompt aborted", this.#signal.reason);
843
+ if (!this.#terminal.acquire("prompt")) throw promptError("overlapping", prompt, this.#terminal.owner === "exec" ? "A command is using the terminal" : "Another prompt is already active");
844
+ let frame = 0;
845
+ let stopped = false;
846
+ let timer;
847
+ let rendering = Promise.resolve();
848
+ let closing;
849
+ let failure;
850
+ const state = (status) => ({
851
+ kind: "wait",
852
+ message,
853
+ status,
854
+ ...this.#interactive ? { frame } : {}
855
+ });
856
+ const recordFailure = (error) => {
857
+ failure ??= error;
858
+ };
859
+ const close = () => {
860
+ stopped = true;
861
+ clearTimeout(timer);
862
+ timer = void 0;
863
+ closing ??= rendering.then(() => this.#print(state("closed"), prompt)).catch(recordFailure);
864
+ return closing;
865
+ };
866
+ const tick = () => {
867
+ timer = void 0;
868
+ frame += 1;
869
+ rendering = rendering.then(() => this.#print(state("active"), prompt)).then(() => {
870
+ if (!stopped) timer = setTimeout(tick, 80);
871
+ }, (error) => {
872
+ recordFailure(error);
873
+ close();
874
+ });
875
+ };
876
+ const onAbort = () => {
877
+ recordFailure(promptError("aborted", prompt, "Prompt aborted", this.#signal.reason));
878
+ close();
879
+ };
880
+ let outcome;
881
+ try {
882
+ rendering = rendering.then(() => this.#print(state("active"), prompt)).catch(recordFailure);
883
+ this.#signal.addEventListener("abort", onAbort, { once: true });
884
+ if (this.#signal.aborted) onAbort();
885
+ await rendering;
886
+ if (failure !== void 0) throw failure;
887
+ if (this.#interactive) timer = setTimeout(tick, 80);
888
+ outcome = {
889
+ ok: true,
890
+ value: await work()
891
+ };
892
+ } catch (error) {
893
+ outcome = {
894
+ ok: false,
895
+ error
896
+ };
897
+ } finally {
898
+ try {
899
+ await close();
900
+ } finally {
901
+ this.#signal.removeEventListener("abort", onAbort);
902
+ this.#terminal.release();
903
+ }
904
+ }
905
+ if (!outcome.ok) throw outcome.error;
906
+ if (failure !== void 0) throw failure;
907
+ return outcome.value;
908
+ }
837
909
  async select(options) {
838
910
  const prompt = validateChoices("select", options);
839
911
  const choices = sortedChoices(options, prompt);
@@ -1185,18 +1257,18 @@ async function executeCommand(root, argv, output, env, signal, fallbackVersion =
1185
1257
  type: "version",
1186
1258
  version
1187
1259
  });
1188
- return;
1260
+ return 0;
1189
1261
  }
1190
1262
  if (resolved.segments.some(({ tokenized }) => tokenized.help)) {
1191
1263
  await showUsage(resolved.command, { printer });
1192
- return;
1264
+ return 0;
1193
1265
  }
1194
1266
  for (const parent of resolved.parents) await parseCommandArgs(parent.command, parent.rawArgs, parent.tokenized, argEnv, commandEnvPath(parent.command));
1195
1267
  const parsed = await parseCommandArgs(resolved.command, resolved.rawArgs, resolved.tokenized, argEnv, commandEnvPath(resolved.command));
1196
1268
  if (!resolved.command.run) throw new HackshUsageError("No command specified", resolved.command);
1197
1269
  signal.throwIfAborted();
1198
1270
  const category = resolved.segments.flatMap(({ command }) => command.name === void 0 ? [] : [command.name]);
1199
- return resolved.command.run({
1271
+ const result = await resolved.command.run({
1200
1272
  command: resolved.command,
1201
1273
  args: parsed.args,
1202
1274
  input: {
@@ -1225,6 +1297,9 @@ async function executeCommand(root, argv, output, env, signal, fallbackVersion =
1225
1297
  }),
1226
1298
  signal
1227
1299
  });
1300
+ if (result === void 0) return 0;
1301
+ if (typeof result !== "number" || !Number.isInteger(result) || result < 0 || result > 255) throw new TypeError("Exit code must be an integer from 0 to 255");
1302
+ return result;
1228
1303
  }
1229
1304
  function prepareOutput(options, env) {
1230
1305
  const input = options.stdin ?? process.stdin;
@@ -1296,7 +1371,8 @@ async function runMain(command, options = {}) {
1296
1371
  let exitCode;
1297
1372
  try {
1298
1373
  try {
1299
- await executeCommand(command, options.argv ?? process.argv.slice(2), output, options.env, signals.signal, () => findPackageVersion(process.argv[1]));
1374
+ const result = await executeCommand(command, options.argv ?? process.argv.slice(2), output, options.env, signals.signal, () => findPackageVersion(process.argv[1]));
1375
+ if (result !== 0) exitCode = result;
1300
1376
  } catch (error) {
1301
1377
  const signalExitCode = signals.exitCode();
1302
1378
  if (signalExitCode !== void 0 && error === signals.signal.reason) exitCode = signalExitCode;
@@ -1316,6 +1392,7 @@ async function runMain(command, options = {}) {
1316
1392
  }
1317
1393
  const code = signals.exitCode() ?? exitCode;
1318
1394
  if (code !== void 0) process.exit(code);
1395
+ else process.exitCode = 0;
1319
1396
  }
1320
1397
  //#endregion
1321
1398
  export { HackshError, HackshExecError, HackshExitError, HackshPromptError, HackshUsageError, HackshValidationError, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage, summarizeUsage };