@reliverse/rempts 1.7.49 → 1.7.50

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.
@@ -1152,40 +1152,43 @@ type EmptyArgs = Record<string, never>;
1152
1152
  interface BaseArgProps {
1153
1153
  description?: string;
1154
1154
  required?: boolean;
1155
- allowed?: string[];
1155
+ allowed?: readonly string[];
1156
1156
  }
1157
1157
  interface BaseArgDefinition {
1158
1158
  type: string;
1159
1159
  description?: string;
1160
1160
  required?: boolean;
1161
1161
  default?: any;
1162
- allowed?: any[];
1162
+ allowed?: readonly any[];
1163
1163
  dependencies?: string[];
1164
1164
  }
1165
1165
  type PositionalArgDefinition = BaseArgDefinition & {
1166
1166
  type: "positional";
1167
1167
  default?: string;
1168
+ allowed?: readonly string[];
1168
1169
  };
1169
1170
  type BooleanArgDefinition = BaseArgDefinition & {
1170
1171
  type: "boolean";
1171
1172
  default?: boolean;
1172
- allowed?: boolean[];
1173
+ allowed?: readonly boolean[];
1173
1174
  alias?: string;
1174
1175
  };
1175
1176
  type StringArgDefinition = BaseArgDefinition & {
1176
1177
  type: "string";
1177
1178
  default?: string;
1179
+ allowed?: readonly string[];
1178
1180
  alias?: string;
1179
1181
  };
1180
1182
  type NumberArgDefinition = BaseArgDefinition & {
1181
1183
  type: "number";
1182
1184
  default?: number;
1183
- allowed?: number[];
1185
+ allowed?: readonly number[];
1184
1186
  alias?: string;
1185
1187
  };
1186
1188
  type ArrayArgDefinition = BaseArgDefinition & {
1187
1189
  type: "array";
1188
1190
  default?: string | readonly string[];
1191
+ allowed?: readonly string[];
1189
1192
  alias?: string;
1190
1193
  };
1191
1194
  type ArgDefinition = PositionalArgDefinition | BooleanArgDefinition | StringArgDefinition | NumberArgDefinition | ArrayArgDefinition;
@@ -1297,49 +1300,69 @@ interface Command<A extends ArgDefinitions = EmptyArgs> {
1297
1300
  */
1298
1301
  router?: AnyRouter;
1299
1302
  }
1303
+ type ExtractAllowed<T extends ArgDefinition> = T extends {
1304
+ type: "positional";
1305
+ allowed: readonly (infer U)[];
1306
+ } ? U : T extends {
1307
+ type: "positional";
1308
+ } ? string : T extends {
1309
+ type: "boolean";
1310
+ allowed: readonly (infer U)[];
1311
+ } ? U : T extends {
1312
+ type: "boolean";
1313
+ } ? boolean : T extends {
1314
+ type: "string";
1315
+ allowed: readonly (infer U)[];
1316
+ } ? U : T extends {
1317
+ type: "string";
1318
+ } ? string : T extends {
1319
+ type: "number";
1320
+ allowed: readonly (infer U)[];
1321
+ } ? U : T extends {
1322
+ type: "number";
1323
+ } ? number : T extends {
1324
+ type: "array";
1325
+ allowed: readonly (infer U)[];
1326
+ } ? U[] : T extends {
1327
+ type: "array";
1328
+ } ? string[] : never;
1300
1329
  type InferArgTypes<A extends ArgDefinitions> = {
1301
- [K in keyof A]: A[K] extends PositionalArgDefinition ? string : A[K] extends BooleanArgDefinition ? boolean : A[K] extends StringArgDefinition ? string : A[K] extends NumberArgDefinition ? number : A[K] extends {
1302
- type: "array";
1303
- } ? string[] : never;
1330
+ [K in keyof A]: ExtractAllowed<A[K]>;
1304
1331
  };
1305
1332
  interface FileBasedOptions {
1306
1333
  enable: boolean;
1307
1334
  cmdsRootPath: string;
1308
1335
  }
1309
1336
 
1337
+ interface CallCmdOptions {
1338
+ /** Whether to automatically exit process on errors (default: false for programmatic usage) */
1339
+ autoExit?: boolean;
1340
+ /** Whether to show debug output */
1341
+ debug?: boolean;
1342
+ /** Whether to call lifecycle hooks (onCmdInit/onCmdExit) */
1343
+ useLifecycleHooks?: boolean;
1344
+ /** Custom parser options for argv processing */
1345
+ parserOptions?: ReliArgParserOptions;
1346
+ }
1310
1347
  /**
1311
- * Load a command from the filesystem.
1348
+ * Programmatically call a defineCommand command with arguments.
1349
+ * Fully compatible with launcher-mod.ts execution logic.
1312
1350
  *
1313
- * @param cmdPath - Path to the command file or directory containing cmd.ts/cmd.js
1314
- * @returns Promise<Command> - The loaded command
1351
+ * @param command - The command definition created with defineCommand()
1352
+ * @param input - Either argv array (CLI-style) or args object (programmatic style)
1353
+ * @param options - Optional configuration for execution
1354
+ * @returns Promise resolving to the command context
1315
1355
  *
1316
1356
  * @example
1317
1357
  * ```ts
1318
- * // Load a command
1319
- * const cmd = await loadCommand("./web/cmd");
1358
+ * // CLI-style with argv array
1359
+ * const result = await callCmd(myCommand, ['--flag', 'value', 'positional']);
1320
1360
  *
1321
- * // Use with runCmd - pass args as separate array elements
1322
- * await runCmd(cmd, ["--dev", "true"]); // Correct
1323
- * await runCmd(cmd, [`--dev ${isDev}`]); // ❌ Wrong - creates single string
1361
+ * // Programmatic style with object
1362
+ * const result = await callCmd(myCommand, { flag: true, name: 'value' });
1324
1363
  * ```
1325
1364
  */
1326
- declare function loadCommand(cmdPath: string): Promise<Command>;
1327
-
1328
- /**
1329
- * Static implementation functions for the typed command system.
1330
- * These functions are imported by the generated cmds.ts file.
1331
- */
1332
- declare function argsToStringArray(args: Record<string, unknown>): string[];
1333
- declare function createCallCmd<TCommandArgsMap>(): Promise<(<T extends keyof TCommandArgsMap>(cmdName: T, args?: TCommandArgsMap[T]) => Promise<void>)>;
1334
- declare function createGetTypedCmd<TCommandArgsMap>(): Promise<(<T extends keyof TCommandArgsMap>(cmdName: T) => Promise<{
1335
- command: Command;
1336
- run: (args?: TCommandArgsMap[T]) => Promise<void>;
1337
- }>)>;
1338
- declare function callCmdImpl<TCommandArgsMap>(cmdName: keyof TCommandArgsMap, args?: TCommandArgsMap[keyof TCommandArgsMap]): Promise<void>;
1339
- declare function getTypedCmdImpl<TCommandArgsMap>(cmdName: keyof TCommandArgsMap): Promise<{
1340
- command: Command;
1341
- run: (args?: TCommandArgsMap[keyof TCommandArgsMap]) => Promise<void>;
1342
- }>;
1365
+ declare function callCmd<A extends ArgDefinitions = EmptyArgs>(command: Command<A>, input: string[] | Partial<InferArgTypes<A>>, options?: CallCmdOptions): Promise<CommandContext<InferArgTypes<A>>>;
1343
1366
 
1344
1367
  /**
1345
1368
  * JSON representation of a commander `Command` instance
@@ -1758,64 +1781,6 @@ declare function createCli<A extends ArgDefinitions = EmptyArgs>(options: Comman
1758
1781
  * for IntelliSense and validation for array defaults against options.
1759
1782
  */
1760
1783
  declare function defineArgs<A extends ArgDefinitions>(args: A): A;
1761
- /**
1762
- * Programmatically run a command with subcommand support and flexible argument handling.
1763
- * This function can handle subcommands (including nested), positional arguments, and automatically normalizes
1764
- * template literals and space-separated strings.
1765
- *
1766
- * @param command The command definition (from defineCommand)
1767
- * @param argv The argv array to parse (default: []). Supports template literals and subcommands.
1768
- * @param parserOptions Optional reliArgParser options
1769
- *
1770
- * @example
1771
- * ```ts
1772
- * // ✅ Single command with template literals
1773
- * await runCmdWithSubcommands(cmd, [`--dev ${isDev}`]);
1774
- *
1775
- * // ✅ Subcommand with arguments
1776
- * await runCmdWithSubcommands(cmd, [`build --input src/mod.ts --someBoolean`]);
1777
- *
1778
- * // ✅ Subcommand with positional arguments
1779
- * await runCmdWithSubcommands(cmd, [`build src/mod.ts --someBoolean`]);
1780
- *
1781
- * // ✅ Nested subcommands
1782
- * await runCmdWithSubcommands(cmd, [`build someSubCmd src/mod.ts --no-cjs`]);
1783
- * await runCmdWithSubcommands(cmd, [`build sub1 sub2 sub3 file.ts --flag`]);
1784
- *
1785
- * // ✅ Mixed array with subcommands
1786
- * await runCmdWithSubcommands(cmd, [
1787
- * `build someSubCmd src/mod.ts`,
1788
- * "--no-cjs",
1789
- * "--verbose"
1790
- * ]);
1791
- * ```
1792
- */
1793
- declare function runCmdWithSubcommands<A extends ArgDefinitions = EmptyArgs>(command: Command<A>, argv?: string[], parserOptions?: ReliArgParserOptions & {
1794
- fileBased?: FileBasedOptions;
1795
- autoExit?: boolean;
1796
- }): Promise<any>;
1797
- /**
1798
- * Programmatically run a command's run() handler with parsed arguments.
1799
- * Does not handle subcommands, file-based commands, or global hooks.
1800
- * Suitable for use in demos, tests, or programmatic invocation.
1801
- *
1802
- * @param command The command definition (from defineCommand)
1803
- * @param argv The argv array to parse (default: []). Each argument should be a separate array element.
1804
- * @param parserOptions Optional reliArgParser options
1805
- *
1806
- * @example
1807
- * **each argument as separate array element**:
1808
- * ```ts
1809
- * await runCmd(cmd, ["--dev", "true"]);
1810
- * await runCmd(cmd, ["--name", "John", "--verbose"]);
1811
- * ```
1812
- * **automatic normalization of template literals**:
1813
- * ```ts
1814
- * await runCmd(cmd, [`--dev ${isDev}`]); // Automatically converted to ["--dev", "true"]
1815
- * await runCmd(cmd, [`--dev ${isDev} --build mod.ts`]); // ["--dev", "true", "--build", "mod.ts"]
1816
- * ```
1817
- */
1818
- declare function runCmd<A extends ArgDefinitions = EmptyArgs>(command: Command<A>, argv?: string[], parserOptions?: ReliArgParserOptions): Promise<void>;
1819
1784
 
1820
1785
  declare const runMain: typeof createCli;
1821
1786
 
@@ -2329,5 +2294,5 @@ declare function createAsciiArt({ message, font, clearConsole, }: {
2329
2294
  clearConsole?: boolean;
2330
2295
  }): Promise<void>;
2331
2296
 
2332
- export { CANCEL, CliValidationError, FailedToExitError, StandardSchemaV1Error, TrpcCommand, addCompletions, animateText, animationMap, anykeyPrompt, applyVariant, argsToStringArray, bar, block, breakLines, callCmdImpl, cancel, colorMap, colorize, commandToJSON, completePrompt, confirm, confirmPrompt, countLines, createAsciiArt, createCallCmd, createCancel, createCli, createGetTypedCmd, createMultiStep, createRpcCli, createShadowCommand, createStep, datePrompt, defineArgs, defineCommand, deleteLastLine, deleteLastLines, endPrompt, errorHandler, fallbackSymbols, figures, flattenedProperties, fmt, getColumns, getDescription, getEnumChoices, getExactTerminalWidth, getSchemaTypes, getTerminalHeight, getTerminalWidth, getTypedCmdImpl, group, incompatiblePropertyPairs, input, inputPrompt, intro, introPrompt, isCancel, isOrpcRouter, isTerminalInteractive, isTrpc11Procedure, isTrpc11Router, isValidName, isValidVariant, isWindows, lineByLineConsoleLogger, lineByLineLogger, loadCommand, log, looksLikeInstanceof, looksLikeStandardSchema, looksLikeStandardSchemaFailure, mainSymbols, msg, msgUndo, msgUndoAll, multiselect, multiselectPrompt, nextStepsPrompt, normalizeName, numMultiSelectPrompt, numSelectPrompt, numberPrompt, outro, outroPrompt, parseProcedureInputs, parseRouter, password, pm, prettifyStandardSchemaError, preventUnsupportedTTY, preventWindowsHomeDirRoot, preventWrongTerminalSize, printLineBar, promptify, relinkaAsyncByRemptsDeprecated, relinkaByRemptsDeprecated, reliversePrompts, removeCursor, renderEndLine, renderEndLineInput, restoreCursor, resultPrompt, runCmd, runCmdWithSubcommands, runMain, select, selectPrompt, selectSimple, setRawMode, showUsage, spinner, startEditor, startPrompt, streamText, streamTextBox, streamTextWithSpinner, symbols, taskProgressPrompt, taskSpinPrompt, text, throwError, toBaseColor, toDotPath, toSolidColor, togglePrompt, typographyMap, useSpinner, variantMap };
2333
- export type { AllKinds, AnyProcedure, AnyRouter, ArgDefinition, ArgDefinitions, ArrayArgDefinition, BaseArgDefinition, BaseArgProps, BooleanArgDefinition, BorderColorName, CancelValue, ChoiceOptions, ClackPromptsLike, ColorName, Command, CommandContext, CommandHook, CommandJSON, CommandMeta, CommandRun, CommandSpec, CommanderProgramLike, CommandsMap, ConfirmPromptOptions, CreateCallerFactoryLike, DatePromptOptions, DefineCommandOptions, Dependencies, EditorExitResult, EmptyArgs, EnquirerLike, FileBasedOptions, FmtMsgOptions, GroupContext, GroupOptions, GroupStep, GroupSteps, InferArgTypes, InputPromptOptions, InquirerPromptOptions, InquirerPromptsLike, Log, Logger, MessageConfig, MessageKind, MsgConfig, MsgType, MultiselectPromptParams, NumberArgDefinition, OmeletteInstanceLike, OrpcProcedureLike, OrpcRouterLike, OutputColor, ParsedProcedure, PositionalArgDefinition, PreventWrongTerminalSizeOptions, ProgressBar, ProgressBarOptions, PromptContext, PromptOptions, PromptType, Promptable, Prompter, PromptsLike, RenderParams, Result, ResultsType, SelectOption, SelectPromptParams, SeparatorOption, StandardColor, StandardSchemaV1, StandardSchemaV1FailureResult, StandardSchemaV1InferInput, StandardSchemaV1InferOutput, StandardSchemaV1Issue, StandardSchemaV1PathSegment, StandardSchemaV1Props, StandardSchemaV1Result, StandardSchemaV1SuccessResult, StandardSchemaV1Types, StreamOptions, StreamTextOptions, StringArgDefinition, SymbolName, Symbols, TogglePromptParams, Trpc10ProcedureLike, Trpc10RouterLike, Trpc11ProcedureLike, Trpc11ProcedureRecordLike, Trpc11RouterLike, TrpcCli, TrpcCliMeta, TrpcCliParams, TrpcCliRunParams, TrpcServerModuleLike, TypographyName, VariantName$1 as VariantName, inferRouterContext };
2297
+ export { CANCEL, CliValidationError, FailedToExitError, StandardSchemaV1Error, TrpcCommand, addCompletions, animateText, animationMap, anykeyPrompt, applyVariant, bar, block, breakLines, callCmd, cancel, colorMap, colorize, commandToJSON, completePrompt, confirm, confirmPrompt, countLines, createAsciiArt, createCancel, createCli, createMultiStep, createRpcCli, createShadowCommand, createStep, datePrompt, defineArgs, defineCommand, deleteLastLine, deleteLastLines, endPrompt, errorHandler, fallbackSymbols, figures, flattenedProperties, fmt, getColumns, getDescription, getEnumChoices, getExactTerminalWidth, getSchemaTypes, getTerminalHeight, getTerminalWidth, group, incompatiblePropertyPairs, input, inputPrompt, intro, introPrompt, isCancel, isOrpcRouter, isTerminalInteractive, isTrpc11Procedure, isTrpc11Router, isValidName, isValidVariant, isWindows, lineByLineConsoleLogger, lineByLineLogger, log, looksLikeInstanceof, looksLikeStandardSchema, looksLikeStandardSchemaFailure, mainSymbols, msg, msgUndo, msgUndoAll, multiselect, multiselectPrompt, nextStepsPrompt, normalizeName, numMultiSelectPrompt, numSelectPrompt, numberPrompt, outro, outroPrompt, parseProcedureInputs, parseRouter, password, pm, prettifyStandardSchemaError, preventUnsupportedTTY, preventWindowsHomeDirRoot, preventWrongTerminalSize, printLineBar, promptify, relinkaAsyncByRemptsDeprecated, relinkaByRemptsDeprecated, reliversePrompts, removeCursor, renderEndLine, renderEndLineInput, restoreCursor, resultPrompt, runMain, select, selectPrompt, selectSimple, setRawMode, showUsage, spinner, startEditor, startPrompt, streamText, streamTextBox, streamTextWithSpinner, symbols, taskProgressPrompt, taskSpinPrompt, text, throwError, toBaseColor, toDotPath, toSolidColor, togglePrompt, typographyMap, useSpinner, variantMap };
2298
+ export type { AllKinds, AnyProcedure, AnyRouter, ArgDefinition, ArgDefinitions, ArrayArgDefinition, BaseArgDefinition, BaseArgProps, BooleanArgDefinition, BorderColorName, CallCmdOptions, CancelValue, ChoiceOptions, ClackPromptsLike, ColorName, Command, CommandContext, CommandHook, CommandJSON, CommandMeta, CommandRun, CommandSpec, CommanderProgramLike, CommandsMap, ConfirmPromptOptions, CreateCallerFactoryLike, DatePromptOptions, DefineCommandOptions, Dependencies, EditorExitResult, EmptyArgs, EnquirerLike, FileBasedOptions, FmtMsgOptions, GroupContext, GroupOptions, GroupStep, GroupSteps, InferArgTypes, InputPromptOptions, InquirerPromptOptions, InquirerPromptsLike, Log, Logger, MessageConfig, MessageKind, MsgConfig, MsgType, MultiselectPromptParams, NumberArgDefinition, OmeletteInstanceLike, OrpcProcedureLike, OrpcRouterLike, OutputColor, ParsedProcedure, PositionalArgDefinition, PreventWrongTerminalSizeOptions, ProgressBar, ProgressBarOptions, PromptContext, PromptOptions, PromptType, Promptable, Prompter, PromptsLike, RenderParams, Result, ResultsType, SelectOption, SelectPromptParams, SeparatorOption, StandardColor, StandardSchemaV1, StandardSchemaV1FailureResult, StandardSchemaV1InferInput, StandardSchemaV1InferOutput, StandardSchemaV1Issue, StandardSchemaV1PathSegment, StandardSchemaV1Props, StandardSchemaV1Result, StandardSchemaV1SuccessResult, StandardSchemaV1Types, StreamOptions, StreamTextOptions, StringArgDefinition, SymbolName, Symbols, TogglePromptParams, Trpc10ProcedureLike, Trpc10RouterLike, Trpc11ProcedureLike, Trpc11ProcedureRecordLike, Trpc11RouterLike, TrpcCli, TrpcCliMeta, TrpcCliParams, TrpcCliRunParams, TrpcServerModuleLike, TypographyName, VariantName$1 as VariantName, inferRouterContext };
@@ -16,12 +16,11 @@ import readline__default from 'node:readline';
16
16
  import { ReadStream, WriteStream } from 'node:tty';
17
17
  import readline$1 from 'node:readline/promises';
18
18
  import { repeat, digit, buildRegExp, startOfString, endOfString } from 'ts-regex-builder';
19
- import path, { resolve, dirname } from '@reliverse/pathkit';
19
+ import path from '@reliverse/pathkit';
20
20
  import fs from '@reliverse/relifso';
21
21
  import { loadConfig } from 'c12';
22
22
  import termkit from 'terminal-kit';
23
23
  import { homedir } from 'node:os';
24
- import { createJiti } from 'jiti';
25
24
  import { reliArgParser } from '@reliverse/reliarg';
26
25
  import { readPackageJSON } from 'pkg-types';
27
26
  import { inspect } from 'node:util';
@@ -3112,310 +3111,230 @@ async function introPrompt(optionsOrTitle) {
3112
3111
  const startPrompt = introPrompt;
3113
3112
  const intro = introPrompt;
3114
3113
 
3115
- const jiti = createJiti(import.meta.url, {
3116
- debug: process$1.env.NODE_ENV === "development",
3117
- fsCache: true,
3118
- sourceMaps: true
3119
- });
3120
- const COMMAND_EXTENSIONS = [".ts", ".js"];
3121
- const COMMAND_FILENAMES = ["cmd.ts", "cmd.js"];
3122
- const getCallerDirectory = async () => {
3123
- const stack = new Error().stack?.split("\n") ?? [];
3124
- const cwd = process$1.cwd();
3125
- if (process$1.env.NODE_ENV === "development") {
3126
- relinka("log", "Stack trace for getCallerDirectory:");
3127
- stack.forEach((line, index) => {
3128
- relinka("log", ` [${index}]: ${line.trim()}`);
3129
- });
3130
- }
3131
- for (const line of stack) {
3132
- const match = /\((.*):(\d+):(\d+)\)/.exec(line) || /at (.*):(\d+):(\d+)/.exec(line);
3133
- if (match?.[1]) {
3134
- const filePath = match[1];
3135
- if (process$1.env.NODE_ENV === "development") {
3136
- relinka("log", `Checking file path: ${filePath}`);
3137
- }
3138
- if (!filePath.includes("node_modules") && !filePath.includes("command-runner") && !filePath.includes("command-typed") && !filePath.includes("launcher-mod") && !filePath.includes("launcher-types") && !filePath.endsWith("mod.mjs") && // Skip compiled output
3139
- !filePath.endsWith("mod.js") && // Skip compiled output
3140
- !filePath.endsWith("mod.ts")) {
3141
- try {
3142
- const fileDir = dirname(filePath);
3143
- let currentDir2 = fileDir;
3144
- let packageRoot = null;
3145
- while (currentDir2 !== dirname(currentDir2)) {
3146
- try {
3147
- const packageJsonPath = resolve(currentDir2, "package.json");
3148
- if (await fs.pathExists(packageJsonPath)) {
3149
- packageRoot = currentDir2;
3150
- if (process$1.env.NODE_ENV === "development") {
3151
- relinka("log", `Found package.json at: ${packageRoot}`);
3152
- }
3153
- const cwdPackageJsonPath = resolve(cwd, "package.json");
3154
- if (await fs.pathExists(cwdPackageJsonPath)) {
3155
- try {
3156
- const callerPackage = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
3157
- const cwdPackage = JSON.parse(await fs.readFile(cwdPackageJsonPath, "utf-8"));
3158
- if (callerPackage.name !== cwdPackage.name || callerPackage.version !== cwdPackage.version) {
3159
- if (process$1.env.NODE_ENV === "development") {
3160
- relinka("log", `Using caller package root: ${packageRoot} (${callerPackage.name}@${callerPackage.version})`);
3161
- }
3162
- return packageRoot;
3163
- }
3164
- } catch {
3165
- if (resolve(packageRoot) !== resolve(cwd)) {
3166
- if (process$1.env.NODE_ENV === "development") {
3167
- relinka("log", `Using caller package root (different path): ${packageRoot}`);
3168
- }
3169
- return packageRoot;
3170
- }
3171
- }
3172
- } else {
3173
- if (process$1.env.NODE_ENV === "development") {
3174
- relinka("log", `Using caller package root (no CWD package.json): ${packageRoot}`);
3175
- }
3176
- return packageRoot;
3177
- }
3178
- break;
3179
- }
3180
- } catch {
3181
- }
3182
- currentDir2 = dirname(currentDir2);
3183
- }
3184
- const resolvedFileDir = resolve(fileDir);
3185
- const resolvedCwd = resolve(cwd);
3186
- if (resolvedFileDir !== resolvedCwd && !resolvedFileDir.startsWith(resolvedCwd)) {
3187
- if (process$1.env.NODE_ENV === "development") {
3188
- relinka("log", `Using caller directory (different from CWD): ${fileDir}`);
3189
- }
3190
- return packageRoot || fileDir;
3191
- }
3192
- } catch {
3193
- continue;
3194
- }
3195
- }
3114
+ async function callCmd(command, input, options = {}) {
3115
+ const { autoExit = false, debug = false, useLifecycleHooks = true, parserOptions = {} } = options;
3116
+ const debugLog = (...args) => {
3117
+ if (debug) {
3118
+ relinka("log", "[callCmd DEBUG]", ...args);
3196
3119
  }
3197
- }
3198
- for (const line of stack) {
3199
- const match = /\((.*):(\d+):(\d+)\)/.exec(line) || /at (.*):(\d+):(\d+)/.exec(line);
3200
- if (match?.[1]) {
3201
- const filePath = match[1];
3202
- if (filePath.includes("node_modules")) {
3203
- try {
3204
- const nodeModulesMatch = filePath.match(/(.+\/node_modules\/[^\/]+)/);
3205
- if (nodeModulesMatch?.[1]) {
3206
- const packageDir = nodeModulesMatch[1];
3207
- const packageJsonPath = resolve(packageDir, "package.json");
3208
- if (await fs.pathExists(packageJsonPath)) {
3209
- if (process$1.env.NODE_ENV === "development") {
3210
- relinka("log", `Found command package in node_modules: ${packageDir}`);
3211
- }
3212
- return packageDir;
3213
- }
3214
- }
3215
- } catch {
3216
- continue;
3217
- }
3120
+ };
3121
+ debugLog("Calling command with input:", input);
3122
+ debugLog("Command meta:", command.meta);
3123
+ try {
3124
+ let ctx;
3125
+ if (Array.isArray(input)) {
3126
+ debugLog("Processing argv input:", input);
3127
+ ctx = await parseArgsFromArgv(command, input, parserOptions);
3128
+ } else {
3129
+ debugLog("Processing object input:", input);
3130
+ ctx = await createContextFromArgs(command, input);
3131
+ }
3132
+ debugLog("Created context:", ctx);
3133
+ if (useLifecycleHooks && command.onCmdInit) {
3134
+ debugLog("Calling onCmdInit hook");
3135
+ await command.onCmdInit(ctx);
3136
+ }
3137
+ if (command.run) {
3138
+ debugLog("Executing command run function");
3139
+ await command.run(ctx);
3140
+ } else {
3141
+ const error = "Command has no run function defined";
3142
+ debugLog(error);
3143
+ if (autoExit) {
3144
+ relinka("error", error);
3145
+ process$1.exit(1);
3218
3146
  }
3147
+ throw new Error(error);
3148
+ }
3149
+ if (useLifecycleHooks && command.onCmdExit) {
3150
+ debugLog("Calling onCmdExit hook");
3151
+ await command.onCmdExit(ctx);
3152
+ }
3153
+ debugLog("Command execution completed successfully");
3154
+ return ctx;
3155
+ } catch (error) {
3156
+ debugLog("Error during command execution:", error);
3157
+ if (autoExit) {
3158
+ relinka("error", `Error while executing command: ${String(error)}`);
3159
+ process$1.exit(1);
3219
3160
  }
3161
+ throw error;
3220
3162
  }
3221
- let currentDir = cwd;
3222
- while (currentDir !== dirname(currentDir)) {
3223
- try {
3224
- const packageJsonPath = resolve(currentDir, "package.json");
3225
- if (await fs.pathExists(packageJsonPath)) {
3226
- if (process$1.env.NODE_ENV === "development") {
3227
- relinka("log", `Found package.json at: ${currentDir}`);
3228
- }
3229
- return currentDir;
3230
- }
3231
- } catch {
3163
+ }
3164
+ async function parseArgsFromArgv(command, argv, parserOptions) {
3165
+ const booleanKeys = Object.keys(command.args || {}).filter(
3166
+ (k) => command.args?.[k]?.type === "boolean"
3167
+ );
3168
+ const defaultMap = {};
3169
+ for (const [argKey, def] of Object.entries(command.args || {})) {
3170
+ if (def.type === "boolean") {
3171
+ defaultMap[argKey] = def.default !== void 0 ? def.default : false;
3172
+ } else if (def.default !== void 0) {
3173
+ defaultMap[argKey] = def.type === "array" && typeof def.default === "string" ? [def.default] : def.default;
3232
3174
  }
3233
- currentDir = dirname(currentDir);
3234
3175
  }
3235
- if (process$1.env.NODE_ENV === "development") {
3236
- relinka("log", `No suitable caller found, using cwd: ${cwd}`);
3176
+ const mergedParserOptions = {
3177
+ ...parserOptions,
3178
+ boolean: [...parserOptions.boolean || [], ...booleanKeys],
3179
+ defaults: { ...defaultMap, ...parserOptions.defaults || {} }
3180
+ };
3181
+ const parsed = reliArgParser(argv, mergedParserOptions);
3182
+ const finalArgs = {};
3183
+ const positionalKeys = Object.keys(command.args || {}).filter(
3184
+ (k) => command.args?.[k]?.type === "positional"
3185
+ );
3186
+ const leftoverPositionals = [...parsed._ || []];
3187
+ for (let i = 0; i < positionalKeys.length; i++) {
3188
+ const key = positionalKeys[i];
3189
+ if (!key || !command.args) continue;
3190
+ const def = command.args[key];
3191
+ const val = leftoverPositionals[i];
3192
+ finalArgs[key] = val != null && def ? castArgValue$1(def, val, key) : def?.default;
3237
3193
  }
3238
- return process$1.cwd();
3239
- };
3240
- const getNodeModulesPackageDirsFromStack = async () => {
3241
- const stack = new Error().stack?.split("\n") ?? [];
3242
- const packageDirs = /* @__PURE__ */ new Set();
3243
- for (const line of stack) {
3244
- const match = /\((.*):(\d+):(\d+)\)/.exec(line) || /at (.*):(\d+):(\d+)/.exec(line);
3245
- if (!match?.[1]) continue;
3246
- const filePath = match[1];
3247
- if (!filePath.includes("node_modules")) continue;
3248
- try {
3249
- const nodeModulesMatch = filePath.match(/(.+\\node_modules\\(?:@[^\\/]+\\)?[^\\/]+)|(.+\/node_modules\/(?:@[^\/]+\/)?[^\/]+)/);
3250
- const packageDir = (nodeModulesMatch?.[1] || nodeModulesMatch?.[2])?.trim();
3251
- if (!packageDir) continue;
3252
- const packageJsonPath = resolve(packageDir, "package.json");
3253
- if (await fs.pathExists(packageJsonPath)) {
3254
- packageDirs.add(packageDir);
3194
+ const otherKeys = Object.keys(command.args || {}).filter(
3195
+ (k) => command.args?.[k]?.type !== "positional"
3196
+ );
3197
+ for (const key of otherKeys) {
3198
+ const def = command.args?.[key];
3199
+ if (!def) continue;
3200
+ let rawVal = parsed[key];
3201
+ if (def.type === "array" && rawVal !== void 0 && !Array.isArray(rawVal)) {
3202
+ rawVal = [rawVal];
3203
+ }
3204
+ const casted = rawVal !== void 0 ? castArgValue$1(def, rawVal, key) : def.default;
3205
+ const argUsed = rawVal !== void 0 && (def.type === "boolean" ? casted === true : true);
3206
+ if (casted == null && def.required) {
3207
+ throw new Error(`Missing required argument: --${key}`);
3208
+ }
3209
+ if (argUsed && def.dependencies?.length) {
3210
+ const missingDeps = def.dependencies.filter((d) => {
3211
+ const depVal = parsed[d] ?? defaultMap[d];
3212
+ return !depVal;
3213
+ });
3214
+ if (missingDeps.length > 0) {
3215
+ const depsList = missingDeps.map((d) => `--${d}`).join(", ");
3216
+ throw new Error(
3217
+ `Argument --${key} can only be used when ${depsList} ${missingDeps.length === 1 ? "is" : "are"} set`
3218
+ );
3255
3219
  }
3256
- } catch {
3257
3220
  }
3221
+ finalArgs[key] = def.type === "boolean" ? Boolean(casted) : casted;
3258
3222
  }
3259
- return Array.from(packageDirs);
3260
- };
3261
- const tryLoadCommand = async (path) => {
3262
- if (!await fs.pathExists(path)) return null;
3263
- try {
3264
- const cmd = await jiti.import(path, { default: true });
3265
- return cmd;
3266
- } catch {
3267
- relinka("log", `Failed to load ${path} as a command file`);
3268
- return null;
3269
- }
3270
- };
3271
- const generateCandidatePaths = async (resolvedPath) => {
3272
- if (!await fs.pathExists(resolvedPath)) {
3273
- return COMMAND_EXTENSIONS.map((ext) => `${resolvedPath}${ext}`);
3274
- }
3275
- if (await fs.isDirectory(resolvedPath)) {
3276
- return COMMAND_FILENAMES.map((filename) => resolve(resolvedPath, filename));
3223
+ return {
3224
+ args: finalArgs,
3225
+ raw: argv
3226
+ };
3227
+ }
3228
+ async function createContextFromArgs(command, inputArgs) {
3229
+ const finalArgs = {};
3230
+ for (const [key, def] of Object.entries(command.args || {})) {
3231
+ const inputValue = inputArgs[key];
3232
+ let value;
3233
+ if (inputValue !== void 0) {
3234
+ value = castArgValue$1(def, inputValue, key);
3235
+ } else if (def.default !== void 0) {
3236
+ value = def.type === "array" && typeof def.default === "string" ? [def.default] : def.default;
3237
+ } else if (def.type === "boolean") {
3238
+ value = false;
3239
+ } else {
3240
+ value = void 0;
3241
+ }
3242
+ if (value == null && def.required) {
3243
+ throw new Error(`Missing required argument: ${key}`);
3244
+ }
3245
+ if (value != null && def.dependencies?.length) {
3246
+ const missingDeps = def.dependencies.filter((d) => {
3247
+ const depVal = inputArgs[d];
3248
+ return !depVal;
3249
+ });
3250
+ if (missingDeps.length > 0) {
3251
+ const depsList = missingDeps.join(", ");
3252
+ throw new Error(
3253
+ `Argument '${key}' can only be used when ${depsList} ${missingDeps.length === 1 ? "is" : "are"} provided`
3254
+ );
3255
+ }
3256
+ }
3257
+ finalArgs[key] = value;
3277
3258
  }
3278
- return [resolvedPath];
3279
- };
3280
- const generateAlternativePaths = async (cmdPath, callerDir) => {
3281
- const normalizedCmdPath = cmdPath.replace(/^\.\//, "");
3282
- const paths = [];
3283
- const commonCommandLocations = [
3284
- // Direct command file
3285
- resolve(callerDir, `${normalizedCmdPath}.ts`),
3286
- resolve(callerDir, `${normalizedCmdPath}.js`),
3287
- // Command in cmd subdirectory
3288
- resolve(callerDir, normalizedCmdPath, "cmd.ts"),
3289
- resolve(callerDir, normalizedCmdPath, "cmd.js"),
3290
- // Command in app subdirectory
3291
- resolve(callerDir, "app", normalizedCmdPath, "cmd.ts"),
3292
- resolve(callerDir, "app", normalizedCmdPath, "cmd.js"),
3293
- // Command in src subdirectory
3294
- resolve(callerDir, "src", normalizedCmdPath, "cmd.ts"),
3295
- resolve(callerDir, "src", normalizedCmdPath, "cmd.js"),
3296
- // Command in src/app subdirectory
3297
- resolve(callerDir, "src", "app", normalizedCmdPath, "cmd.ts"),
3298
- resolve(callerDir, "src", "app", normalizedCmdPath, "cmd.js"),
3299
- // Command in src-ts subdirectory
3300
- resolve(callerDir, "src-ts", normalizedCmdPath, "cmd.ts"),
3301
- resolve(callerDir, "src-ts", normalizedCmdPath, "cmd.js"),
3302
- // Command in src-ts/app subdirectory (for dler-like structures)
3303
- resolve(callerDir, "src-ts", "app", normalizedCmdPath, "cmd.ts"),
3304
- resolve(callerDir, "src-ts", "app", normalizedCmdPath, "cmd.js"),
3305
- // Command in lib subdirectory
3306
- resolve(callerDir, "lib", normalizedCmdPath, "cmd.ts"),
3307
- resolve(callerDir, "lib", normalizedCmdPath, "cmd.js"),
3308
- // Command in lib/app subdirectory
3309
- resolve(callerDir, "lib", "app", normalizedCmdPath, "cmd.ts"),
3310
- resolve(callerDir, "lib", "app", normalizedCmdPath, "cmd.js"),
3311
- // Command in dist subdirectory (compiled)
3312
- resolve(callerDir, "dist", normalizedCmdPath, "cmd.js"),
3313
- resolve(callerDir, "dist", "app", normalizedCmdPath, "cmd.js"),
3314
- // Command in bin subdirectory
3315
- resolve(callerDir, "bin", normalizedCmdPath, "cmd.ts"),
3316
- resolve(callerDir, "bin", normalizedCmdPath, "cmd.js"),
3317
- // Command in bin/app subdirectory (common for CLI tools)
3318
- resolve(callerDir, "bin", "app", normalizedCmdPath, "cmd.ts"),
3319
- resolve(callerDir, "bin", "app", normalizedCmdPath, "cmd.js"),
3320
- // Command in commands subdirectory
3321
- resolve(callerDir, "commands", normalizedCmdPath, "cmd.ts"),
3322
- resolve(callerDir, "commands", normalizedCmdPath, "cmd.js"),
3323
- // Command in cli subdirectory
3324
- resolve(callerDir, "cli", normalizedCmdPath, "cmd.ts"),
3325
- resolve(callerDir, "cli", normalizedCmdPath, "cmd.js"),
3326
- // Command in cli/commands subdirectory
3327
- resolve(callerDir, "cli", "commands", normalizedCmdPath, "cmd.ts"),
3328
- resolve(callerDir, "cli", "commands", normalizedCmdPath, "cmd.js"),
3329
- // Command in tools subdirectory
3330
- resolve(callerDir, "tools", normalizedCmdPath, "cmd.ts"),
3331
- resolve(callerDir, "tools", normalizedCmdPath, "cmd.js"),
3332
- // Command in scripts subdirectory
3333
- resolve(callerDir, "scripts", normalizedCmdPath, "cmd.ts"),
3334
- resolve(callerDir, "scripts", normalizedCmdPath, "cmd.js")
3335
- ];
3336
- for (const path of commonCommandLocations) {
3337
- if (await fs.pathExists(path)) {
3338
- paths.push(path);
3259
+ return {
3260
+ args: finalArgs,
3261
+ raw: []
3262
+ // No raw argv for object input
3263
+ };
3264
+ }
3265
+ function castArgValue$1(def, rawVal, argName) {
3266
+ if (rawVal == null) {
3267
+ if (def.type === "array" && typeof def.default === "string") {
3268
+ return [def.default];
3339
3269
  }
3270
+ return def.default ?? void 0;
3340
3271
  }
3341
- return paths;
3342
- };
3343
- const createCommandNotFoundError = (cmdPath, searchedPaths) => new Error(
3344
- `No command file found for "${cmdPath}". Expected to find either:
3345
- - A valid command file at the specified path
3346
- - A directory containing cmd.ts or cmd.js
3347
- - A file path that can be resolved with .ts or .js extension
3348
-
3349
- Searched paths: ${searchedPaths.join(", ")}
3350
- Please ensure one of these exists and exports a default command.`
3351
- );
3352
- const createLoadError = (cmdPath, originalError) => new Error(
3353
- `Failed to load command from "${cmdPath}"
3354
-
3355
- For developers: Ensure the command file:
3356
- - Exists and is accessible
3357
- - Exports a default command (e.g., export default defineCommand({...}))
3358
- - Is a valid TypeScript/JavaScript module
3359
-
3360
- Original error: ${originalError instanceof Error ? originalError.message : String(originalError)}`
3361
- );
3362
- async function loadCommand(cmdPath) {
3363
- try {
3364
- const callerDir = await getCallerDirectory();
3365
- const normalizedPath = cmdPath.replace(/^\.\//, "");
3366
- const resolvedPath = resolve(callerDir, normalizedPath);
3367
- if (process$1.env.NODE_ENV === "development") {
3368
- relinka("log", `Loading command: ${cmdPath}`);
3369
- relinka("log", `Caller directory: ${callerDir}`);
3370
- relinka("log", `Normalized path: ${normalizedPath}`);
3371
- relinka("log", `Resolved path: ${resolvedPath}`);
3372
- }
3373
- const searchedPaths = [];
3374
- const baseDirs = [callerDir];
3375
- const stackPackageDirs = await getNodeModulesPackageDirsFromStack();
3376
- for (const dir of stackPackageDirs) {
3377
- if (!baseDirs.includes(dir)) baseDirs.push(dir);
3378
- }
3379
- for (const baseDir of baseDirs) {
3380
- const alternativePaths = await generateAlternativePaths(cmdPath, baseDir);
3381
- if (process$1.env.NODE_ENV === "development") {
3382
- relinka("log", `Trying alternative paths in base ${baseDir}: ${alternativePaths.join(", ")}`);
3383
- }
3384
- searchedPaths.push(...alternativePaths);
3385
- for (const path of alternativePaths) {
3386
- const command = await tryLoadCommand(path);
3387
- if (command) {
3388
- if (process$1.env.NODE_ENV === "development") {
3389
- relinka("log", `Successfully loaded command from alternative path: ${path}`);
3390
- }
3391
- return command;
3392
- }
3272
+ let castedValue;
3273
+ switch (def.type) {
3274
+ case "boolean":
3275
+ if (typeof rawVal === "string") {
3276
+ const lower = rawVal.toLowerCase();
3277
+ if (lower === "true") castedValue = true;
3278
+ else if (lower === "false") castedValue = false;
3279
+ else castedValue = Boolean(rawVal);
3280
+ } else {
3281
+ castedValue = Boolean(rawVal);
3282
+ }
3283
+ if (def.allowed && !def.allowed.includes(castedValue)) {
3284
+ throw new Error(
3285
+ `Invalid value for ${argName}: ${rawVal}. Allowed values are: ${def.allowed.join(", ")}`
3286
+ );
3287
+ }
3288
+ return castedValue;
3289
+ case "string":
3290
+ castedValue = typeof rawVal === "string" ? rawVal : String(rawVal);
3291
+ if (def.allowed && !def.allowed.includes(castedValue)) {
3292
+ throw new Error(
3293
+ `Invalid value for ${argName}: ${rawVal}. Allowed values are: ${def.allowed.join(", ")}`
3294
+ );
3295
+ }
3296
+ return castedValue;
3297
+ case "number": {
3298
+ const n = Number(rawVal);
3299
+ if (Number.isNaN(n)) {
3300
+ throw new Error(`Invalid number provided for ${argName}: ${rawVal}`);
3301
+ }
3302
+ if (def.allowed && !def.allowed.includes(n)) {
3303
+ throw new Error(
3304
+ `Invalid value for ${argName}: ${rawVal}. Allowed values are: ${def.allowed.join(", ")}`
3305
+ );
3393
3306
  }
3307
+ return n;
3394
3308
  }
3395
- const looksLikeExplicitPath = /[\\\/]|\.ts$|\.js$/.test(normalizedPath);
3396
- if (looksLikeExplicitPath) {
3397
- const candidatePaths = await generateCandidatePaths(resolvedPath);
3398
- if (process$1.env.NODE_ENV === "development") {
3399
- relinka("log", `Candidate paths: ${candidatePaths.join(", ")}`);
3309
+ case "positional":
3310
+ castedValue = String(rawVal);
3311
+ if (def.allowed && !def.allowed.includes(castedValue)) {
3312
+ throw new Error(
3313
+ `Invalid value for ${argName}: ${rawVal}. Allowed values are: ${def.allowed.join(", ")}`
3314
+ );
3400
3315
  }
3401
- searchedPaths.push(...candidatePaths);
3402
- for (const path of candidatePaths) {
3403
- const command = await tryLoadCommand(path);
3404
- if (command) {
3405
- if (process$1.env.NODE_ENV === "development") {
3406
- relinka("log", `Successfully loaded command from: ${path}`);
3316
+ return castedValue;
3317
+ case "array": {
3318
+ const arrVal = Array.isArray(rawVal) ? rawVal : [String(rawVal)];
3319
+ const result = [];
3320
+ for (let v of arrVal.map(String)) {
3321
+ if (v.startsWith("[") && v.endsWith("]")) {
3322
+ v = v.slice(1, -1);
3323
+ }
3324
+ const parts = v.split(/\s*,\s*/).filter(Boolean);
3325
+ for (const p of parts) {
3326
+ if (def.allowed && !def.allowed.includes(p)) {
3327
+ throw new Error(
3328
+ `Invalid value in array ${argName}: ${p}. Allowed values are: ${def.allowed.join(", ")}`
3329
+ );
3407
3330
  }
3408
- return command;
3409
3331
  }
3332
+ result.push(...parts);
3410
3333
  }
3334
+ return result;
3411
3335
  }
3412
- throw createCommandNotFoundError(cmdPath, searchedPaths);
3413
- } catch (error) {
3414
- if (error instanceof Error && error.message.includes("No command file found")) {
3415
- throw error;
3416
- }
3417
- relinka("error", `Failed to load command from ${cmdPath}:`, error);
3418
- throw createLoadError(cmdPath, error);
3336
+ default:
3337
+ return rawVal;
3419
3338
  }
3420
3339
  }
3421
3340
 
@@ -6250,110 +6169,6 @@ function normalizeArgv(argv) {
6250
6169
  }
6251
6170
  return normalized;
6252
6171
  }
6253
- async function runCmdWithSubcommands(command, argv = [], parserOptions = {}) {
6254
- const normalizedArgv = normalizeArgv(argv);
6255
- let currentCommand = command;
6256
- let currentArgv = normalizedArgv;
6257
- while (currentCommand.commands && currentArgv.length > 0 && currentArgv[0] && !isFlag(currentArgv[0])) {
6258
- const [maybeSub, ...restArgv] = currentArgv;
6259
- let subSpec;
6260
- for (const [key, spec] of Object.entries(currentCommand.commands)) {
6261
- if (key === maybeSub) {
6262
- subSpec = spec;
6263
- break;
6264
- }
6265
- try {
6266
- const cmd = await loadSubCommand(spec);
6267
- if (cmd.meta?.aliases?.includes(maybeSub)) {
6268
- subSpec = spec;
6269
- break;
6270
- }
6271
- } catch (err) {
6272
- debugLog(`Error checking alias for command ${key}:`, err);
6273
- }
6274
- }
6275
- if (!subSpec) break;
6276
- const loaded = await loadSubCommand(subSpec);
6277
- currentCommand = loaded;
6278
- currentArgv = restArgv;
6279
- }
6280
- return await runCommandWithArgs(currentCommand, currentArgv, {
6281
- ...parserOptions,
6282
- autoExit: false
6283
- // Don't exit process in programmatic usage
6284
- });
6285
- }
6286
- async function runCmd(command, argv = [], parserOptions = {}) {
6287
- const normalizedArgv = normalizeArgv(argv);
6288
- const booleanKeys = Object.keys(command.args || {}).filter(
6289
- (k) => command.args?.[k]?.type === "boolean"
6290
- );
6291
- const defaultMap = {};
6292
- for (const [argKey, def] of Object.entries(command.args || {})) {
6293
- if (def.type === "boolean") {
6294
- defaultMap[argKey] = def.default !== void 0 ? def.default : false;
6295
- } else if (def.default !== void 0) {
6296
- defaultMap[argKey] = def.type === "array" && typeof def.default === "string" ? [def.default] : def.default;
6297
- }
6298
- }
6299
- const mergedParserOptions = {
6300
- ...parserOptions,
6301
- boolean: [...parserOptions.boolean || [], ...booleanKeys],
6302
- defaults: { ...defaultMap, ...parserOptions.defaults || {} }
6303
- };
6304
- const parsed = reliArgParser(normalizedArgv, mergedParserOptions);
6305
- debugLog("Parsed arguments (runCmd):", parsed);
6306
- const finalArgs = {};
6307
- const positionalKeys = Object.keys(command.args || {}).filter(
6308
- (k) => command.args?.[k]?.type === "positional"
6309
- );
6310
- const leftoverPositionals = [...parsed._ || []];
6311
- for (let i = 0; i < positionalKeys.length; i++) {
6312
- const key = positionalKeys[i];
6313
- if (!key || !command.args) continue;
6314
- const def = command.args[key];
6315
- const val = leftoverPositionals[i];
6316
- finalArgs[key] = val != null && def ? castArgValue(def, val, key) : def?.default;
6317
- }
6318
- const otherKeys = Object.keys(command.args || {}).filter(
6319
- (k) => command.args?.[k]?.type !== "positional"
6320
- );
6321
- for (const key of otherKeys) {
6322
- const def = command.args?.[key];
6323
- if (!def) continue;
6324
- let rawVal = parsed[key];
6325
- if (def.type === "array" && rawVal !== void 0 && !Array.isArray(rawVal)) {
6326
- rawVal = [rawVal];
6327
- }
6328
- const casted = rawVal !== void 0 ? castArgValue(def, rawVal, key) : def.default;
6329
- const argUsed = rawVal !== void 0 && (def.type === "boolean" ? casted === true : true);
6330
- if (casted == null && def.required) {
6331
- throw new Error(`Missing required argument: --${key}`);
6332
- }
6333
- if (argUsed && def.dependencies?.length) {
6334
- const missingDeps = def.dependencies.filter((d) => {
6335
- const depVal = parsed[d] ?? defaultMap[d];
6336
- return !depVal;
6337
- });
6338
- if (missingDeps.length) {
6339
- const depsList = missingDeps.map((d) => `--${d}`).join(", ");
6340
- throw new Error(
6341
- `Argument --${key} can only be used when ${depsList} ${missingDeps.length === 1 ? "is" : "are"} set`
6342
- );
6343
- }
6344
- }
6345
- finalArgs[key] = def.type === "boolean" ? Boolean(casted) : casted;
6346
- }
6347
- const ctx = {
6348
- args: finalArgs,
6349
- raw: argv
6350
- };
6351
- if (typeof command.run === "function") {
6352
- await command.run(ctx);
6353
- } else {
6354
- throw new Error("Command has no run() handler.");
6355
- }
6356
- }
6357
6172
  function getParsedContext(command, argv, parserOptions) {
6358
6173
  const normalizedArgv = normalizeArgv(argv);
6359
6174
  const booleanKeys = Object.keys(command.args || {}).filter(
@@ -6461,65 +6276,6 @@ function levenshteinDistance(a, b) {
6461
6276
  return matrix[b.length][a.length];
6462
6277
  }
6463
6278
 
6464
- function argsToStringArray(args) {
6465
- const result = [];
6466
- for (const [key, value] of Object.entries(args)) {
6467
- if (value === void 0 || value === null) continue;
6468
- if (typeof value === "boolean") {
6469
- result.push(`--${key}=${value}`);
6470
- } else if (Array.isArray(value)) {
6471
- result.push(`--${key}=${value.join(",")}`);
6472
- } else {
6473
- result.push(`--${key}=${String(value)}`);
6474
- }
6475
- }
6476
- return result;
6477
- }
6478
- async function createCallCmd() {
6479
- return async function callCmd(cmdName, args) {
6480
- try {
6481
- const command = await loadCommand(cmdName);
6482
- const stringArgs = args ? argsToStringArray(args) : [];
6483
- await runCmd(command, stringArgs);
6484
- } catch (error) {
6485
- console.error(`Error running command '${String(cmdName)}':`, error);
6486
- throw error;
6487
- }
6488
- };
6489
- }
6490
- async function createGetTypedCmd() {
6491
- return async function getTypedCmd(cmdName) {
6492
- const command = await loadCommand(cmdName);
6493
- return {
6494
- command,
6495
- run: async (args) => {
6496
- const stringArgs = args ? argsToStringArray(args) : [];
6497
- await runCmd(command, stringArgs);
6498
- }
6499
- };
6500
- };
6501
- }
6502
- async function callCmdImpl(cmdName, args) {
6503
- try {
6504
- const command = await loadCommand(cmdName);
6505
- const stringArgs = args ? argsToStringArray(args) : [];
6506
- await runCmd(command, stringArgs);
6507
- } catch (error) {
6508
- console.error(`Error running command '${String(cmdName)}':`, error);
6509
- throw error;
6510
- }
6511
- }
6512
- async function getTypedCmdImpl(cmdName) {
6513
- const command = await loadCommand(cmdName);
6514
- return {
6515
- command,
6516
- run: async (args) => {
6517
- const stringArgs = args ? argsToStringArray(args) : [];
6518
- await runCmd(command, stringArgs);
6519
- }
6520
- };
6521
- }
6522
-
6523
6279
  const runMain = createCli;
6524
6280
 
6525
6281
  const log = relinka;
@@ -8462,4 +8218,4 @@ function normalizeName(name) {
8462
8218
  return lastSegment.replace(/[^a-zA-Z0-9-]/g, "");
8463
8219
  }
8464
8220
 
8465
- export { CANCEL, CliValidationError, FailedToExitError, StandardSchemaV1Error, TrpcCommand, addCompletions, animateText, animationMap, anykeyPrompt, applyVariant, argsToStringArray, bar, block, breakLines, callCmdImpl, cancel, colorMap, colorize, commandToJSON, completePrompt, confirm, confirmPrompt, countLines$1 as countLines, createAsciiArt, createCallCmd, createCancel, createCli, createGetTypedCmd, createMultiStep, createRpcCli, createShadowCommand, createStep, datePrompt, defineArgs, defineCommand, deleteLastLine, deleteLastLines, endPrompt, errorHandler, fallbackSymbols, figures, flattenedProperties, fmt, getColumns, getDescription, getEnumChoices, getExactTerminalWidth, getSchemaTypes, getTerminalHeight, getTerminalWidth$1 as getTerminalWidth, getTypedCmdImpl, group, incompatiblePropertyPairs, input, inputPrompt, intro, introPrompt, isCancel, isOrpcRouter, isTerminalInteractive, isTrpc11Procedure, isTrpc11Router, isValidName, isValidVariant, isWindows, lineByLineConsoleLogger, lineByLineLogger, loadCommand, log, looksLikeInstanceof, looksLikeStandardSchema, looksLikeStandardSchemaFailure, mainSymbols, msg, msgUndo, msgUndoAll, multiselect, multiselectPrompt, nextStepsPrompt, normalizeName, numMultiSelectPrompt, numSelectPrompt, numberPrompt, outro, outroPrompt, parseProcedureInputs, parseRouter, password, pm, prettifyStandardSchemaError, preventUnsupportedTTY, preventWindowsHomeDirRoot, preventWrongTerminalSize, printLineBar, promptify, relinkaAsyncByRemptsDeprecated, relinkaByRemptsDeprecated, reliversePrompts, removeCursor, renderEndLine, renderEndLineInput, restoreCursor, resultPrompt, runCmd, runCmdWithSubcommands, runMain, select, selectPrompt, selectSimple, setRawMode, showUsage, spinner, startEditor, startPrompt, streamText, streamTextBox, streamTextWithSpinner, symbols, taskProgressPrompt, taskSpinPrompt, text, throwError, toBaseColor, toDotPath, toSolidColor, togglePrompt, typographyMap, useSpinner, variantMap };
8221
+ export { CANCEL, CliValidationError, FailedToExitError, StandardSchemaV1Error, TrpcCommand, addCompletions, animateText, animationMap, anykeyPrompt, applyVariant, bar, block, breakLines, callCmd, cancel, colorMap, colorize, commandToJSON, completePrompt, confirm, confirmPrompt, countLines$1 as countLines, createAsciiArt, createCancel, createCli, createMultiStep, createRpcCli, createShadowCommand, createStep, datePrompt, defineArgs, defineCommand, deleteLastLine, deleteLastLines, endPrompt, errorHandler, fallbackSymbols, figures, flattenedProperties, fmt, getColumns, getDescription, getEnumChoices, getExactTerminalWidth, getSchemaTypes, getTerminalHeight, getTerminalWidth$1 as getTerminalWidth, group, incompatiblePropertyPairs, input, inputPrompt, intro, introPrompt, isCancel, isOrpcRouter, isTerminalInteractive, isTrpc11Procedure, isTrpc11Router, isValidName, isValidVariant, isWindows, lineByLineConsoleLogger, lineByLineLogger, log, looksLikeInstanceof, looksLikeStandardSchema, looksLikeStandardSchemaFailure, mainSymbols, msg, msgUndo, msgUndoAll, multiselect, multiselectPrompt, nextStepsPrompt, normalizeName, numMultiSelectPrompt, numSelectPrompt, numberPrompt, outro, outroPrompt, parseProcedureInputs, parseRouter, password, pm, prettifyStandardSchemaError, preventUnsupportedTTY, preventWindowsHomeDirRoot, preventWrongTerminalSize, printLineBar, promptify, relinkaAsyncByRemptsDeprecated, relinkaByRemptsDeprecated, reliversePrompts, removeCursor, renderEndLine, renderEndLineInput, restoreCursor, resultPrompt, runMain, select, selectPrompt, selectSimple, setRawMode, showUsage, spinner, startEditor, startPrompt, streamText, streamTextBox, streamTextWithSpinner, symbols, taskProgressPrompt, taskSpinPrompt, text, throwError, toBaseColor, toDotPath, toSolidColor, togglePrompt, typographyMap, useSpinner, variantMap };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@reliverse/rempts",
3
3
  "author": "reliverse",
4
- "version": "1.7.49",
4
+ "version": "1.7.50",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "main": "./dist-npm/bin/mod.mjs",
@@ -36,8 +36,8 @@
36
36
  ],
37
37
  "description": "@reliverse/rempts is a modern, type-safe toolkit for building delightful cli experiences. it's fast, flexible, and made for developer happiness. file-based commands keep things simple.",
38
38
  "scripts": {
39
+ "dev": "bun example/cli.ts",
39
40
  "pub": "bun unbuild && bun publish",
40
- "dev": "node -e 'console.log(`👉 bun dev:[prompts,modern,classic]`)'",
41
41
  "dev:prompts": "bun example/prompts/mod.ts",
42
42
  "dev:modern": "bun example/launcher/modern.ts",
43
43
  "dev:classic": "bun example/launcher/classic.ts",
@@ -51,12 +51,12 @@
51
51
  "@clack/prompts": "^0.11.0",
52
52
  "@figliolia/chalk-animation": "^1.0.4",
53
53
  "@inquirer/prompts": "^7.8.3",
54
- "@orpc/server": "^1.8.3",
54
+ "@orpc/server": "^1.8.4",
55
55
  "@reliverse/pathkit": "^1.3.4",
56
56
  "@reliverse/reliarg": "^1.0.3",
57
57
  "@reliverse/relico": "^1.3.5",
58
58
  "@reliverse/relifso": "^1.4.5",
59
- "@reliverse/relinka": "^1.5.5",
59
+ "@reliverse/relinka": "^1.5.6",
60
60
  "@reliverse/runtime": "^1.0.3",
61
61
  "@trpc/server": "^11.5.0",
62
62
  "ansi-escapes": "^7.0.0",
@@ -85,13 +85,13 @@
85
85
  "unicorn-magic": "^0.3.0",
86
86
  "valibot": "^1.1.0",
87
87
  "wrap-ansi": "^9.0.0",
88
- "zod": "^4.0.17",
88
+ "zod": "^4.1.0",
89
89
  "zod-to-json-schema": "^3.24.6"
90
90
  },
91
91
  "devDependencies": {
92
- "@biomejs/biome": "^2.2.0",
93
- "@orpc/contract": "^1.8.3",
94
- "@reliverse/dler": "1.7.96",
92
+ "@biomejs/biome": "^2.2.2",
93
+ "@orpc/contract": "^1.8.4",
94
+ "@reliverse/dler": "1.7.101",
95
95
  "@reliverse/rse": "^1.7.12",
96
96
  "@total-typescript/ts-reset": "^0.6.1",
97
97
  "@types/bun": "^1.2.20",