@nmakarov/cli-toolkit 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1751 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/args/index.ts
9
+ import { readFileSync, existsSync } from "fs";
10
+ import { resolve, dirname, basename, extname, join, isAbsolute } from "path";
11
+ import { config } from "dotenv";
12
+ var Args = class {
13
+ args = {};
14
+ flags = {};
15
+ options = {};
16
+ commands = [];
17
+ usedKeys = /* @__PURE__ */ new Set();
18
+ aliases = {};
19
+ overrides = {};
20
+ defaults = {};
21
+ prefixes = [];
22
+ nots = [];
23
+ configValues = {};
24
+ configsLoaded = [];
25
+ env = "local";
26
+ constructor(config2 = {}) {
27
+ this.aliases = config2.aliases || {};
28
+ this.overrides = config2.overrides || {};
29
+ this.defaults = config2.defaults || {};
30
+ this.prefixes = config2.prefixes || ["not", "no"];
31
+ const args = config2.args || process.argv.slice(2);
32
+ this.parseArgs(args);
33
+ this.env = this.get("env")?.toLowerCase() || "local";
34
+ this.loadDotEnv();
35
+ this.loadConfigFiles();
36
+ this.checkConflicts();
37
+ }
38
+ /**
39
+ * Parse command line arguments
40
+ */
41
+ parseArgs(args) {
42
+ let i = 0;
43
+ while (i < args.length) {
44
+ const arg = args[i];
45
+ if (arg.startsWith("--")) {
46
+ const [key, value] = this.parseLongOption(arg);
47
+ this.setValue(key, value);
48
+ i++;
49
+ } else if (arg.startsWith("-")) {
50
+ const result = this.parseShortOption(arg, args, i);
51
+ if (result.consumed > 0) {
52
+ i += result.consumed;
53
+ } else {
54
+ i++;
55
+ }
56
+ } else {
57
+ this.commands.push(arg);
58
+ i++;
59
+ }
60
+ }
61
+ }
62
+ /**
63
+ * Parse long option (--key=value or --key)
64
+ */
65
+ parseLongOption(arg) {
66
+ const key = arg.slice(2);
67
+ const prefix = this.prefixes.find((p) => key.startsWith(p));
68
+ if (prefix) {
69
+ let strippedKey = key.slice(prefix.length);
70
+ if (strippedKey.startsWith("-")) {
71
+ strippedKey = strippedKey.slice(1);
72
+ }
73
+ this.nots.push(key);
74
+ return [strippedKey, false];
75
+ }
76
+ if (key.includes("=")) {
77
+ const eqIndex = key.indexOf("=");
78
+ const optionKey = key.slice(0, eqIndex);
79
+ const value = key.slice(eqIndex + 1);
80
+ return [optionKey, this.parseValue(value)];
81
+ } else {
82
+ return [key, true];
83
+ }
84
+ }
85
+ /**
86
+ * Parse short option (-k=value, -k, or bundled -vsd)
87
+ */
88
+ parseShortOption(arg, args, index) {
89
+ const key = arg.slice(1);
90
+ if (key.length === 1 && index + 1 < args.length && !args[index + 1].startsWith("-")) {
91
+ const value = args[index + 1];
92
+ this.setValue(key, this.parseValue(value));
93
+ return { consumed: 2 };
94
+ }
95
+ if (key.length > 1 && !key.includes("=")) {
96
+ for (let i = 0; i < key.length; i++) {
97
+ const shortKey = key[i];
98
+ if (shortKey in this.aliases) {
99
+ this.setValue(shortKey, true);
100
+ } else {
101
+ this.args[shortKey] = true;
102
+ }
103
+ }
104
+ return { consumed: 1 };
105
+ }
106
+ if (key.includes("=")) {
107
+ const eqIndex = key.indexOf("=");
108
+ const optionKey = key.slice(0, eqIndex);
109
+ const value = key.slice(eqIndex + 1);
110
+ if (optionKey.length > 1) {
111
+ for (let i = 0; i < optionKey.length - 1; i++) {
112
+ const shortKey = optionKey[i];
113
+ if (shortKey in this.aliases) {
114
+ this.setValue(shortKey, true);
115
+ } else {
116
+ this.args[shortKey] = true;
117
+ }
118
+ }
119
+ const lastKey = optionKey[optionKey.length - 1];
120
+ if (lastKey in this.aliases) {
121
+ this.setValue(lastKey, this.parseValue(value));
122
+ } else {
123
+ this.args[lastKey] = this.parseValue(value);
124
+ }
125
+ } else {
126
+ this.setValue(optionKey, this.parseValue(value));
127
+ }
128
+ return { consumed: 1 };
129
+ } else {
130
+ this.setValue(key, true);
131
+ return { consumed: 1 };
132
+ }
133
+ }
134
+ /**
135
+ * Parse value (handle quotes)
136
+ */
137
+ parseValue(value) {
138
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
139
+ return value.slice(1, -1);
140
+ }
141
+ return value;
142
+ }
143
+ /**
144
+ * Set a value with proper categorization
145
+ */
146
+ setValue(key, value) {
147
+ const resolvedKey = this.aliases[key] || key;
148
+ if (typeof value === "boolean") {
149
+ this.flags[resolvedKey] = value;
150
+ } else {
151
+ this.options[resolvedKey] = value;
152
+ }
153
+ this.args[resolvedKey.toLowerCase()] = value;
154
+ }
155
+ /**
156
+ * Check for conflicts (short + long form of same option)
157
+ */
158
+ checkConflicts() {
159
+ const conflicts = [];
160
+ for (const [shortKey, longKey] of Object.entries(this.aliases)) {
161
+ const hasShort = this.args[shortKey] !== void 0;
162
+ const hasLong = this.args[longKey] !== void 0;
163
+ if (hasShort && hasLong) {
164
+ conflicts.push(`Both -${shortKey} and --${longKey} specified`);
165
+ }
166
+ }
167
+ if (conflicts.length > 0) {
168
+ throw new Error(`Argument conflicts: ${conflicts.join(", ")}`);
169
+ }
170
+ }
171
+ /**
172
+ * Get a value with precedence order
173
+ */
174
+ get(key) {
175
+ const resolvedKey = this.aliases[key] || key;
176
+ this.usedKeys.add(resolvedKey);
177
+ if (this.overrides[resolvedKey] !== void 0) {
178
+ return this.overrides[resolvedKey];
179
+ }
180
+ const lcKey = resolvedKey.toLowerCase();
181
+ const lcKeyWithEnv = `${lcKey}${this.env ? `_${this.env.toLowerCase()}` : ""}`;
182
+ if (this.env && this.args[lcKeyWithEnv] !== void 0) {
183
+ return this.args[lcKeyWithEnv];
184
+ } else if (this.args[lcKey] !== void 0) {
185
+ return this.args[lcKey];
186
+ }
187
+ if (this.configValues[resolvedKey] !== void 0) {
188
+ return this.configValues[resolvedKey];
189
+ }
190
+ const envKey = this.toEnvKey(resolvedKey);
191
+ const envKeyWithEnv = `${envKey}${this.env ? `_${this.env.toUpperCase()}` : ""}`;
192
+ const envSpecificKey = Object.keys(process.env).find(
193
+ (k) => this.env && k.toUpperCase() === envKeyWithEnv
194
+ );
195
+ const envKeyFound = Object.keys(process.env).find((k) => k.toUpperCase() === envKey);
196
+ if (envSpecificKey) {
197
+ return process.env[envSpecificKey];
198
+ } else if (envKeyFound) {
199
+ return process.env[envKeyFound];
200
+ }
201
+ if (this.defaults[resolvedKey] !== void 0) {
202
+ return this.defaults[resolvedKey];
203
+ }
204
+ if (resolvedKey === "env" && process.env.NODE_ENV !== void 0) {
205
+ return process.env.NODE_ENV;
206
+ }
207
+ return void 0;
208
+ }
209
+ /**
210
+ * Set a value (for testing/internal use)
211
+ */
212
+ set(key, value) {
213
+ this.args[key] = value;
214
+ }
215
+ /**
216
+ * Check if a command exists (case-insensitive)
217
+ */
218
+ hasCommand(cmd) {
219
+ return this.commands.some((command) => command.toLowerCase() === cmd.toLowerCase());
220
+ }
221
+ /**
222
+ * Get all commands
223
+ */
224
+ getCommands() {
225
+ return [...this.commands];
226
+ }
227
+ /**
228
+ * Get used keys (as array)
229
+ */
230
+ getUsed() {
231
+ return Array.from(this.usedKeys);
232
+ }
233
+ /**
234
+ * Get unused keys (as array)
235
+ */
236
+ getUnused() {
237
+ const unused = [];
238
+ for (const key of Object.keys(this.args)) {
239
+ if (!this.usedKeys.has(key) && !this.nots.includes(key)) {
240
+ unused.push(key);
241
+ }
242
+ }
243
+ return unused;
244
+ }
245
+ /**
246
+ * Convert key to environment variable format
247
+ */
248
+ toEnvKey(key) {
249
+ return key.replace(
250
+ /[A-Z0-9]/g,
251
+ (match, offset) => offset === 0 ? match : "_" + match.toLowerCase()
252
+ ).toUpperCase();
253
+ }
254
+ /**
255
+ * Load .env file
256
+ */
257
+ loadDotEnv() {
258
+ const dotEnvPath = this.get("dotEnvPath") || process.cwd();
259
+ const dotEnvFile = this.get("dotEnvFile") || ".env";
260
+ if (this.get("dotEnvFile")) {
261
+ const customPath = resolve(dotEnvPath, dotEnvFile);
262
+ if (existsSync(customPath)) {
263
+ config({ path: customPath, quiet: true });
264
+ }
265
+ return;
266
+ }
267
+ let dotEnvPathFile = null;
268
+ const envSpecificFile = `.env.${this.env}`;
269
+ const envSpecificPath = resolve(dotEnvPath, envSpecificFile);
270
+ if (existsSync(envSpecificPath)) {
271
+ dotEnvPathFile = envSpecificPath;
272
+ }
273
+ if (!dotEnvPathFile && !this.get("dotEnvPath")) {
274
+ const examplesPath = resolve(dotEnvPath, "examples");
275
+ const examplesEnvSpecificPath = resolve(examplesPath, envSpecificFile);
276
+ if (existsSync(examplesEnvSpecificPath)) {
277
+ dotEnvPathFile = examplesEnvSpecificPath;
278
+ }
279
+ }
280
+ if (!dotEnvPathFile) {
281
+ dotEnvPathFile = resolve(dotEnvPath, dotEnvFile);
282
+ if (!existsSync(dotEnvPathFile)) {
283
+ if (!this.get("dotEnvPath")) {
284
+ const examplesPath = resolve(dotEnvPath, "examples");
285
+ const examplesEnvFile = resolve(examplesPath, dotEnvFile);
286
+ if (existsSync(examplesEnvFile)) {
287
+ dotEnvPathFile = examplesEnvFile;
288
+ } else {
289
+ dotEnvPathFile = resolve(dotEnvPath, "..", dotEnvFile);
290
+ }
291
+ }
292
+ }
293
+ }
294
+ if (dotEnvPathFile && existsSync(dotEnvPathFile)) {
295
+ config({ path: dotEnvPathFile, quiet: true });
296
+ }
297
+ }
298
+ /**
299
+ * Load configuration files
300
+ */
301
+ loadConfigFiles() {
302
+ this.configsLoaded = [];
303
+ this.configValues = {};
304
+ const _defaultConfigExtension = this.get("defaultConfigExtension") || "js";
305
+ const optConfigFiles = this.get("config") || this.get("configs") || "";
306
+ const configFiles = optConfigFiles ? optConfigFiles.split(/,\s*/) : [];
307
+ const optConfigFilePath = this.get("configPath");
308
+ if (configFiles.length > 0) {
309
+ for (const cfgFile of configFiles) {
310
+ let notLoaded = false;
311
+ let notLoadedEnvSpecific = false;
312
+ const cfgFileWithPath = this.resolveFileWithPath(optConfigFilePath, cfgFile);
313
+ try {
314
+ const cfgContents = this.requireConfigFile(cfgFileWithPath);
315
+ this.configValues = { ...this.configValues, ...cfgContents };
316
+ this.configsLoaded.push(cfgFileWithPath);
317
+ } catch {
318
+ notLoaded = true;
319
+ }
320
+ const cfgEnvFileWithPath = this.resolveFileWithPath(
321
+ optConfigFilePath,
322
+ cfgFile,
323
+ this.env
324
+ );
325
+ if (cfgEnvFileWithPath !== cfgFileWithPath) {
326
+ try {
327
+ const cfgContents = this.requireConfigFile(cfgEnvFileWithPath);
328
+ this.configValues = { ...this.configValues, ...cfgContents };
329
+ this.configsLoaded.push(cfgEnvFileWithPath);
330
+ } catch {
331
+ notLoadedEnvSpecific = true;
332
+ }
333
+ } else {
334
+ notLoadedEnvSpecific = true;
335
+ }
336
+ if (notLoaded && notLoadedEnvSpecific) {
337
+ throw new Error(`can't load config file "${cfgFileWithPath}"`);
338
+ }
339
+ }
340
+ }
341
+ }
342
+ /**
343
+ * Resolve file path with environment-specific naming
344
+ */
345
+ resolveFileWithPath(optConfigFilePath, cfgFile, env) {
346
+ let cfgFileWithPath = optConfigFilePath ? isAbsolute(optConfigFilePath) ? resolve(optConfigFilePath, cfgFile) : resolve(process.cwd(), optConfigFilePath, cfgFile) : isAbsolute(cfgFile) ? cfgFile : resolve(process.cwd(), cfgFile);
347
+ const { basePathWithName, extension } = this.splitPath(cfgFileWithPath);
348
+ if (env) {
349
+ cfgFileWithPath = `${basePathWithName}.${env}.${extension || "js"}`;
350
+ } else {
351
+ cfgFileWithPath = `${basePathWithName}.${extension || "js"}`;
352
+ }
353
+ return cfgFileWithPath;
354
+ }
355
+ /**
356
+ * Split file path into base path and extension
357
+ */
358
+ splitPath(filePath) {
359
+ const basePathWithName = join(dirname(filePath), basename(filePath, extname(filePath)));
360
+ const extension = extname(filePath).slice(1);
361
+ return { basePathWithName, extension };
362
+ }
363
+ /**
364
+ * Require a configuration file (supports .js and .json)
365
+ */
366
+ requireConfigFile(filePath) {
367
+ if (!existsSync(filePath)) {
368
+ throw new Error(`Config file not found: ${filePath}`);
369
+ }
370
+ const ext = extname(filePath).toLowerCase();
371
+ if (ext === ".json") {
372
+ const content = readFileSync(filePath, "utf8");
373
+ return JSON.parse(content);
374
+ } else if (ext === ".js") {
375
+ try {
376
+ delete __require.cache[__require.resolve(filePath)];
377
+ return __require(filePath);
378
+ } catch (error) {
379
+ throw new Error(`Failed to load JS config file: ${error instanceof Error ? error.message : String(error)}`);
380
+ }
381
+ } else {
382
+ throw new Error(`Unsupported file extension: ${ext}`);
383
+ }
384
+ }
385
+ /**
386
+ * Get all parsed data
387
+ */
388
+ getParsed() {
389
+ return {
390
+ command: this.commands[0] || "",
391
+ flags: { ...this.flags },
392
+ options: { ...this.options },
393
+ usedKeys: new Set(this.usedKeys)
394
+ };
395
+ }
396
+ /**
397
+ * Set prefixes dynamically and re-parse arguments (like legacy)
398
+ */
399
+ setPrefixes(prefixes) {
400
+ const arr = Array.isArray(prefixes) ? prefixes : prefixes.split(/,\s*/);
401
+ const sortedArr = arr.sort(
402
+ (a, b) => a.length < b.length ? 1 : a.length > b.length ? -1 : 0
403
+ );
404
+ this.prefixes = sortedArr.map((el) => el.toLowerCase());
405
+ const args = process.argv.slice(2);
406
+ this.parseArgs(args);
407
+ }
408
+ };
409
+ var instance = null;
410
+ function getArgsInstance() {
411
+ return instance;
412
+ }
413
+
414
+ // src/params/index.ts
415
+ import Joi from "joi";
416
+
417
+ // src/errors.ts
418
+ var FrameworkError = class extends Error {
419
+ constructor(message) {
420
+ super(message);
421
+ this.name = "FrameworkError";
422
+ }
423
+ };
424
+ var ParamError = class extends FrameworkError {
425
+ constructor(message) {
426
+ super(message);
427
+ this.name = "ParamError";
428
+ }
429
+ };
430
+
431
+ // src/params/custom-types.ts
432
+ var joiEdateType = (value, helpers) => {
433
+ if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(value)) {
434
+ const testDate = new Date(value);
435
+ if (!isNaN(testDate.getTime())) {
436
+ return value;
437
+ }
438
+ }
439
+ if (value instanceof Date) {
440
+ return value.toISOString();
441
+ }
442
+ if (typeof value !== "string") {
443
+ value = String(value);
444
+ }
445
+ if (value.toLowerCase() === "now") {
446
+ return (/* @__PURE__ */ new Date()).toISOString();
447
+ }
448
+ const referenceRegex = /^@(\w+)([+-]\d+[smhdwy])$/i;
449
+ const referenceMatch = value.match(referenceRegex);
450
+ if (referenceMatch) {
451
+ const [, paramName, relativeExpr] = referenceMatch;
452
+ const context = helpers.prefs?.context;
453
+ if (!context || !context.params) {
454
+ throw new ParamError(`Cannot resolve cross-parameter reference @${paramName}: context not available. Ensure parameters are processed with proper context.`);
455
+ }
456
+ const referencedValue = context.params[paramName];
457
+ if (referencedValue === void 0 || referencedValue === null) {
458
+ throw new ParamError(`Cannot resolve @${paramName}: parameter "${paramName}" is not defined or has no value. Parameters are evaluated left-to-right.`);
459
+ }
460
+ let referenceDate;
461
+ if (referencedValue instanceof Date) {
462
+ referenceDate = referencedValue;
463
+ } else if (typeof referencedValue === "string") {
464
+ referenceDate = new Date(referencedValue);
465
+ if (isNaN(referenceDate.getTime())) {
466
+ throw new ParamError(`Referenced parameter @${paramName} has invalid date value: ${referencedValue}`);
467
+ }
468
+ } else {
469
+ throw new ParamError(`Referenced parameter @${paramName} is not a valid date type (found: ${typeof referencedValue})`);
470
+ }
471
+ const relativeMatch2 = relativeExpr.match(/^([+-])(\d+)([smhdwy])$/i);
472
+ if (!relativeMatch2) {
473
+ throw new ParamError(`Invalid relative time expression in @${paramName}${relativeExpr}`);
474
+ }
475
+ const [, sign, amount, unit] = relativeMatch2;
476
+ const offset = calculateTimeOffset(parseInt(amount, 10), unit, sign);
477
+ const resultDate = new Date(referenceDate.getTime() + offset);
478
+ return resultDate.toISOString();
479
+ }
480
+ const relativeTimeRegex = /^([+-])(\d+)([smhdwy])$/i;
481
+ const relativeMatch = value.match(relativeTimeRegex);
482
+ if (relativeMatch) {
483
+ const [, sign, amount, unit] = relativeMatch;
484
+ const numAmount = parseInt(amount, 10);
485
+ if (isNaN(numAmount)) {
486
+ throw new ParamError(`Invalid relative time amount: ${amount}`);
487
+ }
488
+ const offset = calculateTimeOffset(numAmount, unit, sign);
489
+ const resultDate = new Date(Date.now() + offset);
490
+ return resultDate.toISOString();
491
+ }
492
+ const parsedDate = new Date(value);
493
+ if (isNaN(parsedDate.getTime())) {
494
+ throw new ParamError(`Invalid date format: ${value}. Expected a valid date string, "now", relative time expression (e.g., "-2h", "+1d"), or cross-parameter reference (e.g., "@startTime+2h")`);
495
+ }
496
+ return parsedDate.toISOString();
497
+ };
498
+ function calculateTimeOffset(amount, unit, sign) {
499
+ let multiplier = 1;
500
+ switch (unit.toLowerCase()) {
501
+ case "s":
502
+ multiplier = 1e3;
503
+ break;
504
+ case "m":
505
+ multiplier = 60 * 1e3;
506
+ break;
507
+ case "h":
508
+ multiplier = 60 * 60 * 1e3;
509
+ break;
510
+ case "d":
511
+ multiplier = 24 * 60 * 60 * 1e3;
512
+ break;
513
+ case "w":
514
+ multiplier = 7 * 24 * 60 * 60 * 1e3;
515
+ break;
516
+ case "y":
517
+ multiplier = 365 * 24 * 60 * 60 * 1e3;
518
+ break;
519
+ default:
520
+ throw new ParamError(`Invalid time unit: ${unit}. Supported units: s, m, h, d, w, y`);
521
+ }
522
+ return sign === "+" ? amount * multiplier : -amount * multiplier;
523
+ }
524
+ var joiStringArrayType = (type) => (value, helpers) => {
525
+ if (value === void 0 || typeof value === "function") {
526
+ return [];
527
+ }
528
+ const arr = value.split(/,\s*/).map((el) => {
529
+ if (type === "number") {
530
+ const v = parseInt(el, 10);
531
+ if (isNaN(v)) {
532
+ throw new ParamError(`array element "${el}" should be numeric`);
533
+ }
534
+ return v;
535
+ } else if (type === "boolean") {
536
+ const v = el.match(/true|t|yes|1/i) ? true : el.match(/false|f|no|0/i) ? false : null;
537
+ if (v === null) {
538
+ throw new ParamError(`array element "${el}" should be boolean`);
539
+ }
540
+ return v;
541
+ } else if (type === "string") {
542
+ return el;
543
+ } else {
544
+ throw new ParamError(`unknown type "${type}" for array elements`);
545
+ }
546
+ });
547
+ return arr;
548
+ };
549
+
550
+ // src/params/index.ts
551
+ var Params = class {
552
+ params = {};
553
+ definitions = {};
554
+ args;
555
+ paramSetters = [];
556
+ paramGetters = [];
557
+ constructor({ args }, opts = {}) {
558
+ this.args = args;
559
+ for (const [k, v] of Object.entries(opts)) {
560
+ this.params[k] = v;
561
+ }
562
+ }
563
+ /**
564
+ * Assign a parameter definition
565
+ */
566
+ assignDefinition(key, definition) {
567
+ if (this.definitions[key] && !definition) {
568
+ return this.definitions[key];
569
+ }
570
+ let type;
571
+ if (!definition) {
572
+ type = Joi.string();
573
+ } else if (Joi.isSchema(definition)) {
574
+ type = definition;
575
+ } else if (Joi.isSchema(definition.type)) {
576
+ type = definition.type;
577
+ } else if (typeof definition === "string") {
578
+ type = this.toJoi(definition);
579
+ } else if (typeof definition.type === "string") {
580
+ type = this.toJoi(definition.type);
581
+ } else if (!definition.type) {
582
+ type = Joi.string();
583
+ } else {
584
+ type = Joi.string();
585
+ }
586
+ if (!this.definitions[key]) {
587
+ this.definitions[key] = {};
588
+ }
589
+ this.definitions[key].type = type;
590
+ if (definition && definition.values) {
591
+ if (Array.isArray(definition.values)) {
592
+ this.definitions[key].values = definition.values;
593
+ }
594
+ }
595
+ return this.definitions[key];
596
+ }
597
+ /**
598
+ * Convert string definition to Joi schema
599
+ */
600
+ toJoi(str) {
601
+ let type;
602
+ if (str.match(/^string|^text/i)) {
603
+ type = Joi.string();
604
+ } else if (str.match(/^number|^integer|^int/i)) {
605
+ type = Joi.number();
606
+ } else if (str.match(/^boolean|^bool/i)) {
607
+ type = Joi.boolean();
608
+ } else if (str.match(/^date/i)) {
609
+ type = Joi.date();
610
+ } else if (str.match(/^edate/i)) {
611
+ type = Joi.custom(joiEdateType);
612
+ } else if (str.match(/^duration/i)) {
613
+ type = Joi.string().isoDuration();
614
+ } else if (str.match(/^array/i)) {
615
+ let elementTypes = "string";
616
+ const tmp = str.match(/\((.*)\)/);
617
+ if (tmp && tmp[1].match(/string/i)) {
618
+ elementTypes = "string";
619
+ } else if (tmp && tmp[1].match(/number|integer|int/i)) {
620
+ elementTypes = "number";
621
+ } else if (tmp && tmp[1].match(/boolean|bool/i)) {
622
+ elementTypes = "boolean";
623
+ }
624
+ type = Joi.custom(joiStringArrayType(elementTypes));
625
+ } else {
626
+ type = Joi.string();
627
+ }
628
+ const regexForDefault = /\bdefault\s+([^\s]+)/;
629
+ const matchForDefault = str.match(regexForDefault);
630
+ if (matchForDefault) {
631
+ const defValObj = type.validate(matchForDefault[1]);
632
+ if (defValObj.error) {
633
+ throw new ParamError(`default value "${defValObj.value}" type mismatch`);
634
+ }
635
+ type = type.default(defValObj.value);
636
+ } else if (str.match(/required/)) {
637
+ type = type.required();
638
+ }
639
+ return type;
640
+ }
641
+ /**
642
+ * Validate a value against a definition
643
+ */
644
+ validate(key, val, def) {
645
+ const { value, error } = def.type.validate(val, { context: { params: this.params } });
646
+ if (error) {
647
+ const errs = error.details.map((el) => el.message).join(", ");
648
+ throw new ParamError(`"${key}" validation error: ${errs}`);
649
+ }
650
+ return value;
651
+ }
652
+ /**
653
+ * Get a parameter value with validation
654
+ */
655
+ get(key, definition) {
656
+ const def = this.assignDefinition(key, definition);
657
+ let valFromGetters = void 0;
658
+ if (def.volatile || true) {
659
+ valFromGetters = this.runAllRegisteredGetters(key);
660
+ }
661
+ const valFromArgs = this.args.get(key);
662
+ const valFromParams = this.params[key];
663
+ const res = valFromGetters ? this.validate(key, valFromGetters, def) : valFromArgs ? this.validate(key, valFromArgs, def) : this.validate(key, valFromParams, def);
664
+ if (res !== void 0 && def.values && !def.values.includes(res)) {
665
+ throw new ParamError(`key ${key} should be one of ${def.values}`);
666
+ }
667
+ return res;
668
+ }
669
+ /**
670
+ * Set a parameter value with validation
671
+ */
672
+ set(key, val, definition) {
673
+ if (val && val.type && val.value) {
674
+ definition = val;
675
+ val = val.value;
676
+ }
677
+ const def = this.assignDefinition(key, definition);
678
+ if (!this.runAllRegisteredSetters(key, val)) {
679
+ this.params[key] = val;
680
+ }
681
+ }
682
+ /**
683
+ * Get all parameters from definitions
684
+ * Processes parameters left-to-right to support cross-parameter references
685
+ */
686
+ getAll(defs) {
687
+ const res = {};
688
+ for (const [k, def] of Object.entries(defs)) {
689
+ const value = this.get(k, def);
690
+ res[k] = value;
691
+ if (value !== void 0) {
692
+ this.params[k] = value;
693
+ }
694
+ }
695
+ return res;
696
+ }
697
+ /**
698
+ * Run all registered getters for a key
699
+ */
700
+ runAllRegisteredGetters(key) {
701
+ let val = null;
702
+ for (const getter of this.paramGetters) {
703
+ val = getter(key, this.definitions[key]);
704
+ if (val !== void 0) {
705
+ break;
706
+ }
707
+ }
708
+ return val;
709
+ }
710
+ /**
711
+ * Run all registered setters for a key
712
+ */
713
+ runAllRegisteredSetters(key, value) {
714
+ let setterUsed = false;
715
+ for (const setter of this.paramSetters) {
716
+ setterUsed = setter(key, value);
717
+ if (setterUsed) {
718
+ break;
719
+ }
720
+ }
721
+ return setterUsed;
722
+ }
723
+ /**
724
+ * Register a parameter getter
725
+ */
726
+ registerParamGetter(fn) {
727
+ this.paramGetters.push(fn);
728
+ }
729
+ /**
730
+ * Register a parameter setter
731
+ */
732
+ registerParamSetter(fn) {
733
+ this.paramSetters.push(fn);
734
+ }
735
+ };
736
+ var paramsInstance = null;
737
+ var getParamsInstance = () => paramsInstance;
738
+
739
+ // src/screen/screens.ts
740
+ import { useState as useState2, createElement as h3 } from "react";
741
+ import { render, useInput, Text as Text3 } from "ink";
742
+
743
+ // src/screen/components.ts
744
+ import { createElement as h } from "react";
745
+ import { Box, Text } from "ink";
746
+ function getScreenWidth(maxWidth = null) {
747
+ const terminalWidth = process.stdout.columns || 80;
748
+ const availableWidth = Math.max(20, terminalWidth - 4);
749
+ return maxWidth ? Math.min(availableWidth, maxWidth) : availableWidth;
750
+ }
751
+ function ScreenContainer({ children }) {
752
+ const width = getScreenWidth();
753
+ return h(Box, {
754
+ flexDirection: "column",
755
+ marginTop: 1,
756
+ borderStyle: "single",
757
+ borderColor: "cyan",
758
+ paddingX: 1,
759
+ width
760
+ // Use the calculated width directly
761
+ }, children);
762
+ }
763
+ function ScreenRow({ children }) {
764
+ return h(Box, { flexDirection: "column" }, children);
765
+ }
766
+ function ScreenTitle({ text }) {
767
+ return h(
768
+ ScreenRow,
769
+ {},
770
+ h(Text, { bold: true, color: "cyan" }, text)
771
+ );
772
+ }
773
+ function ScreenDivider({ width }) {
774
+ const dividerWidth = width || getScreenWidth() - 4;
775
+ return h(Text, { color: "cyan", dimColor: true }, "\u2500".repeat(dividerWidth));
776
+ }
777
+ function ScreenBody({ children, alignItems = "flex-start" }) {
778
+ return h(Box, { flexDirection: "column", alignItems }, children);
779
+ }
780
+ function ScreenFooter({ lines, textStyle }) {
781
+ const defaultTextStyle = {
782
+ dimColor: true,
783
+ color: "white"
784
+ };
785
+ const finalTextStyle = { ...defaultTextStyle, ...textStyle };
786
+ const flattenAndWrap = (items, keyPrefix = "") => {
787
+ const result = [];
788
+ let keyIndex = 0;
789
+ items.forEach((item, index) => {
790
+ if (Array.isArray(item)) {
791
+ const nested = flattenAndWrap(item, `${keyPrefix}-${index}`);
792
+ result.push(...nested);
793
+ } else if (typeof item === "string") {
794
+ result.push(
795
+ h(Text, { key: `${keyPrefix}-${keyIndex++}`, ...finalTextStyle }, item)
796
+ );
797
+ } else {
798
+ const element = item;
799
+ if (element.key === null || element.key === void 0) {
800
+ result.push(
801
+ h(Text, { key: `${keyPrefix}-${keyIndex++}`, ...finalTextStyle }, element)
802
+ );
803
+ } else {
804
+ result.push(element);
805
+ }
806
+ }
807
+ });
808
+ return result;
809
+ };
810
+ const wrappedItems = flattenAndWrap(lines);
811
+ return h(
812
+ Box,
813
+ { flexDirection: "column" },
814
+ h(Box, { flexDirection: "row" }, ...wrappedItems)
815
+ );
816
+ }
817
+
818
+ // src/screen/list-components.ts
819
+ import React2, { useState, useEffect, useRef, createElement } from "react";
820
+ import { Box as Box2, Text as Text2 } from "ink";
821
+ var h2 = createElement;
822
+ function MultiColumnListComponent({ items, ctx, selectedIndexRef }) {
823
+ const [, forceUpdate] = useState({});
824
+ const termWidth = (process.stdout.columns || 80) - 8;
825
+ const maxItemLength = Math.max(...items.map((w) => w.length));
826
+ const columnWidth = maxItemLength + 3;
827
+ const columns = Math.max(1, Math.floor(termWidth / columnWidth));
828
+ const itemsPerColumn = Math.ceil(items.length / columns);
829
+ useEffect(() => {
830
+ ctx.setAction("moveUp", () => {
831
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - 1);
832
+ forceUpdate({});
833
+ });
834
+ ctx.setAction("moveDown", () => {
835
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + 1);
836
+ forceUpdate({});
837
+ });
838
+ ctx.setAction("moveLeft", () => {
839
+ if (selectedIndexRef.current === 0) {
840
+ ctx.goBack();
841
+ } else {
842
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - itemsPerColumn);
843
+ forceUpdate({});
844
+ }
845
+ });
846
+ ctx.setAction("moveRight", () => {
847
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + itemsPerColumn);
848
+ forceUpdate({});
849
+ });
850
+ ctx.setKeyBinding([
851
+ { key: "leftArrow", caption: "navigate", action: "moveLeft", order: 0 },
852
+ { key: "rightArrow", caption: "navigate", action: "moveRight", order: 0 },
853
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
854
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
855
+ ]);
856
+ ctx.addFooter(`Total: ${items.length} items`);
857
+ }, []);
858
+ const selectedIndex = selectedIndexRef.current;
859
+ const rows = [];
860
+ for (let row = 0; row < itemsPerColumn; row++) {
861
+ const cols = [];
862
+ for (let col = 0; col < columns; col++) {
863
+ const index = col * itemsPerColumn + row;
864
+ if (index < items.length) {
865
+ const isSelected = index === selectedIndex;
866
+ cols.push(
867
+ h2(
868
+ Box2,
869
+ { key: index, width: columnWidth },
870
+ h2(Text2, {
871
+ color: isSelected ? "black" : "white",
872
+ backgroundColor: isSelected ? "cyan" : void 0,
873
+ bold: isSelected
874
+ }, items[index].padEnd(maxItemLength))
875
+ )
876
+ );
877
+ }
878
+ }
879
+ rows.push(
880
+ h2(ScreenRow, { key: row, children: h2(Box2, { flexDirection: "row" }, ...cols) })
881
+ );
882
+ }
883
+ return h2(Box2, { flexDirection: "column" }, ...rows);
884
+ }
885
+ function MultiColumnListWithPreviewComponent({
886
+ items,
887
+ getPreviewContent,
888
+ ctx,
889
+ selectedIndexRef
890
+ }) {
891
+ const [, forceUpdate] = useState({});
892
+ const termWidth = (process.stdout.columns || 80) - 8;
893
+ const maxItemLength = Math.max(...items.map((w) => w.length));
894
+ const columnWidth = maxItemLength + 3;
895
+ const columns = Math.max(1, Math.floor(termWidth / columnWidth));
896
+ const itemsPerColumn = Math.ceil(items.length / columns);
897
+ useEffect(() => {
898
+ ctx.setAction("moveUp", () => {
899
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - 1);
900
+ forceUpdate({});
901
+ });
902
+ ctx.setAction("moveDown", () => {
903
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + 1);
904
+ forceUpdate({});
905
+ });
906
+ ctx.setAction("moveLeft", () => {
907
+ if (selectedIndexRef.current === 0) {
908
+ ctx.goBack();
909
+ } else {
910
+ selectedIndexRef.current = Math.max(0, selectedIndexRef.current - itemsPerColumn);
911
+ forceUpdate({});
912
+ }
913
+ });
914
+ ctx.setAction("moveRight", () => {
915
+ selectedIndexRef.current = Math.min(items.length - 1, selectedIndexRef.current + itemsPerColumn);
916
+ forceUpdate({});
917
+ });
918
+ ctx.setKeyBinding([
919
+ { key: "leftArrow", caption: "navigate", action: "moveLeft", order: 0 },
920
+ { key: "rightArrow", caption: "navigate", action: "moveRight", order: 0 },
921
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
922
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
923
+ ]);
924
+ ctx.addFooter(`Total: ${items.length} items`);
925
+ }, []);
926
+ const selectedIndex = selectedIndexRef.current;
927
+ const selectedItem = items[selectedIndex];
928
+ const rows = [];
929
+ for (let row = 0; row < itemsPerColumn; row++) {
930
+ const cols = [];
931
+ for (let col = 0; col < columns; col++) {
932
+ const index = col * itemsPerColumn + row;
933
+ if (index < items.length) {
934
+ const isSelected = index === selectedIndex;
935
+ cols.push(
936
+ h2(
937
+ Box2,
938
+ { key: index, width: columnWidth },
939
+ h2(Text2, {
940
+ color: isSelected ? "black" : "white",
941
+ backgroundColor: isSelected ? "cyan" : void 0,
942
+ bold: isSelected
943
+ }, items[index].padEnd(maxItemLength))
944
+ )
945
+ );
946
+ }
947
+ }
948
+ rows.push(
949
+ h2(ScreenRow, { key: row, children: h2(Box2, { flexDirection: "row" }, ...cols) })
950
+ );
951
+ }
952
+ const previewContent = getPreviewContent ? getPreviewContent(selectedItem) : selectedItem;
953
+ const previewRows = [];
954
+ if (typeof previewContent === "string") {
955
+ previewRows.push(h2(ScreenRow, { key: "preview-string", children: h2(Text2, { bold: true }, previewContent) }));
956
+ } else if (typeof previewContent === "object" && !React2.isValidElement(previewContent) && previewContent !== null) {
957
+ Object.entries(previewContent).forEach(([key, value], idx) => {
958
+ previewRows.push(h2(ScreenRow, { key: `preview-${key}-${idx}`, children: h2(Text2, {}, `${key}: ${value}`) }));
959
+ });
960
+ } else if (React2.isValidElement(previewContent)) {
961
+ previewRows.push(h2(ScreenRow, { key: "preview-element", children: previewContent }));
962
+ }
963
+ return h2(
964
+ Box2,
965
+ { flexDirection: "column" },
966
+ ...rows,
967
+ h2(ScreenRow, { key: "spacer-1", children: h2(Text2, {}, " ") }),
968
+ h2(ScreenDivider, { key: "divider" }),
969
+ h2(ScreenRow, { key: "spacer-2", children: h2(Text2, {}, " ") }),
970
+ ...previewRows
971
+ );
972
+ }
973
+ function ListComponent({ items, ctx, selectedIndexRef, renderItem, getTitle, sortable = false, maxHeight, sortHighlightStyle, selectionMarker = " " }) {
974
+ const [, forceUpdate] = useState({});
975
+ const [sortOrder, setSortOrder] = useState("none");
976
+ const [scrollOffset, setScrollOffset] = useState(0);
977
+ const scrollStateRef = useRef({ scrollOffset: 0, maxHeight: 0, totalItems: 0 });
978
+ const defaultGetTitle = (item) => {
979
+ return getTitle ? getTitle(item) : typeof item.value === "string" ? item.value : item.value?.title || item.name;
980
+ };
981
+ const titleGetter = getTitle || defaultGetTitle;
982
+ const displayItems = sortable && sortOrder !== "none" ? [...items].sort((a, b) => {
983
+ const titleA = titleGetter(a).toLowerCase();
984
+ const titleB = titleGetter(b).toLowerCase();
985
+ if (sortOrder === "asc") {
986
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
987
+ } else {
988
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
989
+ }
990
+ }) : items;
991
+ const effectiveMaxHeight = maxHeight || displayItems.length;
992
+ const canScroll = displayItems.length > effectiveMaxHeight;
993
+ const maxScrollOffset = Math.max(0, displayItems.length - effectiveMaxHeight);
994
+ const clampedScrollOffset = Math.min(Math.max(0, scrollOffset), maxScrollOffset);
995
+ const visibleItems = displayItems.slice(clampedScrollOffset, clampedScrollOffset + effectiveMaxHeight);
996
+ const canScrollUp = clampedScrollOffset > 0;
997
+ const canScrollDown = clampedScrollOffset < maxScrollOffset;
998
+ scrollStateRef.current = { scrollOffset, maxHeight: effectiveMaxHeight, totalItems: displayItems.length };
999
+ useEffect(() => {
1000
+ ctx.setAction("moveUp", () => {
1001
+ const newIndex = Math.max(0, selectedIndexRef.current - 1);
1002
+ selectedIndexRef.current = newIndex;
1003
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
1004
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
1005
+ const currentClampedScrollOffset = Math.min(Math.max(0, currentScrollOffset), currentMaxScrollOffset);
1006
+ if (newIndex < currentClampedScrollOffset) {
1007
+ setScrollOffset(newIndex);
1008
+ }
1009
+ forceUpdate({});
1010
+ });
1011
+ ctx.setAction("moveDown", () => {
1012
+ const currentItems = sortable && sortOrder !== "none" ? [...items].sort((a, b) => {
1013
+ const titleA = titleGetter(a).toLowerCase();
1014
+ const titleB = titleGetter(b).toLowerCase();
1015
+ if (sortOrder === "asc") {
1016
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
1017
+ } else {
1018
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
1019
+ }
1020
+ }) : items;
1021
+ const maxIndex = currentItems.length - 1;
1022
+ const newIndex = Math.min(maxIndex, selectedIndexRef.current + 1);
1023
+ selectedIndexRef.current = newIndex;
1024
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
1025
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
1026
+ const currentClampedScrollOffset = Math.min(Math.max(0, currentScrollOffset), currentMaxScrollOffset);
1027
+ if (newIndex >= currentClampedScrollOffset + currentMaxHeight) {
1028
+ setScrollOffset(newIndex - currentMaxHeight + 1);
1029
+ }
1030
+ forceUpdate({});
1031
+ });
1032
+ ctx.setAction("scrollUp", () => {
1033
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
1034
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
1035
+ const newScrollOffset = Math.max(0, currentScrollOffset - 1);
1036
+ setScrollOffset(newScrollOffset);
1037
+ forceUpdate({});
1038
+ });
1039
+ ctx.setAction("scrollDown", () => {
1040
+ const { scrollOffset: currentScrollOffset, maxHeight: currentMaxHeight, totalItems } = scrollStateRef.current;
1041
+ const currentMaxScrollOffset = Math.max(0, totalItems - currentMaxHeight);
1042
+ const newScrollOffset = Math.min(currentMaxScrollOffset, currentScrollOffset + 1);
1043
+ setScrollOffset(newScrollOffset);
1044
+ forceUpdate({});
1045
+ });
1046
+ if (sortable) {
1047
+ ctx.setAction("toggleSort", () => {
1048
+ const nextSort = sortOrder === "none" ? "asc" : sortOrder === "asc" ? "desc" : "none";
1049
+ const currentSelectedItem = displayItems[selectedIndexRef.current];
1050
+ setSortOrder(nextSort);
1051
+ const newSortedItems = nextSort !== "none" ? [...items].sort((a, b) => {
1052
+ const titleA = titleGetter(a).toLowerCase();
1053
+ const titleB = titleGetter(b).toLowerCase();
1054
+ if (nextSort === "asc") {
1055
+ return titleA < titleB ? -1 : titleA > titleB ? 1 : 0;
1056
+ } else {
1057
+ return titleA > titleB ? -1 : titleA < titleB ? 1 : 0;
1058
+ }
1059
+ }) : items;
1060
+ const newIndex = newSortedItems.findIndex((item) => item === currentSelectedItem);
1061
+ if (newIndex !== -1) {
1062
+ selectedIndexRef.current = newIndex;
1063
+ setScrollOffset(newIndex);
1064
+ } else {
1065
+ selectedIndexRef.current = 0;
1066
+ setScrollOffset(0);
1067
+ }
1068
+ forceUpdate({});
1069
+ });
1070
+ const defaultHighlightStyle = {
1071
+ color: "black",
1072
+ backgroundColor: "green",
1073
+ bold: true
1074
+ };
1075
+ const highlightStyle = { ...defaultHighlightStyle, ...sortHighlightStyle };
1076
+ const sortCaption = () => {
1077
+ if (sortOrder === "none") {
1078
+ return h2(Text2, {}, "s to toggle sort");
1079
+ } else {
1080
+ const sortLabel = sortOrder === "asc" ? "ASC" : "DESC";
1081
+ return h2(
1082
+ Text2,
1083
+ {},
1084
+ "s to toggle ",
1085
+ h2(Text2, { color: "white", bold: true }, "sort"),
1086
+ " ",
1087
+ h2(Text2, highlightStyle, ` ${sortLabel} `)
1088
+ );
1089
+ }
1090
+ };
1091
+ ctx.setKeyBinding([
1092
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
1093
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 },
1094
+ {
1095
+ key: "s",
1096
+ caption: sortCaption,
1097
+ action: "toggleSort",
1098
+ order: 5
1099
+ }
1100
+ ]);
1101
+ ctx.update();
1102
+ } else {
1103
+ ctx.setKeyBinding([
1104
+ { key: "upArrow", caption: "navigate", action: "moveUp", order: 0 },
1105
+ { key: "downArrow", caption: "navigate", action: "moveDown", order: 0 }
1106
+ ]);
1107
+ }
1108
+ }, [sortOrder, sortable]);
1109
+ const selectedIndex = selectedIndexRef.current;
1110
+ const defaultRenderItem = (item, isSelected, displayIndex, actualIndex) => {
1111
+ const isFirstVisible = displayIndex === 0;
1112
+ const isLastVisible = displayIndex === visibleItems.length - 1;
1113
+ let arrowPrefix = "";
1114
+ let selectionPrefix = "";
1115
+ if (isFirstVisible && canScrollUp) {
1116
+ arrowPrefix = "\u2191 ";
1117
+ } else if (isLastVisible && canScrollDown) {
1118
+ arrowPrefix = "\u2193 ";
1119
+ } else {
1120
+ arrowPrefix = " ";
1121
+ }
1122
+ if (isSelected) {
1123
+ selectionPrefix = selectionMarker;
1124
+ } else {
1125
+ selectionPrefix = " ".repeat(selectionMarker.length);
1126
+ }
1127
+ return h2(
1128
+ Box2,
1129
+ { flexDirection: "row" },
1130
+ // Arrow (clickable if functional, not highlighted)
1131
+ h2(Text2, {
1132
+ key: `arrow-${actualIndex}`,
1133
+ color: "white"
1134
+ }, arrowPrefix),
1135
+ // Selection marker space (always same width, not highlighted)
1136
+ h2(Text2, { key: `marker-${actualIndex}`, color: "white" }, selectionPrefix),
1137
+ // Item name (highlighted if selected)
1138
+ h2(Text2, {
1139
+ key: `name-${actualIndex}`,
1140
+ color: isSelected ? "black" : "white",
1141
+ backgroundColor: isSelected ? "cyan" : void 0,
1142
+ bold: isSelected
1143
+ }, item.name)
1144
+ );
1145
+ };
1146
+ const itemRenderer = renderItem || defaultRenderItem;
1147
+ return h2(
1148
+ Box2,
1149
+ { flexDirection: "column" },
1150
+ ...visibleItems.map((item, displayIndex) => {
1151
+ const actualIndex = clampedScrollOffset + displayIndex;
1152
+ const isSelected = actualIndex === selectedIndex;
1153
+ if (renderItem) {
1154
+ const isFirstVisible = displayIndex === 0;
1155
+ const isLastVisible = displayIndex === visibleItems.length - 1;
1156
+ let arrowPrefix = "";
1157
+ let selectionPrefix = "";
1158
+ if (isFirstVisible && canScrollUp) {
1159
+ arrowPrefix = "\u2191 ";
1160
+ } else if (isLastVisible && canScrollDown) {
1161
+ arrowPrefix = "\u2193 ";
1162
+ } else {
1163
+ arrowPrefix = " ";
1164
+ }
1165
+ if (isSelected) {
1166
+ selectionPrefix = selectionMarker;
1167
+ } else {
1168
+ selectionPrefix = " ".repeat(selectionMarker.length);
1169
+ }
1170
+ return h2(ScreenRow, {
1171
+ key: `item-${actualIndex}`,
1172
+ children: h2(
1173
+ Box2,
1174
+ { flexDirection: "row" },
1175
+ // Arrow (clickable if functional, not highlighted)
1176
+ h2(Text2, {
1177
+ key: `arrow-${actualIndex}`,
1178
+ color: "white"
1179
+ }, arrowPrefix),
1180
+ // Selection marker space (always same width, not highlighted)
1181
+ h2(Text2, { key: `marker-${actualIndex}`, color: "white" }, selectionPrefix),
1182
+ // Custom rendered content
1183
+ renderItem(item, isSelected, displayIndex)
1184
+ )
1185
+ });
1186
+ } else {
1187
+ return h2(ScreenRow, {
1188
+ key: `item-${actualIndex}`,
1189
+ children: itemRenderer(item, isSelected, displayIndex, actualIndex)
1190
+ });
1191
+ }
1192
+ })
1193
+ );
1194
+ }
1195
+
1196
+ // src/screen/screens.ts
1197
+ function groupKeyBindings(bindings) {
1198
+ const groups = {};
1199
+ const enabledBindings = bindings.filter((b) => b.enabled !== false);
1200
+ enabledBindings.forEach((binding) => {
1201
+ const caption = typeof binding.caption === "string" ? binding.caption : "";
1202
+ if (!groups[caption]) {
1203
+ groups[caption] = {
1204
+ keys: [],
1205
+ caption,
1206
+ order: binding.order || 999
1207
+ };
1208
+ }
1209
+ groups[caption].keys.push(binding.key);
1210
+ });
1211
+ return Object.values(groups);
1212
+ }
1213
+ function formatKeyBindings(bindings, mode = "long") {
1214
+ const resolvedBindings = bindings.map((binding) => {
1215
+ let resolvedCaption = binding.caption;
1216
+ if (typeof binding.caption === "function") {
1217
+ resolvedCaption = binding.caption();
1218
+ }
1219
+ return {
1220
+ ...binding,
1221
+ resolvedCaption
1222
+ };
1223
+ });
1224
+ const groups = groupKeyBindings(resolvedBindings.map((b) => ({
1225
+ ...b,
1226
+ caption: typeof b.resolvedCaption === "string" ? b.resolvedCaption : ""
1227
+ })));
1228
+ groups.sort((a, b) => a.order - b.order);
1229
+ const items = [];
1230
+ groups.forEach((group) => {
1231
+ const bindingWithCustom = resolvedBindings.find(
1232
+ (b) => group.keys.includes(b.key) && typeof b.resolvedCaption !== "string"
1233
+ );
1234
+ if (bindingWithCustom && bindingWithCustom.resolvedCaption) {
1235
+ items.push(bindingWithCustom.resolvedCaption);
1236
+ } else {
1237
+ const keyStr = formatKeys(group.keys);
1238
+ if (mode === "long") {
1239
+ items.push(`${keyStr} to ${group.caption}`);
1240
+ } else {
1241
+ items.push(keyStr);
1242
+ }
1243
+ }
1244
+ });
1245
+ return items;
1246
+ }
1247
+ function formatKeys(keys) {
1248
+ const keyMap = {
1249
+ "escape": "esc",
1250
+ "leftArrow": "\u2190",
1251
+ "rightArrow": "\u2192",
1252
+ "upArrow": "\u2191",
1253
+ "downArrow": "\u2193",
1254
+ "return": "enter"
1255
+ };
1256
+ return keys.map((k) => keyMap[k] || k).join("/");
1257
+ }
1258
+ async function showScreen(config2) {
1259
+ const {
1260
+ title,
1261
+ onRender,
1262
+ parentData = {}
1263
+ } = config2;
1264
+ return new Promise((resolve2) => {
1265
+ let instance2;
1266
+ const keyBindings = [];
1267
+ const actions = {};
1268
+ const customFooterItems = [];
1269
+ let renderResult = null;
1270
+ let initialized = false;
1271
+ const Screen = () => {
1272
+ const [updateCounter, setUpdateCounter] = useState2(0);
1273
+ if (!initialized) {
1274
+ const defaultBindings = [
1275
+ { key: "escape", caption: "go back", action: "back", protected: true, order: 1 },
1276
+ { key: "leftArrow", caption: "go back", action: "back", protected: false, order: 1 }
1277
+ // Note: 'select' is not a default - components add it if needed
1278
+ ];
1279
+ defaultBindings.forEach((binding) => {
1280
+ keyBindings.push(binding);
1281
+ });
1282
+ actions.back = () => {
1283
+ cleanup(null);
1284
+ };
1285
+ initialized = true;
1286
+ }
1287
+ const context = {
1288
+ setAction: (actionName, handlerFn) => {
1289
+ actions[actionName] = handlerFn;
1290
+ },
1291
+ setKeyBinding: (bindingOrBindings) => {
1292
+ const bindingsToSet = Array.isArray(bindingOrBindings) ? bindingOrBindings : [bindingOrBindings];
1293
+ bindingsToSet.forEach((binding) => {
1294
+ const existingIndex = keyBindings.findIndex((b) => b.key === binding.key);
1295
+ if (existingIndex >= 0) {
1296
+ const existing = keyBindings[existingIndex];
1297
+ if (existing.protected) {
1298
+ console.warn(`Cannot override protected key: ${binding.key}`);
1299
+ return;
1300
+ }
1301
+ keyBindings[existingIndex] = {
1302
+ ...existing,
1303
+ ...binding,
1304
+ order: binding.order !== void 0 ? binding.order : existing.order,
1305
+ enabled: binding.enabled !== void 0 ? binding.enabled : existing.enabled !== void 0 ? existing.enabled : true
1306
+ };
1307
+ } else {
1308
+ keyBindings.push({
1309
+ protected: false,
1310
+ order: 999,
1311
+ enabled: true,
1312
+ ...binding
1313
+ });
1314
+ }
1315
+ });
1316
+ },
1317
+ updateKeyBinding: (keyName, updates) => {
1318
+ const index = keyBindings.findIndex((b) => b.key === keyName);
1319
+ if (index >= 0) {
1320
+ keyBindings[index] = {
1321
+ ...keyBindings[index],
1322
+ ...updates
1323
+ };
1324
+ }
1325
+ },
1326
+ removeKeyBinding: (keyName) => {
1327
+ const index = keyBindings.findIndex((b) => b.key === keyName);
1328
+ if (index >= 0) {
1329
+ if (keyBindings[index].protected) {
1330
+ console.warn(`Cannot remove protected key: ${keyName}`);
1331
+ return;
1332
+ }
1333
+ keyBindings.splice(index, 1);
1334
+ }
1335
+ },
1336
+ addFooter: (item) => {
1337
+ customFooterItems.push(item);
1338
+ },
1339
+ clearFooter: () => {
1340
+ customFooterItems.length = 0;
1341
+ },
1342
+ setFooter: (items) => {
1343
+ customFooterItems.length = 0;
1344
+ const itemsArray = Array.isArray(items) ? items : [items];
1345
+ customFooterItems.push(...itemsArray);
1346
+ },
1347
+ update: () => {
1348
+ setUpdateCounter((c) => c + 1);
1349
+ },
1350
+ goBack: () => {
1351
+ if (actions.back) {
1352
+ actions.back();
1353
+ }
1354
+ },
1355
+ close: (result) => {
1356
+ cleanup(result);
1357
+ },
1358
+ parentData
1359
+ };
1360
+ if (!renderResult) {
1361
+ renderResult = onRender(context);
1362
+ }
1363
+ useInput((input, key) => {
1364
+ if (key.ctrl && input === "c") {
1365
+ cleanup(null);
1366
+ process.exit(0);
1367
+ return;
1368
+ }
1369
+ let matchedBinding = null;
1370
+ for (const binding of keyBindings) {
1371
+ let keyMatches = false;
1372
+ if (key[binding.key]) {
1373
+ keyMatches = true;
1374
+ } else if (input === binding.key) {
1375
+ keyMatches = true;
1376
+ }
1377
+ if (keyMatches) {
1378
+ if (binding.enabled === false) {
1379
+ continue;
1380
+ }
1381
+ if (binding.condition && !binding.condition(context)) {
1382
+ continue;
1383
+ }
1384
+ matchedBinding = binding;
1385
+ break;
1386
+ }
1387
+ }
1388
+ if (matchedBinding && actions[matchedBinding.action]) {
1389
+ const actionResult = actions[matchedBinding.action]({
1390
+ input,
1391
+ key,
1392
+ binding: matchedBinding
1393
+ });
1394
+ }
1395
+ });
1396
+ const footerLines = [];
1397
+ const bindingItems = formatKeyBindings(keyBindings, "long");
1398
+ if (bindingItems.length > 0) {
1399
+ const bindingsLine = [];
1400
+ bindingItems.forEach((item, idx) => {
1401
+ if (idx > 0) {
1402
+ bindingsLine.push(", ");
1403
+ }
1404
+ bindingsLine.push(item);
1405
+ });
1406
+ const allStrings = bindingItems.every((item) => typeof item === "string");
1407
+ if (allStrings) {
1408
+ footerLines.push(bindingsLine.join(""));
1409
+ } else {
1410
+ const wrappedBindingsLine = bindingsLine.map(
1411
+ (item) => typeof item === "string" ? h3(Text3, {}, item) : item
1412
+ );
1413
+ footerLines.push(wrappedBindingsLine);
1414
+ }
1415
+ }
1416
+ customFooterItems.forEach((item) => {
1417
+ if (typeof item === "string") {
1418
+ footerLines.push(item);
1419
+ } else {
1420
+ footerLines.push(item);
1421
+ }
1422
+ });
1423
+ return h3(
1424
+ ScreenContainer,
1425
+ {},
1426
+ h3(ScreenTitle, { text: title }),
1427
+ h3(ScreenDivider),
1428
+ h3(ScreenRow, {}, h3(Text3, {}, " ")),
1429
+ renderResult,
1430
+ h3(ScreenRow, {}, h3(Text3, {}, " ")),
1431
+ h3(ScreenDivider),
1432
+ h3(ScreenFooter, { lines: footerLines })
1433
+ );
1434
+ };
1435
+ const cleanup = (result) => {
1436
+ if (instance2) instance2.unmount();
1437
+ setTimeout(() => resolve2(result), 50);
1438
+ };
1439
+ instance2 = render(h3(Screen));
1440
+ });
1441
+ }
1442
+ async function showListScreen(config2) {
1443
+ const { title, items, onSelect, onEscape, parentData, initialSelectedIndex = 0, renderItem, getTitle, sortable, maxHeight, sortHighlightStyle, selectionMarker } = config2;
1444
+ return showScreen({
1445
+ title,
1446
+ parentData,
1447
+ onRender: (ctx) => {
1448
+ const selectedIndexRef = { current: initialSelectedIndex };
1449
+ ctx.setAction("select", () => {
1450
+ const selected = items[selectedIndexRef.current];
1451
+ if (onSelect) {
1452
+ const result = onSelect(selected.value, selectedIndexRef.current);
1453
+ ctx.close(result);
1454
+ }
1455
+ });
1456
+ if (onEscape) {
1457
+ ctx.setAction("back", () => {
1458
+ const result = onEscape(selectedIndexRef.current);
1459
+ ctx.close(result);
1460
+ });
1461
+ }
1462
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
1463
+ return h3(ListComponent, { items, ctx, selectedIndexRef, renderItem, getTitle, sortable, maxHeight, sortHighlightStyle, selectionMarker });
1464
+ }
1465
+ });
1466
+ }
1467
+ async function showMultiColumnListScreen(config2) {
1468
+ const { title, items, onSelect, onEscape, parentData, initialSelectedIndex = 0 } = config2;
1469
+ return showScreen({
1470
+ title,
1471
+ parentData,
1472
+ onRender: (ctx) => {
1473
+ const selectedIndexRef = { current: initialSelectedIndex };
1474
+ ctx.setAction("select", () => {
1475
+ const selected = items[selectedIndexRef.current];
1476
+ if (onSelect) {
1477
+ const result = onSelect(selected, selectedIndexRef.current);
1478
+ ctx.close(result);
1479
+ }
1480
+ });
1481
+ if (onEscape) {
1482
+ ctx.setAction("back", () => {
1483
+ const result = onEscape(selectedIndexRef.current);
1484
+ ctx.close(result);
1485
+ });
1486
+ }
1487
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
1488
+ return h3(MultiColumnListComponent, { items, ctx, selectedIndexRef });
1489
+ }
1490
+ });
1491
+ }
1492
+ async function showMultiColumnListWithPreviewScreen(config2) {
1493
+ const { title, items, getPreviewContent, onSelect, onEscape, parentData, initialSelectedIndex = 0 } = config2;
1494
+ return showScreen({
1495
+ title,
1496
+ parentData,
1497
+ onRender: (ctx) => {
1498
+ const selectedIndexRef = { current: initialSelectedIndex };
1499
+ ctx.setAction("select", () => {
1500
+ const selected = items[selectedIndexRef.current];
1501
+ if (onSelect) {
1502
+ const result = onSelect(selected, selectedIndexRef.current);
1503
+ ctx.close(result);
1504
+ }
1505
+ });
1506
+ if (onEscape) {
1507
+ ctx.setAction("back", () => {
1508
+ const result = onEscape(selectedIndexRef.current);
1509
+ ctx.close(result);
1510
+ });
1511
+ }
1512
+ ctx.setKeyBinding({ key: "return", caption: "select", action: "select", order: 2 });
1513
+ return h3(MultiColumnListWithPreviewComponent, { items, getPreviewContent, ctx, selectedIndexRef });
1514
+ }
1515
+ });
1516
+ }
1517
+ var showMenuScreen = showListScreen;
1518
+ var showWordGridScreen = showMultiColumnListScreen;
1519
+
1520
+ // src/screen/ui-elements.ts
1521
+ import { createElement as h4 } from "react";
1522
+ import { Box as Box4, Text as Text4 } from "ink";
1523
+ function ListItem({
1524
+ children,
1525
+ isSelected = false,
1526
+ color = "white",
1527
+ backgroundColor,
1528
+ bold = false,
1529
+ dimColor = false
1530
+ }) {
1531
+ return h4(
1532
+ Box4,
1533
+ {},
1534
+ h4(Text4, {
1535
+ color: isSelected ? backgroundColor || "green" : color,
1536
+ backgroundColor: isSelected ? color : backgroundColor,
1537
+ bold: isSelected || bold,
1538
+ dimColor: !isSelected && dimColor
1539
+ }, children)
1540
+ );
1541
+ }
1542
+ function TextBlock({
1543
+ text,
1544
+ color = "white",
1545
+ dimmed = false,
1546
+ bold = false,
1547
+ maxWidth
1548
+ }) {
1549
+ return h4(
1550
+ Box4,
1551
+ {},
1552
+ h4(Text4, {
1553
+ color,
1554
+ dimColor: dimmed,
1555
+ bold
1556
+ }, text)
1557
+ );
1558
+ }
1559
+ function Divider({ character = "\u2500", width = 80 }) {
1560
+ return h4(
1561
+ Box4,
1562
+ { marginY: 1 },
1563
+ h4(Text4, { dimColor: true }, character.repeat(width))
1564
+ );
1565
+ }
1566
+ function GridCell({
1567
+ children,
1568
+ width,
1569
+ color = "white",
1570
+ backgroundColor,
1571
+ bold = false,
1572
+ dimColor = false,
1573
+ align = "left"
1574
+ }) {
1575
+ return h4(
1576
+ Box4,
1577
+ { width },
1578
+ h4(Text4, {
1579
+ color,
1580
+ backgroundColor,
1581
+ bold,
1582
+ dimColor,
1583
+ textAlign: align
1584
+ }, children)
1585
+ );
1586
+ }
1587
+ function InputField({ prompt, value, onChange, onSubmit }) {
1588
+ return h4(
1589
+ Box4,
1590
+ { flexDirection: "column" },
1591
+ h4(Text4, {}, prompt),
1592
+ h4(
1593
+ Box4,
1594
+ { marginTop: 1 },
1595
+ h4(Text4, { color: "cyan" }, " > ", value, "_")
1596
+ )
1597
+ );
1598
+ }
1599
+
1600
+ // src/screen/utils.ts
1601
+ function buildBreadcrumb(parts) {
1602
+ if (parts.length === 0) return "";
1603
+ if (parts.length === 1) return parts[0];
1604
+ return parts.slice(1).map((part) => `\u2190 ${part}`).join(" ");
1605
+ }
1606
+ function buildDetailBreadcrumb(path, suffix = "") {
1607
+ if (path.length <= 1) {
1608
+ return suffix ? `\u2190 ${suffix}` : path[0] || "";
1609
+ }
1610
+ const breadcrumb = buildBreadcrumb(path);
1611
+ return suffix ? `${breadcrumb} ${suffix}` : breadcrumb;
1612
+ }
1613
+
1614
+ // src/screen/footer-builder.ts
1615
+ function buildFooter(config2 = {}) {
1616
+ const {
1617
+ navigation = null,
1618
+ actions = null,
1619
+ info = null,
1620
+ escape = "Esc to go back",
1621
+ custom = null
1622
+ } = config2;
1623
+ const lines = [];
1624
+ const mainParts = [];
1625
+ if (navigation) {
1626
+ mainParts.push(navigation);
1627
+ }
1628
+ if (actions) {
1629
+ mainParts.push(actions);
1630
+ }
1631
+ if (escape) {
1632
+ mainParts.push(escape);
1633
+ }
1634
+ if (mainParts.length > 0) {
1635
+ lines.push(mainParts.join(", "));
1636
+ }
1637
+ if (info) {
1638
+ const infoLines = Array.isArray(info) ? info : [info];
1639
+ lines.push(...infoLines);
1640
+ }
1641
+ if (custom) {
1642
+ const customLines = Array.isArray(custom) ? custom : [custom];
1643
+ lines.push(...customLines);
1644
+ }
1645
+ return lines;
1646
+ }
1647
+ var FooterPresets = {
1648
+ /**
1649
+ * Menu screen footer
1650
+ */
1651
+ menu: (customInfo = null) => buildFooter({
1652
+ navigation: "\u2191/\u2193 to navigate",
1653
+ actions: "Enter to select",
1654
+ escape: "Esc to go back",
1655
+ info: customInfo
1656
+ }),
1657
+ /**
1658
+ * Word grid footer
1659
+ */
1660
+ wordGrid: (totalWords) => buildFooter({
1661
+ navigation: "\u2191\u2193\u2190\u2192 to navigate",
1662
+ actions: "Enter to select",
1663
+ escape: "Esc to go back",
1664
+ info: `Total: ${totalWords} words`
1665
+ }),
1666
+ /**
1667
+ * Text input footer
1668
+ */
1669
+ textInput: () => buildFooter({
1670
+ actions: "Type and press Enter to submit",
1671
+ escape: "Esc to cancel"
1672
+ }),
1673
+ /**
1674
+ * Info/static screen footer
1675
+ */
1676
+ info: () => buildFooter({
1677
+ escape: "Esc to continue"
1678
+ }),
1679
+ /**
1680
+ * Main menu footer (escape exits)
1681
+ */
1682
+ mainMenu: () => buildFooter({
1683
+ navigation: "\u2191/\u2193 to navigate",
1684
+ actions: "Enter to select",
1685
+ escape: "Esc to exit"
1686
+ }),
1687
+ /**
1688
+ * Action menu footer (for word cards, etc.)
1689
+ */
1690
+ actionMenu: (hasAudio = false) => {
1691
+ const parts = buildFooter({
1692
+ navigation: "\u2191/\u2193 to navigate",
1693
+ actions: "Enter to select",
1694
+ escape: "Esc to go back"
1695
+ });
1696
+ if (hasAudio) {
1697
+ parts.push("Audio available");
1698
+ }
1699
+ return parts;
1700
+ }
1701
+ };
1702
+ function organizeFooterMessages(messages) {
1703
+ if (!messages || messages.length === 0) {
1704
+ return ["Esc to go back"];
1705
+ }
1706
+ const navigation = messages.filter((m) => m.includes("\u2191") || m.includes("\u2193") || m.includes("\u2190") || m.includes("\u2192"));
1707
+ const actions = messages.filter((m) => m.includes("Enter") || m.includes("select") || m.includes("submit"));
1708
+ const escape = messages.filter((m) => m.includes("Esc"));
1709
+ const others = messages.filter(
1710
+ (m) => !navigation.includes(m) && !actions.includes(m) && !escape.includes(m)
1711
+ );
1712
+ const lines = [];
1713
+ const mainLine = [...navigation, ...actions, ...escape].join(", ");
1714
+ if (mainLine) lines.push(mainLine);
1715
+ lines.push(...others);
1716
+ return lines;
1717
+ }
1718
+ export {
1719
+ Args,
1720
+ Divider,
1721
+ FooterPresets,
1722
+ GridCell,
1723
+ InputField,
1724
+ ListComponent,
1725
+ ListItem,
1726
+ MultiColumnListComponent,
1727
+ MultiColumnListWithPreviewComponent,
1728
+ Params,
1729
+ ScreenBody,
1730
+ ScreenContainer,
1731
+ ScreenDivider,
1732
+ ScreenFooter,
1733
+ ScreenRow,
1734
+ ScreenTitle,
1735
+ TextBlock,
1736
+ buildBreadcrumb,
1737
+ buildDetailBreadcrumb,
1738
+ buildFooter,
1739
+ getArgsInstance,
1740
+ getParamsInstance,
1741
+ joiEdateType,
1742
+ joiStringArrayType,
1743
+ organizeFooterMessages,
1744
+ showListScreen,
1745
+ showMenuScreen,
1746
+ showMultiColumnListScreen,
1747
+ showMultiColumnListWithPreviewScreen,
1748
+ showScreen,
1749
+ showWordGridScreen
1750
+ };
1751
+ //# sourceMappingURL=index.js.map