@kjanat/dreamcli 3.0.0-rc.17 → 3.0.0-rc.19

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/CHANGELOG.md CHANGED
@@ -7,6 +7,50 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.0.0-rc.19] - 2026-07-21
11
+
12
+ ### Added
13
+
14
+ - **Expanded config discovery** (#61) — the default search now covers three
15
+ scopes, first match wins, no merging:
16
+ 1. **Project**: the base directory (default `cwd`) and every ancestor up
17
+ to the filesystem root, nearest first, each probed for
18
+ `.{appName}.{ext}`, `{appName}.config.{ext}`, and the new
19
+ `.config/{appName}.{ext}` convention.
20
+ 2. **User**: XDG / AppData as before, plus
21
+ `~/Library/Application Support/{appName}/config.{ext}` on macOS.
22
+ 3. **System**: `/etc/{appName}/config.{ext}` on Linux and macOS.
23
+ - **`baseDir` discovery option** — `discoverConfig()` accepts a base
24
+ directory to anchor the project-scope walk somewhere other than `cwd`.
25
+ - **`RuntimeAdapter.userConfigDirs` / `systemConfigDirs`** — optional
26
+ ordered config roots supplied by the runtime adapters; discovery falls
27
+ back to `[configDir]` / `[]` when a custom adapter omits them.
28
+
29
+ ### Changed
30
+
31
+ - **Breaking**: `buildConfigSearchPaths(appName, options)` replaces the
32
+ positional `(appName, cwd, configDir, loaders?)` signature; options carry
33
+ `baseDir`, `userConfigDirs`, `systemConfigDirs`, and `loaders`.
34
+
35
+ ## [3.0.0-rc.18] - 2026-07-21
36
+
37
+ ### Added
38
+
39
+ - **`flag.path({ type: 'directory', create: true })`** — creates the directory
40
+ (recursively) at resolution time when nothing exists at the path. Only
41
+ available with `type: 'directory'`, enforced at the type level. Creation
42
+ runs through a new `mkdir` seam: `RuntimeAdapter.mkdir`, overridable via
43
+ run options, noop in the test adapter, so `src/core` stays process-free.
44
+
45
+ ### Fixed
46
+
47
+ - **`flag.path({ type, mustExist: false })` rejected missing paths** — the
48
+ builder recorded the explicit `mustExist: false`, but resolution errored on
49
+ any missing path whenever path checks were active, making an optional
50
+ to-be-created path (e.g. an `--outdir` that the command itself creates)
51
+ impossible to declare. A missing path now passes when `mustExist` is
52
+ `false`; an existing path is still type-checked.
53
+
10
54
  ## [3.0.0-rc.17] - 2026-07-20
11
55
 
12
56
  ### Added
package/README.md CHANGED
@@ -92,9 +92,9 @@ cli('greet').default(greet).run();
92
92
  ### Multi-command CLI
93
93
 
94
94
  <picture>
95
- <source media="(prefers-color-scheme: dark)" width="700" height="400" alt="dreamcli-migrate-dark" srcset="https://github.com/user-attachments/assets/1ef7f20c-9ffb-4cb6-a6bc-fb562895aa6f">
96
- <source media="(prefers-color-scheme: light)" width="700" height="400" alt="dreamcli-migrate-light" srcset="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
97
- <img alt="DreamCLI migration progress demo" width="700" height="400" src="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
95
+ <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/1ef7f20c-9ffb-4cb6-a6bc-fb562895aa6f">
96
+ <source media="(prefers-color-scheme: light)" srcset="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
97
+ <img alt="DreamCLI migration progress demo" width="700" src="https://github.com/user-attachments/assets/1ee5f38d-cad8-47ec-94b2-c826eabab76b">
98
98
  </picture>
99
99
 
100
100
  ```ts
@@ -497,12 +497,16 @@ declare class CLIBuilder {
497
497
  /**
498
498
  * Enable automatic config file discovery.
499
499
  *
500
- * When enabled, `.run()` probes standard paths before dispatching:
501
- * 1. `$CWD/.{appName}.json`
502
- * 2. `$CWD/{appName}.config.json`
503
- * 3. `$CONFIG_DIR/{appName}/config.json`
504
- * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
500
+ * When enabled, `.run()` probes standard paths before dispatching,
501
+ * first match wins, no merging:
502
+ * 1. Project scope — for `$CWD` and each ancestor directory up to the
503
+ * filesystem root, nearest first:
504
+ * `.{appName}.json`, `{appName}.config.json`, `.config/{appName}.json`
505
+ * 2. User scope — `{dir}/{appName}/config.json` for each user config
506
+ * root (`$XDG_CONFIG_HOME` / `~/.config` on Unix, plus
507
+ * `~/Library/Application Support` on macOS,
505
508
  * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
509
+ * 3. System scope — `/etc/{appName}/config.json` on Linux and macOS
506
510
  *
507
511
  * The user can override the path via `--config <path>` or `--config=<path>`.
508
512
  *
@@ -170,6 +170,7 @@ function buildCommandRunOptions(options, helpOptions, meta) {
170
170
  ...options?.prompter !== void 0 ? { prompter: options.prompter } : {},
171
171
  ...options?.answers !== void 0 ? { answers: options.answers } : {},
172
172
  ...options?.stat !== void 0 ? { stat: options.stat } : {},
173
+ ...options?.mkdir !== void 0 ? { mkdir: options.mkdir } : {},
173
174
  ...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
174
175
  ...options?.jsonMode !== void 0 ? { jsonMode: options.jsonMode } : {},
175
176
  ...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
@@ -313,12 +314,16 @@ var CLIBuilder = class CLIBuilder {
313
314
  /**
314
315
  * Enable automatic config file discovery.
315
316
  *
316
- * When enabled, `.run()` probes standard paths before dispatching:
317
- * 1. `$CWD/.{appName}.json`
318
- * 2. `$CWD/{appName}.config.json`
319
- * 3. `$CONFIG_DIR/{appName}/config.json`
320
- * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
317
+ * When enabled, `.run()` probes standard paths before dispatching,
318
+ * first match wins, no merging:
319
+ * 1. Project scope — for `$CWD` and each ancestor directory up to the
320
+ * filesystem root, nearest first:
321
+ * `.{appName}.json`, `{appName}.config.json`, `.config/{appName}.json`
322
+ * 2. User scope — `{dir}/{appName}/config.json` for each user config
323
+ * root (`$XDG_CONFIG_HOME` / `~/.config` on Unix, plus
324
+ * `~/Library/Application Support` on macOS,
321
325
  * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
326
+ * 3. System scope — `/etc/{appName}/config.json` on Linux and macOS
322
327
  *
323
328
  * The user can override the path via `--config <path>` or `--config=<path>`.
324
329
  *
@@ -114,6 +114,8 @@ interface RuntimePreflightOptions {
114
114
  readonly isTTY?: boolean;
115
115
  /** Filesystem probe override for `flag.path()` checks; bypasses the adapter probe. */
116
116
  readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
117
+ /** Directory creation override for `flag.path()` `create` checks; bypasses the adapter. */
118
+ readonly mkdir?: (path: string) => Promise<void>;
117
119
  }
118
120
  /**
119
121
  * Fully resolved runtime inputs ready for the execution pipeline.
@@ -139,6 +141,8 @@ interface RuntimeExecutionInputs {
139
141
  readonly config?: Readonly<Record<string, unknown>>;
140
142
  /** Filesystem probe (from the adapter) for `flag.path()` checks. */
141
143
  readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
144
+ /** Directory creation (from the adapter) for `flag.path()` `create` checks. */
145
+ readonly mkdir?: (path: string) => Promise<void>;
142
146
  }
143
147
  /** Preflight succeeded — all runtime inputs are resolved and ready for execution. @internal */
144
148
  interface ReadyRuntimePreflight {
@@ -160,6 +160,7 @@ async function prepareRuntimePreflight(options) {
160
160
  jsonMode,
161
161
  verbosity: hasQuietFlag ? "quiet" : options.options?.verbosity ?? "normal",
162
162
  stat: options.options?.stat ?? options.adapter.stat,
163
+ mkdir: options.options?.mkdir ?? options.adapter.mkdir,
163
164
  ...stdinData !== void 0 ? { stdinData } : {},
164
165
  ...options.options?.prompter !== void 0 ? { prompter: options.options.prompter } : autoPrompter !== void 0 ? { prompter: autoPrompter } : {},
165
166
  ...loadedConfig !== void 0 ? { config: loadedConfig } : {}
@@ -41,6 +41,14 @@ interface ConfigDiscoveryOptions {
41
41
  * Probed in order; first found wins.
42
42
  */
43
43
  readonly searchPaths?: readonly string[];
44
+ /**
45
+ * Directory the project-scope ancestor walk starts from.
46
+ * Anchors discovery to a location other than the process working
47
+ * directory (e.g. the directory of a file an editor integration is
48
+ * operating on).
49
+ * @defaultValue `adapter.cwd`
50
+ */
51
+ readonly baseDir?: string;
44
52
  }
45
53
  /** Successful config discovery — file found and parsed. */
46
54
  interface ConfigFound {
@@ -60,6 +68,23 @@ interface ConfigNotFound {
60
68
  }
61
69
  /** Discriminated result of config discovery. */
62
70
  type ConfigDiscoveryResult = ConfigFound | ConfigNotFound;
71
+ /** Directory scopes feeding {@link buildConfigSearchPaths}. */
72
+ interface ConfigSearchPathOptions {
73
+ /** Directory the project-scope ancestor walk starts from. */
74
+ readonly baseDir: string;
75
+ /**
76
+ * User-scope config roots, highest priority first
77
+ * (XDG / AppData, plus `~/Library/Application Support` on macOS).
78
+ */
79
+ readonly userConfigDirs: readonly string[];
80
+ /**
81
+ * System-scope config roots (`/etc` on Linux and macOS).
82
+ * @defaultValue `[]`
83
+ */
84
+ readonly systemConfigDirs?: readonly string[];
85
+ /** Custom {@link FormatLoader}s whose extensions expand the search set. */
86
+ readonly loaders?: readonly FormatLoader[];
87
+ }
63
88
  /**
64
89
  * Build the default config search paths for an app.
65
90
  *
@@ -68,34 +93,40 @@ type ConfigDiscoveryResult = ConfigFound | ConfigNotFound;
68
93
  * manually. Exported for debugging, custom discovery flows, and help text.
69
94
  *
70
95
  * Search order (first match wins):
71
- * 1. `$CWD/.{appName}.json` — dotfile in project root
72
- * 2. `$CWD/{appName}.config.json` — explicit config in project root
73
- * 3. `$CONFIG_DIR/{appName}/config.json` — XDG / AppData standard
74
- * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
75
- * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
96
+ * 1. Project scope — for `baseDir` and each ancestor directory up to the
97
+ * filesystem root, nearest first:
98
+ * 1. `{dir}/.{appName}.json` — dotfile
99
+ * 2. `{dir}/{appName}.config.json` — explicit config
100
+ * 3. `{dir}/.config/{appName}.json` — project `.config/` convention
101
+ * 2. User scope — `{userConfigDir}/{appName}/config.json` for each entry of
102
+ * `userConfigDirs`, in order.
103
+ * 3. System scope — `{systemConfigDir}/{appName}/config.json` for each entry
104
+ * of `systemConfigDirs`, in order.
76
105
  *
77
106
  * When custom {@link ConfigDiscoveryOptions.loaders | loaders} are registered,
78
107
  * each path pattern is repeated per supported extension (JSON always first).
79
108
  *
80
109
  * @param appName - CLI application name used to derive config filenames.
81
- * @param cwd - Current working directory (project-root search location).
82
- * @param configDir - Platform config directory (XDG / AppData).
83
- * @param loaders - Optional custom {@link FormatLoader}s whose extensions expand the search set.
110
+ * @param options - Directory scopes and loaders (see {@link ConfigSearchPathOptions}).
84
111
  * @returns Ordered list of candidate config file paths (first match wins).
85
112
  *
86
113
  * @example
87
114
  * ```ts
88
- * const paths = buildConfigSearchPaths('mycli', '/repo', '/home/me/.config');
115
+ * const paths = buildConfigSearchPaths('mycli', {
116
+ * baseDir: '/repo/packages/app',
117
+ * userConfigDirs: ['/home/me/.config'],
118
+ * systemConfigDirs: ['/etc'],
119
+ * });
89
120
  * ```
90
121
  */
91
- declare function buildConfigSearchPaths(appName: string, cwd: string, configDir: string, loaders?: readonly FormatLoader[]): readonly string[];
122
+ declare function buildConfigSearchPaths(appName: string, options: ConfigSearchPathOptions): readonly string[];
92
123
  /**
93
124
  * The subset of {@link RuntimeAdapter} needed for config discovery.
94
125
  *
95
126
  * Exported so custom hosts and tests can type the minimal adapter required by
96
127
  * {@link discoverConfig} without depending on the full runtime adapter shape.
97
128
  */
98
- type ConfigAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd' | 'configDir'>;
129
+ type ConfigAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd' | 'configDir'> & Partial<Pick<RuntimeAdapter, 'userConfigDirs' | 'systemConfigDirs'>>;
99
130
  /**
100
131
  * Discover and load a config file.
101
132
  *
@@ -157,4 +188,4 @@ declare function discoverConfig(appName: string, adapter: ConfigAdapter, options
157
188
  */
158
189
  declare function configFormat(extensions: readonly string[], parse: (content: string) => unknown): FormatLoader;
159
190
  //#endregion
160
- export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type FormatLoader, type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, type PackageRepositoryUrlOptions, buildConfigSearchPaths, configFormat, discoverConfig, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
191
+ export { type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSearchPathOptions, type FormatLoader, type ManifestDiscoveryOptions, type PackageJsonAdapter, type PackageJsonData, type PackageRepository, type PackageRepositoryUrlOptions, buildConfigSearchPaths, configFormat, discoverConfig, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -39,7 +39,31 @@ const jsonLoader = {
39
39
  */
40
40
  function joinPath(base, ...segments) {
41
41
  const sep = base.includes("\\") ? "\\" : "/";
42
- return [base, ...segments].join(sep);
42
+ return [base.endsWith(sep) ? base.slice(0, -1) : base, ...segments].join(sep);
43
+ }
44
+ /**
45
+ * List a directory and every ancestor up to the filesystem root,
46
+ * nearest first. Separator is inferred from the input; POSIX (`/`) and
47
+ * Windows drive roots (`C:\`) both terminate the walk.
48
+ *
49
+ * @internal
50
+ */
51
+ function ancestorDirs(base) {
52
+ const sep = base.includes("\\") ? "\\" : "/";
53
+ let current = base;
54
+ while (current.length > 1 && current.endsWith(sep) && !current.endsWith(`:${sep}`)) current = current.slice(0, -1);
55
+ const dirs = [current];
56
+ while (true) {
57
+ const idx = current.lastIndexOf(sep);
58
+ if (idx < 0) break;
59
+ let parent = current.slice(0, idx);
60
+ if (parent === "") parent = sep;
61
+ else if (/^[A-Za-z]:$/.test(parent)) parent = `${parent}${sep}`;
62
+ if (parent === current) break;
63
+ dirs.push(parent);
64
+ current = parent;
65
+ }
66
+ return dirs;
43
67
  }
44
68
  /**
45
69
  * Extract the file extension (without leading dot, lowercased).
@@ -60,32 +84,42 @@ function getExtension(path) {
60
84
  * manually. Exported for debugging, custom discovery flows, and help text.
61
85
  *
62
86
  * Search order (first match wins):
63
- * 1. `$CWD/.{appName}.json` — dotfile in project root
64
- * 2. `$CWD/{appName}.config.json` — explicit config in project root
65
- * 3. `$CONFIG_DIR/{appName}/config.json` — XDG / AppData standard
66
- * (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
67
- * `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
87
+ * 1. Project scope — for `baseDir` and each ancestor directory up to the
88
+ * filesystem root, nearest first:
89
+ * 1. `{dir}/.{appName}.json` — dotfile
90
+ * 2. `{dir}/{appName}.config.json` — explicit config
91
+ * 3. `{dir}/.config/{appName}.json` — project `.config/` convention
92
+ * 2. User scope — `{userConfigDir}/{appName}/config.json` for each entry of
93
+ * `userConfigDirs`, in order.
94
+ * 3. System scope — `{systemConfigDir}/{appName}/config.json` for each entry
95
+ * of `systemConfigDirs`, in order.
68
96
  *
69
97
  * When custom {@link ConfigDiscoveryOptions.loaders | loaders} are registered,
70
98
  * each path pattern is repeated per supported extension (JSON always first).
71
99
  *
72
100
  * @param appName - CLI application name used to derive config filenames.
73
- * @param cwd - Current working directory (project-root search location).
74
- * @param configDir - Platform config directory (XDG / AppData).
75
- * @param loaders - Optional custom {@link FormatLoader}s whose extensions expand the search set.
101
+ * @param options - Directory scopes and loaders (see {@link ConfigSearchPathOptions}).
76
102
  * @returns Ordered list of candidate config file paths (first match wins).
77
103
  *
78
104
  * @example
79
105
  * ```ts
80
- * const paths = buildConfigSearchPaths('mycli', '/repo', '/home/me/.config');
106
+ * const paths = buildConfigSearchPaths('mycli', {
107
+ * baseDir: '/repo/packages/app',
108
+ * userConfigDirs: ['/home/me/.config'],
109
+ * systemConfigDirs: ['/etc'],
110
+ * });
81
111
  * ```
82
112
  */
83
- function buildConfigSearchPaths(appName, cwd, configDir, loaders) {
84
- const extensions = buildExtensionList(loaders);
113
+ function buildConfigSearchPaths(appName, options) {
114
+ const extensions = buildExtensionList(options.loaders);
85
115
  const paths = [];
86
- for (const ext of extensions) paths.push(joinPath(cwd, `.${appName}.${ext}`));
87
- for (const ext of extensions) paths.push(joinPath(cwd, `${appName}.config.${ext}`));
88
- for (const ext of extensions) paths.push(joinPath(configDir, appName, `config.${ext}`));
116
+ for (const dir of ancestorDirs(options.baseDir)) {
117
+ for (const ext of extensions) paths.push(joinPath(dir, `.${appName}.${ext}`));
118
+ for (const ext of extensions) paths.push(joinPath(dir, `${appName}.config.${ext}`));
119
+ for (const ext of extensions) paths.push(joinPath(dir, ".config", `${appName}.${ext}`));
120
+ }
121
+ for (const dir of options.userConfigDirs) for (const ext of extensions) paths.push(joinPath(dir, appName, `config.${ext}`));
122
+ for (const dir of options.systemConfigDirs ?? []) for (const ext of extensions) paths.push(joinPath(dir, appName, `config.${ext}`));
89
123
  return paths;
90
124
  }
91
125
  /**
@@ -158,7 +192,12 @@ function buildLoaderMap(loaders) {
158
192
  */
159
193
  async function discoverConfig(appName, adapter, options) {
160
194
  const loaderMap = buildLoaderMap(options?.loaders);
161
- const searchPaths = options?.configPath !== void 0 ? [options.configPath] : options?.searchPaths ?? buildConfigSearchPaths(appName, adapter.cwd, adapter.configDir, options?.loaders);
195
+ const searchPaths = options?.configPath !== void 0 ? [options.configPath] : options?.searchPaths ?? buildConfigSearchPaths(appName, {
196
+ baseDir: options?.baseDir ?? adapter.cwd,
197
+ userConfigDirs: adapter.userConfigDirs ?? [adapter.configDir],
198
+ systemConfigDirs: adapter.systemConfigDirs ?? [],
199
+ ...options?.loaders !== void 0 ? { loaders: options.loaders } : {}
200
+ });
162
201
  for (const candidatePath of searchPaths) {
163
202
  const content = await adapter.readFile(candidatePath);
164
203
  if (content === null) {
@@ -63,7 +63,8 @@ async function executeCommand(request) {
63
63
  ...options?.env !== void 0 ? { env: options.env } : {},
64
64
  ...options?.config !== void 0 ? { config: options.config } : {},
65
65
  ...effectivePrompter !== void 0 ? { prompter: effectivePrompter } : {},
66
- ...options?.stat !== void 0 ? { stat: options.stat } : {}
66
+ ...options?.stat !== void 0 ? { stat: options.stat } : {},
67
+ ...options?.mkdir !== void 0 ? { mkdir: options.mkdir } : {}
67
68
  });
68
69
  const resolvedParams = {
69
70
  args: resolved.args,
@@ -137,7 +137,8 @@ function serializeFlag(schema, opts) {
137
137
  if (schema.unique) result.unique = true;
138
138
  if (schema.pathChecks !== void 0) result.pathChecks = {
139
139
  mustExist: schema.pathChecks.mustExist,
140
- ...schema.pathChecks.type !== void 0 ? { type: schema.pathChecks.type } : {}
140
+ ...schema.pathChecks.type !== void 0 ? { type: schema.pathChecks.type } : {},
141
+ ...schema.pathChecks.create ? { create: true } : {}
141
142
  };
142
143
  if (schema.valueHint !== void 0) result.valueHint = schema.valueHint;
143
144
  if (opts.includePrompts && schema.prompt !== void 0) result.prompt = serializePrompt(schema.prompt);
@@ -656,7 +657,8 @@ const definitionMetaSchema = withDefinitionMetaSchemaDescriptions({
656
657
  additionalProperties: false,
657
658
  properties: {
658
659
  mustExist: { type: "boolean" },
659
- type: { enum: ["file", "directory"] }
660
+ type: { enum: ["file", "directory"] },
661
+ create: { type: "boolean" }
660
662
  },
661
663
  required: ["mustExist"]
662
664
  },
@@ -53,6 +53,11 @@ interface ResolveOptions {
53
53
  * `null` when nothing does. When absent, path checks are skipped.
54
54
  */
55
55
  readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
56
+ /**
57
+ * Recursive directory creation for `flag.path()` `create` checks. When
58
+ * absent, missing paths are not created and existence rules apply as-is.
59
+ */
60
+ readonly mkdir?: (path: string) => Promise<void>;
56
61
  }
57
62
  /** Structured deprecation notice emitted for explicitly sourced values. */
58
63
  interface DeprecationWarning {
@@ -10,8 +10,10 @@ import { ErasedInteractiveResolver } from "../schema/command.mjs";
10
10
  * Returns what exists at the path, or `null` when nothing does.
11
11
  */
12
12
  type StatFn = (path: string) => Promise<'file' | 'directory' | null>;
13
+ /** Recursive directory creation injected by the caller for `flag.path()` `create` checks. */
14
+ type MkdirFn = (path: string) => Promise<void>;
13
15
  /** Walk every declared flag through the resolution chain (cli -> env -> config -> prompt -> default), collecting deprecations and throwing aggregated errors. */
14
- declare function resolveFlags(flagSchemas: Readonly<Record<string, FlagSchema>>, parsedFlags: Readonly<Record<string, unknown>>, env: Readonly<Record<string, string | undefined>>, config: Readonly<Record<string, unknown>>, prompter: PromptEngine | undefined, interactive: ErasedInteractiveResolver | undefined, deprecations: DeprecationWarning[], stat: StatFn | undefined): Promise<Readonly<Record<string, unknown>>>;
16
+ declare function resolveFlags(flagSchemas: Readonly<Record<string, FlagSchema>>, parsedFlags: Readonly<Record<string, unknown>>, env: Readonly<Record<string, string | undefined>>, config: Readonly<Record<string, unknown>>, prompter: PromptEngine | undefined, interactive: ErasedInteractiveResolver | undefined, deprecations: DeprecationWarning[], stat: StatFn | undefined, mkdir: MkdirFn | undefined): Promise<Readonly<Record<string, unknown>>>;
15
17
  /** Maps each flag kind to the prompt kinds that produce compatible values. */
16
18
  declare const COMPATIBLE_PROMPT_KINDS: Record<FlagKind, readonly PromptKind[]>;
17
19
  //#endregion
@@ -11,7 +11,7 @@ import { resolveConfigPath } from "./config.mjs";
11
11
  * @internal
12
12
  */
13
13
  /** Walk every declared flag through the resolution chain (cli -> env -> config -> prompt -> default), collecting deprecations and throwing aggregated errors. */
14
- async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, interactive, deprecations, stat) {
14
+ async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, interactive, deprecations, stat, mkdir) {
15
15
  const resolved = {};
16
16
  const errors = [];
17
17
  const hardErrorFlags = /* @__PURE__ */ new Set();
@@ -125,7 +125,7 @@ async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, int
125
125
  const value = resolved[name];
126
126
  if (schema.kind === "array" && schema.unique && Array.isArray(value)) resolved[name] = [...new Set(value)];
127
127
  if (schema.pathChecks !== void 0 && typeof value === "string" && stat !== void 0) {
128
- const violation = await validatePathChecks(name, value, schema.pathChecks, stat);
128
+ const violation = await validatePathChecks(name, value, schema.pathChecks, stat, mkdir);
129
129
  if (violation !== void 0) errors.push(violation);
130
130
  }
131
131
  }
@@ -139,17 +139,34 @@ async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, int
139
139
  * {@link ValidationError} with code `'CONSTRAINT_VIOLATED'` otherwise.
140
140
  * @internal
141
141
  */
142
- async function validatePathChecks(flagName, value, checks, stat) {
142
+ async function validatePathChecks(flagName, value, checks, stat, mkdir) {
143
143
  const found = await stat(value);
144
- if (found === null) return new ValidationError(`Path '${value}' for flag --${flagName} does not exist`, {
145
- code: "CONSTRAINT_VIOLATED",
146
- details: {
147
- flag: flagName,
148
- value,
149
- constraint: "mustExist"
150
- },
151
- suggest: `Provide an existing path for --${flagName}`
152
- });
144
+ if (found === null) {
145
+ if (checks.create && mkdir !== void 0) try {
146
+ await mkdir(value);
147
+ return;
148
+ } catch (error) {
149
+ return new ValidationError(`Failed to create directory '${value}' for flag --${flagName}: ${error instanceof Error ? error.message : String(error)}`, {
150
+ code: "CONSTRAINT_VIOLATED",
151
+ details: {
152
+ flag: flagName,
153
+ value,
154
+ constraint: "create"
155
+ },
156
+ suggest: `Provide a creatable or existing directory path for --${flagName}`
157
+ });
158
+ }
159
+ if (!checks.mustExist) return void 0;
160
+ return new ValidationError(`Path '${value}' for flag --${flagName} does not exist`, {
161
+ code: "CONSTRAINT_VIOLATED",
162
+ details: {
163
+ flag: flagName,
164
+ value,
165
+ constraint: "mustExist"
166
+ },
167
+ suggest: `Provide an existing path for --${flagName}`
168
+ });
169
+ }
153
170
  if (checks.type !== void 0 && found !== checks.type) return new ValidationError(`Path '${value}' for flag --${flagName} is a ${found}, expected a ${checks.type}`, {
154
171
  code: "CONSTRAINT_VIOLATED",
155
172
  details: {
@@ -64,7 +64,7 @@ async function resolve(schema, parsed, options) {
64
64
  let args = {};
65
65
  const errors = [];
66
66
  try {
67
- flags = await resolveFlags(schema.flags, parsed.flags, env, config, prompter, schema.interactive, deprecations, options?.stat);
67
+ flags = await resolveFlags(schema.flags, parsed.flags, env, config, prompter, schema.interactive, deprecations, options?.stat, options?.mkdir);
68
68
  } catch (error) {
69
69
  if (!isValidationError(error)) throw error;
70
70
  errors.push(...collectValidationErrors(error));
@@ -123,19 +123,45 @@ type FlagKind = (typeof FLAG_KINDS)[number];
123
123
  * value from config files. Narrow inside the function as needed.
124
124
  */
125
125
  type FlagParseFn<T> = (raw: unknown) => T;
126
- /** Options accepted by `flag.path()`. */
127
- interface PathFlagOptions {
126
+ /** Options accepted by `flag.path()` for any-kind or file paths. */
127
+ interface FilePathFlagOptions {
128
128
  /**
129
129
  * Reject the value if nothing exists at the path.
130
130
  * @defaultValue `false` (`true` when `type` is set)
131
131
  */
132
132
  readonly mustExist?: boolean;
133
133
  /**
134
- * Require the path to be a file or a directory. Implies existence.
134
+ * Require the path to be a file or a directory. Implies existence
135
+ * unless `mustExist` is explicitly `false`, in which case a missing
136
+ * path passes and only an existing path is type-checked.
135
137
  * @defaultValue `undefined` (any kind)
136
138
  */
137
- readonly type?: 'file' | 'directory';
139
+ readonly type?: 'file';
140
+ /** Directory creation is only available with `type: 'directory'`. */
141
+ readonly create?: never;
138
142
  }
143
+ /** Options accepted by `flag.path()` for directory paths. */
144
+ interface DirectoryPathFlagOptions {
145
+ /**
146
+ * Reject the value if nothing exists at the path.
147
+ * @defaultValue `false` (`true` when `type` is set)
148
+ */
149
+ readonly mustExist?: boolean;
150
+ /**
151
+ * Require the path to be a directory. Implies existence unless
152
+ * `mustExist` is explicitly `false`, in which case a missing path
153
+ * passes and only an existing path is type-checked.
154
+ */
155
+ readonly type: 'directory';
156
+ /**
157
+ * Create the directory (recursively) when nothing exists at the path.
158
+ * An existing non-directory path still fails the type check.
159
+ * @defaultValue `false`
160
+ */
161
+ readonly create?: boolean;
162
+ }
163
+ /** Options accepted by `flag.path()`. */
164
+ type PathFlagOptions = FilePathFlagOptions | DirectoryPathFlagOptions;
139
165
  /**
140
166
  * Filesystem expectations attached by `flag.path()`.
141
167
  *
@@ -148,9 +174,11 @@ interface PathChecks {
148
174
  readonly mustExist: boolean;
149
175
  /**
150
176
  * Require the existing path to be a file or a directory. Implies
151
- * existence when set.
177
+ * existence when set, unless `mustExist` is `false`.
152
178
  */
153
179
  readonly type: 'file' | 'directory' | undefined;
180
+ /** Create the directory (recursively) when nothing exists at the path. */
181
+ readonly create: boolean;
154
182
  }
155
183
  /** Runtime descriptor for a flag alias. */
156
184
  interface FlagAlias {
@@ -975,7 +1003,7 @@ interface FlagFactory {
975
1003
  * env, and config values are validated identically.
976
1004
  *
977
1005
  * @param options - Optional existence/type checks. `type` implies
978
- * existence.
1006
+ * existence unless `mustExist` is explicitly `false`.
979
1007
  * @returns A {@link FlagBuilder} for path strings.
980
1008
  *
981
1009
  * @example
@@ -983,6 +1011,10 @@ interface FlagFactory {
983
1011
  * flag.path() // any string, help shows <path>
984
1012
  * flag.path({ mustExist: true }) // rejects missing paths
985
1013
  * flag.path({ type: 'directory' }) // must exist and be a directory
1014
+ * flag.path({ type: 'directory', mustExist: false })
1015
+ * // missing passes; existing must be a directory
1016
+ * flag.path({ type: 'directory', create: true })
1017
+ * // created recursively when missing
986
1018
  * ```
987
1019
  */
988
1020
  path(options?: PathFlagOptions): FlagBuilder<{
@@ -671,7 +671,8 @@ const flag = {
671
671
  return new FlagBuilder(createSchema("string", {
672
672
  pathChecks: options?.mustExist === true || options?.type !== void 0 ? {
673
673
  mustExist: options.mustExist ?? true,
674
- type: options.type
674
+ type: options.type,
675
+ create: options.type === "directory" && options.create === true
675
676
  } : void 0,
676
677
  valueHint: "path"
677
678
  }));
@@ -68,6 +68,13 @@ interface RunOptions {
68
68
  * override), path checks are skipped.
69
69
  */
70
70
  readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
71
+ /**
72
+ * Recursive directory creation for `flag.path()` `create` checks.
73
+ *
74
+ * `CLIBuilder.run()` supplies the runtime adapter's implementation
75
+ * automatically. When absent, missing paths are not created.
76
+ */
77
+ readonly mkdir?: (path: string) => Promise<void>;
71
78
  /**
72
79
  * Verbosity level for the output channel.
73
80
  * @defaultValue `'normal'`
@@ -91,6 +91,15 @@ interface RuntimeAdapter {
91
91
  * Used by `flag.path()` existence/type checks after resolution.
92
92
  */
93
93
  readonly stat: (path: string) => Promise<'file' | 'directory' | null>;
94
+ /**
95
+ * Create a directory, including missing parents.
96
+ *
97
+ * Succeeds when the directory already exists. Throws on other I/O errors
98
+ * (permission denied, existing file at the path, etc.).
99
+ *
100
+ * Used by `flag.path()` `create` checks after resolution.
101
+ */
102
+ readonly mkdir: (path: string) => Promise<void>;
94
103
  /**
95
104
  * User home directory (absolute path).
96
105
  *
@@ -107,6 +116,21 @@ interface RuntimeAdapter {
107
116
  * Config discovery appends the app-specific subdirectory.
108
117
  */
109
118
  readonly configDir: string;
119
+ /**
120
+ * User-scope config roots for discovery, highest priority first.
121
+ *
122
+ * - Unix: `[configDir]`
123
+ * - macOS: `[configDir, ~/Library/Application Support]`
124
+ * - Windows: `[configDir]`
125
+ *
126
+ * When absent, discovery falls back to `[configDir]`.
127
+ */
128
+ readonly userConfigDirs?: readonly string[];
129
+ /**
130
+ * System-scope config roots for discovery (`['/etc']` on Linux and
131
+ * macOS, `[]` on Windows). When absent, discovery probes none.
132
+ */
133
+ readonly systemConfigDirs?: readonly string[];
110
134
  }
111
135
  /** Current terminal dimensions in columns and rows. */
112
136
  interface TerminalSize {
@@ -194,10 +218,19 @@ interface TestAdapterOptions {
194
218
  * ```
195
219
  */
196
220
  readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
221
+ /**
222
+ * Directory creation stub for `flag.path()` `create` checks (defaults to
223
+ * a noop that resolves without creating anything).
224
+ */
225
+ readonly mkdir?: (path: string) => Promise<void>;
197
226
  /** Home directory (defaults to `'/home/test'`). */
198
227
  readonly homedir?: string;
199
228
  /** Config directory (defaults to `'/home/test/.config'`). */
200
229
  readonly configDir?: string;
230
+ /** User-scope config roots for discovery (defaults to `[configDir]`). */
231
+ readonly userConfigDirs?: readonly string[];
232
+ /** System-scope config roots for discovery (defaults to `[]`). */
233
+ readonly systemConfigDirs?: readonly string[];
201
234
  }
202
235
  /**
203
236
  * Error thrown by adapter implementations that model process exit as an
@@ -34,6 +34,8 @@ const eofRead = () => Promise.resolve(null);
34
34
  const noopReadFile = () => Promise.resolve(null);
35
35
  /** Noop stat — reports `null` (nothing exists) for all paths. */
36
36
  const noopStat = () => Promise.resolve(null);
37
+ /** Noop mkdir — resolves without creating anything. */
38
+ const noopMkdir = () => Promise.resolve();
37
39
  /**
38
40
  * Create a test runtime adapter with injectable process state.
39
41
  *
@@ -79,8 +81,11 @@ function createTestAdapter(options) {
79
81
  }),
80
82
  readFile: options?.readFile ?? noopReadFile,
81
83
  stat: options?.stat ?? noopStat,
84
+ mkdir: options?.mkdir ?? noopMkdir,
82
85
  homedir: options?.homedir ?? "/home/test",
83
- configDir: options?.configDir ?? "/home/test/.config"
86
+ configDir: options?.configDir ?? "/home/test/.config",
87
+ userConfigDirs: options?.userConfigDirs ?? [options?.configDir ?? "/home/test/.config"],
88
+ systemConfigDirs: options?.systemConfigDirs ?? []
84
89
  };
85
90
  }
86
91
  //#endregion
@@ -66,6 +66,10 @@ interface DenoNamespace {
66
66
  stat(path: string): Promise<{
67
67
  readonly isDirectory: boolean;
68
68
  }>;
69
+ /** Create a directory (requires `--allow-write`). */
70
+ mkdir(path: string, options?: {
71
+ readonly recursive?: boolean;
72
+ }): Promise<void>;
69
73
  }
70
74
  /**
71
75
  * Create a runtime adapter backed by the Deno namespace.
@@ -113,8 +113,11 @@ function createDenoAdapter(ns) {
113
113
  exit: (code) => d.exit(code),
114
114
  readFile,
115
115
  stat,
116
+ mkdir: (path) => d.mkdir(path, { recursive: true }),
116
117
  homedir,
117
- configDir
118
+ configDir,
119
+ userConfigDirs: d.build.os === "darwin" ? [configDir, `${homedir}/Library/Application Support`] : [configDir],
120
+ systemConfigDirs: d.build.os === "windows" ? [] : ["/etc"]
118
121
  };
119
122
  }
120
123
  /** Normalize terminal dimensions and discard unusable values. @internal */
@@ -99,8 +99,13 @@ function createNodeAdapter(proc) {
99
99
  throw err;
100
100
  }
101
101
  };
102
+ const mkdir = async (path) => {
103
+ await (await import("node:fs/promises")).mkdir(path, { recursive: true });
104
+ };
102
105
  const homedir = resolveHomedir(p.env, p.platform);
103
106
  const configDir = resolveConfigDir(p.env, p.platform, homedir);
107
+ const userConfigDirs = p.platform === "darwin" ? [configDir, `${homedir}/Library/Application Support`] : [configDir];
108
+ const systemConfigDirs = p.platform === "win32" ? [] : ["/etc"];
104
109
  const stdinIsTTY = p.stdin.isTTY === true;
105
110
  return {
106
111
  argv: p.argv,
@@ -117,8 +122,11 @@ function createNodeAdapter(proc) {
117
122
  exit: (code) => p.exit(code),
118
123
  readFile,
119
124
  stat,
125
+ mkdir,
120
126
  homedir,
121
- configDir
127
+ configDir,
128
+ userConfigDirs,
129
+ systemConfigDirs
122
130
  };
123
131
  }
124
132
  /** Normalize terminal dimensions and discard unusable values. @internal */
package/dist/version.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  //#region src/version.ts
2
2
  /** Package version (e.g. `"0.9.1"`). `"dev"` when running unbundled. */
3
- const DREAMCLI_VERSION = "3.0.0-rc.17";
3
+ const DREAMCLI_VERSION = "3.0.0-rc.19";
4
4
  /** Git short SHA (e.g. `"f9b5f1a"`). `"dev"` when running unbundled. */
5
- const DREAMCLI_REVISION = "58d3353";
5
+ const DREAMCLI_REVISION = "349859e";
6
6
  //#endregion
7
7
  export { DREAMCLI_REVISION, DREAMCLI_VERSION };
@@ -227,6 +227,9 @@
227
227
  "file",
228
228
  "directory"
229
229
  ]
230
+ },
231
+ "create": {
232
+ "type": "boolean"
230
233
  }
231
234
  },
232
235
  "required": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "3.0.0-rc.17",
3
+ "version": "3.0.0-rc.19",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
6
  "dreamcli",