@kjanat/dreamcli 2.3.0 → 2.4.1

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 (38) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/README.md +94 -34
  3. package/dist/core/cli/index.mjs +1 -1
  4. package/dist/core/cli/planner.mjs +1 -1
  5. package/dist/core/config/package-json.mjs +1 -1
  6. package/dist/core/execution/index.mjs +1 -1
  7. package/dist/core/json-schema/meta-descriptions.generated.d.mts +59 -59
  8. package/dist/core/output/activity.mjs +1 -1
  9. package/dist/core/output/bind.d.mts +37 -0
  10. package/dist/core/output/bind.mjs +1 -0
  11. package/dist/core/output/index.d.mts +6 -1
  12. package/dist/core/output/index.mjs +2 -2
  13. package/dist/core/parse/index.mjs +1 -1
  14. package/dist/core/schema/activity.d.mts +1 -1
  15. package/dist/core/schema/command.d.mts +8 -0
  16. package/dist/core/schema/run.d.mts +8 -5
  17. package/dist/core/schema-dsl/runtime.mjs +1 -1
  18. package/dist/core/testkit/index.mjs +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/runtime/paths.mjs +1 -1
  21. package/dist/strings.d.mts +27 -0
  22. package/dist/strings.mjs +1 -0
  23. package/dist/testkit.mjs +1 -1
  24. package/dist/version.mjs +1 -1
  25. package/package.json +46 -35
  26. package/src/core/cli/index.ts +9 -3
  27. package/src/core/cli/planner.ts +58 -2
  28. package/src/core/config/package-json.ts +3 -2
  29. package/src/core/execution/index.ts +7 -1
  30. package/src/core/help/index.ts +2 -2
  31. package/src/core/output/activity.ts +7 -0
  32. package/src/core/output/bind.ts +59 -0
  33. package/src/core/output/index.ts +35 -0
  34. package/src/core/parse/index.ts +2 -2
  35. package/src/core/schema/command.ts +8 -0
  36. package/src/core/schema/run.ts +8 -5
  37. package/src/runtime/paths.ts +4 -2
  38. package/src/strings.ts +34 -0
@@ -10,7 +10,6 @@
10
10
 
11
11
  import { formatDisplayValue } from '#internals/core/output/display-value.ts';
12
12
  import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
13
- import { padEnd, wrapText } from './ansi.ts';
14
13
  import type {
15
14
  ArgSchema,
16
15
  CommandArgEntry,
@@ -18,6 +17,7 @@ import type {
18
17
  CommandSchema,
19
18
  FlagSchema,
20
19
  } from '#internals/core/schema/index.ts';
20
+ import { padEnd, wrapText } from './ansi.ts';
21
21
 
22
22
  // --- Configuration
23
23
 
@@ -511,6 +511,6 @@ function formatExamplesSection(examples: readonly CommandExample[]): string {
511
511
 
512
512
  // --- Exports
513
513
 
514
- export type { HelpOptions };
515
514
  export { osc8, visibleWidth } from './ansi.ts';
515
+ export type { HelpOptions };
516
516
  export { formatHelp, formatHelpSections };
@@ -21,6 +21,7 @@ import type {
21
21
  ProgressOptions,
22
22
  SpinnerHandle,
23
23
  } from '#internals/core/schema/activity.ts';
24
+ import { bindMethods } from './bind.ts';
24
25
  import type { WriteFn } from './writer.ts';
25
26
  import { writeLine } from './writer.ts';
26
27
 
@@ -90,6 +91,7 @@ class StaticSpinnerHandle implements SpinnerHandle {
90
91
  private readonly write: WriteFn,
91
92
  ) {
92
93
  writeLine(write, text);
94
+ bindMethods(this);
93
95
  }
94
96
 
95
97
  update(_text: string): void {
@@ -153,6 +155,7 @@ class StaticProgressHandle implements ProgressHandle {
153
155
  if (label !== undefined) {
154
156
  writeLine(write, label);
155
157
  }
158
+ bindMethods(this);
156
159
  }
157
160
 
158
161
  increment(_n?: number): void {
@@ -263,6 +266,7 @@ class TTYSpinnerHandle implements SpinnerHandle {
263
266
  this.frameIndex = (this.frameIndex + 1) % SPINNER_FRAMES.length;
264
267
  this.render();
265
268
  }, SPINNER_INTERVAL_MS);
269
+ bindMethods(this);
266
270
  }
267
271
 
268
272
  /** Render the current frame + text, overwriting the current line. */
@@ -372,6 +376,7 @@ class TTYProgressHandle implements ProgressHandle {
372
376
  this.render();
373
377
  }, PULSE_INTERVAL_MS);
374
378
  }
379
+ bindMethods(this);
375
380
  }
376
381
 
377
382
  /** Advance the indeterminate pulse position with bounce logic. */
@@ -472,6 +477,7 @@ class CaptureSpinnerHandle implements SpinnerHandle {
472
477
  private readonly events: ActivityEvent[],
473
478
  ) {
474
479
  events.push({ type: 'spinner:start', text });
480
+ bindMethods(this);
475
481
  }
476
482
 
477
483
  update(text: string): void {
@@ -529,6 +535,7 @@ class CaptureProgressHandle implements ProgressHandle {
529
535
  private readonly events: ActivityEvent[],
530
536
  ) {
531
537
  events.push({ type: 'progress:start', label: opts.label ?? '', total: opts.total });
538
+ bindMethods(this);
532
539
  }
533
540
 
534
541
  increment(n?: number): void {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Method-binding helper for value objects handed to consumers.
3
+ *
4
+ * Output value objects — the `Out` channel and the spinner/progress handles
5
+ * — expose methods that read instance state via `this`. Consumers naturally
6
+ * detach those methods, either by destructuring
7
+ * (`const { log } = out` / `const { succeed, fail } = spinner`) or by passing
8
+ * them as callbacks (`promise.finally(spinner.stop)`). Detached, an unbound
9
+ * prototype method loses its `this` and crashes on the first field access.
10
+ *
11
+ * {@linkcode bindMethods} eliminates that footgun by installing instance-bound
12
+ * copies of every method, so the ergonomic usage is also the correct one.
13
+ *
14
+ * @module dreamcli/core/output/bind
15
+ * @internal
16
+ */
17
+
18
+ /**
19
+ * Bind every method on an instance's prototype chain to the instance.
20
+ *
21
+ * Walks the prototype chain up to (but excluding) `Object.prototype`, binding
22
+ * each method name exactly once — the most-derived definition wins, so subclass
23
+ * overrides (e.g. `CaptureOutputChannel.spinner`) are preserved rather than
24
+ * clobbered by a base-class version. Bound methods are installed as
25
+ * non-enumerable own properties, mirroring the enumerability of the prototype
26
+ * methods they shadow. Getters and non-function members are left untouched.
27
+ *
28
+ * Call this once, last, in a class constructor. Because it reads the live
29
+ * prototype rather than a hand-maintained name list, methods added later are
30
+ * bound automatically — the binding can't silently fall out of date.
31
+ *
32
+ * @param instance - The object whose methods should be bound to it.
33
+ * @internal
34
+ */
35
+ function bindMethods(instance: object): void {
36
+ const bound = instance as Record<PropertyKey, unknown>;
37
+ const seen = new Set<string>();
38
+ let proto: object | null = Object.getPrototypeOf(instance);
39
+
40
+ while (proto !== null && proto !== Object.prototype) {
41
+ for (const name of Object.getOwnPropertyNames(proto)) {
42
+ if (name === 'constructor' || seen.has(name)) continue;
43
+ seen.add(name);
44
+
45
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
46
+ if (descriptor === undefined || typeof descriptor.value !== 'function') continue;
47
+
48
+ Object.defineProperty(bound, name, {
49
+ value: descriptor.value.bind(instance),
50
+ writable: true,
51
+ enumerable: false,
52
+ configurable: true,
53
+ });
54
+ }
55
+ proto = Object.getPrototypeOf(proto);
56
+ }
57
+ }
58
+
59
+ export { bindMethods };
@@ -31,6 +31,7 @@ import {
31
31
  TTYProgressHandle,
32
32
  TTYSpinnerHandle,
33
33
  } from './activity.ts';
34
+ import { bindMethods } from './bind.ts';
34
35
  import type { OutputPolicy, Verbosity } from './contracts.ts';
35
36
  import {
36
37
  resolveOutputPolicy,
@@ -115,6 +116,27 @@ interface ResolvedOutputOptions {
115
116
  */
116
117
  const noopWrite: WriteFn = () => {};
117
118
 
119
+ const requestedExitCodes = new WeakMap<Out, number>();
120
+
121
+ function validateExitCode(code: number): number {
122
+ if (!Number.isInteger(code) || code < 0 || code > 255) {
123
+ throw new RangeError('Exit code must be an integer from 0 to 255');
124
+ }
125
+ return code;
126
+ }
127
+
128
+ function setRequestedExitCode(out: Out, code: number): void {
129
+ requestedExitCodes.set(out, validateExitCode(code));
130
+ }
131
+
132
+ function getRequestedExitCode(out: Out): number | undefined {
133
+ return requestedExitCodes.get(out);
134
+ }
135
+
136
+ function clearRequestedExitCode(out: Out): void {
137
+ requestedExitCodes.delete(out);
138
+ }
139
+
118
140
  /** Merge user-supplied options with defaults. */
119
141
  function resolveOptions(options?: OutputOptions): ResolvedOutputOptions {
120
142
  return {
@@ -164,6 +186,11 @@ class OutputChannel implements Out {
164
186
  this.policy = resolveOutputPolicy(options);
165
187
  this.jsonMode = options.jsonMode;
166
188
  this.isTTY = options.isTTY;
189
+
190
+ // Bind methods to the instance so they keep working when destructured
191
+ // off `out` (e.g. `const { log } = out`). Resolves subclass overrides
192
+ // (spinner/progress in CaptureOutputChannel) automatically.
193
+ bindMethods(this);
167
194
  }
168
195
 
169
196
  /**
@@ -199,6 +226,11 @@ class OutputChannel implements Out {
199
226
  writeLine(this.options.stderr, message);
200
227
  }
201
228
 
229
+ /** Request a successful-process exit code without writing error output. */
230
+ setExitCode(code: number): void {
231
+ setRequestedExitCode(this, code);
232
+ }
233
+
202
234
  /**
203
235
  * Emit a structured JSON value to stdout.
204
236
  *
@@ -656,13 +688,16 @@ export {
656
688
  CaptureOutputChannel,
657
689
  CaptureProgressHandle,
658
690
  CaptureSpinnerHandle,
691
+ clearRequestedExitCode,
659
692
  createCaptureOutput,
660
693
  createOutput,
694
+ getRequestedExitCode,
661
695
  noopProgressHandle,
662
696
  noopSpinnerHandle,
663
697
  OutputChannel,
664
698
  StaticProgressHandle,
665
699
  StaticSpinnerHandle,
700
+ setRequestedExitCode,
666
701
  TTYProgressHandle,
667
702
  TTYSpinnerHandle,
668
703
  writeLine,
@@ -445,7 +445,7 @@ function parseLongFlag(
445
445
 
446
446
  // --flag value (next token is the value)
447
447
  const nextToken = tokens[startIdx + 1];
448
- if (!nextToken || nextToken.kind !== 'positional') {
448
+ if (nextToken?.kind !== 'positional') {
449
449
  throw new ParseError(`Flag --${token.name} requires a value`, {
450
450
  code: 'MISSING_VALUE',
451
451
  details: { flag: canonicalName, input: token.name, kind: flagSchema.kind },
@@ -505,7 +505,7 @@ function parseShortFlags(
505
505
 
506
506
  // Last char in the group — consume next token as value
507
507
  const nextToken = tokens[nextIdx];
508
- if (!nextToken || nextToken.kind !== 'positional') {
508
+ if (nextToken?.kind !== 'positional') {
509
509
  throw new ParseError(`Flag -${ch} requires a value`, {
510
510
  code: 'MISSING_VALUE',
511
511
  details: { flag: canonicalName, input: ch, kind: flagSchema.kind },
@@ -152,6 +152,14 @@ interface Out {
152
152
  warn(message: string): void;
153
153
  /** Error to stderr. */
154
154
  error(message: string): void;
155
+ /**
156
+ * Request a process exit code without emitting error-shaped output.
157
+ *
158
+ * Use this for check/status commands that should print normal output but
159
+ * still signal a non-zero status to scripts. This does not stop execution;
160
+ * later calls overwrite earlier calls, and thrown errors still win.
161
+ */
162
+ setExitCode(code: number): void;
155
163
  /**
156
164
  * Emit a structured JSON value to stdout.
157
165
  *
@@ -155,9 +155,10 @@ export interface RunOptions {
155
155
  /**
156
156
  * Structured result from {@linkcode runCommand}.
157
157
  *
158
- * Contains the exit code, captured stdout/stderr output, recorded
159
- * {@linkcode ActivityEvent | activity events}, and an `error` field
160
- * that is `undefined` on success and a {@linkcode CLIError} on failure.
158
+ * Contains the exit code, captured stdout/stderr output, recorded
159
+ * {@linkcode ActivityEvent | activity events}, and an `error` field.
160
+ * `error` is `undefined` when execution completed without throwing, even if
161
+ * the handler requested a non-zero status via {@linkcode Out.setExitCode}.
161
162
  *
162
163
  * @example
163
164
  * ```ts
@@ -188,8 +189,10 @@ export interface RunResult {
188
189
  readonly activity: readonly ActivityEvent[];
189
190
 
190
191
  /**
191
- * The error that caused a non-zero exit, or `undefined` on success.
192
- * {@linkcode CLIError} instances are preserved; unknown errors are wrapped.
192
+ * The error that caused a failure, or `undefined` when execution completed.
193
+ * A non-zero `exitCode` can still have no error when a handler calls
194
+ * {@linkcode Out.setExitCode}. {@linkcode CLIError} instances are preserved;
195
+ * unknown errors are wrapped.
193
196
  */
194
197
  readonly error: CLIError | undefined;
195
198
  }
@@ -8,6 +8,8 @@
8
8
  * @module @kjanat/dreamcli/runtime/paths
9
9
  */
10
10
 
11
+ import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts';
12
+
11
13
  /**
12
14
  * Resolve the user's home directory from environment variables.
13
15
  *
@@ -46,10 +48,10 @@ function resolveConfigDirectory(
46
48
  ): string {
47
49
  if (isWindows) {
48
50
  if (env.APPDATA !== undefined && env.APPDATA !== '') return env.APPDATA;
49
- const normalizedHome = homedir.replace(/[\\/]+$/, '') || homedir;
51
+ const normalizedHome = stripTrailing(homedir, [SLASH, BACKSLASH]) || homedir;
50
52
  return `${normalizedHome}\\AppData\\Roaming`;
51
53
  }
52
- const normalizedHome = homedir.replace(/\/+$/, '');
54
+ const normalizedHome = stripTrailing(homedir, [SLASH]);
53
55
  if (env.XDG_CONFIG_HOME !== undefined && env.XDG_CONFIG_HOME !== '') {
54
56
  return env.XDG_CONFIG_HOME;
55
57
  }
package/src/strings.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Internal string utilities shared across runtime and core modules.
3
+ *
4
+ * @module dreamcli/strings
5
+ */
6
+
7
+ /** Character code for `/` (forward slash). */
8
+ const SLASH = 0x2f;
9
+ /** Character code for `\` (backslash). */
10
+ const BACKSLASH = 0x5c;
11
+
12
+ /**
13
+ * Remove trailing characters whose code points appear in `codes`.
14
+ *
15
+ * Linear-time replacement for trailing-character regexes such as
16
+ * `/[\\/]+$/`. Those patterns are polynomial-ReDoS prone: the engine
17
+ * greedily consumes the run, fails the end anchor, backtracks one
18
+ * character at a time, and repeats that work from every start position —
19
+ * O(n²) on adversarial input. This scan is O(n) with no backtracking.
20
+ *
21
+ * @param input - Source string.
22
+ * @param codes - Character codes to strip from the end of `input`.
23
+ * @returns `input` with all trailing matching characters removed.
24
+ * @internal
25
+ */
26
+ function stripTrailing(input: string, codes: readonly number[]): string {
27
+ let end = input.length;
28
+ while (end > 0 && codes.includes(input.charCodeAt(end - 1))) {
29
+ end -= 1;
30
+ }
31
+ return end === input.length ? input : input.slice(0, end);
32
+ }
33
+
34
+ export { BACKSLASH, SLASH, stripTrailing };