Skip to content

Commit 586e4c3

Browse files
JasonVMoCopilot
andauthored
Fix desktop CLI errors, shutdown hangs, and run verdicts (#4478)
* Report desktop-driver CLI usage errors in every reporter mode Commander copies exit and output settings only into commands created after they are set, so subcommand usage errors went to an in-memory buffer and exited silently. Apply the reporter output and exit override to the whole command tree. - Route usage errors through the selected reporter: one error record in json and ndjson, a stderr message in plain. - Throw InvalidArgumentError from option parsers so they are reported as usage errors instead of internal. - Resolve the reporter mode once and before any action, so an invalid DESKTOP_REPORTER no longer lets serve start listening. - Write the serve readiness record inside the try so a write failure still closes the server. - Make the NDJSON error record the single terminal record, matching JSON. - Map WebDriver error codes to matching CLI error kinds, including busy for target-busy session failures. - Clip doctor error messages to the same byte limit as other errors. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Report storybook-desktop CLI option errors as usage errors Option parsers and input checks threw TypeError, which the reporter classified as internal. Throw InvalidArgumentError so the error is reported as a usage error in every mode. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Document desktop-driver CLI error records Describe the single error record written for usage and configuration failures in json and ndjson modes, and correct the NDJSON terminal record rule. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Decide desktop-test verdicts from decisive attempts and reported work Retried tests no longer pass when a failed attempt is followed only by skipped attempts, selected worker work that reported no tests is incomplete, and presentation errors become warnings that keep the verdict. Incomplete lane runs list their unmet work and throw a typed error, secrets are sanitized once at finalize, run-query errors use a closed code set without filesystem paths, NDJSON milestones never suppress failures, run.json writes are throttled, and IPC producers cannot send collector-only events. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Order WDIO attempts by arrival and surface empty specs The producer's attempt number is opaque, so retry numbering no longer corrupts workerAttempt, a spec that ran no tests is reported as a warning, and the generated config raises the framework log level so spec import failures show. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Document desktop-test verdict rules and add changeset Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix desktop-test shutdown hangs and cancellation - Integrations borrow the supervisor scope without closing it; the CLI awaits the integration run outside the scope with a bound, and scope draining is bounded (drainTimeoutMs), so Storybook serve and story tests exit after SIGINT (LIFE-1). storybook-desktop closes only a scope it created. - Stage, suite and storybook-desktop stage commands receive the scope signal; abort stops the POSIX process group as failed, a late spawn is refused, and sync spawn failures leave nothing tracked (LIFE-2, LIFE-9). - Interrupt handlers cover SIGINT/SIGTERM/SIGHUP until cleanup completes; a second signal force-kills owned trees, a third exits (LIFE-3..5). - Close disposes services and resources in one reverse order, isolates observer failures and releases spawn-failure claims (LIFE-10, LIFE-13). - Per-user claim directory, atomic claim replacement and start-time tolerance (LIFE-6, LIFE-8 partial); one short private local-socket helper for process control and reporting transport, with IPC only for services (LIFE-7, REP-11). - Generated WDIO config reads settings from a file; PowerShell reads the AppX name from the environment; suiteTimeoutMs bounds the launcher; NUL is rejected in command args and env (LIFE-11, LIFE-12, LIFE-15, LIFE-17). - Tests: commands, services, signals, localSocket, transport negatives, lifecycle and CLI-interrupt contracts, public-entry consumer, borrowed-scope regression (LIFE-16, REP-16). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Document desktop-test shutdown, cancellation and claim location Records the fixed idle-CLI-after-interrupt cause, signal escalation, bounded draining, reverse disposal, the per-user claim directory, suiteTimeoutMs and the NUL rule, and the borrowed storybook-desktop scope. Adds changesets. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Defer workload-claim start-time identity Remove the one-second start-time tolerance from workload-claim inspection. The recorded start time comes from the Node.js clock rather than the operating system, and a tolerance would let a reused process ID match a live owner. Inspection compares exactly again; the lifecycle and status references record that `pid-reused` is unproven until the claim records a helper-described start time (LIFE-8 deferred). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Keep interrupt handlers through storybook-desktop cleanup Export the desktop-test interrupt policy as `handleDesktopInterrupts` and use it in the storybook-desktop CLI and standalone Storybook channel. The handlers now stay installed until cleanup completes, SIGHUP is handled, a second interrupt force-stops owned commands, and a third exits without cleanup. Previously the one-shot `process.once` listeners were consumed by the first signal, so a second SIGINT or a SIGHUP killed the CLI mid-cleanup. An interrupted one-shot command, such as a stage, now reports `incomplete` instead of passed with exit 0. Tests: interrupted stage under SIGINT/SIGINT and SIGHUP/SIGTERM, standalone channel SIGHUP, and an owned service escalating on a second SIGINT; each fails without the change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address Windows process trees only before recorded exit Run `taskkill /T /F` synchronously, and only while the command's exit is unrecorded. Windows reuses a process ID only after every handle to the process closes, and Node closes the child handle while processing the exit on the same event loop, so the ID still names the owned leader. A failed taskkill is now judged by the recorded completion rather than by probing a process ID that may have been reused, and the asynchronous force-stop spawn that could race the exit is gone. This is not descendant containment: `/T` follows parent process IDs, so a descendant whose parent already exited still escapes until Job Object containment exists. Emulated-Windows tests cover the exit gate, the synchronous call, and a failed taskkill for a leader that keeps running. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Assert spec-load failures name the failed spec The spec-load-failure contract now also requires the failed work item to be labelled with the spec that threw. The original error text remains in the worker command log only; run.json and junit.xml do not carry it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Print aggregate members when a desktop-test contract fails The contract runner printed only the outer error stack, so an AggregateError from disposal hid the cleanup failure that caused it. Print the error with `util.inspect` so members and causes are included. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent f14e254 commit 586e4c3

66 files changed

Lines changed: 3800 additions & 555 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/cli-usage-errors.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@fluentui-react-native/desktop-driver': patch
3+
'@fluentui-react-native/storybook-desktop': patch
4+
---
5+
6+
Report desktop-driver CLI usage errors in every reporter mode. Subcommand usage errors now reach stderr (plain) or a single `error` record (json and ndjson) and exit 1 instead of exiting silently. An invalid `DESKTOP_REPORTER` no longer lets `serve` start. NDJSON failures emit the error record as their terminal record, matching JSON. WebDriver errors map to matching CLI error codes, and `doctor` messages are clipped.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@fluentui-react-native/desktop-test': patch
3+
---
4+
5+
Fix shutdown hangs and cancellation. An integration's run is no longer tracked in the scope it borrows, so a Storybook `serve` or story test exits after SIGINT instead of idling, and scope draining is bounded. Cancellation stops running stage and suite commands, including their POSIX process groups, reports them failed, and refuses late spawns. A second interrupt force-stops owned process trees, SIGHUP is handled, and handlers stay installed until cleanup completes; `handleDesktopInterrupts` exports that policy for integrations. On Windows, `taskkill` runs synchronously and only before the command's exit is recorded, so it cannot address a reused process ID. Close disposes services and resources in one reverse order even when an observer throws. Workload claims move to a per-user directory independent of TMPDIR and are replaced atomically; local sockets use short private paths. Generated WDIO configs read settings from a file, suites accept `suiteTimeoutMs`, and command arguments and environment reject NUL.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@fluentui-react-native/storybook-desktop': patch
3+
---
4+
5+
Leave an injected desktop-test service scope to its owner instead of closing it from `driver`, `server`, and the smoke lifecycle, which made a supervising `desktop-test serve` or story test wait on itself after a stop. Stage commands now receive the scope's cancellation signal. The CLI and the standalone Storybook channel keep their interrupt handlers until cleanup completes, handle SIGHUP, and force-stop owned commands on a second interrupt; an interrupted one-shot command reports `incomplete` instead of passed.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@fluentui-react-native/desktop-test': patch
3+
---
4+
5+
Fix verdicts that passed without coverage. A test takes the status of its decisive attempt, so a failed attempt followed only by skipped or unsupported retries stays failed. Selected worker work that reports no tests is `incomplete`, and the WDIO reporter warns when a spec ran no tests, with the jasmine and mocha framework loggers raised to `warn` so an import failure is visible. WDIO attempts keep their arrival order whatever numbers the runner reports. Console stalls, closed pipes, and queue overflow are warnings that no longer fail a passing run, and the final line comes from the terminal result. Incomplete runs list their unmet work and a JUnit message that names it, and result checks throw a typed `DesktopIncompleteError` that reporters record as the run's verdict instead of an infrastructure failure. Failures and late-registered secrets are sanitized once at finalization, and run-query errors use a closed code set without filesystem paths. NDJSON milestones no longer suppress a later failure after many skips, record IDs are not clipped, a projection failure still emits a summary record, `run.json` snapshots are throttled, and producers can no longer send `run-finished`.

‎packages/agentic/desktop-driver/references/getting-started.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,10 @@ desktop-driver stories list --platform windows --url http://127.0.0.1:7007 --tar
111111
`--reporter auto|plain|github-actions|json|ndjson` is also configurable with
112112
`DESKTOP_REPORTER`; `--json` aliases `--reporter json`. In `auto`, existing
113113
indented JSON is retained. One-shot commands write one result, while `serve`
114-
emits one readiness result and then waits for shutdown.
114+
emits one readiness result and then waits for shutdown. A usage or
115+
configuration error in `json` or `ndjson` writes one `error` record
116+
(`{"schemaVersion":1,"type":"error","error":{"code","message"}}`) to stdout and
117+
exits 1; `plain` writes the message to stderr.
115118

116119
## Resolve and diagnose
117120

‎packages/agentic/desktop-driver/references/remaining-work.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -425,12 +425,12 @@ alias for `--reporter json`. Resolve the mode from the flag, then
425425
`DESKTOP_REPORTER`, then configuration, then `auto`. Do not try to detect
426426
whether the caller is an agent.
427427

428-
| Mode | stdout | stderr |
429-
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
430-
| `auto` (default) | `github-actions` when `GITHUB_ACTIONS=true`; otherwise `plain`. A future interactive renderer may be selected only for a TTY. | Current diagnostics |
431-
| `plain`, `github-actions` | Existing human renderers. `reporting.console` remains a compatible configuration source. | Current diagnostics |
432-
| `json` | Exactly one compact document at exit. Long-lived commands (`serve`, Storybook `driver` and `server`) print one readiness document instead and nothing afterward. | Empty, except for failures before mode resolution or loss of stdout |
433-
| `ndjson` | Compact LF-terminated records ending with exactly one terminal record, identical to the `json` document. One-shot commands emit one record. | Same as `json` |
428+
| Mode | stdout | stderr |
429+
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
430+
| `auto` (default) | `github-actions` when `GITHUB_ACTIONS=true`; otherwise `plain`. A future interactive renderer may be selected only for a TTY. | Current diagnostics |
431+
| `plain`, `github-actions` | Existing human renderers. `reporting.console` remains a compatible configuration source. | Current diagnostics |
432+
| `json` | Exactly one compact document at exit. Long-lived commands (`serve`, Storybook `driver` and `server`) print one readiness document instead and nothing afterward. | Empty, except for failures before mode resolution or loss of stdout |
433+
| `ndjson` | Compact LF-terminated records. A run ends with exactly one `terminal` record, identical to the `json` document. A failure before a run starts emits only its `error` record, identical to `json`. | Same as `json` |
434434

435435
`--events <milestones|progress|all>` applies to `ndjson`; the default is
436436
`milestones`:
@@ -714,7 +714,7 @@ exit-path gaps.
714714
**Complete when:** every reporter mode is tested on every exit path: pass,
715715
test failure, infrastructure failure, usage or configuration error,
716716
interruption, and closed stdout. Structured stdout must parse as exactly one
717-
document or as valid NDJSON ending in one terminal record, and structured
717+
document or as valid NDJSON ending in one terminal or error record, and structured
718718
stderr must be empty on normal paths. Documents and default streams stay within
719719
limits for synthetic runs with at least 10,000 tests, 1,000 failures, and
720720
1 MiB messages. Secrets remain redacted, and delegated runs render once.

‎packages/agentic/desktop-driver/src/cli/DesktopDriverCli.test.ts‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import path from 'node:path';
77
import { NativeDriverError } from '../native/NativeDriverError';
88
import type { NativeDriverArtifact } from '../native/types';
99
import type { DesktopStoryManifest } from '../storybook.js';
10-
import { createDesktopDriverCommand } from './createDesktopDriverCommand';
10+
import { createDesktopDriverCommand, runDesktopDriverCli } from './createDesktopDriverCommand';
1111

1212
jest.setTimeout(30_000);
1313

@@ -134,6 +134,84 @@ describe('desktop-driver CLI', () => {
134134
}
135135
});
136136

137+
test('reports subcommand usage errors on stderr in plain mode', async () => {
138+
const result = await runInProcessCli(['stories', 'list']);
139+
140+
expect(result.stdout).toBe('');
141+
expect(result.stderr).toContain("required option '--url <url>' not specified");
142+
expect(result.exitCode).toBe(1);
143+
});
144+
145+
test('reports subcommand usage errors as one structured record in JSON and NDJSON modes', async () => {
146+
const json = await runInProcessCli(['--reporter', 'json', 'stories', 'list']);
147+
const ndjson = await runInProcessCli(['--reporter', 'ndjson', 'stories', 'list']);
148+
149+
for (const result of [json, ndjson]) {
150+
expect(result.stderr).toBe('');
151+
expect(result.exitCode).toBe(1);
152+
expect(JSON.parse(result.stdout)).toMatchObject({
153+
schemaVersion: 1,
154+
type: 'error',
155+
error: { code: 'usage', message: expect.stringContaining("required option '--url <url>' not specified") },
156+
});
157+
}
158+
expect(ndjson.stdout).toBe(json.stdout);
159+
});
160+
161+
test('reports bad choices and invalid option values as usage errors', async () => {
162+
const choice = await runInProcessCli([
163+
'--reporter',
164+
'ndjson',
165+
'stories',
166+
'list',
167+
'--platform',
168+
'linux',
169+
'--url',
170+
'https://127.0.0.1:1',
171+
'--target',
172+
'target',
173+
]);
174+
const port = await runInProcessCli(['--reporter', 'json', 'serve', '--port', 'abc']);
175+
176+
expect(JSON.parse(choice.stdout)).toMatchObject({
177+
type: 'error',
178+
error: { code: 'usage', message: expect.stringContaining('Allowed choices are macos, windows') },
179+
});
180+
expect(JSON.parse(port.stdout)).toMatchObject({
181+
type: 'error',
182+
error: { code: 'usage', message: expect.stringContaining('Port must be an integer between 0 and 65535') },
183+
});
184+
});
185+
186+
test('does not start serve when DESKTOP_REPORTER is invalid', async () => {
187+
const result = await runInProcessCli(['serve', '--port', '0'], 'xml');
188+
189+
expect(result.stdout).toBe('');
190+
expect(result.stderr).toContain('Reporter must be one of auto, plain, github-actions, json, ndjson. Received "xml".');
191+
expect(result.exitCode).toBe(1);
192+
});
193+
194+
test('clips long doctor failure messages', async () => {
195+
const output: string[] = [];
196+
const program = createDesktopDriverCommand({
197+
resolveDriver: jest.fn(async () => {
198+
throw new Error('native helper failure '.repeat(200));
199+
}),
200+
stdout: {
201+
write(value) {
202+
output.push(String(value));
203+
return true;
204+
},
205+
},
206+
});
207+
208+
await program.parseAsync(['node', 'test', 'doctor', '--platform', 'macos']);
209+
210+
const message = JSON.parse(output.join('')).error.message as string;
211+
expect(Buffer.byteLength(message)).toBeLessThanOrEqual(1024);
212+
expect(message.endsWith('…')).toBe(true);
213+
});
214+
137215
test('does not crash when the consumer closes stdout before a structured error is written', async () => {
138216
const response = await new Promise<{ code: number | null; stderr: string }>((resolve, reject) => {
139217
const child = spawnCli(['--reporter', 'json', 'unknown']);
@@ -417,6 +495,32 @@ describe('desktop-driver CLI', () => {
417495
}
418496
});
419497

498+
async function runInProcessCli(argv: readonly string[], reporterEnvironment?: string) {
499+
const previousReporter = process.env.DESKTOP_REPORTER;
500+
const stdout: string[] = [];
501+
const stderr: string[] = [];
502+
const writeOut = jest.spyOn(process.stdout, 'write').mockImplementation((chunk: string | Uint8Array) => {
503+
stdout.push(String(chunk));
504+
return true;
505+
});
506+
const writeErr = jest.spyOn(process.stderr, 'write').mockImplementation((chunk: string | Uint8Array) => {
507+
stderr.push(String(chunk));
508+
return true;
509+
});
510+
try {
511+
if (reporterEnvironment === undefined) delete process.env.DESKTOP_REPORTER;
512+
else process.env.DESKTOP_REPORTER = reporterEnvironment;
513+
process.exitCode = undefined;
514+
await runDesktopDriverCli(['node', 'desktop-driver', ...argv]);
515+
return { stdout: stdout.join(''), stderr: stderr.join(''), exitCode: process.exitCode };
516+
} finally {
517+
writeOut.mockRestore();
518+
writeErr.mockRestore();
519+
if (previousReporter === undefined) delete process.env.DESKTOP_REPORTER;
520+
else process.env.DESKTOP_REPORTER = previousReporter;
521+
}
522+
}
523+
420524
function spawnCli(args: readonly string[]) {
421525
return spawn(process.execPath, [path.resolve(__dirname, '../../config/cli.cjs'), ...args], {
422526
stdio: ['ignore', 'pipe', 'pipe'],

‎packages/agentic/desktop-driver/src/cli/createDesktopDriverCommand.ts‎

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { spawn } from 'node:child_process';
22
import fs from 'node:fs';
33

4-
import { Command, Option } from 'commander';
4+
import { Command, InvalidArgumentError, Option } from 'commander';
55

66
import { connectDesktopAgent } from '../agent/DesktopAgent.js';
77
import { validateDesktopStoryTests } from '../authoring/storyTests.js';
88
import { FakeDesktopHost } from '../hosts/fake/FakeDesktopHost.js';
99
import { buildNativeDesktopDriver, resolveNativeDesktopDriver } from '../native/nativeDriver.js';
1010
import {
11+
configureDesktopCliCommandTree,
12+
describeDesktopCliError,
1113
desktopReporterModes,
1214
formatDesktopReporterError,
1315
formatDesktopReporterValue,
@@ -66,18 +68,22 @@ export function createDesktopDriverCommand(options: CreateDesktopDriverCommandOp
6668
.name('desktop-driver')
6769
.description('Drive React Native desktop applications through W3C WebDriver without Appium.')
6870
.addOption(new Option('--reporter <mode>', 'output format').choices([...desktopReporterModes]))
69-
.option('--json', 'alias for --reporter json')
70-
.configureOutput({
71-
writeErr: (value) => stderr.write(value),
72-
writeOut: (value) => stdout.write(value),
73-
});
71+
.option('--json', 'alias for --reporter json');
72+
let resolvedReporterMode: ResolvedDesktopReporterMode | undefined;
7473
const reporterMode = (): ResolvedDesktopReporterMode => {
75-
const flags = program.opts<{ reporter?: string; json?: boolean }>();
76-
return resolveDesktopReporterMode({
77-
flag: flags.json ? 'json' : flags.reporter,
78-
environment: process.env.DESKTOP_REPORTER,
79-
});
74+
if (!resolvedReporterMode) {
75+
const flags = program.opts<{ reporter?: string; json?: boolean }>();
76+
resolvedReporterMode = resolveDesktopReporterMode({
77+
flag: flags.json ? 'json' : flags.reporter,
78+
environment: process.env.DESKTOP_REPORTER,
79+
});
80+
}
81+
return resolvedReporterMode;
8082
};
83+
// Resolving before any action keeps an invalid DESKTOP_REPORTER from running a command such as serve.
84+
program.hook('preAction', () => {
85+
reporterMode();
86+
});
8187
const writeValue = (value: unknown) => stdout.write(formatDesktopReporterValue(reporterMode(), value));
8288

8389
addNativeBuildCommand(program, buildDriver, writeValue);
@@ -117,8 +123,8 @@ export function createDesktopDriverCommand(options: CreateDesktopDriverCommandOp
117123
},
118124
],
119125
});
120-
writeValue({ server: server.url, targetId: flags.target });
121126
try {
127+
writeValue({ server: server.url, targetId: flags.target });
122128
await waitForSignal();
123129
} finally {
124130
await server.close();
@@ -234,6 +240,10 @@ export function createDesktopDriverCommand(options: CreateDesktopDriverCommandOp
234240
}),
235241
);
236242

243+
configureDesktopCliCommandTree(program, {
244+
writeErr: (value) => stderr.write(value),
245+
writeOut: (value) => stdout.write(value),
246+
});
237247
return program;
238248
}
239249

@@ -306,7 +316,7 @@ function addNativeDoctorCommand(
306316
writeValue({
307317
error: {
308318
code: error instanceof Error && 'code' in error ? String(error.code) : 'unknown',
309-
message: error instanceof Error ? error.message : String(error),
319+
message: describeDesktopCliError(error),
310320
},
311321
ready: false,
312322
});
@@ -330,7 +340,7 @@ export async function runDesktopDriverCli(argv: readonly string[] = process.argv
330340
reporterMode = 'plain';
331341
}
332342
}
333-
const program = createDesktopDriverCommand({ stderr: { write: (text) => ((diagnostics += text), true) } }).exitOverride();
343+
const program = createDesktopDriverCommand({ stderr: { write: (text) => ((diagnostics += text), true) } });
334344
try {
335345
await program.parseAsync([...argv]);
336346
} catch (error) {
@@ -403,7 +413,7 @@ function toResolveOptions(flags: NativeResolveFlags): NativeDriverResolveOptions
403413

404414
function parseChoice<T extends string>(value: string, choices: readonly T[], name: string): T {
405415
if (!choices.includes(value as T)) {
406-
throw new TypeError(`${name} must be one of ${choices.join(', ')}. Received "${value}".`);
416+
throw new InvalidArgumentError(`${name} must be one of ${choices.join(', ')}. Received "${value}".`);
407417
}
408418
return value as T;
409419
}
@@ -457,31 +467,31 @@ function waitForSignal(): Promise<void> {
457467
function parsePort(value: string): number {
458468
const port = Number(value);
459469
if (!Number.isInteger(port) || port < 0 || port > 65_535) {
460-
throw new TypeError(`Port must be an integer between 0 and 65535. Received "${value}".`);
470+
throw new InvalidArgumentError(`Port must be an integer between 0 and 65535. Received "${value}".`);
461471
}
462472

463473
return port;
464474
}
465475

466476
function requireOption(value: string | undefined, name: string): string {
467477
if (!value) {
468-
throw new TypeError(`${name} requires a non-empty value.`);
478+
throw new InvalidArgumentError(`${name} requires a non-empty value.`);
469479
}
470480
return value;
471481
}
472482

473483
function parseNonNegativeInteger(value: string): number {
474484
const parsed = Number(value);
475485
if (!Number.isInteger(parsed) || parsed < 0) {
476-
throw new TypeError(`Expected a non-negative integer. Received "${value}".`);
486+
throw new InvalidArgumentError(`Expected a non-negative integer. Received "${value}".`);
477487
}
478488
return parsed;
479489
}
480490

481491
function parsePositiveInteger(value: string): number {
482492
const parsed = Number(value);
483493
if (!Number.isInteger(parsed) || parsed < 1) {
484-
throw new TypeError(`Expected a positive integer. Received "${value}".`);
494+
throw new InvalidArgumentError(`Expected a positive integer. Received "${value}".`);
485495
}
486496
return parsed;
487497
}

0 commit comments

Comments
 (0)