@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

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 (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -0,0 +1,96 @@
1
+ //#region src/core/schema/number-constraints.d.ts
2
+ /**
3
+ * Numeric constraints for number-valued flags and args.
4
+ *
5
+ * A single, shared representation and validator so the parse path
6
+ * (`core/parse`) and the resolver coercion path (`core/resolve/coerce`) cannot
7
+ * drift: both import {@link validateNumberConstraints} and apply the checks in
8
+ * the same order (finite → int → min → max).
9
+ *
10
+ * @module dreamcli/core/schema/number-constraints
11
+ */
12
+ /**
13
+ * Runtime numeric constraints attached to a number flag/arg schema.
14
+ *
15
+ * Bounds are **inclusive**. All fields are optional; an absent field means "no
16
+ * constraint" except for {@link NumberConstraints.finite | finite}, which
17
+ * defaults to `true` (so `Infinity` / `-Infinity` are rejected unless opted
18
+ * back in).
19
+ */
20
+ interface NumberConstraints {
21
+ /**
22
+ * Inclusive lower bound. Values below this are rejected.
23
+ * @defaultValue `undefined` (no lower bound)
24
+ */
25
+ readonly min?: number;
26
+ /**
27
+ * Inclusive upper bound. Values above this are rejected.
28
+ * @defaultValue `undefined` (no upper bound)
29
+ */
30
+ readonly max?: number;
31
+ /**
32
+ * Require an integer value. Non-integers (e.g. `3.7`) are rejected.
33
+ * @defaultValue `false`
34
+ */
35
+ readonly int?: boolean;
36
+ /**
37
+ * Require a finite value. When `true`, `Infinity` / `-Infinity` are rejected.
38
+ * @defaultValue `true`
39
+ */
40
+ readonly finite?: boolean;
41
+ }
42
+ /**
43
+ * A failed numeric constraint, discriminated by which rule was violated.
44
+ *
45
+ * `min` / `max` carry the offending bound so callers can render it.
46
+ */
47
+ type NumberConstraintViolation = {
48
+ readonly kind: 'finite';
49
+ } | {
50
+ readonly kind: 'int';
51
+ } | {
52
+ readonly kind: 'min';
53
+ readonly bound: number;
54
+ } | {
55
+ readonly kind: 'max';
56
+ readonly bound: number;
57
+ };
58
+ /** Default for {@link NumberConstraints.finite} — reject `Infinity` unless opted out. */
59
+ declare const DEFAULT_FINITE = true;
60
+ /**
61
+ * Validate a numeric value against constraints.
62
+ *
63
+ * The single source of truth for numeric-constraint checks, shared by the
64
+ * parse and coerce paths. Checks run in a fixed order — **finite → int → min →
65
+ * max** — and the first failure is returned. `NaN` is always rejected as a
66
+ * `finite` violation, regardless of the `finite` option (a non-finite value can
67
+ * otherwise slip past `min`/`max`, since `NaN < x` and `NaN > x` are both false).
68
+ *
69
+ * @param value - The numeric value to validate.
70
+ * @param constraints - Constraints to enforce, or `undefined` for defaults.
71
+ * @returns The first {@link NumberConstraintViolation}, or `undefined` if valid.
72
+ */
73
+ declare function validateNumberConstraints(value: number, constraints: NumberConstraints | undefined): NumberConstraintViolation | undefined;
74
+ /**
75
+ * Render a terse, human-readable reason for a constraint violation.
76
+ *
77
+ * @param violation - The violation to describe.
78
+ * @returns A message suffix such as `must be an integer` or `must be >= 0`.
79
+ */
80
+ declare function describeNumberConstraintViolation(violation: NumberConstraintViolation): string;
81
+ /**
82
+ * Assert that a constraints object is well-formed at schema-construction time.
83
+ *
84
+ * `min` / `max` must be finite — an infinite or `NaN` bound is meaningless (omit
85
+ * the field for "no bound") and would serialize to `null` in the emitted JSON
86
+ * Schema. An inverted range (`min > max`) is also rejected, since it makes the
87
+ * flag/arg permanently unsatisfiable. Throws so the misconfiguration surfaces
88
+ * where the flag/arg is declared, not at parse time.
89
+ *
90
+ * @param constraints - The constraints to validate.
91
+ * @throws RangeError if `min` or `max` is non-finite (`Infinity` / `-Infinity` /
92
+ * `NaN`), or if `min` exceeds `max`.
93
+ */
94
+ declare function assertNumberConstraints(constraints: NumberConstraints): void;
95
+ //#endregion
96
+ export { DEFAULT_FINITE, type NumberConstraintViolation, type NumberConstraints, assertNumberConstraints, describeNumberConstraintViolation, validateNumberConstraints };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Validate a numeric value against constraints.
3
+ *
4
+ * The single source of truth for numeric-constraint checks, shared by the
5
+ * parse and coerce paths. Checks run in a fixed order — **finite → int → min →
6
+ * max** — and the first failure is returned. `NaN` is always rejected as a
7
+ * `finite` violation, regardless of the `finite` option (a non-finite value can
8
+ * otherwise slip past `min`/`max`, since `NaN < x` and `NaN > x` are both false).
9
+ *
10
+ * @param value - The numeric value to validate.
11
+ * @param constraints - Constraints to enforce, or `undefined` for defaults.
12
+ * @returns The first {@link NumberConstraintViolation}, or `undefined` if valid.
13
+ */
14
+ function validateNumberConstraints(value, constraints) {
15
+ if (Number.isNaN(value)) return { kind: "finite" };
16
+ if ((constraints?.finite ?? true) && !Number.isFinite(value)) return { kind: "finite" };
17
+ if (constraints?.int === true && !Number.isInteger(value)) return { kind: "int" };
18
+ if (constraints?.min !== void 0 && value < constraints.min) return {
19
+ kind: "min",
20
+ bound: constraints.min
21
+ };
22
+ if (constraints?.max !== void 0 && value > constraints.max) return {
23
+ kind: "max",
24
+ bound: constraints.max
25
+ };
26
+ }
27
+ /**
28
+ * Render a terse, human-readable reason for a constraint violation.
29
+ *
30
+ * @param violation - The violation to describe.
31
+ * @returns A message suffix such as `must be an integer` or `must be >= 0`.
32
+ */
33
+ function describeNumberConstraintViolation(violation) {
34
+ switch (violation.kind) {
35
+ case "finite": return "must be a finite number";
36
+ case "int": return "must be an integer";
37
+ case "min": return `must be >= ${violation.bound}`;
38
+ case "max": return `must be <= ${violation.bound}`;
39
+ }
40
+ }
41
+ /**
42
+ * Assert that a constraints object is well-formed at schema-construction time.
43
+ *
44
+ * `min` / `max` must be finite — an infinite or `NaN` bound is meaningless (omit
45
+ * the field for "no bound") and would serialize to `null` in the emitted JSON
46
+ * Schema. An inverted range (`min > max`) is also rejected, since it makes the
47
+ * flag/arg permanently unsatisfiable. Throws so the misconfiguration surfaces
48
+ * where the flag/arg is declared, not at parse time.
49
+ *
50
+ * @param constraints - The constraints to validate.
51
+ * @throws RangeError if `min` or `max` is non-finite (`Infinity` / `-Infinity` /
52
+ * `NaN`), or if `min` exceeds `max`.
53
+ */
54
+ function assertNumberConstraints(constraints) {
55
+ if (constraints.min !== void 0 && !Number.isFinite(constraints.min)) throw new RangeError(`number constraint 'min' must be a finite number (got ${constraints.min}); omit it for no lower bound`);
56
+ if (constraints.max !== void 0 && !Number.isFinite(constraints.max)) throw new RangeError(`number constraint 'max' must be a finite number (got ${constraints.max}); omit it for no upper bound`);
57
+ if (constraints.min !== void 0 && constraints.max !== void 0 && constraints.min > constraints.max) throw new RangeError(`number constraint 'min' (${constraints.min}) must not exceed 'max' (${constraints.max})`);
58
+ }
59
+ //#endregion
60
+ export { assertNumberConstraints, describeNumberConstraintViolation, validateNumberConstraints };
@@ -29,6 +29,12 @@ interface PromptConfigBase {
29
29
  interface ConfirmPromptConfig extends PromptConfigBase {
30
30
  /** Discriminator identifying this as a yes/no confirmation prompt. */
31
31
  readonly kind: 'confirm';
32
+ /**
33
+ * Value used when the user submits an empty line (presses Enter). Also
34
+ * drives the displayed hint: `true` → `(Y/n)`, `false` → `(y/N)`.
35
+ * @defaultValue `true`
36
+ */
37
+ readonly default?: boolean;
32
38
  }
33
39
  /** Free-text input prompt — maps to `string` and `number` flags. Part of {@link PromptConfig}. */
34
40
  interface InputPromptConfig extends PromptConfigBase {
@@ -36,6 +42,15 @@ interface InputPromptConfig extends PromptConfigBase {
36
42
  readonly kind: 'input';
37
43
  /** Placeholder text shown before user types (informational only). */
38
44
  readonly placeholder?: string;
45
+ /**
46
+ * Value used when the user submits an empty line (presses Enter), shown in
47
+ * the hint as `(default: <value>)`. When set, an empty submission resolves
48
+ * to this value without running {@link InputPromptConfig.validate | validate}.
49
+ * When omitted, an empty submission is treated as "no answer" so resolution
50
+ * falls through to the flag's `.default()`.
51
+ * @defaultValue `undefined`
52
+ */
53
+ readonly default?: string;
39
54
  /**
40
55
  * Inline validation function. Return `true` if valid, or a string
41
56
  * error message if invalid. Called before coercion to flag kind.
@@ -133,10 +133,10 @@ interface RunOptions {
133
133
  /**
134
134
  * Structured result from {@linkcode runCommand}.
135
135
  *
136
- * Contains the exit code, captured stdout/stderr output, recorded
137
- * {@linkcode ActivityEvent | activity events}, and an `error` field.
138
- * `error` is `undefined` when execution completed without throwing, even if
139
- * the handler requested a non-zero status via {@linkcode Out.setExitCode}.
136
+ * Contains the exit code, captured stdout/stderr output, recorded
137
+ * {@linkcode ActivityEvent | activity events}, and an `error` field.
138
+ * `error` is `undefined` when execution completed without throwing, even if
139
+ * the handler requested a non-zero status via {@linkcode Out.setExitCode}.
140
140
  *
141
141
  * @example
142
142
  * ```ts
@@ -1,2 +1,271 @@
1
- const e={"{":`lbrace`,"}":`rbrace`,"[":`lbracket`,"]":`rbracket`,"<":`langle`,">":`rangle`,",":`comma`,":":`colon`,";":`semicolon`,"?":`question`,"|":`pipe`};function t(e){return e===` `||e===`
2
- `||e===` `||e===`\r`}function n(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`_`||e===`$`}function r(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`||e===`$`}function i(i){let a=[],o=0;for(;o<i.length;){let s=i[o]??``;if(t(s)){o++;continue}let c=e[s];if(c!==void 0){a.push({kind:c,value:s}),o++;continue}if(s===`'`){let e=``;for(o++;o<i.length&&i[o]!==`'`;)e+=i[o],o++;if(o>=i.length)throw SyntaxError(`Unterminated string literal`);o++,a.push({kind:`string_literal`,value:e});continue}if(s===`@`){o++;let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}if(e.length===0)throw SyntaxError(`Expected identifier after '@' at position ${String(o)}`);a.push({kind:`ref`,value:e});continue}if(r(s)){let e=``;for(;o<i.length;){let t=i[o]??``;if(!n(t))break;e+=t,o++}a.push({kind:`ident`,value:e});continue}throw SyntaxError(`Unexpected character '${s}' at position ${String(o)}`)}return a}const a=new Set([`string`,`number`,`integer`,`boolean`,`true`,`false`,`null`,`undefined`,`unknown`,`never`]);function o(e){switch(e){case`string`:return{kind:`string`};case`number`:return{kind:`number`};case`integer`:return{kind:`integer`};case`boolean`:return{kind:`boolean`};case`true`:return{kind:`true`};case`false`:return{kind:`false`};case`null`:return{kind:`null`};case`undefined`:return{kind:`undefined`};case`unknown`:return{kind:`unknown`};case`never`:return{kind:`never`};default:throw SyntaxError(`Unknown type '${e}'`)}}var s=class{tokens;pos=0;constructor(e){this.tokens=e}parseRoot(){let e=this.parseValue();if(this.pos<this.tokens.length){let e=this.peek();throw SyntaxError(`Unexpected token '${e?.value??`?`}' at position ${String(this.pos)}`)}return e}parseValue(){return this.parseUnion()}parseUnion(){let e=this.parsePostfix();if(!this.check(`pipe`))return e;let t=[e];for(;this.match(`pipe`);)t.push(this.parsePostfix());return{kind:`union`,members:t}}parsePostfix(){let e=this.parsePrimary();for(;this.check(`lbracket`)&&this.checkAt(this.pos+1,`rbracket`);)this.advance(),this.advance(),e={kind:`array`,element:e};return e}parsePrimary(){if(this.check(`lbrace`))return this.parseObject();if(this.check(`string_literal`))return{kind:`literal`,value:this.advance().value};if(this.check(`ref`))return{kind:`ref`,target:this.advance().value};let e=this.expectIdent();if(e===`Record`){if(this.expect(`langle`),this.parseValue().kind!==`string`)throw SyntaxError(`Record key type must be 'string' because JSON object keys are always strings`);this.expect(`comma`);let e=this.parseValue();return this.expect(`rangle`),{kind:`record`,value:e}}if(!a.has(e))throw SyntaxError(`Unknown type '${e}' at position ${String(this.pos-1)}`);return o(e)}parseObject(){this.expect(`lbrace`);let e={};for(;!this.check(`rbrace`);){let t=this.expectIdent();if(Object.hasOwn(e,t))throw SyntaxError(`Duplicate property '${t}' at position ${String(this.pos-1)}`);let n=this.match(`question`);this.expect(`colon`),e[t]={optional:n,schema:this.parseValue()},this.match(`semicolon`)}return this.expect(`rbrace`),{kind:`object`,properties:e}}peek(){return this.tokens[this.pos]}check(e){return this.peek()?.kind===e}checkAt(e,t){return this.tokens[e]?.kind===t}advance(){let e=this.tokens[this.pos];if(e===void 0)throw SyntaxError(`Unexpected end of input`);return this.pos++,e}match(e){return this.check(e)?(this.pos++,!0):!1}expect(e){if(!this.check(e)){let t=this.peek();throw SyntaxError(t?`Expected '${e}' but got '${t.kind}' ('${t.value}') at position ${String(this.pos)}`:`Expected '${e}' but reached end of input`)}return this.advance()}expectIdent(){return this.expect(`ident`).value}};function c(e){return new s(i(e)).parseRoot()}export{c as parseSchema};
1
+ //#region src/core/schema-dsl/runtime.ts
2
+ /** Map single characters to their token kinds. */
3
+ const SINGLE_CHAR_TOKENS = {
4
+ "{": "lbrace",
5
+ "}": "rbrace",
6
+ "[": "lbracket",
7
+ "]": "rbracket",
8
+ "<": "langle",
9
+ ">": "rangle",
10
+ ",": "comma",
11
+ ":": "colon",
12
+ ";": "semicolon",
13
+ "?": "question",
14
+ "|": "pipe"
15
+ };
16
+ /** Whitespace characters to skip. */
17
+ function isWhitespace(c) {
18
+ return c === " " || c === "\n" || c === " " || c === "\r";
19
+ }
20
+ /** Identifier-valid characters (a-z, A-Z, 0-9, _, $). */
21
+ function isIdentChar(c) {
22
+ return c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c >= "0" && c <= "9" || c === "_" || c === "$";
23
+ }
24
+ /** Identifier start characters (a-z, A-Z, _, $). */
25
+ function isIdentStart(c) {
26
+ return c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "_" || c === "$";
27
+ }
28
+ /**
29
+ * Tokenize a schema source string.
30
+ *
31
+ * Produces a flat array of tokens: identifiers (`string`, `number`, etc.),
32
+ * punctuation (`{`, `}`, `[`, `]`, `:`, `;`, `?`, `|`), and skips
33
+ * whitespace. Throws on unrecognized characters.
34
+ */
35
+ function tokenize(source) {
36
+ const tokens = [];
37
+ let i = 0;
38
+ while (i < source.length) {
39
+ const c = source[i] ?? "";
40
+ if (isWhitespace(c)) {
41
+ i++;
42
+ continue;
43
+ }
44
+ const singleKind = SINGLE_CHAR_TOKENS[c];
45
+ if (singleKind !== void 0) {
46
+ tokens.push({
47
+ kind: singleKind,
48
+ value: c
49
+ });
50
+ i++;
51
+ continue;
52
+ }
53
+ if (c === "'") {
54
+ let lit = "";
55
+ i++;
56
+ while (i < source.length && source[i] !== "'") {
57
+ lit += source[i];
58
+ i++;
59
+ }
60
+ if (i >= source.length) throw new SyntaxError("Unterminated string literal");
61
+ i++;
62
+ tokens.push({
63
+ kind: "string_literal",
64
+ value: lit
65
+ });
66
+ continue;
67
+ }
68
+ if (c === "@") {
69
+ i++;
70
+ let ref = "";
71
+ while (i < source.length) {
72
+ const ch = source[i] ?? "";
73
+ if (!isIdentChar(ch)) break;
74
+ ref += ch;
75
+ i++;
76
+ }
77
+ if (ref.length === 0) throw new SyntaxError(`Expected identifier after '@' at position ${String(i)}`);
78
+ tokens.push({
79
+ kind: "ref",
80
+ value: ref
81
+ });
82
+ continue;
83
+ }
84
+ if (isIdentStart(c)) {
85
+ let ident = "";
86
+ while (i < source.length) {
87
+ const ch = source[i] ?? "";
88
+ if (!isIdentChar(ch)) break;
89
+ ident += ch;
90
+ i++;
91
+ }
92
+ tokens.push({
93
+ kind: "ident",
94
+ value: ident
95
+ });
96
+ continue;
97
+ }
98
+ throw new SyntaxError(`Unexpected character '${c}' at position ${String(i)}`);
99
+ }
100
+ return tokens;
101
+ }
102
+ /** Primitive type names recognized by the parser. */
103
+ const PRIMITIVES = /* @__PURE__ */ new Set([
104
+ "string",
105
+ "number",
106
+ "integer",
107
+ "boolean",
108
+ "true",
109
+ "false",
110
+ "null",
111
+ "undefined",
112
+ "unknown",
113
+ "never"
114
+ ]);
115
+ /** Map a primitive name to its AST node. */
116
+ function primitiveNode(name) {
117
+ switch (name) {
118
+ case "string": return { kind: "string" };
119
+ case "number": return { kind: "number" };
120
+ case "integer": return { kind: "integer" };
121
+ case "boolean": return { kind: "boolean" };
122
+ case "true": return { kind: "true" };
123
+ case "false": return { kind: "false" };
124
+ case "null": return { kind: "null" };
125
+ case "undefined": return { kind: "undefined" };
126
+ case "unknown": return { kind: "unknown" };
127
+ case "never": return { kind: "never" };
128
+ default: throw new SyntaxError(`Unknown type '${name}'`);
129
+ }
130
+ }
131
+ /**
132
+ * Parse a token stream into a {@link SchemaNode} AST.
133
+ *
134
+ * Implements the grammar documented at the module level using standard
135
+ * recursive descent. Each grammar rule maps to one `parse*` method.
136
+ */
137
+ var SchemaParser = class {
138
+ tokens;
139
+ pos = 0;
140
+ constructor(tokens) {
141
+ this.tokens = tokens;
142
+ }
143
+ /** Parse the full token stream, asserting all tokens are consumed. */
144
+ parseRoot() {
145
+ const result = this.parseValue();
146
+ if (this.pos < this.tokens.length) {
147
+ const leftover = this.peek();
148
+ throw new SyntaxError(`Unexpected token '${leftover?.value ?? "?"}' at position ${String(this.pos)}`);
149
+ }
150
+ return result;
151
+ }
152
+ /** value = union */
153
+ parseValue() {
154
+ return this.parseUnion();
155
+ }
156
+ /** union = postfix ('|' postfix)* */
157
+ parseUnion() {
158
+ const first = this.parsePostfix();
159
+ if (!this.check("pipe")) return first;
160
+ const members = [first];
161
+ while (this.match("pipe")) members.push(this.parsePostfix());
162
+ return {
163
+ kind: "union",
164
+ members
165
+ };
166
+ }
167
+ /** postfix = primary ('[]')* */
168
+ parsePostfix() {
169
+ let node = this.parsePrimary();
170
+ while (this.check("lbracket") && this.checkAt(this.pos + 1, "rbracket")) {
171
+ this.advance();
172
+ this.advance();
173
+ node = {
174
+ kind: "array",
175
+ element: node
176
+ };
177
+ }
178
+ return node;
179
+ }
180
+ /** primary = object | record | ref | literal | IDENT */
181
+ parsePrimary() {
182
+ if (this.check("lbrace")) return this.parseObject();
183
+ if (this.check("string_literal")) return {
184
+ kind: "literal",
185
+ value: this.advance().value
186
+ };
187
+ if (this.check("ref")) return {
188
+ kind: "ref",
189
+ target: this.advance().value
190
+ };
191
+ const name = this.expectIdent();
192
+ if (name === "Record") {
193
+ this.expect("langle");
194
+ if (this.parseValue().kind !== "string") throw new SyntaxError("Record key type must be 'string' because JSON object keys are always strings");
195
+ this.expect("comma");
196
+ const valueSchema = this.parseValue();
197
+ this.expect("rangle");
198
+ return {
199
+ kind: "record",
200
+ value: valueSchema
201
+ };
202
+ }
203
+ if (!PRIMITIVES.has(name)) throw new SyntaxError(`Unknown type '${name}' at position ${String(this.pos - 1)}`);
204
+ return primitiveNode(name);
205
+ }
206
+ /** object = '{' properties '}' */
207
+ parseObject() {
208
+ this.expect("lbrace");
209
+ const properties = {};
210
+ while (!this.check("rbrace")) {
211
+ const name = this.expectIdent();
212
+ if (Object.hasOwn(properties, name)) throw new SyntaxError(`Duplicate property '${name}' at position ${String(this.pos - 1)}`);
213
+ const optional = this.match("question");
214
+ this.expect("colon");
215
+ properties[name] = {
216
+ optional,
217
+ schema: this.parseValue()
218
+ };
219
+ this.match("semicolon");
220
+ }
221
+ this.expect("rbrace");
222
+ return {
223
+ kind: "object",
224
+ properties
225
+ };
226
+ }
227
+ peek() {
228
+ return this.tokens[this.pos];
229
+ }
230
+ check(kind) {
231
+ return this.peek()?.kind === kind;
232
+ }
233
+ checkAt(pos, kind) {
234
+ return this.tokens[pos]?.kind === kind;
235
+ }
236
+ advance() {
237
+ const token = this.tokens[this.pos];
238
+ if (token === void 0) throw new SyntaxError("Unexpected end of input");
239
+ this.pos++;
240
+ return token;
241
+ }
242
+ match(kind) {
243
+ if (this.check(kind)) {
244
+ this.pos++;
245
+ return true;
246
+ }
247
+ return false;
248
+ }
249
+ expect(kind) {
250
+ if (!this.check(kind)) {
251
+ const got = this.peek();
252
+ throw new SyntaxError(got ? `Expected '${kind}' but got '${got.kind}' ('${got.value}') at position ${String(this.pos)}` : `Expected '${kind}' but reached end of input`);
253
+ }
254
+ return this.advance();
255
+ }
256
+ expectIdent() {
257
+ return this.expect("ident").value;
258
+ }
259
+ };
260
+ /**
261
+ * Parse a schema source string into a runtime AST.
262
+ *
263
+ * @param source - Schema string (e.g. `"{ name: string; age: number }"`).
264
+ * @returns The root {@link SchemaNode}.
265
+ * @throws {@link SyntaxError} on malformed input.
266
+ */
267
+ function parseSchema(source) {
268
+ return new SchemaParser(tokenize(source)).parseRoot();
269
+ }
270
+ //#endregion
271
+ export { parseSchema };
@@ -1 +1,74 @@
1
- function e(t){switch(t.kind){case`string`:return{type:`string`};case`number`:return{type:`number`};case`integer`:return{type:`integer`};case`boolean`:return{type:`boolean`};case`true`:return{const:!0};case`false`:return{const:!1};case`null`:return{type:`null`};case`literal`:return{const:t.value};case`undefined`:throw Error(`Cannot convert 'undefined' type to JSON Schema; model optionality at the parent level`);case`unknown`:return{};case`never`:return{not:{}};case`ref`:return{$ref:`#/$defs/${t.target}`};case`array`:return{type:`array`,items:e(t.element)};case`record`:return{type:`object`,additionalProperties:e(t.value)};case`object`:{let n={},r=[];for(let[i,a]of Object.entries(t.properties))n[i]=e(a.schema),a.optional||r.push(i);let i={type:`object`,additionalProperties:!1,properties:n};return r.length>0&&(i.required=r),i}case`union`:{let n=[],r=!0;for(let e of t.members)e.kind===`literal`?n.push(e.value):r=!1;return r?{enum:n}:{oneOf:t.members.map(e)}}}}export{e as nodeToJsonSchema};
1
+ //#region src/core/schema-dsl/to-json-schema.ts
2
+ /**
3
+ * Convert a {@link SchemaNode} AST node to a JSON Schema fragment.
4
+ *
5
+ * Mapping:
6
+ * - `string` → `{ type: 'string' }`
7
+ * - `number` → `{ type: 'number' }`
8
+ * - `integer` → `{ type: 'integer' }`
9
+ * - `boolean` → `{ type: 'boolean' }`
10
+ * - `true` → `{ const: true }`
11
+ * - `false` → `{ const: false }`
12
+ * - `null` → `{ type: 'null' }`
13
+ * - `undefined` → throws (JSON Schema has no `undefined` type)
14
+ * - `unknown` → `{}` (accepts any value)
15
+ * - `never` → `{ not: {} }` (rejects all values)
16
+ * - `'literal'` → `{ const: 'literal' }`
17
+ * - `@ref` → `{ $ref: '#/$defs/ref' }`
18
+ * - `T[]` → `{ type: 'array', items: convert(T) }`
19
+ * - `Record<K,V>` → `{ type: 'object', additionalProperties: convert(V) }`
20
+ * - `{...}` → `{ type: 'object', properties: ..., required: [...] }`
21
+ * - `A | B` → `{ enum: [...] }` if all literals, else `{ oneOf: [...] }`
22
+ *
23
+ * @param node - The AST node to convert.
24
+ * @returns A plain JSON Schema fragment.
25
+ */
26
+ function nodeToJsonSchema(node) {
27
+ switch (node.kind) {
28
+ case "string": return { type: "string" };
29
+ case "number": return { type: "number" };
30
+ case "integer": return { type: "integer" };
31
+ case "boolean": return { type: "boolean" };
32
+ case "true": return { const: true };
33
+ case "false": return { const: false };
34
+ case "null": return { type: "null" };
35
+ case "literal": return { const: node.value };
36
+ case "undefined": throw new Error("Cannot convert 'undefined' type to JSON Schema; model optionality at the parent level");
37
+ case "unknown": return {};
38
+ case "never": return { not: {} };
39
+ case "ref": return { $ref: `#/$defs/${node.target}` };
40
+ case "array": return {
41
+ type: "array",
42
+ items: nodeToJsonSchema(node.element)
43
+ };
44
+ case "record": return {
45
+ type: "object",
46
+ additionalProperties: nodeToJsonSchema(node.value)
47
+ };
48
+ case "object": {
49
+ const properties = {};
50
+ const required = [];
51
+ for (const [key, prop] of Object.entries(node.properties)) {
52
+ properties[key] = nodeToJsonSchema(prop.schema);
53
+ if (!prop.optional) required.push(key);
54
+ }
55
+ const result = {
56
+ type: "object",
57
+ additionalProperties: false,
58
+ properties
59
+ };
60
+ if (required.length > 0) result.required = required;
61
+ return result;
62
+ }
63
+ case "union": {
64
+ const literalValues = [];
65
+ let allLiteral = true;
66
+ for (const member of node.members) if (member.kind === "literal") literalValues.push(member.value);
67
+ else allLiteral = false;
68
+ if (allLiteral) return { enum: literalValues };
69
+ return { oneOf: node.members.map(nodeToJsonSchema) };
70
+ }
71
+ }
72
+ }
73
+ //#endregion
74
+ export { nodeToJsonSchema };
@@ -6,16 +6,20 @@ import { RunnableCommand } from "../schema/command.mjs";
6
6
  * Run a command builder against the given argv with injected options.
7
7
  *
8
8
  * This is the testkit wrapper around the shared executor:
9
- * 1. Create or reuse capture output
10
- * 2. Build standalone schema/meta defaults when CLI dispatch did not
11
- * 3. Delegate parse -> resolve -> execute to the shared executor
12
- * 4. Return the structured result with captured buffers
9
+ * 1. Apply the CLI root-flag layer (detect/strip `--json`) so copied real argv works
10
+ * 2. Create or reuse capture output
11
+ * 3. Build standalone schema/meta defaults when CLI dispatch did not
12
+ * 4. Delegate parse -> resolve -> execute to the shared executor
13
+ * 5. Return the structured result with captured buffers
13
14
  *
14
15
  * Errors are normalized by the shared executor into structured {@linkcode RunResult}s
15
16
  * with appropriate exit codes. The function never throws.
16
17
  *
17
18
  * @param cmd - The command builder (must have an action handler)
18
- * @param argv - Raw argv strings (NOT including the command name itself)
19
+ * @param argv - Raw argv strings (NOT including the command name itself). A
20
+ * CLI-level `--json` before the `--` separator is honored and stripped here,
21
+ * just like the real CLI root — so `['--json']` enables JSON mode rather than
22
+ * failing as an unknown flag. Equivalent to passing `{ jsonMode: true }`.
19
23
  * @param options - Injectable runtime state
20
24
  * @returns Structured run result with exit code and captured output
21
25
  */
@@ -1 +1,83 @@
1
- import{createCaptureOutput as e}from"../output/index.mjs";import{buildRunResult as t,executeCommand as n}from"../execution/index.mjs";async function r(r,i,a){let o,s;if(a?.out!==void 0)o=a.out,s=a.captured??{stdout:[],stderr:[],activity:[]};else{let t={...a?.verbosity===void 0?{}:{verbosity:a.verbosity},...a?.jsonMode===void 0?{}:{jsonMode:a.jsonMode},...a?.isTTY===void 0?{}:{isTTY:a.isTTY}};[o,s]=e(Object.keys(t).length>0?t:void 0)}let c=a?.mergedSchema??r.schema,l=a?.meta??{name:c.name,bin:a?.help?.binName??c.name,version:void 0,command:c.name};return t(await n({command:r,argv:i,out:o,schema:c,meta:l,...a===void 0?{}:{options:a}}),s)}export{r as runCommand};
1
+ import { createCaptureOutput } from "../output/index.mjs";
2
+ import { includesBeforeSeparator, stripBeforeSeparator } from "../parse/index.mjs";
3
+ import { buildRunResult, executeCommand } from "../execution/index.mjs";
4
+ //#region src/core/testkit/index.ts
5
+ /**
6
+ * Test harness: command.run() with injected state, output capture.
7
+ *
8
+ * Provides {@linkcode runCommand()} — the in-process test harness wrapper over DreamCLI's
9
+ * shared executor.\
10
+ * It wires capture output and standalone command metadata,
11
+ * then returns a structured {@linkcode RunResult} with exitCode and captured output.
12
+ *
13
+ * This keeps command tests process-free without testkit owning the canonical pipeline:
14
+ *
15
+ * ```text
16
+ * parse -> resolve -> execute
17
+ * ```
18
+ * @module dreamcli/core/testkit
19
+ */
20
+ /**
21
+ * Run a command builder against the given argv with injected options.
22
+ *
23
+ * This is the testkit wrapper around the shared executor:
24
+ * 1. Apply the CLI root-flag layer (detect/strip `--json`) so copied real argv works
25
+ * 2. Create or reuse capture output
26
+ * 3. Build standalone schema/meta defaults when CLI dispatch did not
27
+ * 4. Delegate parse -> resolve -> execute to the shared executor
28
+ * 5. Return the structured result with captured buffers
29
+ *
30
+ * Errors are normalized by the shared executor into structured {@linkcode RunResult}s
31
+ * with appropriate exit codes. The function never throws.
32
+ *
33
+ * @param cmd - The command builder (must have an action handler)
34
+ * @param argv - Raw argv strings (NOT including the command name itself). A
35
+ * CLI-level `--json` before the `--` separator is honored and stripped here,
36
+ * just like the real CLI root — so `['--json']` enables JSON mode rather than
37
+ * failing as an unknown flag. Equivalent to passing `{ jsonMode: true }`.
38
+ * @param options - Injectable runtime state
39
+ * @returns Structured run result with exit code and captured output
40
+ */
41
+ async function runCommand(cmd, argv, options) {
42
+ const hasJsonFlag = includesBeforeSeparator(argv, "--json");
43
+ const jsonMode = hasJsonFlag || options?.jsonMode === true;
44
+ const effectiveArgv = hasJsonFlag ? stripBeforeSeparator(argv, "--json") : argv;
45
+ let out;
46
+ let captured;
47
+ if (options?.out !== void 0) {
48
+ out = options.out;
49
+ captured = options.captured ?? {
50
+ stdout: [],
51
+ stderr: [],
52
+ activity: []
53
+ };
54
+ } else {
55
+ const captureOptions = {
56
+ ...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
57
+ ...jsonMode ? { jsonMode } : {},
58
+ ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {}
59
+ };
60
+ [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
61
+ }
62
+ const schema = options?.mergedSchema ?? cmd.schema;
63
+ const meta = options?.meta ?? {
64
+ name: schema.name,
65
+ bin: options?.help?.binName ?? schema.name,
66
+ version: void 0,
67
+ command: schema.name
68
+ };
69
+ const effectiveOptions = options !== void 0 ? {
70
+ ...options,
71
+ ...jsonMode ? { jsonMode } : {}
72
+ } : jsonMode ? { jsonMode } : void 0;
73
+ return buildRunResult(await executeCommand({
74
+ command: cmd,
75
+ argv: effectiveArgv,
76
+ out,
77
+ schema,
78
+ meta,
79
+ ...effectiveOptions !== void 0 ? { options: effectiveOptions } : {}
80
+ }), captured);
81
+ }
82
+ //#endregion
83
+ export { runCommand };