padrone 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # padrone
2
2
 
3
+ ## 1.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 365ad1f: Fix positional arguments and make results always thenable
8
+
9
+ - Show choices and default values in help output for positional arguments
10
+ - Fix type detection for optional array enum positionals (`z.array(z.enum([...])).optional()`)
11
+ - Coerce single values to arrays when schema expects an array type
12
+ - Make `cli()`, `eval()`, and `parse()` results always thenable (supports `.then()` and `await`)
13
+
14
+ ### Patch Changes
15
+
16
+ - 79f51ae: Fix false async warning when action is async but validation is sync
17
+
3
18
  ## 1.3.0
4
19
 
5
20
  ### Minor Changes
@@ -134,22 +134,24 @@ function coerceArgs(data, schema) {
134
134
  if (value === "true" || value === "1") result[key] = true;
135
135
  else if (value === "false" || value === "0") result[key] = false;
136
136
  }
137
- } else if (targetType === "array" && Array.isArray(value)) {
137
+ } else if (targetType === "array") {
138
+ const arr = Array.isArray(value) ? value : [value];
138
139
  const itemType = prop.items?.type;
139
- if (itemType === "number" || itemType === "integer") result[key] = value.map((v) => {
140
+ if (itemType === "number" || itemType === "integer") result[key] = arr.map((v) => {
140
141
  if (typeof v === "string") {
141
142
  const num = Number(v);
142
143
  return Number.isNaN(num) ? v : num;
143
144
  }
144
145
  return v;
145
146
  });
146
- else if (itemType === "boolean") result[key] = value.map((v) => {
147
+ else if (itemType === "boolean") result[key] = arr.map((v) => {
147
148
  if (typeof v === "string") {
148
149
  if (v === "true" || v === "1") return true;
149
150
  if (v === "false" || v === "0") return false;
150
151
  }
151
152
  return v;
152
153
  });
154
+ else if (!Array.isArray(value)) result[key] = arr;
153
155
  }
154
156
  }
155
157
  return result;
@@ -194,4 +196,4 @@ function detectUnknownArgs(data, schema, flags, aliases, suggestFn) {
194
196
  //#endregion
195
197
  export { parsePositionalConfig as a, extractSchemaMetadata as i, coerceArgs as n, parseStdinConfig as o, detectUnknownArgs as r, preprocessArgs as s, camelToKebab as t };
196
198
 
197
- //# sourceMappingURL=args-DFEI7_G_.mjs.map
199
+ //# sourceMappingURL=args-CVDbyyzG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args-CVDbyyzG.mjs","names":[],"sources":["../src/args.ts"],"sourcesContent":["import type { StandardJSONSchemaV1 } from '@standard-schema/spec';\n\ntype Letter =\n | 'a'\n | 'b'\n | 'c'\n | 'd'\n | 'e'\n | 'f'\n | 'g'\n | 'h'\n | 'i'\n | 'j'\n | 'k'\n | 'l'\n | 'm'\n | 'n'\n | 'o'\n | 'p'\n | 'q'\n | 'r'\n | 's'\n | 't'\n | 'u'\n | 'v'\n | 'w'\n | 'x'\n | 'y'\n | 'z';\n\n/** A single letter character, valid as a short CLI flag (e.g. `'v'`, `'n'`, `'V'`). */\nexport type SingleChar = Letter | Uppercase<Letter>;\n\nexport interface PadroneFieldMeta {\n description?: string;\n /** Single-character short flags (stackable: `-abc` = `-a -b -c`). Used with single dash. */\n flags?: SingleChar[] | SingleChar;\n /** Multi-character alternative long names. Used with double dash (e.g. `--dry-run` for `--dryRun`). */\n alias?: string[] | string;\n deprecated?: boolean | string;\n hidden?: boolean;\n examples?: unknown[];\n}\n\ntype PositionalArgs<TObj> =\n TObj extends Record<string, any>\n ? {\n [K in keyof TObj]: NonNullable<TObj[K]> extends Array<any> ? `...${K & string}` | (K & string) : K & string;\n }[keyof TObj]\n : string;\n\n/**\n * Meta configuration for arguments, including positional arguments.\n * The `positional` array defines which arguments are positional and their order.\n * Use '...name' prefix to indicate variadic (rest) arguments, matching JS/TS rest syntax.\n *\n * @example\n * ```ts\n * .arguments(schema, {\n * positional: ['source', '...files', 'dest'], // '...files' is variadic\n * })\n * ```\n */\n/**\n * Configuration for reading from stdin and mapping it to an argument field.\n */\nexport type StdinConfig<TObj = Record<string, any>> =\n | (keyof TObj & string)\n | {\n /** The argument field to populate with stdin data. */\n field: keyof TObj & string;\n /**\n * How to consume stdin:\n * - `'text'` (default): read all stdin as a single string.\n * - `'lines'`: read stdin as an array of lines (string[]).\n */\n as?: 'text' | 'lines';\n };\n\nexport interface PadroneArgsSchemaMeta<TObj = Record<string, any>> {\n /**\n * Array of argument names that should be treated as positional arguments.\n * Order in array determines position. Use '...name' prefix for variadic args.\n * @example ['source', '...files', 'dest'] - 'files' captures multiple values\n */\n positional?: PositionalArgs<TObj>[];\n /**\n * Per-argument metadata.\n */\n fields?: { [K in keyof TObj]?: PadroneFieldMeta };\n /**\n * Automatically generate kebab-case aliases for camelCase option names.\n * For example, `dryRun` automatically gets `--dry-run` as an alias.\n * Defaults to `true`. Set to `false` to disable.\n *\n * @default true\n * @example\n * ```ts\n * // Auto-aliases enabled (default): --dry-run → dryRun\n * .arguments(z.object({ dryRun: z.boolean() }))\n *\n * // Disable auto-aliases\n * .arguments(z.object({ dryRun: z.boolean() }), { autoAlias: false })\n * ```\n */\n autoAlias?: boolean;\n /**\n * Read from stdin and inject the data into the specified argument field.\n * Only reads when stdin is piped (not a TTY) and the field wasn't already provided via CLI flags.\n *\n * - `string`: shorthand for `{ field: name, as: 'text' }` — read all stdin as a string.\n * - `{ field, as }`: explicit form. `as: 'text'` reads all stdin as a string,\n * `as: 'lines'` reads stdin as an array of line strings.\n *\n * Precedence: CLI flags > stdin > env vars > config file > schema defaults.\n *\n * @example\n * ```ts\n * // Shorthand: read all stdin as text into 'data' field\n * .arguments(z.object({ data: z.string() }), { stdin: 'data' })\n *\n * // Explicit: read stdin lines into 'lines' field\n * .arguments(z.object({ lines: z.string().array() }), {\n * stdin: { field: 'lines', as: 'lines' },\n * })\n * ```\n */\n stdin?: StdinConfig<TObj>;\n /**\n * Fields to interactively prompt for when their values are missing after CLI/env/config resolution.\n * - `true`: prompt for all required fields that are missing.\n * - `string[]`: prompt for these specific fields if missing.\n *\n * Interactive prompting only occurs in `cli()` when the runtime has `interactive: true`.\n * Setting this makes `parse()` and `cli()` return Promises.\n *\n * @example\n * ```ts\n * .arguments(schema, {\n * interactive: true, // prompt all missing required fields\n * interactive: ['name', 'template'], // prompt only these fields\n * })\n * ```\n */\n interactive?: true | (keyof TObj & string)[];\n /**\n * Optional fields offered after required interactive prompts.\n * Users are shown a multi-select to choose which of these fields to configure.\n * - `true`: offer all optional fields that are missing.\n * - `string[]`: offer these specific fields.\n *\n * @example\n * ```ts\n * .arguments(schema, {\n * interactive: ['name'],\n * optionalInteractive: ['typescript', 'eslint', 'prettier'],\n * })\n * ```\n */\n optionalInteractive?: true | (keyof TObj & string)[];\n}\n\n/**\n * Convert a camelCase string to kebab-case.\n * Returns null if the string has no uppercase letters (no conversion needed).\n */\nexport function camelToKebab(str: string): string | null {\n if (!/[A-Z]/.test(str)) return null;\n return str.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);\n}\n\n/**\n * Normalizes stdin config into its explicit form.\n */\nexport function parseStdinConfig(stdin: StdinConfig): { field: string; as: 'text' | 'lines' } {\n if (typeof stdin === 'string') return { field: stdin, as: 'text' };\n return { field: stdin.field as string, as: stdin.as ?? 'text' };\n}\n\n/**\n * Parse positional configuration to extract names and variadic info.\n */\nexport function parsePositionalConfig(positional: string[]): { name: string; variadic: boolean }[] {\n return positional.map((p) => {\n const isVariadic = p.startsWith('...');\n const name = isVariadic ? p.slice(3) : p;\n return { name, variadic: isVariadic };\n });\n}\n\n/**\n * Result type for extractSchemaMetadata function.\n */\ninterface SchemaMetadataResult {\n /** Single-char flags: maps flag char → full arg name (e.g. `{ v: 'verbose' }`) */\n flags: Record<string, string>;\n /** Multi-char aliases: maps alias → full arg name (e.g. `{ 'dry-run': 'dryRun' }`) */\n aliases: Record<string, string>;\n}\n\nfunction addEntries(target: Record<string, string>, key: string, items: string | string[], filter?: (item: string) => boolean) {\n const list = typeof items === 'string' ? [items] : items;\n for (const item of list) {\n if (typeof item === 'string' && item && item !== key && !(item in target) && (!filter || filter(item))) {\n target[item] = key;\n }\n }\n}\n\n/**\n * Extract all arg metadata from schema and meta in a single pass.\n * Returns flags (single-char, stackable) and aliases (multi-char, long names) separately.\n * When `autoAlias` is true (default), camelCase property names automatically get kebab-case aliases.\n */\nexport function extractSchemaMetadata(\n schema: StandardJSONSchemaV1,\n meta?: Record<string, PadroneFieldMeta | undefined>,\n autoAlias?: boolean,\n): SchemaMetadataResult {\n const flags: Record<string, string> = {};\n const aliases: Record<string, string> = {};\n\n // Extract from meta object\n if (meta) {\n for (const [key, value] of Object.entries(meta)) {\n if (!value) continue;\n\n if (value.flags) {\n addEntries(flags, key, value.flags, (item) => item.length === 1);\n }\n if (value.alias) {\n addEntries(aliases, key, value.alias, (item) => item.length > 1);\n }\n }\n }\n\n // Extract from JSON schema properties\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n for (const [propertyName, propertySchema] of Object.entries(jsonSchema.properties as Record<string, any>)) {\n if (!propertySchema) continue;\n\n // Extract flags from schema `.meta({ flags: ... })`\n const propFlags = propertySchema.flags;\n if (propFlags) {\n addEntries(flags, propertyName, propFlags, (item) => item.length === 1);\n }\n\n // Extract aliases from schema `.meta({ alias: ... })`\n const propAlias = propertySchema.alias;\n if (propAlias) {\n const list = typeof propAlias === 'string' ? [propAlias] : propAlias;\n if (Array.isArray(list)) {\n addEntries(aliases, propertyName, list, (item) => item.length > 1);\n }\n }\n\n // Auto-generate kebab-case alias for camelCase property names\n if (autoAlias !== false) {\n const kebab = camelToKebab(propertyName);\n if (kebab && !(kebab in aliases)) {\n aliases[kebab] = propertyName;\n }\n }\n }\n }\n } catch {\n // Ignore errors from JSON schema generation\n }\n\n return { flags, aliases };\n}\n\nfunction preprocessMappings(data: Record<string, unknown>, mappings: Record<string, string>): Record<string, unknown> {\n const result = { ...data };\n\n for (const [mappedKey, fullArgName] of Object.entries(mappings)) {\n if (mappedKey in data && mappedKey !== fullArgName) {\n const mappedValue = data[mappedKey];\n // Prefer full arg name if it exists\n if (!(fullArgName in result)) result[fullArgName] = mappedValue;\n delete result[mappedKey];\n }\n }\n\n return result;\n}\n\ninterface ParseArgsContext {\n flags?: Record<string, string>;\n aliases?: Record<string, string>;\n stdinData?: Record<string, unknown>;\n envData?: Record<string, unknown>;\n configData?: Record<string, unknown>;\n}\n\n/**\n * Apply values directly to arguments.\n * CLI values take precedence over the provided values.\n */\nfunction applyValues(data: Record<string, unknown>, values: Record<string, unknown>): Record<string, unknown> {\n const result = { ...data };\n\n for (const [key, value] of Object.entries(values)) {\n // Only apply value if arg wasn't already set\n if (key in result && result[key] !== undefined) continue;\n if (value !== undefined) {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Combined preprocessing of arguments with all features.\n * Precedence order (highest to lowest): CLI args > stdin > env vars > config file\n */\nexport function preprocessArgs(data: Record<string, unknown>, ctx: ParseArgsContext): Record<string, unknown> {\n let result = { ...data };\n\n // 1. Apply flags and aliases first\n if (ctx.flags && Object.keys(ctx.flags).length > 0) {\n result = preprocessMappings(result, ctx.flags);\n }\n if (ctx.aliases && Object.keys(ctx.aliases).length > 0) {\n result = preprocessMappings(result, ctx.aliases);\n }\n\n // 2. Apply stdin data (higher precedence than env)\n // Only applies if CLI didn't set the arg\n if (ctx.stdinData) {\n result = applyValues(result, ctx.stdinData);\n }\n\n // 3. Apply environment variables (higher precedence than config)\n // These only apply if CLI/stdin didn't set the arg\n if (ctx.envData) {\n result = applyValues(result, ctx.envData);\n }\n\n // 4. Apply config file values (lowest precedence)\n // These only apply if neither CLI, stdin, nor env set the arg\n if (ctx.configData) {\n result = applyValues(result, ctx.configData);\n }\n\n return result;\n}\n\n/**\n * Auto-coerce CLI string values to match the expected schema types.\n * Handles: string → number, string → boolean for primitive schema fields.\n * Arrays of primitives are also coerced element-wise.\n */\nexport function coerceArgs(data: Record<string, unknown>, schema: StandardJSONSchemaV1): Record<string, unknown> {\n let properties: Record<string, any>;\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n if (jsonSchema.type !== 'object' || !jsonSchema.properties) return data;\n properties = jsonSchema.properties;\n } catch {\n return data;\n }\n\n const result = { ...data };\n\n for (const [key, value] of Object.entries(result)) {\n const prop = properties[key];\n if (!prop) continue;\n\n const targetType = prop.type as string | undefined;\n\n if (targetType === 'number' || targetType === 'integer') {\n if (typeof value === 'string') {\n const num = Number(value);\n if (!Number.isNaN(num)) result[key] = num;\n }\n } else if (targetType === 'boolean') {\n if (typeof value === 'string') {\n if (value === 'true' || value === '1') result[key] = true;\n else if (value === 'false' || value === '0') result[key] = false;\n }\n } else if (targetType === 'array') {\n // Coerce single items to array\n const arr = Array.isArray(value) ? value : [value];\n const itemType = prop.items?.type as string | undefined;\n if (itemType === 'number' || itemType === 'integer') {\n result[key] = arr.map((v) => {\n if (typeof v === 'string') {\n const num = Number(v);\n return Number.isNaN(num) ? v : num;\n }\n return v;\n });\n } else if (itemType === 'boolean') {\n result[key] = arr.map((v) => {\n if (typeof v === 'string') {\n if (v === 'true' || v === '1') return true;\n if (v === 'false' || v === '0') return false;\n }\n return v;\n });\n } else if (!Array.isArray(value)) {\n result[key] = arr;\n }\n }\n }\n\n return result;\n}\n\n/** Keys consumed by the CLI framework that are not user-defined args. */\nconst frameworkReservedKeys = new Set(['config', 'c']);\n\n/**\n * Detect unknown keys in the args that don't match any schema property.\n * Returns an array of { key, suggestion? } for each unknown key.\n * Framework-reserved keys (--config, -c) are always allowed.\n */\nexport function detectUnknownArgs(\n data: Record<string, unknown>,\n schema: StandardJSONSchemaV1,\n flags: Record<string, string>,\n aliases: Record<string, string>,\n suggestFn: (input: string, candidates: string[]) => string,\n): { key: string; suggestion: string }[] {\n let properties: Record<string, any>;\n let isLoose = false;\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n if (jsonSchema.type !== 'object' || !jsonSchema.properties) return [];\n properties = jsonSchema.properties;\n // If additionalProperties is set (true, {}, or a schema), the schema allows extra keys\n if (jsonSchema.additionalProperties !== undefined && jsonSchema.additionalProperties !== false) isLoose = true;\n } catch {\n return [];\n }\n\n if (isLoose) return [];\n\n const knownKeys = new Set<string>([\n ...Object.keys(properties),\n ...Object.keys(flags),\n ...Object.values(flags),\n ...Object.keys(aliases),\n ...Object.values(aliases),\n ]);\n const propertyNames = Object.keys(properties);\n const unknowns: { key: string; suggestion: string }[] = [];\n\n for (const key of Object.keys(data)) {\n if (!knownKeys.has(key) && !frameworkReservedKeys.has(key)) {\n const suggestion = suggestFn(key, propertyNames);\n unknowns.push({ key, suggestion });\n }\n }\n\n return unknowns;\n}\n"],"mappings":";;;;;AAsKA,SAAgB,aAAa,KAA4B;AACvD,KAAI,CAAC,QAAQ,KAAK,IAAI,CAAE,QAAO;AAC/B,QAAO,IAAI,QAAQ,WAAW,OAAO,IAAI,GAAG,aAAa,GAAG;;;;;AAM9D,SAAgB,iBAAiB,OAA6D;AAC5F,KAAI,OAAO,UAAU,SAAU,QAAO;EAAE,OAAO;EAAO,IAAI;EAAQ;AAClE,QAAO;EAAE,OAAO,MAAM;EAAiB,IAAI,MAAM,MAAM;EAAQ;;;;;AAMjE,SAAgB,sBAAsB,YAA6D;AACjG,QAAO,WAAW,KAAK,MAAM;EAC3B,MAAM,aAAa,EAAE,WAAW,MAAM;AAEtC,SAAO;GAAE,MADI,aAAa,EAAE,MAAM,EAAE,GAAG;GACxB,UAAU;GAAY;GACrC;;AAaJ,SAAS,WAAW,QAAgC,KAAa,OAA0B,QAAoC;CAC7H,MAAM,OAAO,OAAO,UAAU,WAAW,CAAC,MAAM,GAAG;AACnD,MAAK,MAAM,QAAQ,KACjB,KAAI,OAAO,SAAS,YAAY,QAAQ,SAAS,OAAO,EAAE,QAAQ,YAAY,CAAC,UAAU,OAAO,KAAK,EACnG,QAAO,QAAQ;;;;;;;AAUrB,SAAgB,sBACd,QACA,MACA,WACsB;CACtB,MAAM,QAAgC,EAAE;CACxC,MAAM,UAA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AC;CACF,MAAM,gBAAgB,OAAO,KAAK,WAAW;CAC7C,MAAM,WAAkD,EAAE;AAE1D,MAAK,MAAM,OAAO,OAAO,KAAK,KAAK,CACjC,KAAI,CAAC,UAAU,IAAI,IAAI,IAAI,CAAC,sBAAsB,IAAI,IAAI,EAAE;EAC1D,MAAM,aAAa,UAAU,KAAK,cAAc;AAChD,WAAS,KAAK;GAAE;GAAK;GAAY,CAAC;;AAItC,QAAO"}
@@ -1,4 +1,4 @@
1
- import { n as AnyPadroneCommand } from "./types-BS7RP5Ls.mjs";
1
+ import { n as AnyPadroneCommand } from "./types-DjIdJN5G.mjs";
2
2
 
3
3
  //#region src/shell-utils.d.ts
4
4
  type ShellType = 'bash' | 'zsh' | 'fish' | 'powershell';
@@ -1,5 +1,5 @@
1
1
  import { t as __require } from "./chunk-y_GBKt04.mjs";
2
- import { i as extractSchemaMetadata } from "./args-DFEI7_G_.mjs";
2
+ import { i as extractSchemaMetadata } from "./args-CVDbyyzG.mjs";
3
3
  //#region src/shell-utils.ts
4
4
  /**
5
5
  * Detects the current shell from environment variables and process info.
@@ -1,4 +1,4 @@
1
- import { r as HelpInfo } from "../formatter-XroimS3Q.mjs";
1
+ import { r as HelpInfo } from "../formatter-ClUK5hcQ.mjs";
2
2
 
3
3
  //#region src/docs/index.d.ts
4
4
  type DocsFormat = 'markdown' | 'html' | 'man' | 'json';
@@ -1,4 +1,4 @@
1
- import { a as commandSymbol, n as getHelpInfo } from "../help-CgGP7hQU.mjs";
1
+ import { a as commandSymbol, n as getHelpInfo } from "../help-CcBe91bV.mjs";
2
2
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  //#region src/docs/index.ts
@@ -10,6 +10,7 @@ type HelpPositionalInfo = {
10
10
  optional: boolean;
11
11
  default?: unknown;
12
12
  type?: string;
13
+ enum?: string[];
13
14
  };
14
15
  /**
15
16
  * Information about a single argument/flag.
@@ -80,4 +81,4 @@ type HelpInfo = {
80
81
  };
81
82
  //#endregion
82
83
  export { HelpFormat as n, HelpInfo as r, HelpDetail as t };
83
- //# sourceMappingURL=formatter-XroimS3Q.d.mts.map
84
+ //# sourceMappingURL=formatter-ClUK5hcQ.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter-ClUK5hcQ.d.mts","names":[],"sources":["../src/formatter.ts"],"mappings":";KAGY,UAAA;AAAA,KACA,UAAA;;;;KASA,kBAAA;EACV,IAAA;EACA,WAAA;EACA,QAAA;EACA,OAAA;EACA,IAAA;EACA,IAAA;AAAA;;;;KAMU,gBAAA;EACV,IAAA;EACA,WAAA;EACA,QAAA;EACA,OAAA;EACA,IAAA;EACA,IAAA,aANU;EAQV,KAAA;EAEA,OAAA;EACA,UAAA;EACA,MAAA;EACA,QAAA,cATA;EAWA,GAAA,sBATA;EAWA,QAAA,YAPA;EASA,SAAA,YAPA;EASA,SAAA;AAAA;;;;KAMU,kBAAA;EACV,IAAA;EACA,KAAA;EACA,WAAA;EACA,OAAA;EACA,UAAA;EACA,MAAA;EACA,cAAA;AAAA;;;;KAMU,eAAA;EACV,IAAA;EACA,WAAA;EACA,GAAA;IAAQ,IAAA;IAAc,WAAA;EAAA;AAAA;;;;;KAOZ,QAAA;EAPuB,4DASjC,IAAA,UAFkB;EAIlB,KAAA,WAmBc;EAjBd,WAAA,WAqBY;EAnBZ,OAAA,aAuBiB;EArBjB,UAAA,qBAqByB;EAnBzB,MAAA,YARA;EAUA,KAAA;IACE,OAAA;IACA,cAAA;IACA,cAAA;IACA,YAAA,WAHA;IAKA,UAAA;EAAA,GAFA;EAKF,WAAA,GAAc,kBAAA,IAAd;EAEA,WAAA,GAAc,kBAAA,IAAd;EAEA,SAAA,GAAY,gBAAA,IAAZ;EAEA,QAAA,GAAW,eAAA,IAAX;EAEA,cAAA,GAAiB,QAAA;AAAA"}
@@ -1,5 +1,5 @@
1
1
  import { t as __require } from "./chunk-y_GBKt04.mjs";
2
- import { a as parsePositionalConfig, i as extractSchemaMetadata, o as parseStdinConfig, t as camelToKebab } from "./args-DFEI7_G_.mjs";
2
+ import { a as parsePositionalConfig, i as extractSchemaMetadata, o as parseStdinConfig, t as camelToKebab } from "./args-CVDbyyzG.mjs";
3
3
  //#region src/utils.ts
4
4
  function getRootCommand(cmd) {
5
5
  let current = cmd;
@@ -327,6 +327,29 @@ function thenMaybe(value, fn) {
327
327
  if (value instanceof Promise) return value.then(fn);
328
328
  return fn(value);
329
329
  }
330
+ /**
331
+ * Makes a sync result object thenable by adding a `.then()` method.
332
+ * If the value is already a Promise, returns it as-is.
333
+ * This allows users to write `await program.cli()` or `program.cli().then(...)` regardless of sync/async.
334
+ *
335
+ * The `.then()` resolves with a plain copy (without `.then`) to avoid infinite
336
+ * recursive unwrapping by the Promise resolution algorithm.
337
+ */
338
+ function makeThenable(value) {
339
+ if (value instanceof Promise) return value;
340
+ if (value !== null && typeof value === "object" && !("then" in value)) value.then = (onfulfilled, onrejected) => {
341
+ try {
342
+ const plain = { ...value };
343
+ delete plain.then;
344
+ const result = onfulfilled ? onfulfilled(plain) : plain;
345
+ return Promise.resolve(result);
346
+ } catch (err) {
347
+ if (onrejected) return Promise.resolve(onrejected(err));
348
+ return Promise.reject(err);
349
+ }
350
+ };
351
+ return value;
352
+ }
330
353
  function isIterator(value) {
331
354
  return typeof value === "object" && value !== null && Symbol.iterator in value && typeof value[Symbol.iterator] === "function";
332
355
  }
@@ -818,6 +841,7 @@ function createGenericFormatter(styler, layout) {
818
841
  const descParts = [];
819
842
  if (arg.description) descParts.push(styler.description(arg.description));
820
843
  if (info.usage.stdinField === arg.name) descParts.push(styler.meta("(stdin)"));
844
+ if (arg.enum) descParts.push(styler.meta(`(choices: ${arg.enum.join(", ")})`));
821
845
  if (arg.default !== void 0) descParts.push(styler.meta(`(default: ${String(arg.default)})`));
822
846
  lines.push(indent(1) + styler.arg(arg.name) + padding + join(descParts));
823
847
  }
@@ -1027,7 +1051,8 @@ function extractPositionalArgsInfo(schema, meta) {
1027
1051
  description: optMeta?.description ?? prop.description,
1028
1052
  optional: !required.includes(name),
1029
1053
  default: prop.default,
1030
- type: variadic ? `array<${prop.items?.type || "string"}>` : prop.type
1054
+ type: variadic ? `array<${prop.items?.type || "string"}>` : prop.type,
1055
+ enum: prop.enum ?? prop.items?.enum
1031
1056
  });
1032
1057
  }
1033
1058
  }
@@ -1224,6 +1249,6 @@ function generateHelp(rootCommand, commandObj = rootCommand, prefs) {
1224
1249
  return createFormatter(prefs?.format ?? "auto", prefs?.detail).format(helpInfo);
1225
1250
  }
1226
1251
  //#endregion
1227
- export { getVersion as S, warnIfUnexpectedAsync as _, commandSymbol as a, createTerminalReplSession as b, hasInteractiveConfig as c, noop as d, outputValue as f, thenMaybe as g, suggestSimilar as h, buildReplCompleter as i, isAsyncBranded as l, runPluginChain as m, getHelpInfo as n, findCommandByName as o, repathCommandTree as p, asyncSchema as r, getCommandRuntime as s, generateHelp as t, mergeCommands as u, wrapWithLifecycle as v, resolveStdin as x, REPL_SIGINT as y };
1252
+ export { getVersion as C, resolveStdin as S, thenMaybe as _, commandSymbol as a, REPL_SIGINT as b, hasInteractiveConfig as c, mergeCommands as d, noop as f, suggestSimilar as g, runPluginChain as h, buildReplCompleter as i, isAsyncBranded as l, repathCommandTree as m, getHelpInfo as n, findCommandByName as o, outputValue as p, asyncSchema as r, getCommandRuntime as s, generateHelp as t, makeThenable as u, warnIfUnexpectedAsync as v, createTerminalReplSession as x, wrapWithLifecycle as y };
1228
1253
 
1229
- //# sourceMappingURL=help-CgGP7hQU.mjs.map
1254
+ //# sourceMappingURL=help-CcBe91bV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help-CcBe91bV.mjs","names":[],"sources":["../src/utils.ts","../src/runtime.ts","../src/command-utils.ts","../src/colorizer.ts","../src/formatter.ts","../src/help.ts"],"sourcesContent":["import type { AnyPadroneCommand } from './types.ts';\n\nexport function getRootCommand(cmd: AnyPadroneCommand): AnyPadroneCommand {\n let current = cmd;\n while (current.parent) current = current.parent;\n return current;\n}\n\n/**\n * Attempts to get the version from various sources:\n * 1. Explicit version set on the command\n * 2. npm_package_version environment variable (set by npm/yarn/pnpm when running scripts)\n * 3. package.json in current or parent directories\n * @param explicitVersion - Version explicitly set via .version()\n * @returns The version string or '0.0.0' if not found\n */\nexport function getVersion(explicitVersion?: string): string {\n // 1. Use explicit version if provided\n if (explicitVersion) return explicitVersion;\n\n // 2. Check npm_package_version env var (set by npm/yarn/pnpm during script execution)\n if (typeof process !== 'undefined' && process.env?.npm_package_version) {\n return process.env.npm_package_version;\n }\n\n // 3. Try to read from package.json\n if (typeof process !== 'undefined') {\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n let dir = process.cwd();\n\n // Walk up the directory tree looking for package.json\n for (let i = 0; i < 10; i++) {\n const pkgPath = path.join(dir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n if (pkg.version) return pkg.version;\n }\n const parentDir = path.dirname(dir);\n if (parentDir === dir) break; // Reached root\n dir = parentDir;\n }\n } catch {\n // Ignore errors (e.g., fs not available in browser)\n }\n }\n\n return '0.0.0';\n}\n\n/**\n * Loads and parses a config file from the given path.\n * Supports JSON, JSONC (JSON with comments), and attempts to parse other formats.\n * @param configPath - Path to the config file\n * @returns Parsed config data or undefined if loading fails\n */\nexport function loadConfigFile(configPath: string): Record<string, unknown> | undefined {\n if (typeof process === 'undefined') return undefined;\n\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n\n // Resolve to absolute path\n const absolutePath = path.isAbsolute(configPath) ? configPath : path.resolve(process.cwd(), configPath);\n\n if (!fs.existsSync(absolutePath)) {\n console.error(`Config file not found: ${absolutePath}`);\n return undefined;\n }\n\n const getContent = () => fs.readFileSync(absolutePath, 'utf-8');\n const ext = path.extname(absolutePath).toLowerCase();\n\n if (ext === '.yaml' || ext === '.yml') {\n return Bun.YAML.parse(getContent()) as any;\n }\n\n if (ext === '.toml') {\n return Bun.TOML.parse(getContent()) as any;\n }\n\n if (ext === '.json') {\n if (Bun.JSONC) return Bun.JSONC.parse(getContent()) as any;\n try {\n return JSON.parse(getContent());\n } catch {\n return Bun.JSONC.parse(getContent()) as any;\n }\n }\n\n if (ext === '.jsonc') {\n return Bun.JSONC.parse(getContent()) as any;\n }\n\n if (ext === '.js' || ext === '.cjs' || ext === '.mjs' || ext === '.ts' || ext === '.cts' || ext === '.mts') {\n // For JS files, require them\n return require(absolutePath);\n }\n\n // For unknown extensions, try to parse as JSON\n try {\n return JSON.parse(getContent());\n } catch {\n console.error(`Unable to parse config file: ${absolutePath}`);\n return undefined;\n }\n } catch (error) {\n console.error(`Error loading config file: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Searches for a config file from a list of possible file names.\n * Searches in the current working directory.\n * @param configFiles - Array of possible config file names to search for\n * @returns The path to the first found config file, or undefined if none found\n */\nexport function findConfigFile(configFiles: string[]): string | undefined {\n if (typeof process === 'undefined' || !configFiles?.length) return undefined;\n\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n const cwd = process.cwd();\n\n for (const configFile of configFiles) {\n const configPath = path.isAbsolute(configFile) ? configFile : path.resolve(cwd, configFile);\n if (fs.existsSync(configPath)) {\n return configPath;\n }\n }\n } catch {\n // Ignore errors (e.g., fs not available in browser)\n }\n\n return undefined;\n}\n","import type { HelpFormat } from './formatter.ts';\nimport { findConfigFile, loadConfigFile } from './utils.ts';\n\n/**\n * Controls interactive prompting capability and default behavior at the runtime level.\n * - `'supported'` — capable; caller decides.\n * - `'unsupported'` — hard veto; nothing can override.\n * - `'forced'` — capable and forces prompts by default.\n * - `'disabled'` — capable but suppresses prompts by default.\n */\nexport type InteractiveMode = 'supported' | 'unsupported' | 'forced' | 'disabled';\n\n/**\n * Configuration passed to the runtime's `prompt` function for interactive field prompting.\n * The prompt type and choices are auto-detected from the field's JSON schema.\n */\nexport type InteractivePromptConfig = {\n /** The field name being prompted. */\n name: string;\n /** Human-readable message/label for the prompt, derived from the field's description or name. */\n message: string;\n /** The prompt type, auto-detected from the JSON schema. */\n type: 'input' | 'confirm' | 'select' | 'multiselect' | 'password';\n /** Available choices for select/multiselect prompts. */\n choices?: { label: string; value: unknown }[];\n /** Default value from the schema. */\n default?: unknown;\n};\n\n/**\n * Defines the execution context for a Padrone program.\n * Abstracts all environment-dependent I/O so the CLI framework\n * can run outside of a terminal (e.g., web UIs, chat interfaces, testing).\n *\n * All fields are optional — unspecified fields fall back to the Node.js/Bun defaults.\n */\nexport type PadroneRuntime = {\n /** Write normal output (replaces console.log). Receives the raw value — runtime handles formatting. */\n output?: (...args: unknown[]) => void;\n /** Write error output (replaces console.error). */\n error?: (text: string) => void;\n /** Return the raw CLI arguments (replaces process.argv.slice(2)). */\n argv?: () => string[];\n /** Return environment variables (replaces process.env). */\n env?: () => Record<string, string | undefined>;\n /** Default help output format. */\n format?: HelpFormat | 'auto';\n /** Load and parse a config file by path. Return undefined if not found or unparsable. */\n loadConfigFile?: (path: string) => Record<string, unknown> | undefined;\n /** Find the first existing file from a list of candidate names. */\n findFile?: (names: string[]) => string | undefined;\n /**\n * Standard input abstraction. Provides methods to read piped data from stdin.\n * When not provided, defaults to reading from `process.stdin`.\n *\n * Used by commands that declare a `stdin` field in their arguments meta.\n * The framework reads stdin automatically during the validate phase and\n * injects the data into the specified argument field.\n */\n stdin?: {\n /** Whether stdin is a TTY (interactive terminal) vs a pipe/file. */\n isTTY?: boolean;\n /** Read all of stdin as a string. */\n text: () => Promise<string>;\n /** Async iterable of lines for streaming. */\n lines: () => AsyncIterable<string>;\n };\n /**\n * Controls interactive prompting capability and default behavior.\n * - `'supported'` — runtime can handle prompts; caller (flag/pref) decides whether to prompt. This is the default when `prompt` is provided.\n * - `'unsupported'` — runtime cannot handle prompts; hard veto that nothing can override.\n * - `'forced'` — runtime supports prompts and forces them by default (prompts even for provided values).\n * - `'disabled'` — runtime supports prompts but suppresses them by default.\n *\n * `'unsupported'` is the only immutable state. For the others, the `--interactive`/`-i` flag\n * and `cli()` preferences can override the default behavior.\n */\n interactive?: InteractiveMode;\n /**\n * Prompt the user for input. Called during `cli()` for fields marked as interactive.\n * When `interactive` is `true` and this is not provided, defaults to an Enquirer-based terminal prompt.\n */\n prompt?: (config: InteractivePromptConfig) => Promise<unknown>;\n /**\n * Read a line of input from the user. Used by `repl()` for custom runtimes\n * (web UIs, chat interfaces, testing).\n * Returns the input string, `null` on EOF (e.g. Ctrl+D, closed connection),\n * or `REPL_SIGINT` when the user presses Ctrl+C.\n *\n * When not provided, `repl()` uses a built-in Node.js readline session\n * with command history (up/down arrows) and tab completion.\n */\n readLine?: (prompt: string) => Promise<string | typeof REPL_SIGINT | null>;\n};\n\n/**\n * Internal resolved runtime where all fields are guaranteed to be present.\n * The `prompt`, `interactive`, and `readLine` fields remain optional since not all runtimes provide them.\n */\nexport type ResolvedPadroneRuntime = Required<Omit<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin'>> &\n Pick<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin'>;\n\n/**\n * Default terminal prompt implementation powered by Enquirer.\n * Lazily imported to avoid loading Enquirer when not needed.\n */\nasync function defaultTerminalPrompt(config: InteractivePromptConfig): Promise<unknown> {\n const Enquirer = (await import('enquirer')).default;\n\n const question: Record<string, unknown> = {\n type: config.type,\n name: config.name,\n message: config.message,\n };\n\n if (config.default !== undefined) {\n question.initial = config.default;\n }\n\n if (config.choices) {\n question.choices = config.choices.map((c) => ({\n name: String(c.value),\n message: c.label,\n }));\n }\n\n const response = (await Enquirer.prompt(question as any)) as Record<string, unknown>;\n return response[config.name];\n}\n\n/**\n * Internal session config for the REPL's persistent readline interface.\n */\nexport type ReplSessionConfig = {\n completer?: (line: string) => [string[], string];\n history?: string[];\n};\n\n/**\n * Creates a persistent Node.js readline session for the REPL.\n * Enables up/down arrow history navigation and tab completion.\n * Used internally by `repl()` when no custom `readLine` is provided.\n */\n/**\n * Sentinel value returned by the terminal REPL session when Ctrl+C is pressed.\n * Distinguished from empty string (user pressed enter) and null (EOF/Ctrl+D).\n */\nexport const REPL_SIGINT = Symbol('REPL_SIGINT');\n\nexport function createTerminalReplSession(config: ReplSessionConfig) {\n // History accumulates across per-call interfaces, giving us\n // up/down arrow navigation without a persistent stdin listener\n // that would conflict with Enquirer or other stdin consumers.\n let history: string[] = config.history ? [...config.history] : [];\n let currentCompleter = config.completer;\n\n return {\n /** Update the tab completer (e.g. when REPL scope changes). Takes effect on the next question. */\n set completer(fn: ((line: string) => [string[], string]) | undefined) {\n currentCompleter = fn;\n },\n async question(prompt: string): Promise<string | typeof REPL_SIGINT | null> {\n const { createInterface } = await import('node:readline');\n const opts: Record<string, unknown> = {\n input: process.stdin,\n output: process.stdout,\n terminal: true,\n history: [...history],\n historySize: Math.max(history.length, 1000),\n };\n if (currentCompleter) {\n opts.completer = currentCompleter;\n }\n const rl = createInterface(opts as any);\n\n return new Promise((resolve) => {\n let resolved = false;\n const settle = (value: string | typeof REPL_SIGINT | null) => {\n if (resolved) return;\n resolved = true;\n rl.close();\n resolve(value);\n };\n\n rl.question(prompt, (answer) => {\n // Grab updated history (includes the new entry) before closing.\n if (Array.isArray((rl as any).history)) history = [...(rl as any).history];\n settle(answer);\n });\n // Ctrl+C: cancel current line, print newline, resolve SIGINT sentinel.\n rl.once('SIGINT', () => {\n process.stdout.write('\\n');\n settle(REPL_SIGINT);\n });\n // EOF (Ctrl+D) fires close without the question callback.\n rl.once('close', () => {\n // Write newline so zsh doesn't show '%' (partial-line indicator).\n process.stdout.write('\\n');\n settle(null);\n });\n });\n },\n close() {\n // No persistent interface to clean up.\n },\n };\n}\n\n/**\n * Auto-detect interactive mode when not explicitly set.\n * Returns 'disabled' in CI environments or non-TTY contexts, 'supported' otherwise.\n */\nfunction detectInteractiveMode(): InteractiveMode {\n if (typeof process === 'undefined') return 'disabled';\n if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) return 'disabled';\n if (!process.stdout?.isTTY) return 'disabled';\n return 'supported';\n}\n\n/**\n * Creates the default Node.js/Bun runtime.\n */\n/**\n * Creates a default stdin reader from `process.stdin`.\n * Only created when a command actually declares a `stdin` meta field.\n */\nfunction createDefaultStdin(): NonNullable<PadroneRuntime['stdin']> {\n return {\n get isTTY() {\n // process.stdin.isTTY is `true` when interactive terminal, `undefined` when piped/redirected.\n // Node.js never sets it to `false` — it's either `true` or absent.\n if (typeof process === 'undefined') return true;\n return process.stdin?.isTTY === true;\n },\n async text() {\n if (typeof process === 'undefined') return '';\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks).toString('utf-8');\n },\n async *lines() {\n if (typeof process === 'undefined') return;\n const { createInterface } = await import('node:readline');\n const rl = createInterface({ input: process.stdin });\n try {\n for await (const line of rl) {\n yield line;\n }\n } finally {\n rl.close();\n }\n },\n };\n}\n\nexport function createDefaultRuntime(): ResolvedPadroneRuntime {\n return {\n output: (...args) => console.log(...args),\n error: (text) => console.error(text),\n argv: () => (typeof process !== 'undefined' ? process.argv.slice(2) : []),\n env: () => (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : {}),\n format: 'auto',\n loadConfigFile,\n findFile: findConfigFile,\n prompt: defaultTerminalPrompt,\n interactive: detectInteractiveMode(),\n };\n}\n\n/**\n * Merges a partial runtime with the default runtime.\n */\n/**\n * Returns the stdin abstraction: custom runtime stdin > default process.stdin.\n * Returns `undefined` when no custom stdin is provided and process.stdin is not piped.\n */\nexport function resolveStdin(partial?: PadroneRuntime): NonNullable<PadroneRuntime['stdin']> | undefined {\n if (partial?.stdin) return partial.stdin;\n const defaultStdin = createDefaultStdin();\n // Only use default stdin if it's actually piped (isTTY === false).\n // This avoids accidentally blocking on stdin in tests/CI.\n if (defaultStdin.isTTY) return undefined;\n return defaultStdin;\n}\n\nexport function resolveRuntime(partial?: PadroneRuntime): ResolvedPadroneRuntime {\n const defaults = createDefaultRuntime();\n if (!partial) return defaults;\n return {\n output: partial.output ?? defaults.output,\n error: partial.error ?? defaults.error,\n argv: partial.argv ?? defaults.argv,\n env: partial.env ?? defaults.env,\n format: partial.format ?? defaults.format,\n loadConfigFile: partial.loadConfigFile ?? defaults.loadConfigFile,\n findFile: partial.findFile ?? defaults.findFile,\n interactive: partial.interactive ?? defaults.interactive,\n prompt: partial.prompt ?? defaults.prompt,\n readLine: partial.readLine ?? defaults.readLine,\n stdin: partial.stdin,\n };\n}\n","import { extractSchemaMetadata } from './args.ts';\nimport { type ResolvedPadroneRuntime, resolveRuntime } from './runtime.ts';\nimport type {\n AnyPadroneCommand,\n PadronePlugin,\n PadroneSchema,\n PluginErrorContext,\n PluginErrorResult,\n PluginShutdownContext,\n PluginStartContext,\n} from './types.ts';\n\n/**\n * Brands a schema as async, signaling that its `validate()` may return a Promise.\n * When an async-branded schema is passed to `.arguments()`, `.configFile()`, or `.env()`,\n * the command's `parse()` and `cli()` will return Promises.\n *\n * @example\n * ```ts\n * const schema = asyncSchema(z.object({\n * name: z.string(),\n * }).check(async (data) => {\n * // async validation logic\n * }));\n *\n * const program = createPadrone('app')\n * .command('greet', (c) => c.arguments(schema).action((args) => args.name));\n *\n * // parse() now returns Promise<PadroneParseResult>\n * const result = await program.parse('greet --name world');\n * ```\n */\nexport function asyncSchema<T extends PadroneSchema>(schema: T): T & { '~async': true } {\n return Object.assign(schema, { '~async': true as const });\n}\n\nexport const commandSymbol = Symbol('padrone_command');\n\nexport const noop = <TRes>() => undefined as TRes;\n\n/** Config keys that are merged when overriding a command. */\nexport const configKeys = [\n 'title',\n 'description',\n 'version',\n 'deprecated',\n 'hidden',\n 'needsApproval',\n 'autoOutput',\n 'updateCheck',\n] as const;\n\n/**\n * Merges an existing command with an override.\n * - Config fields are shallow-merged (new overrides old).\n * - Action, arguments, meta, config schema, env schema are taken from the override if set.\n * - Subcommands are recursively merged by name.\n */\nexport function mergeCommands(existing: AnyPadroneCommand, override: AnyPadroneCommand): AnyPadroneCommand {\n const merged: AnyPadroneCommand = { ...existing };\n\n // Merge config fields\n for (const key of configKeys) {\n if (override[key] !== undefined) (merged as any)[key] = override[key];\n }\n\n // Override fields: take from override if explicitly set (not inherited from existing via spread)\n if (override.action !== existing.action) merged.action = override.action;\n if (override.argsSchema !== existing.argsSchema) merged.argsSchema = override.argsSchema;\n if (override.meta !== existing.meta) merged.meta = override.meta;\n if (override.configSchema !== existing.configSchema) merged.configSchema = override.configSchema;\n if (override.envSchema !== existing.envSchema) merged.envSchema = override.envSchema;\n if (override.configFiles !== existing.configFiles) merged.configFiles = override.configFiles;\n if (override.isAsync !== existing.isAsync) merged.isAsync = override.isAsync || existing.isAsync;\n if (override.runtime !== existing.runtime) merged.runtime = override.runtime;\n if (override.plugins !== existing.plugins) merged.plugins = override.plugins;\n if (override.aliases !== existing.aliases) merged.aliases = override.aliases;\n\n // Recursively merge subcommands by name\n if (override.commands) {\n const baseCommands = [...(existing.commands || [])];\n for (const overrideChild of override.commands) {\n const existingIndex = baseCommands.findIndex((c) => c.name === overrideChild.name);\n if (existingIndex >= 0) {\n baseCommands[existingIndex] = mergeCommands(baseCommands[existingIndex]!, overrideChild);\n } else {\n baseCommands.push(overrideChild);\n }\n }\n merged.commands = baseCommands;\n }\n\n return merged;\n}\n\n/**\n * Maps over a value that may or may not be a Promise.\n * If the value is a Promise, chains with `.then()`. Otherwise, calls the function synchronously.\n * This preserves sync behavior for sync schemas and async behavior for async schemas.\n */\nexport function thenMaybe<T, U>(value: T | Promise<T>, fn: (v: T) => U | Promise<U>): U | Promise<U> {\n if (value instanceof Promise) return value.then(fn);\n return fn(value);\n}\n\n/**\n * Makes a sync result object thenable by adding a `.then()` method.\n * If the value is already a Promise, returns it as-is.\n * This allows users to write `await program.cli()` or `program.cli().then(...)` regardless of sync/async.\n *\n * The `.then()` resolves with a plain copy (without `.then`) to avoid infinite\n * recursive unwrapping by the Promise resolution algorithm.\n */\nexport function makeThenable<T>(value: T | Promise<T>): T & PromiseLike<T> {\n if (value instanceof Promise) return value as any;\n if (value !== null && typeof value === 'object' && !('then' in value)) {\n // biome-ignore lint/suspicious/noThenProperty: intentional thenable shim for sync results\n (value as any).then = (onfulfilled?: (v: T) => any, onrejected?: (reason: any) => any) => {\n try {\n // Resolve with a plain copy to prevent infinite thenable unwrapping\n const plain = { ...value } as any;\n delete plain.then;\n const result = onfulfilled ? onfulfilled(plain) : plain;\n return Promise.resolve(result);\n } catch (err) {\n if (onrejected) return Promise.resolve(onrejected(err));\n return Promise.reject(err);\n }\n };\n }\n return value as any;\n}\n\nexport function isIterator(value: unknown): value is Iterator<unknown> {\n return typeof value === 'object' && value !== null && Symbol.iterator in value && typeof (value as any)[Symbol.iterator] === 'function';\n}\n\nexport function isAsyncIterator(value: unknown): value is AsyncIterator<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof (value as any)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/**\n * Writes a command's return value to output, handling promises, iterators, and async iterators.\n * Values are passed directly to the output function without stringification —\n * runtimes like Node/Bun already format objects via console.log.\n * Returns void or a Promise depending on whether async consumption is needed.\n */\nexport function outputValue(value: unknown, output: (...args: unknown[]) => void): void | Promise<void> {\n if (value == null) return;\n\n // Async iterator — consume and output each yielded value\n if (isAsyncIterator(value)) {\n return (async () => {\n const iter = (value as any)[Symbol.asyncIterator]();\n while (true) {\n const { done, value: item } = await iter.next();\n if (done) break;\n if (item != null) output(item);\n }\n })();\n }\n\n // Sync iterator (but not a plain string/array which also have Symbol.iterator)\n if (typeof value !== 'string' && !Array.isArray(value) && isIterator(value)) {\n const iter = (value as any)[Symbol.iterator]();\n while (true) {\n const { done, value: item } = iter.next();\n if (done) break;\n if (item != null) output(item);\n }\n return;\n }\n\n // Promise — await then output\n if (value instanceof Promise) {\n return value.then((resolved) => outputValue(resolved, output));\n }\n\n // Pass value directly — runtime handles formatting\n output(value);\n}\n\n/**\n * Runs a plugin chain for a given phase using the onion/middleware pattern.\n * Plugins are sorted by `order` (ascending, stable), then composed so that\n * the first plugin in sorted order is the outermost wrapper.\n * If no plugins handle this phase, `core` is called directly.\n */\nexport function runPluginChain<TCtx, TResult>(\n phase: 'start' | 'parse' | 'validate' | 'execute' | 'error' | 'shutdown',\n plugins: PadronePlugin[],\n ctx: TCtx,\n core: () => TResult | Promise<TResult>,\n): TResult | Promise<TResult> {\n // Filter to plugins that have a handler for this phase, preserve insertion order\n const phasePlugins = plugins.filter((p) => p[phase]);\n if (phasePlugins.length === 0) return core();\n\n // Stable sort by order (lower = outermost). Equal order preserves registration order.\n phasePlugins.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n // Build chain from inside out: last plugin wraps core, first plugin is outermost\n let next = core;\n for (let i = phasePlugins.length - 1; i >= 0; i--) {\n const handler = phasePlugins[i]![phase]! as unknown as (\n ctx: TCtx,\n next: () => TResult | Promise<TResult>,\n ) => TResult | Promise<TResult>;\n const prevNext = next;\n next = () => handler(ctx, prevNext);\n }\n\n return next();\n}\n\n/**\n * Wraps a pipeline with start → error → shutdown lifecycle hooks.\n * - `start` plugins wrap the pipeline (onion pattern, root plugins only).\n * - On error: `error` plugins run (can transform/suppress the error).\n * - Always: `shutdown` plugins run (success or failure).\n */\nexport function wrapWithLifecycle<T>(\n plugins: PadronePlugin[],\n command: AnyPadroneCommand,\n state: Record<string, unknown>,\n input: string | undefined,\n pipeline: () => T | Promise<T>,\n wrapErrorResult?: (result: unknown) => T,\n): T | Promise<T> {\n const hasStart = plugins.some((p) => p.start);\n const hasError = plugins.some((p) => p.error);\n const hasShutdown = plugins.some((p) => p.shutdown);\n\n // Fast path: no lifecycle plugins\n if (!hasStart && !hasError && !hasShutdown) return pipeline();\n\n const runShutdown = (error?: unknown, result?: unknown) => {\n if (!hasShutdown) return;\n const ctx: PluginShutdownContext = { command, state, error, result };\n return runPluginChain('shutdown', plugins, ctx, () => {});\n };\n\n const runError = (error: unknown): T | Promise<T> => {\n if (!hasError) {\n const s = runShutdown(error);\n if (s instanceof Promise)\n return s.then(() => {\n throw error;\n });\n throw error;\n }\n const ctx: PluginErrorContext = { command, state, error };\n const errorResult = runPluginChain('error', plugins, ctx, (): PluginErrorResult => ({ error }));\n return thenMaybe(errorResult, (er) => {\n if (er.error !== undefined) {\n const s = runShutdown(er.error);\n return thenMaybe(s as void | Promise<void>, () => {\n throw er.error;\n });\n }\n const wrapped = wrapErrorResult ? wrapErrorResult(er.result) : (er.result as T);\n const s = runShutdown(undefined, wrapped);\n return thenMaybe(s as void | Promise<void>, () => wrapped);\n });\n };\n\n const handleSuccess = (result: T): T | Promise<T> => {\n const s = runShutdown(undefined, result);\n if (s instanceof Promise) return s.then(() => result);\n return result;\n };\n\n // Run start phase wrapping the pipeline\n const startCtx: PluginStartContext = { command, state, input };\n let result: T | Promise<T>;\n try {\n result = (hasStart ? runPluginChain('start', plugins, startCtx, pipeline) : pipeline()) as T | Promise<T>;\n } catch (e) {\n return runError(e);\n }\n\n if (result instanceof Promise) {\n return result.then(handleSuccess, runError);\n }\n\n return handleSuccess(result);\n}\n\n/**\n * Resolves the runtime for a command by walking up the parent chain.\n * Returns a fully resolved runtime with all defaults filled in.\n */\nexport function getCommandRuntime(cmd: AnyPadroneCommand): ResolvedPadroneRuntime {\n let current: AnyPadroneCommand | undefined = cmd;\n while (current) {\n if (current.runtime) return resolveRuntime(current.runtime);\n current = current.parent;\n }\n return resolveRuntime();\n}\n\nexport function isAsyncBranded(schema: unknown): boolean {\n return !!schema && typeof schema === 'object' && '~async' in schema && (schema as any)['~async'] === true;\n}\n\nexport function hasInteractiveConfig(meta: unknown): boolean {\n if (!meta || typeof meta !== 'object') return false;\n const m = meta as Record<string, unknown>;\n return m.interactive === true || Array.isArray(m.interactive) || m.optionalInteractive === true || Array.isArray(m.optionalInteractive);\n}\n\nexport function warnIfUnexpectedAsync<T>(value: T, command: AnyPadroneCommand): T {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return value;\n if (value instanceof Promise && !command.isAsync) {\n const runtime = getCommandRuntime(command);\n runtime.error(\n `[padrone] Command \"${command.path || command.name}\" returned a Promise from validation, ` +\n `but was not marked as async. Use \\`.async()\\` on the builder or \\`asyncSchema()\\` to brand your schema. ` +\n `Without this, TypeScript will infer a sync return type and the result will be a Promise at runtime.`,\n );\n }\n return value;\n}\n\n/**\n * Recursively re-paths a command tree under a new parent path, updating parent references.\n */\nexport function repathCommandTree(\n cmd: AnyPadroneCommand,\n newName: string,\n parentPath: string,\n parent: AnyPadroneCommand,\n): AnyPadroneCommand {\n const newPath = parentPath ? `${parentPath} ${newName}` : newName;\n const remounted: AnyPadroneCommand = {\n ...cmd,\n name: newName,\n path: newPath,\n parent,\n version: undefined,\n };\n\n if (cmd.commands?.length) {\n remounted.commands = cmd.commands.map((child) => repathCommandTree(child, child.name, newPath, remounted));\n }\n\n return remounted;\n}\n\n/**\n * Builds a completer function for the REPL from the command tree.\n * Completes command names, subcommand names, option names (--foo), and aliases (-f).\n * Also includes dot-prefixed built-in REPL commands (.exit, .clear, .scope, .help, .history).\n */\nexport function buildReplCompleter(\n rootCommand: AnyPadroneCommand,\n builtins: {\n inScope?: boolean;\n },\n): (line: string) => [string[], string] {\n return (line: string): [string[], string] => {\n const trimmed = line.trimStart();\n const parts = trimmed.split(/\\s+/);\n const lastPart = parts[parts.length - 1] ?? '';\n\n // If we're completing a dot-command\n if (lastPart.startsWith('.')) {\n const dotCmds = ['.exit', '.clear', '.help', '.history'];\n if (rootCommand.commands?.some((c) => c.commands?.length) || builtins.inScope) dotCmds.push('.scope');\n const hits = dotCmds.filter((c) => c.startsWith(lastPart));\n return [hits.length ? hits : dotCmds, lastPart];\n }\n\n // If we're completing an option (starts with -)\n if (lastPart.startsWith('-')) {\n // Find which command we're in\n const commandParts = parts.slice(0, -1).filter((p) => !p.startsWith('-'));\n let targetCommand = rootCommand;\n for (const part of commandParts) {\n const sub = targetCommand.commands?.find((c) => c.name === part || c.aliases?.includes(part));\n if (sub) targetCommand = sub;\n else break;\n }\n\n // Get options for this command\n const options: string[] = [];\n if (targetCommand.argsSchema) {\n try {\n const argsMeta = targetCommand.meta?.fields;\n const { flags, aliases } = extractSchemaMetadata(targetCommand.argsSchema, argsMeta, targetCommand.meta?.autoAlias);\n const jsonSchema = targetCommand.argsSchema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n for (const key of Object.keys(jsonSchema.properties)) {\n options.push(`--${key}`);\n }\n for (const flag of Object.keys(flags)) {\n options.push(`-${flag}`);\n }\n for (const alias of Object.keys(aliases)) {\n options.push(`--${alias}`);\n }\n }\n } catch {\n // Ignore schema parsing errors\n }\n }\n // Add global flags\n options.push('--help', '-h');\n\n const hits = options.filter((o) => o.startsWith(lastPart));\n return [hits.length ? hits : options, lastPart];\n }\n\n // Completing command names\n const commandParts = parts.filter((p) => !p.startsWith('-'));\n // Walk into subcommands for all but the last token\n let targetCommand = rootCommand;\n for (let i = 0; i < commandParts.length - 1; i++) {\n const sub = targetCommand.commands?.find((c) => c.name === commandParts[i] || c.aliases?.includes(commandParts[i]!));\n if (sub) targetCommand = sub;\n else break;\n }\n\n const candidates: string[] = [];\n\n // Add subcommand names and aliases\n if (targetCommand.commands) {\n for (const cmd of targetCommand.commands) {\n if (!cmd.hidden) {\n candidates.push(cmd.name);\n if (cmd.aliases) candidates.push(...cmd.aliases);\n }\n }\n }\n\n // Add dot-commands and `..` shorthand at the root level (relative to current scope)\n if (targetCommand === rootCommand) {\n candidates.push('.help', '.exit', '.clear', '.history');\n if (rootCommand.commands?.some((c) => c.commands?.length) || builtins.inScope) candidates.push('.scope');\n if (builtins.inScope) candidates.push('..');\n }\n\n const hits = candidates.filter((c) => c.startsWith(lastPart));\n return [hits.length ? hits : candidates, lastPart];\n };\n}\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n */\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp: number[] = Array.from({ length: n + 1 }, (_, i) => i);\n\n for (let i = 1; i <= m; i++) {\n let prev = dp[0]!;\n dp[0] = i;\n for (let j = 1; j <= n; j++) {\n const temp = dp[j]!;\n dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j]!, dp[j - 1]!);\n prev = temp;\n }\n }\n\n return dp[n]!;\n}\n\n/**\n * Finds the closest match from a list of candidates using Levenshtein distance.\n * Returns the suggestion string (e.g. 'Did you mean \"deploy\"?') or empty string if no good match.\n * Threshold: distance must be at most 40% of the longer string's length (min 1, max 3).\n */\nexport function suggestSimilar(input: string, candidates: string[]): string {\n if (candidates.length === 0) return '';\n\n const lower = input.toLowerCase();\n let bestDist = Infinity;\n let bestMatch = '';\n\n for (const candidate of candidates) {\n const dist = levenshtein(lower, candidate.toLowerCase());\n if (dist < bestDist) {\n bestDist = dist;\n bestMatch = candidate;\n }\n }\n\n const maxLen = Math.max(input.length, bestMatch.length);\n const threshold = Math.min(3, Math.max(1, Math.ceil(maxLen * 0.4)));\n\n if (bestDist > 0 && bestDist <= threshold) {\n return `Did you mean \"${bestMatch}\"?`;\n }\n\n return '';\n}\n\nexport function findCommandByName(name: string, commands?: AnyPadroneCommand[]): AnyPadroneCommand | undefined {\n if (!commands) return undefined;\n\n const foundByName = commands.find((cmd) => cmd.name === name);\n if (foundByName) return foundByName;\n\n // Check for aliases\n const foundByAlias = commands.find((cmd) => cmd.aliases?.includes(name));\n if (foundByAlias) return foundByAlias;\n\n for (const cmd of commands) {\n if (cmd.commands && name.startsWith(`${cmd.name} `)) {\n const subCommandName = name.slice(cmd.name.length + 1);\n const subCommand = findCommandByName(subCommandName, cmd.commands);\n if (subCommand) return subCommand;\n }\n // Check aliases for nested commands\n if (cmd.commands && cmd.aliases) {\n for (const alias of cmd.aliases) {\n if (name.startsWith(`${alias} `)) {\n const subCommandName = name.slice(alias.length + 1);\n const subCommand = findCommandByName(subCommandName, cmd.commands);\n if (subCommand) return subCommand;\n }\n }\n }\n }\n return undefined;\n}\n","// ANSI color codes\nconst colors = {\n reset: '\\x1b[0m',\n bold: '\\x1b[1m',\n dim: '\\x1b[2m',\n italic: '\\x1b[3m',\n underline: '\\x1b[4m',\n strikethrough: '\\x1b[9m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n gray: '\\x1b[90m',\n};\n\nexport type Colorizer = {\n command: (text: string) => string;\n arg: (text: string) => string;\n type: (text: string) => string;\n description: (text: string) => string;\n label: (text: string) => string;\n meta: (text: string) => string;\n example: (text: string) => string;\n exampleValue: (text: string) => string;\n deprecated: (text: string) => string;\n};\n\nexport function createColorizer(): Colorizer {\n return {\n command: (text: string) => `${colors.cyan}${colors.bold}${text}${colors.reset}`,\n arg: (text: string) => `${colors.green}${text}${colors.reset}`,\n type: (text: string) => `${colors.yellow}${text}${colors.reset}`,\n description: (text: string) => `${colors.dim}${text}${colors.reset}`,\n label: (text: string) => `${colors.bold}${text}${colors.reset}`,\n meta: (text: string) => `${colors.gray}${text}${colors.reset}`,\n example: (text: string) => `${colors.underline}${text}${colors.reset}`,\n exampleValue: (text: string) => `${colors.italic}${text}${colors.reset}`,\n deprecated: (text: string) => `${colors.strikethrough}${colors.gray}${text}${colors.reset}`,\n };\n}\n","import { camelToKebab } from './args.ts';\nimport { createColorizer } from './colorizer.ts';\n\nexport type HelpFormat = 'text' | 'ansi' | 'console' | 'markdown' | 'html' | 'json';\nexport type HelpDetail = 'minimal' | 'standard' | 'full';\n\n// ============================================================================\n// Help Info Types (shared with help.ts)\n// ============================================================================\n\n/**\n * Information about a single positional argument.\n */\nexport type HelpPositionalInfo = {\n name: string;\n description?: string;\n optional: boolean;\n default?: unknown;\n type?: string;\n enum?: string[];\n};\n\n/**\n * Information about a single argument/flag.\n */\nexport type HelpArgumentInfo = {\n name: string;\n description?: string;\n optional: boolean;\n default?: unknown;\n type?: string;\n enum?: string[];\n /** Single-character short flags (shown as `-v`) */\n flags?: string[];\n /** Multi-character alternative long names (shown as `--dry-run`) */\n aliases?: string[];\n deprecated?: boolean | string;\n hidden?: boolean;\n examples?: unknown[];\n /** Environment variable(s) this arg can be set from */\n env?: string | string[];\n /** Whether this arg is an array type (shown as <type...>) */\n variadic?: boolean;\n /** Whether this arg is a boolean (shown as --[no-]arg) */\n negatable?: boolean;\n /** Config file key that maps to this arg */\n configKey?: string;\n};\n\n/**\n * Information about a subcommand (minimal info for listing).\n */\nexport type HelpSubcommandInfo = {\n name: string;\n title?: string;\n description?: string;\n aliases?: string[];\n deprecated?: boolean | string;\n hidden?: boolean;\n hasSubcommands?: boolean;\n};\n\n/**\n * Information about a built-in command/flag entry.\n */\nexport type HelpBuiltinInfo = {\n name: string;\n description?: string;\n sub?: { name: string; description?: string }[];\n};\n\n/**\n * Comprehensive JSON structure for help information.\n * This is the single source of truth that all formatters use.\n */\nexport type HelpInfo = {\n /** The full command name (e.g., \"cli serve\" or \"<root>\") */\n name: string;\n /** Short title for the command */\n title?: string;\n /** Command description */\n description?: string;\n /** Alternative names/aliases for this command */\n aliases?: string[];\n /** Whether the command is deprecated */\n deprecated?: boolean | string;\n /** Whether the command is hidden */\n hidden?: boolean;\n /** Usage string parts for flexible formatting */\n usage: {\n command: string;\n hasSubcommands: boolean;\n hasPositionals: boolean;\n hasArguments: boolean;\n /** The name of the field that reads from stdin, if any. Shown as `[stdin > field]` in usage. */\n stdinField?: string;\n };\n /** List of subcommands */\n subcommands?: HelpSubcommandInfo[];\n /** Positional arguments */\n positionals?: HelpPositionalInfo[];\n /** Arguments/flags (only visible ones, hidden filtered out) */\n arguments?: HelpArgumentInfo[];\n /** Built-in commands and flags (shown only for root command) */\n builtins?: HelpBuiltinInfo[];\n /** Full help info for nested commands (used in 'full' detail mode) */\n nestedCommands?: HelpInfo[];\n};\n\n// ============================================================================\n// Formatter Interface\n// ============================================================================\n\n/**\n * A formatter that takes the entire HelpInfo structure and produces formatted output.\n */\nexport type Formatter = {\n /** Format the entire help info structure into a string */\n format: (info: HelpInfo) => string;\n};\n\n// ============================================================================\n// Internal Styling Types\n// ============================================================================\n\n/**\n * Internal styling functions used by formatters.\n * These handle the visual styling of individual text elements.\n */\ntype Styler = {\n command: (text: string) => string;\n arg: (text: string) => string;\n type: (text: string) => string;\n description: (text: string) => string;\n label: (text: string) => string;\n meta: (text: string) => string;\n example: (text: string) => string;\n exampleValue: (text: string) => string;\n deprecated: (text: string) => string;\n};\n\n/**\n * Layout configuration for formatters.\n */\ntype LayoutConfig = {\n newline: string;\n indent: (level: number) => string;\n join: (parts: string[]) => string;\n wrapDocument?: (content: string) => string;\n usageLabel: string;\n};\n\n// ============================================================================\n// Styler Factories\n// ============================================================================\n\nfunction createTextStyler(): Styler {\n return {\n command: (text) => text,\n arg: (text) => text,\n type: (text) => text,\n description: (text) => text,\n label: (text) => text,\n meta: (text) => text,\n example: (text) => text,\n exampleValue: (text) => text,\n deprecated: (text) => text,\n };\n}\n\nfunction createAnsiStyler(): Styler {\n const colorizer = createColorizer();\n return {\n command: colorizer.command,\n arg: colorizer.arg,\n type: colorizer.type,\n description: colorizer.description,\n label: colorizer.label,\n meta: colorizer.meta,\n example: colorizer.example,\n exampleValue: colorizer.exampleValue,\n deprecated: colorizer.deprecated,\n };\n}\n\nfunction createConsoleStyler(): Styler {\n const colors = {\n reset: '\\x1b[0m',\n bold: '\\x1b[1m',\n dim: '\\x1b[2m',\n italic: '\\x1b[3m',\n underline: '\\x1b[4m',\n strikethrough: '\\x1b[9m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n gray: '\\x1b[90m',\n };\n return {\n command: (text) => `${colors.cyan}${colors.bold}${text}${colors.reset}`,\n arg: (text) => `${colors.green}${text}${colors.reset}`,\n type: (text) => `${colors.yellow}${text}${colors.reset}`,\n description: (text) => `${colors.dim}${text}${colors.reset}`,\n label: (text) => `${colors.bold}${text}${colors.reset}`,\n meta: (text) => `${colors.gray}${text}${colors.reset}`,\n example: (text) => `${colors.underline}${text}${colors.reset}`,\n exampleValue: (text) => `${colors.italic}${text}${colors.reset}`,\n deprecated: (text) => `${colors.strikethrough}${colors.gray}${text}${colors.reset}`,\n };\n}\n\nfunction createMarkdownStyler(): Styler {\n return {\n command: (text) => `**${text}**`,\n arg: (text) => `\\`${text}\\``,\n type: (text) => `\\`${text}\\``,\n description: (text) => text,\n label: (text) => `### ${text}`,\n meta: (text) => `*${text}*`,\n example: (text) => `**${text}**`,\n exampleValue: (text) => `\\`${text}\\``,\n deprecated: (text) => `~~${text}~~`,\n };\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\n}\n\nfunction createHtmlStyler(): Styler {\n return {\n command: (text) => `<strong style=\"color: #00bcd4;\">${escapeHtml(text)}</strong>`,\n arg: (text) => `<code style=\"color: #4caf50;\">${escapeHtml(text)}</code>`,\n type: (text) => `<code style=\"color: #ff9800;\">${escapeHtml(text)}</code>`,\n description: (text) => `<span style=\"color: #666;\">${escapeHtml(text)}</span>`,\n label: (text) => `<h3>${escapeHtml(text)}</h3>`,\n meta: (text) => `<span style=\"color: #999;\">${escapeHtml(text)}</span>`,\n example: (text) => `<strong style=\"text-decoration: underline;\">${escapeHtml(text)}</strong>`,\n exampleValue: (text) => `<em>${escapeHtml(text)}</em>`,\n deprecated: (text) => `<del style=\"color: #999;\">${escapeHtml(text)}</del>`,\n };\n}\n\n// ============================================================================\n// Layout Configurations\n// ============================================================================\n\nfunction createTextLayout(): LayoutConfig {\n return {\n newline: '\\n',\n indent: (level) => ' '.repeat(level),\n join: (parts) => parts.filter(Boolean).join(' '),\n usageLabel: 'Usage:',\n };\n}\n\nfunction createMarkdownLayout(): LayoutConfig {\n return {\n newline: '\\n\\n',\n indent: (level) => {\n if (level === 0) return '';\n if (level === 1) return ' ';\n return ' ';\n },\n join: (parts) => parts.filter(Boolean).join(' '),\n usageLabel: 'Usage:',\n };\n}\n\nfunction createHtmlLayout(): LayoutConfig {\n return {\n newline: '<br>',\n indent: (level) => '&nbsp;&nbsp;'.repeat(level),\n join: (parts) => parts.filter(Boolean).join(' '),\n wrapDocument: (content) => `<div style=\"font-family: monospace; line-height: 1.6;\">${content}</div>`,\n usageLabel: '<strong>Usage:</strong>',\n };\n}\n\n// ============================================================================\n// Generic Formatter Implementation\n// ============================================================================\n\n/**\n * Creates a formatter that uses the given styler and layout configuration.\n */\nfunction createGenericFormatter(styler: Styler, layout: LayoutConfig): Formatter {\n const { newline, indent, join, wrapDocument, usageLabel } = layout;\n\n function formatUsageSection(info: HelpInfo): string[] {\n const usageParts: string[] = [styler.command(info.usage.command), info.usage.hasSubcommands ? styler.meta('[command]') : ''];\n // Show actual positional argument names in usage line\n if (info.positionals && info.positionals.length > 0) {\n for (const arg of info.positionals) {\n const name = arg.name.startsWith('...') ? `${arg.name}` : arg.name;\n usageParts.push(styler.meta(arg.optional ? `[${name}]` : `<${name}>`));\n }\n }\n if (info.usage.hasArguments) usageParts.push(styler.meta('[options]'));\n return [`${usageLabel} ${join(usageParts)}`];\n }\n\n function formatSubcommandsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const subcommands = info.subcommands!;\n\n lines.push(styler.label('Commands:'));\n\n const subcommandSuffix = (c: HelpSubcommandInfo) => (c.hasSubcommands ? ' <subcommand>' : '');\n const formatAliasParts = (c: HelpSubcommandInfo) => {\n if (!c.aliases?.length) return { plain: '', styled: '' };\n const realAliases = c.aliases.filter((a) => a !== '[default]');\n const hasDefault = c.aliases.some((a) => a === '[default]');\n const parts: string[] = [];\n const styledParts: string[] = [];\n if (realAliases.length) {\n parts.push(`(${realAliases.join(', ')})`);\n styledParts.push(`(${realAliases.join(', ')})`);\n }\n if (hasDefault) {\n parts.push('[default]');\n styledParts.push(styler.meta('[default]'));\n }\n return { plain: parts.length ? ` ${parts.join(' ')}` : '', styled: styledParts.length ? ` ${styledParts.join(' ')}` : '' };\n };\n const maxNameLength = Math.max(\n ...subcommands.map((c) => {\n return (c.name + subcommandSuffix(c) + formatAliasParts(c).plain).length;\n }),\n );\n for (const subCmd of subcommands) {\n const aliasParts = formatAliasParts(subCmd);\n const suffix = subcommandSuffix(subCmd);\n const commandDisplay = subCmd.name + suffix + aliasParts.plain;\n const padding = ' '.repeat(Math.max(0, maxNameLength - commandDisplay.length + 2));\n const isDeprecated = !!subCmd.deprecated;\n const isDefaultEntry = subCmd.name === '[default]';\n const commandName = isDeprecated\n ? styler.deprecated(commandDisplay)\n : (isDefaultEntry ? styler.meta(subCmd.name) : styler.command(subCmd.name)) +\n (suffix ? styler.meta(suffix) : '') +\n aliasParts.styled;\n const lineParts: string[] = [commandName, padding];\n\n // Use title if available, otherwise use description\n const displayText = subCmd.title ?? subCmd.description;\n if (displayText) {\n lineParts.push(isDeprecated ? styler.deprecated(displayText) : styler.description(displayText));\n }\n if (isDeprecated) {\n const deprecatedMeta =\n typeof subCmd.deprecated === 'string' ? styler.meta(` (deprecated: ${subCmd.deprecated})`) : styler.meta(' (deprecated)');\n lineParts.push(deprecatedMeta);\n }\n lines.push(indent(1) + lineParts.join(''));\n }\n\n lines.push('');\n lines.push(styler.meta(`Run \"${info.name} [command] --help\" for more information on a command.`));\n\n return lines;\n }\n\n function formatPositionalsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const args = info.positionals!;\n\n lines.push(styler.label('Arguments:'));\n\n const maxNameLength = Math.min(32, Math.max(...args.map((a) => a.name.length)));\n\n for (const arg of args) {\n const padding = ' '.repeat(Math.max(2, maxNameLength - arg.name.length + 2));\n const descParts: string[] = [];\n if (arg.description) descParts.push(styler.description(arg.description));\n if (info.usage.stdinField === arg.name) descParts.push(styler.meta('(stdin)'));\n if (arg.enum) descParts.push(styler.meta(`(choices: ${arg.enum.join(', ')})`));\n if (arg.default !== undefined) descParts.push(styler.meta(`(default: ${String(arg.default)})`));\n lines.push(indent(1) + styler.arg(arg.name) + padding + join(descParts));\n }\n\n return lines;\n }\n\n function formatArgumentsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const argList = info.arguments || [];\n\n lines.push(styler.label('Options:'));\n\n // Helper to check if a default value is meaningful (not empty string/array)\n const hasDefault = (value: unknown): boolean => {\n if (value === undefined) return false;\n if (value === '') return false;\n if (Array.isArray(value) && value.length === 0) return false;\n return true;\n };\n\n // Build left column (signature) for each arg to compute alignment\n const argColumns: { plain: string; styled: string; arg: HelpArgumentInfo }[] = argList.map((arg) => {\n // Promote kebab-case alias to primary display name if it exists\n const kebab = camelToKebab(arg.name);\n const primaryName = kebab && arg.aliases?.includes(kebab) ? kebab : arg.name;\n const remainingAliases = arg.aliases?.filter((a) => a !== primaryName);\n const argName = `--${primaryName}`;\n const flagNames = arg.flags?.length ? arg.flags.map((f) => `-${f}`).join(', ') : '';\n const aliasNames = remainingAliases?.length ? remainingAliases.map((a) => `--${a}`).join(', ') : '';\n const shortNames = [flagNames, aliasNames].filter(Boolean).join(', ');\n const fullArgName = shortNames ? `${argName}, ${shortNames}` : argName;\n const isDeprecated = !!arg.deprecated;\n const formattedArgName = isDeprecated ? styler.deprecated(fullArgName) : styler.arg(fullArgName);\n\n const plainParts: string[] = [fullArgName];\n const styledParts: string[] = [formattedArgName];\n\n if (arg.type && arg.type !== 'boolean') {\n const typePart = arg.optional ? `[${arg.type}]` : `<${arg.type}>`;\n plainParts.push(typePart);\n styledParts.push(styler.type(typePart));\n }\n if (isDeprecated) {\n const deprecatedPart = typeof arg.deprecated === 'string' ? `(deprecated: ${arg.deprecated})` : '(deprecated)';\n plainParts.push(deprecatedPart);\n styledParts.push(styler.meta(deprecatedPart));\n }\n\n return { plain: plainParts.join(' '), styled: join(styledParts), arg };\n });\n\n const maxColumnWidth = Math.min(32, Math.max(...argColumns.map((c) => c.plain.length)));\n\n for (const { plain, styled, arg } of argColumns) {\n const padding = ' '.repeat(Math.max(2, maxColumnWidth - plain.length + 2));\n\n // Description followed by metadata (choices, default)\n const descParts: string[] = [];\n if (arg.description) descParts.push(styler.description(arg.description));\n if (info.usage.stdinField === arg.name) descParts.push(styler.meta('(stdin)'));\n if (arg.enum) descParts.push(styler.meta(`(choices: ${arg.enum.join(', ')})`));\n if (hasDefault(arg.default)) descParts.push(styler.meta(`(default: ${String(arg.default)})`));\n\n lines.push(indent(1) + styled + padding + join(descParts));\n\n // Environment variable line\n if (arg.env) {\n const envVars = typeof arg.env === 'string' ? [arg.env] : arg.env;\n const envParts: string[] = [styler.example('Env:'), styler.exampleValue(envVars.join(', '))];\n lines.push(indent(3) + join(envParts));\n }\n\n // Config key line\n if (arg.configKey) {\n const configParts: string[] = [styler.example('Config:'), styler.exampleValue(arg.configKey)];\n lines.push(indent(3) + join(configParts));\n }\n\n // Examples line\n if (arg.examples && arg.examples.length > 0) {\n const exampleValues = arg.examples.map((example) => (typeof example === 'string' ? example : JSON.stringify(example))).join(', ');\n const exampleParts: string[] = [styler.example('Example:'), styler.exampleValue(exampleValues)];\n lines.push(indent(3) + join(exampleParts));\n }\n }\n\n return lines;\n }\n\n function formatBuiltinsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const builtins = info.builtins!;\n\n lines.push(styler.label('Built-in:'));\n\n // Compute max effective name length for alignment across main and sub entries\n const allLengths: number[] = [];\n for (const entry of builtins) {\n allLengths.push(entry.name.length);\n if (entry.sub) {\n for (const sub of entry.sub) {\n // Sub entries get extra indent(2) - indent(1) = 2 chars\n allLengths.push(sub.name.length + 2);\n }\n }\n }\n const maxLen = Math.max(...allLengths);\n\n for (const entry of builtins) {\n const padding = ' '.repeat(Math.max(2, maxLen - entry.name.length + 2));\n const parts: string[] = [styler.command(entry.name)];\n if (entry.description) parts.push(padding + styler.description(entry.description));\n lines.push(indent(1) + parts.join(''));\n\n if (entry.sub) {\n for (const sub of entry.sub) {\n const subPadding = ' '.repeat(Math.max(2, maxLen - sub.name.length));\n const subParts: string[] = [styler.arg(sub.name)];\n if (sub.description) subParts.push(subPadding + styler.description(sub.description));\n lines.push(indent(2) + subParts.join(''));\n }\n }\n }\n\n return lines;\n }\n\n return {\n format(info: HelpInfo): string {\n const lines: string[] = [];\n\n // Show deprecation warning at the top if command is deprecated\n if (info.deprecated) {\n const deprecationMessage =\n typeof info.deprecated === 'string' ? `⚠️ This command is deprecated: ${info.deprecated}` : '⚠️ This command is deprecated';\n lines.push(styler.deprecated(deprecationMessage));\n lines.push('');\n }\n\n // Usage section\n lines.push(...formatUsageSection(info));\n lines.push('');\n\n // Title section (if present, shows a short summary line)\n if (info.title) {\n lines.push(styler.label(info.title));\n lines.push('');\n }\n\n // Aliases section (if present)\n if (info.aliases && info.aliases.length > 0) {\n lines.push(styler.meta(`Aliases: ${info.aliases.join(', ')}`));\n lines.push('');\n }\n\n // Description section (if present)\n if (info.description) {\n lines.push(styler.description(info.description));\n lines.push('');\n }\n\n // Subcommands section\n if (info.subcommands && info.subcommands.length > 0) {\n lines.push(...formatSubcommandsSection(info));\n lines.push('');\n }\n\n if (info.positionals && info.positionals.length > 0) {\n lines.push(...formatPositionalsSection(info));\n lines.push('');\n }\n\n if (info.arguments && info.arguments.length > 0) {\n lines.push(...formatArgumentsSection(info));\n lines.push('');\n }\n\n if (info.builtins && info.builtins.length > 0) {\n lines.push(...formatBuiltinsSection(info));\n lines.push('');\n }\n\n // Show --no- hint when there are negatable boolean options defaulting to true\n if (info.arguments?.some((arg) => arg.negatable && arg.default === true)) {\n lines.push(styler.meta('Boolean options can be negated with --no-<option>.'));\n lines.push('');\n }\n\n // Nested commands section (full detail mode)\n if (info.nestedCommands?.length) {\n lines.push(styler.label('Subcommand Details:'));\n lines.push('');\n for (const nestedCmd of info.nestedCommands) {\n lines.push(styler.meta('─'.repeat(60)));\n lines.push(this.format(nestedCmd));\n }\n }\n\n const result = lines.join(newline);\n return wrapDocument ? wrapDocument(result) : result;\n },\n };\n}\n\n// ============================================================================\n// JSON Formatter\n// ============================================================================\n\nfunction createJsonFormatter(): Formatter {\n return {\n format(info: HelpInfo): string {\n return JSON.stringify(info, null, 2);\n },\n };\n}\n\n// ============================================================================\n// Formatter Factory\n// ============================================================================\n\nfunction shouldUseAnsi(): boolean {\n if (typeof process === 'undefined') return false;\n if (process.env.NO_COLOR) return false;\n if (process.env.CI) return false;\n if (process.stdout && typeof process.stdout.isTTY === 'boolean') return process.stdout.isTTY;\n return false;\n}\n\n// ============================================================================\n// Minimal Formatter\n// ============================================================================\n\n/**\n * Creates a minimal formatter that outputs just a single-line usage string.\n */\nfunction createMinimalFormatter(): Formatter {\n return {\n format(info: HelpInfo): string {\n const parts: string[] = [info.usage.command];\n if (info.usage.hasSubcommands) parts.push('[command]');\n if (info.positionals && info.positionals.length > 0) {\n for (const arg of info.positionals) {\n const name = arg.name.startsWith('...') ? `${arg.name}` : arg.name;\n parts.push(arg.optional ? `[${name}]` : `<${name}>`);\n }\n }\n if (info.usage.hasArguments) parts.push('[options]');\n return parts.join(' ');\n },\n };\n}\n\nexport function createFormatter(format: HelpFormat | 'auto', detail: HelpDetail = 'standard'): Formatter {\n if (detail === 'minimal') return createMinimalFormatter();\n if (format === 'json') return createJsonFormatter();\n if (format === 'ansi' || (format === 'auto' && shouldUseAnsi())) return createGenericFormatter(createAnsiStyler(), createTextLayout());\n if (format === 'console') return createGenericFormatter(createConsoleStyler(), createTextLayout());\n if (format === 'markdown') return createGenericFormatter(createMarkdownStyler(), createMarkdownLayout());\n if (format === 'html') return createGenericFormatter(createHtmlStyler(), createHtmlLayout());\n return createGenericFormatter(createTextStyler(), createTextLayout());\n}\n","import type { StandardJSONSchemaV1 } from '@standard-schema/spec';\nimport { extractSchemaMetadata, type PadroneArgsSchemaMeta, parsePositionalConfig, parseStdinConfig } from './args.ts';\nimport { findCommandByName } from './command-utils.ts';\nimport {\n createFormatter,\n type HelpArgumentInfo,\n type HelpDetail,\n type HelpFormat,\n type HelpInfo,\n type HelpPositionalInfo,\n type HelpSubcommandInfo,\n} from './formatter.ts';\nimport type { AnyPadroneCommand } from './types.ts';\nimport { getRootCommand } from './utils.ts';\n\nexport type HelpPreferences = {\n format?: HelpFormat | 'auto';\n detail?: HelpDetail;\n};\n\n/**\n * Extract positional arguments info from schema based on meta.positional config.\n */\nfunction extractPositionalArgsInfo(\n schema: StandardJSONSchemaV1,\n meta?: PadroneArgsSchemaMeta,\n): { args: HelpPositionalInfo[]; positionalNames: Set<string> } {\n const args: HelpPositionalInfo[] = [];\n const positionalNames = new Set<string>();\n\n if (!schema || !meta?.positional || meta.positional.length === 0) {\n return { args, positionalNames };\n }\n\n const positionalConfig = parsePositionalConfig(meta.positional);\n\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const properties = jsonSchema.properties as Record<string, any>;\n const required = (jsonSchema.required as string[]) || [];\n\n for (const { name, variadic } of positionalConfig) {\n const prop = properties[name];\n if (!prop) continue;\n\n positionalNames.add(name);\n const optMeta = meta.fields?.[name];\n\n args.push({\n name: variadic ? `...${name}` : name,\n description: optMeta?.description ?? prop.description,\n optional: !required.includes(name),\n default: prop.default,\n type: variadic ? `array<${prop.items?.type || 'string'}>` : prop.type,\n enum: (prop.enum ?? prop.items?.enum) as string[] | undefined,\n });\n }\n }\n } catch {\n // Fallback to empty result if toJSONSchema fails\n }\n\n return { args, positionalNames };\n}\n\nfunction extractArgsInfo(schema: StandardJSONSchemaV1, meta?: PadroneArgsSchemaMeta, positionalNames?: Set<string>) {\n const result: HelpArgumentInfo[] = [];\n if (!schema) return result;\n\n const vendor = schema['~standard'].vendor;\n if (!vendor.includes('zod')) return result;\n\n const argsMeta = meta?.fields;\n\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;\n\n // Handle object: z.object({ key: z.string(), ... })\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const properties = jsonSchema.properties as Record<string, any>;\n const required = (jsonSchema.required as string[]) || [];\n const propertyNames = new Set(Object.keys(properties));\n\n // Helper to check if a negated version of an arg exists\n const hasExplicitNegation = (key: string): boolean => {\n // Check for noVerbose style (camelCase)\n const camelNegated = `no${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n if (propertyNames.has(camelNegated)) return true;\n // Check for no-verbose style (kebab-case, though rare in JS)\n const kebabNegated = `no-${key}`;\n if (propertyNames.has(kebabNegated)) return true;\n return false;\n };\n\n // Helper to check if this arg is itself a negation of another arg\n const isNegationOf = (key: string): boolean => {\n // Check for noVerbose -> verbose (camelCase)\n if (key.startsWith('no') && key.length > 2 && key[2] === key[2]?.toUpperCase()) {\n const positiveKey = key.charAt(2).toLowerCase() + key.slice(3);\n if (propertyNames.has(positiveKey)) return true;\n }\n // Check for no-verbose -> verbose (kebab-case)\n if (key.startsWith('no-')) {\n const positiveKey = key.slice(3);\n if (propertyNames.has(positiveKey)) return true;\n }\n return false;\n };\n\n for (const [key, prop] of Object.entries(properties)) {\n // Skip positional arguments - they are shown in arguments section\n if (positionalNames?.has(key)) continue;\n\n const isOptional = !required.includes(key);\n const enumValues = (prop.enum ?? prop.items?.enum) as string[] | undefined;\n const optMeta = argsMeta?.[key];\n const propType = prop.type as string;\n\n // Booleans are negatable unless there's an explicit noArg property\n // or this arg is itself a negation of another arg\n const isNegatable = propType === 'boolean' && !hasExplicitNegation(key) && !isNegationOf(key);\n\n result.push({\n name: key,\n description: optMeta?.description ?? prop.description,\n optional: isOptional,\n default: prop.default,\n type: propType === 'array' ? `${prop.items?.type || 'string'}[]` : propType,\n enum: enumValues,\n deprecated: optMeta?.deprecated ?? prop?.deprecated,\n hidden: optMeta?.hidden ?? prop?.hidden,\n examples: optMeta?.examples ?? prop?.examples,\n variadic: propType === 'array',\n negatable: isNegatable,\n });\n }\n }\n } catch {\n // Fallback to empty result if toJSONSchema fails\n }\n\n return result;\n}\n\n// ============================================================================\n// Core Help Info Builder\n// ============================================================================\n\n/**\n * Builds a comprehensive HelpInfo structure from a command.\n * This is the single source of truth that all formatters use.\n * @param cmd - The command to build help info for\n * @param detail - The level of detail ('minimal', 'standard', or 'full')\n */\nexport function getHelpInfo(cmd: AnyPadroneCommand, detail: HelpPreferences['detail'] = 'standard'): HelpInfo {\n const rootCmd = getRootCommand(cmd);\n // A command is a \"default\" command if its name is '' or it has '' as an alias\n const isDefaultCommand = cmd.parent && (!cmd.name || cmd.aliases?.includes(''));\n // For commands with empty name, use the first non-empty alias as display name\n const nonEmptyAliases = cmd.aliases?.filter(Boolean);\n const commandName = cmd.path || cmd.name || nonEmptyAliases?.[0] || (cmd.parent ? '[default]' : 'program');\n // Build display aliases: real aliases (excluding the one promoted to display name) + [default] marker\n const remainingAliases = !cmd.name && nonEmptyAliases?.length ? nonEmptyAliases.slice(1) : (nonEmptyAliases ?? []);\n const displayAliases = isDefaultCommand ? [...remainingAliases, '[default]'] : nonEmptyAliases;\n\n // Extract positional args from schema based on meta.positional\n const { args: positionalArgs, positionalNames } = cmd.argsSchema\n ? extractPositionalArgsInfo(cmd.argsSchema, cmd.meta)\n : { args: [], positionalNames: new Set<string>() };\n\n const hasPositionals = positionalArgs.length > 0;\n\n const helpInfo: HelpInfo = {\n name: commandName,\n title: cmd.title,\n description: cmd.description,\n aliases: displayAliases,\n deprecated: cmd.deprecated,\n hidden: cmd.hidden,\n usage: {\n command: rootCmd === cmd ? commandName : `${rootCmd.name} ${commandName}`,\n hasSubcommands: !!(cmd.commands && cmd.commands.length > 0),\n hasPositionals,\n hasArguments: false, // updated below after extracting arguments\n stdinField: cmd.meta?.stdin ? parseStdinConfig(cmd.meta.stdin).field : undefined,\n },\n };\n\n // Build subcommands info (filter out hidden commands unless showing full detail)\n if (cmd.commands && cmd.commands.length > 0) {\n const visibleCommands = detail === 'full' ? cmd.commands : cmd.commands.filter((c) => !c.hidden);\n // If the command has both a handler and subcommands, show the handler as a \"[default]\" entry\n const selfEntry: typeof helpInfo.subcommands = cmd.action\n ? [{ name: '[default]', title: cmd.title, description: cmd.description }]\n : [];\n\n helpInfo.subcommands = [\n ...selfEntry,\n ...visibleCommands.flatMap((c): HelpSubcommandInfo[] => {\n const isDefault = !c.name || c.aliases?.includes('');\n const nonEmptyAliases = c.aliases?.filter(Boolean);\n const displayName = c.name || nonEmptyAliases?.[0] || '[default]';\n const remainingAliases = !c.name && nonEmptyAliases?.length ? nonEmptyAliases.slice(1) : (nonEmptyAliases ?? []);\n // Only add [default] alias marker if it's not already the display name\n const displayAliases =\n isDefault && displayName !== '[default]' ? [...remainingAliases, '[default]'] : isDefault ? remainingAliases : nonEmptyAliases;\n const hasSubcommands = !!(c.commands && c.commands.length > 0);\n\n // If a command has subcommands AND a default handler (direct or '' subcommand),\n // show two entries: one for the default action, one for the subcommand router\n const hasDefaultHandler = c.action || c.commands?.some((sub) => !sub.name || sub.aliases?.includes(''));\n if (hasSubcommands && hasDefaultHandler) {\n const defaultSub = !c.action ? c.commands?.find((sub) => !sub.name || sub.aliases?.includes('')) : undefined;\n const hasDefaultSubInfo = defaultSub && (defaultSub.title || defaultSub.description);\n return [\n {\n name: displayName,\n title: hasDefaultSubInfo ? defaultSub.title : c.title,\n description: hasDefaultSubInfo ? defaultSub.description : c.description,\n aliases: displayAliases?.length ? displayAliases : undefined,\n deprecated: c.deprecated,\n hidden: c.hidden,\n },\n {\n name: displayName,\n title: c.title,\n description: c.description,\n deprecated: c.deprecated,\n hidden: c.hidden,\n hasSubcommands: true,\n },\n ];\n }\n\n return [\n {\n name: displayName,\n title: c.title,\n description: c.description,\n aliases: displayAliases?.length ? displayAliases : undefined,\n deprecated: c.deprecated,\n hidden: c.hidden,\n hasSubcommands,\n },\n ];\n }),\n ];\n\n // In 'full' detail mode, recursively build help for all nested commands\n if (detail === 'full') {\n helpInfo.nestedCommands = visibleCommands.map((c) => getHelpInfo(c, 'full'));\n }\n }\n\n // Build arguments info from positionals\n if (hasPositionals) {\n helpInfo.positionals = positionalArgs;\n }\n\n // Build arguments info with aliases (excluding positional args)\n if (cmd.argsSchema) {\n const argsInfo = extractArgsInfo(cmd.argsSchema, cmd.meta, positionalNames);\n const argMap: Record<string, HelpArgumentInfo> = Object.fromEntries(argsInfo.map((arg) => [arg.name, arg]));\n\n // Merge flags and aliases into arguments\n const { flags, aliases } = extractSchemaMetadata(cmd.argsSchema, cmd.meta?.fields, cmd.meta?.autoAlias);\n for (const [flag, name] of Object.entries(flags)) {\n const arg = argMap[name];\n if (!arg) continue;\n arg.flags = [...(arg.flags || []), flag];\n }\n for (const [alias, name] of Object.entries(aliases)) {\n const arg = argMap[name];\n if (!arg) continue;\n arg.aliases = [...(arg.aliases || []), alias];\n }\n\n // Filter out hidden arguments\n const visibleArgs = argsInfo.filter((arg) => !arg.hidden);\n if (visibleArgs.length > 0) {\n helpInfo.arguments = visibleArgs;\n helpInfo.usage.hasArguments = true;\n }\n }\n\n // Add built-in commands/flags for root command only\n if (!cmd.parent) {\n const builtins: HelpInfo['builtins'] = [];\n\n if (!findCommandByName('help', cmd.commands)) {\n builtins.push({\n name: 'help [command], -h, --help',\n description: 'Show help for a command',\n sub: [\n { name: '--detail <level>', description: 'Detail level (minimal, standard, full)' },\n { name: '--format <format>', description: 'Output format (text, ansi, json, markdown, html)' },\n ],\n });\n }\n\n if (!findCommandByName('version', cmd.commands)) {\n builtins.push({\n name: 'version, -v, --version',\n description: 'Show version information',\n });\n }\n\n if (!findCommandByName('completion', cmd.commands)) {\n builtins.push({\n name: 'completion [shell]',\n description: 'Generate shell completions (bash, zsh, fish, powershell)',\n });\n }\n\n builtins.push({\n name: '[command] --repl',\n description: 'Start interactive REPL scoped to a command',\n });\n\n if (builtins.length > 0) {\n helpInfo.builtins = builtins;\n }\n }\n\n return helpInfo;\n}\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\nexport function generateHelp(rootCommand: AnyPadroneCommand, commandObj: AnyPadroneCommand = rootCommand, prefs?: HelpPreferences): string {\n const helpInfo = getHelpInfo(commandObj, prefs?.detail);\n const formatter = createFormatter(prefs?.format ?? 'auto', prefs?.detail);\n return formatter.format(helpInfo);\n}\n"],"mappings":";;;AAEA,SAAgB,eAAe,KAA2C;CACxE,IAAI,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AAE,MAAM;IAAoB,aAAa;IAA0C,EACnF;IAAE,MAAM;IAAqB,aAAa;IAAoD,CAC/F;GACF,CAAC;AAGJ,MAAI,CAAC,kBAAkB,WAAW,IAAI,SAAS,CAC7C,UAAS,KAAK;GACZ,MAAM;GACN,aAAa;GACd,CAAC;AAGJ,MAAI,CAAC,kBAAkB,cAAc,IAAI,SAAS,CAChD,UAAS,KAAK;GACZ,MAAM;GACN,aAAa;GACd,CAAC;AAGJ,WAAS,KAAK;GACZ,MAAM;GACN,aAAa;GACd,CAAC;AAEF,MAAI,SAAS,SAAS,EACpB,UAAS,WAAW;;AAIxB,QAAO;;AAOT,SAAgB,aAAa,aAAgC,aAAgC,aAAa,OAAiC;CACzI,MAAM,WAAW,YAAY,YAAY,OAAO,OAAO;AAEvD,QADkB,gBAAgB,OAAO,UAAU,QAAQ,OAAO,OAAO,CACxD,OAAO,SAAS"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as PossibleCommands, a as PadroneActionContext, b as PadroneRuntime, c as PadroneCommandResult, d as PadroneProgram, f as PadroneSchema, g as PickCommandByName, h as UpdateCheckConfig, i as AsyncPadroneSchema, l as PadroneParseResult, m as WrapResult, n as AnyPadroneCommand, o as PadroneBuilder, p as WrapConfig, r as AnyPadroneProgram, s as PadroneCommand, t as AnyPadroneBuilder, u as PadronePlugin, v as InteractiveMode, x as REPL_SIGINT, y as InteractivePromptConfig } from "./types-BS7RP5Ls.mjs";
2
- import { r as HelpInfo } from "./formatter-XroimS3Q.mjs";
1
+ import { _ as PossibleCommands, a as PadroneActionContext, b as PadroneRuntime, c as PadroneCommandResult, d as PadroneProgram, f as PadroneSchema, g as PickCommandByName, h as UpdateCheckConfig, i as AsyncPadroneSchema, l as PadroneParseResult, m as WrapResult, n as AnyPadroneCommand, o as PadroneBuilder, p as WrapConfig, r as AnyPadroneProgram, s as PadroneCommand, t as AnyPadroneBuilder, u as PadronePlugin, v as InteractiveMode, x as REPL_SIGINT, y as InteractivePromptConfig } from "./types-DjIdJN5G.mjs";
2
+ import { r as HelpInfo } from "./formatter-ClUK5hcQ.mjs";
3
3
 
4
4
  //#region src/command-utils.d.ts
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/command-utils.ts","../src/create.ts","../src/errors.ts","../src/type-helpers.ts"],"mappings":";;;;;;AAgCA;;;;;;;;;;;;;;;;AA2SA;;iBA3SgB,WAAA,WAAsB,aAAA,CAAA,CAAe,MAAA,EAAQ,CAAA,GAAI,CAAA;EAAM,QAAA;AAAA;;;;;;iBA2SvD,kBAAA,CACd,WAAA,EAAa,iBAAA,EACb,QAAA;EACE,OAAA;AAAA,KAEA,IAAA;;;iBChSY,aAAA,6BAAA,CAA2C,IAAA,EAAM,YAAA,GAAe,cAAA,CAAe,YAAA;;;;;;;ADhB/F;;;;KEvBY,mBAAA;EFuBqD,wCErB/D,QAAA,WFqBgE;EEnBhE,WAAA,aFmBoC;EEjBpC,OAAA,WFiBmD;EEfnD,KAAA,gDFeqE;EEbrE,KAAA;AAAA;AFwTF;;;;;;;;;;;;AAAA,cEzSa,YAAA,SAAqB,KAAA;EAAA,SACvB,QAAA;EAAA,SACA,WAAA;EAAA,SACA,OAAA;EAAA,SACA,KAAA;cAEG,OAAA,UAAiB,OAAA,GAAU,mBAAA;EDQsD;;;;ECK7F,MAAA,CAAA;IACE,IAAA;IACA,OAAA;IACA,QAAA;IACA,WAAA;IACA,OAAA;IACA,KAAA;EAAA;AAAA;;AAlDJ;;cAkEa,YAAA,SAAqB,YAAA;cACpB,OAAA,UAAiB,OAAA,GAAU,mBAAA;AAAA;;;;;cAU5B,eAAA,SAAwB,YAAA;EAAA,SAC1B,MAAA;IAAmB,IAAA,GAAO,WAAA;IAAe,OAAA;EAAA;cAEtC,OAAA,UAAiB,MAAA;IAAmB,IAAA,GAAO,WAAA;IAAe,OAAA;EAAA,KAAqB,OAAA,GAAU,mBAAA;EAM5F,MAAA,CAAA;;;;;;;;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AiB,OAAA,GAAU,mBAAA;EDSsD;;;;ECI7F,MAAA,CAAA;IACE,IAAA;IACA,OAAA;IACA,QAAA;IACA,WAAA;IACA,OAAA;IACA,KAAA;EAAA;AAAA;;AAlDJ;;cAkEa,YAAA,SAAqB,YAAA;cACpB,OAAA,UAAiB,OAAA,GAAU,mBAAA;AAAA;;;;;cAU5B,eAAA,SAAwB,YAAA;EAAA,SAC1B,MAAA;IAAmB,IAAA,GAAO,WAAA;IAAe,OAAA;EAAA;cAEtC,OAAA,UAAiB,MAAA;IAAmB,IAAA,GAAO,WAAA;IAAe,OAAA;EAAA,KAAqB,OAAA,GAAU,mBAAA;EAM5F,MAAA,CAAA;;;;;;;;;;;;;;;AApBX;cA+Ba,WAAA,SAAoB,YAAA;cACnB,OAAA,UAAiB,OAAA,GAAU,mBAAA;AAAA;;;;;;;;AArBzC;;;;;cAuCa,WAAA,SAAoB,YAAA;cACnB,OAAA,UAAiB,OAAA,GAAU,mBAAA;AAAA;;;;;AF9FzC;;;;;KGtBY,cAAA,WAAyB,iBAAA,IAAqB,CAAA;;;;;;;;KAS9C,eAAA,WAA0B,iBAAA,IAAqB,CAAA;;;;;;;;;;;ADe3D;;;;;KCyCY,YAAA,WACA,iBAAA,GAAoB,iBAAA,gBAChB,gBAAA,CAAiB,CAAA,SAAU,iBAAA,IAAqB,CAAA,IAAK,CAAA,uCACjE,CAAA,SAAU,iBAAA,GACV,iBAAA,EAAmB,cAAA,mBAAiC,CAAA,0BAA2B,KAAA,IAC/E,CAAA,SAAU,iBAAA,GACR,iBAAA,EAAmB,CAAA,GAAI,KAAA"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { a as parsePositionalConfig, i as extractSchemaMetadata, n as coerceArgs, o as parseStdinConfig, r as detectUnknownArgs, s as preprocessArgs } from "./args-DFEI7_G_.mjs";
2
- import { S as getVersion, _ as warnIfUnexpectedAsync, a as commandSymbol, b as createTerminalReplSession, c as hasInteractiveConfig, d as noop, f as outputValue, g as thenMaybe, h as suggestSimilar, i as buildReplCompleter, l as isAsyncBranded, m as runPluginChain, o as findCommandByName, p as repathCommandTree, r as asyncSchema, s as getCommandRuntime, t as generateHelp, u as mergeCommands, v as wrapWithLifecycle, x as resolveStdin, y as REPL_SIGINT } from "./help-CgGP7hQU.mjs";
1
+ import { a as parsePositionalConfig, i as extractSchemaMetadata, n as coerceArgs, o as parseStdinConfig, r as detectUnknownArgs, s as preprocessArgs } from "./args-CVDbyyzG.mjs";
2
+ import { C as getVersion, S as resolveStdin, _ as thenMaybe, a as commandSymbol, b as REPL_SIGINT, c as hasInteractiveConfig, d as mergeCommands, f as noop, g as suggestSimilar, h as runPluginChain, i as buildReplCompleter, l as isAsyncBranded, m as repathCommandTree, o as findCommandByName, p as outputValue, r as asyncSchema, s as getCommandRuntime, t as generateHelp, u as makeThenable, v as warnIfUnexpectedAsync, x as createTerminalReplSession, y as wrapWithLifecycle } from "./help-CcBe91bV.mjs";
3
3
  //#region src/errors.ts
4
4
  /**
5
5
  * Base error class for all Padrone errors.
@@ -957,7 +957,7 @@ function createPadroneBuilder(inputCommand) {
957
957
  argsResult: v.argsResult
958
958
  })), command);
959
959
  };
960
- return thenMaybe(parsedOrPromise, continueAfterParse);
960
+ return makeThenable(thenMaybe(parsedOrPromise, continueAfterParse));
961
961
  };
962
962
  const stringify = (command = "", args) => {
963
963
  const commandObj = typeof command === "string" ? findCommandByName(command, existingCommand.commands) : command;
@@ -1455,7 +1455,7 @@ function createPadroneBuilder(inputCommand) {
1455
1455
  return commandResult;
1456
1456
  });
1457
1457
  };
1458
- return warnIfUnexpectedAsync(thenMaybe(validatedOrPromise, continueAfterValidate), command);
1458
+ return thenMaybe(warnIfUnexpectedAsync(validatedOrPromise, command), continueAfterValidate);
1459
1459
  };
1460
1460
  return thenMaybe(parsedOrPromise, continueAfterParse);
1461
1461
  };
@@ -1467,7 +1467,7 @@ function createPadroneBuilder(inputCommand) {
1467
1467
  }));
1468
1468
  };
1469
1469
  const evalCommand = (input, evalOptions) => {
1470
- return execCommand(input, evalOptions, "soft");
1470
+ return makeThenable(execCommand(input, evalOptions, "soft"));
1471
1471
  };
1472
1472
  /**
1473
1473
  * Collects plugins from the command's parent chain (root → ... → target).
@@ -1529,7 +1529,7 @@ function createPadroneBuilder(inputCommand) {
1529
1529
  });
1530
1530
  updateCheckPromise.then((show) => show?.());
1531
1531
  }
1532
- return result;
1532
+ return makeThenable(result);
1533
1533
  };
1534
1534
  const run = (command, args) => {
1535
1535
  const commandObj = typeof command === "string" ? findCommandByName(command, existingCommand.commands) : command;