@nmakarov/cli-toolkit 0.4.0 → 0.5.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.cjs +284 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +283 -0
- package/dist/index.js.map +1 -1
- package/dist/init.cjs +1110 -0
- package/dist/init.cjs.map +1 -0
- package/dist/init.js +1079 -0
- package/dist/init.js.map +1 -0
- package/dist/logger.cjs +13 -2
- package/dist/logger.cjs.map +1 -1
- package/dist/logger.js +13 -2
- package/dist/logger.js.map +1 -1
- package/package.json +4 -2
package/dist/init.cjs
ADDED
|
@@ -0,0 +1,1110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/init.ts
|
|
31
|
+
var init_exports = {};
|
|
32
|
+
__export(init_exports, {
|
|
33
|
+
init: () => init,
|
|
34
|
+
setupContext: () => setupContext
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(init_exports);
|
|
37
|
+
|
|
38
|
+
// src/args/index.ts
|
|
39
|
+
var import_fs = require("fs");
|
|
40
|
+
var import_path = require("path");
|
|
41
|
+
var import_dotenv = require("dotenv");
|
|
42
|
+
var Args = class {
|
|
43
|
+
args = {};
|
|
44
|
+
flags = {};
|
|
45
|
+
options = {};
|
|
46
|
+
commands = [];
|
|
47
|
+
usedKeys = /* @__PURE__ */ new Set();
|
|
48
|
+
aliases = {};
|
|
49
|
+
overrides = {};
|
|
50
|
+
defaults = {};
|
|
51
|
+
prefixes = [];
|
|
52
|
+
nots = [];
|
|
53
|
+
configValues = {};
|
|
54
|
+
configsLoaded = [];
|
|
55
|
+
env = "local";
|
|
56
|
+
constructor(config2 = {}) {
|
|
57
|
+
this.aliases = config2.aliases || {};
|
|
58
|
+
this.overrides = config2.overrides || {};
|
|
59
|
+
this.defaults = config2.defaults || {};
|
|
60
|
+
this.prefixes = config2.prefixes || ["not", "no"];
|
|
61
|
+
const args = config2.args || process.argv.slice(2);
|
|
62
|
+
this.parseArgs(args);
|
|
63
|
+
this.env = this.get("env")?.toLowerCase() || "local";
|
|
64
|
+
this.loadDotEnv();
|
|
65
|
+
this.loadConfigFiles();
|
|
66
|
+
this.checkConflicts();
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Parse command line arguments
|
|
70
|
+
*/
|
|
71
|
+
parseArgs(args) {
|
|
72
|
+
let i = 0;
|
|
73
|
+
while (i < args.length) {
|
|
74
|
+
const arg = args[i];
|
|
75
|
+
if (arg.startsWith("--")) {
|
|
76
|
+
const [key, value] = this.parseLongOption(arg);
|
|
77
|
+
this.setValue(key, value);
|
|
78
|
+
i++;
|
|
79
|
+
} else if (arg.startsWith("-")) {
|
|
80
|
+
const result = this.parseShortOption(arg, args, i);
|
|
81
|
+
if (result.consumed > 0) {
|
|
82
|
+
i += result.consumed;
|
|
83
|
+
} else {
|
|
84
|
+
i++;
|
|
85
|
+
}
|
|
86
|
+
} else {
|
|
87
|
+
this.commands.push(arg);
|
|
88
|
+
i++;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Parse long option (--key=value or --key)
|
|
94
|
+
*/
|
|
95
|
+
parseLongOption(arg) {
|
|
96
|
+
const key = arg.slice(2);
|
|
97
|
+
const prefix = this.prefixes.find((p) => key.startsWith(p));
|
|
98
|
+
if (prefix) {
|
|
99
|
+
let strippedKey = key.slice(prefix.length);
|
|
100
|
+
if (strippedKey.startsWith("-")) {
|
|
101
|
+
strippedKey = strippedKey.slice(1);
|
|
102
|
+
}
|
|
103
|
+
this.nots.push(key);
|
|
104
|
+
return [strippedKey, false];
|
|
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
|
+
return [optionKey, this.parseValue(value)];
|
|
111
|
+
} else {
|
|
112
|
+
return [key, true];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Parse short option (-k=value, -k, or bundled -vsd)
|
|
117
|
+
*/
|
|
118
|
+
parseShortOption(arg, args, index) {
|
|
119
|
+
const key = arg.slice(1);
|
|
120
|
+
if (key.length === 1 && index + 1 < args.length && !args[index + 1].startsWith("-")) {
|
|
121
|
+
const value = args[index + 1];
|
|
122
|
+
this.setValue(key, this.parseValue(value));
|
|
123
|
+
return { consumed: 2 };
|
|
124
|
+
}
|
|
125
|
+
if (key.length > 1 && !key.includes("=")) {
|
|
126
|
+
for (let i = 0; i < key.length; i++) {
|
|
127
|
+
const shortKey = key[i];
|
|
128
|
+
if (shortKey in this.aliases) {
|
|
129
|
+
this.setValue(shortKey, true);
|
|
130
|
+
} else {
|
|
131
|
+
this.args[shortKey] = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { consumed: 1 };
|
|
135
|
+
}
|
|
136
|
+
if (key.includes("=")) {
|
|
137
|
+
const eqIndex = key.indexOf("=");
|
|
138
|
+
const optionKey = key.slice(0, eqIndex);
|
|
139
|
+
const value = key.slice(eqIndex + 1);
|
|
140
|
+
if (optionKey.length > 1) {
|
|
141
|
+
for (let i = 0; i < optionKey.length - 1; i++) {
|
|
142
|
+
const shortKey = optionKey[i];
|
|
143
|
+
if (shortKey in this.aliases) {
|
|
144
|
+
this.setValue(shortKey, true);
|
|
145
|
+
} else {
|
|
146
|
+
this.args[shortKey] = true;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const lastKey = optionKey[optionKey.length - 1];
|
|
150
|
+
if (lastKey in this.aliases) {
|
|
151
|
+
this.setValue(lastKey, this.parseValue(value));
|
|
152
|
+
} else {
|
|
153
|
+
this.args[lastKey] = this.parseValue(value);
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
this.setValue(optionKey, this.parseValue(value));
|
|
157
|
+
}
|
|
158
|
+
return { consumed: 1 };
|
|
159
|
+
} else {
|
|
160
|
+
this.setValue(key, true);
|
|
161
|
+
return { consumed: 1 };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Parse value (handle quotes)
|
|
166
|
+
*/
|
|
167
|
+
parseValue(value) {
|
|
168
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
169
|
+
return value.slice(1, -1);
|
|
170
|
+
}
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Set a value with proper categorization
|
|
175
|
+
*/
|
|
176
|
+
setValue(key, value) {
|
|
177
|
+
const resolvedKey = this.aliases[key] || key;
|
|
178
|
+
if (typeof value === "boolean") {
|
|
179
|
+
this.flags[resolvedKey] = value;
|
|
180
|
+
} else {
|
|
181
|
+
this.options[resolvedKey] = value;
|
|
182
|
+
}
|
|
183
|
+
this.args[resolvedKey.toLowerCase()] = value;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Check for conflicts (short + long form of same option)
|
|
187
|
+
*/
|
|
188
|
+
checkConflicts() {
|
|
189
|
+
const conflicts = [];
|
|
190
|
+
for (const [shortKey, longKey] of Object.entries(this.aliases)) {
|
|
191
|
+
const hasShort = this.args[shortKey] !== void 0;
|
|
192
|
+
const hasLong = this.args[longKey] !== void 0;
|
|
193
|
+
if (hasShort && hasLong) {
|
|
194
|
+
conflicts.push(`Both -${shortKey} and --${longKey} specified`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (conflicts.length > 0) {
|
|
198
|
+
throw new Error(`Argument conflicts: ${conflicts.join(", ")}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Get a value with precedence order
|
|
203
|
+
*/
|
|
204
|
+
get(key) {
|
|
205
|
+
const resolvedKey = this.aliases[key] || key;
|
|
206
|
+
this.usedKeys.add(resolvedKey);
|
|
207
|
+
if (this.overrides[resolvedKey] !== void 0) {
|
|
208
|
+
return this.overrides[resolvedKey];
|
|
209
|
+
}
|
|
210
|
+
const lcKey = resolvedKey.toLowerCase();
|
|
211
|
+
const lcKeyWithEnv = `${lcKey}${this.env ? `_${this.env.toLowerCase()}` : ""}`;
|
|
212
|
+
if (this.env && this.args[lcKeyWithEnv] !== void 0) {
|
|
213
|
+
return this.args[lcKeyWithEnv];
|
|
214
|
+
} else if (this.args[lcKey] !== void 0) {
|
|
215
|
+
return this.args[lcKey];
|
|
216
|
+
}
|
|
217
|
+
if (this.configValues[resolvedKey] !== void 0) {
|
|
218
|
+
return this.configValues[resolvedKey];
|
|
219
|
+
}
|
|
220
|
+
const envKey = this.toEnvKey(resolvedKey);
|
|
221
|
+
const envKeyWithEnv = `${envKey}${this.env ? `_${this.env.toUpperCase()}` : ""}`;
|
|
222
|
+
const envSpecificKey = Object.keys(process.env).find(
|
|
223
|
+
(k) => this.env && k.toUpperCase() === envKeyWithEnv
|
|
224
|
+
);
|
|
225
|
+
const envKeyFound = Object.keys(process.env).find((k) => k.toUpperCase() === envKey);
|
|
226
|
+
if (envSpecificKey) {
|
|
227
|
+
return process.env[envSpecificKey];
|
|
228
|
+
} else if (envKeyFound) {
|
|
229
|
+
return process.env[envKeyFound];
|
|
230
|
+
}
|
|
231
|
+
if (this.defaults[resolvedKey] !== void 0) {
|
|
232
|
+
return this.defaults[resolvedKey];
|
|
233
|
+
}
|
|
234
|
+
if (resolvedKey === "env" && process.env.NODE_ENV !== void 0) {
|
|
235
|
+
return process.env.NODE_ENV;
|
|
236
|
+
}
|
|
237
|
+
return void 0;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Set a value (for testing/internal use)
|
|
241
|
+
*/
|
|
242
|
+
set(key, value) {
|
|
243
|
+
this.args[key] = value;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Check if a command exists (case-insensitive)
|
|
247
|
+
*/
|
|
248
|
+
hasCommand(cmd) {
|
|
249
|
+
return this.commands.some((command) => command.toLowerCase() === cmd.toLowerCase());
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Get all commands
|
|
253
|
+
*/
|
|
254
|
+
getCommands() {
|
|
255
|
+
return [...this.commands];
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Get used keys (as array)
|
|
259
|
+
*/
|
|
260
|
+
getUsed() {
|
|
261
|
+
return Array.from(this.usedKeys);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get unused keys (as array)
|
|
265
|
+
*/
|
|
266
|
+
getUnused() {
|
|
267
|
+
const unused = [];
|
|
268
|
+
for (const key of Object.keys(this.args)) {
|
|
269
|
+
if (!this.usedKeys.has(key) && !this.nots.includes(key)) {
|
|
270
|
+
unused.push(key);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return unused;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Convert key to environment variable format
|
|
277
|
+
*/
|
|
278
|
+
toEnvKey(key) {
|
|
279
|
+
return key.replace(
|
|
280
|
+
/[A-Z0-9]/g,
|
|
281
|
+
(match, offset) => offset === 0 ? match : "_" + match.toLowerCase()
|
|
282
|
+
).toUpperCase();
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Load .env file
|
|
286
|
+
*/
|
|
287
|
+
loadDotEnv() {
|
|
288
|
+
const dotEnvPath = this.get("dotEnvPath") || process.cwd();
|
|
289
|
+
const dotEnvFile = this.get("dotEnvFile") || ".env";
|
|
290
|
+
if (this.get("dotEnvFile")) {
|
|
291
|
+
const customPath = (0, import_path.resolve)(dotEnvPath, dotEnvFile);
|
|
292
|
+
if ((0, import_fs.existsSync)(customPath)) {
|
|
293
|
+
(0, import_dotenv.config)({ path: customPath, quiet: true });
|
|
294
|
+
}
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
let dotEnvPathFile = null;
|
|
298
|
+
const envSpecificFile = `.env.${this.env}`;
|
|
299
|
+
const envSpecificPath = (0, import_path.resolve)(dotEnvPath, envSpecificFile);
|
|
300
|
+
if ((0, import_fs.existsSync)(envSpecificPath)) {
|
|
301
|
+
dotEnvPathFile = envSpecificPath;
|
|
302
|
+
}
|
|
303
|
+
if (!dotEnvPathFile && !this.get("dotEnvPath")) {
|
|
304
|
+
const examplesPath = (0, import_path.resolve)(dotEnvPath, "examples");
|
|
305
|
+
const examplesEnvSpecificPath = (0, import_path.resolve)(examplesPath, envSpecificFile);
|
|
306
|
+
if ((0, import_fs.existsSync)(examplesEnvSpecificPath)) {
|
|
307
|
+
dotEnvPathFile = examplesEnvSpecificPath;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (!dotEnvPathFile) {
|
|
311
|
+
dotEnvPathFile = (0, import_path.resolve)(dotEnvPath, dotEnvFile);
|
|
312
|
+
if (!(0, import_fs.existsSync)(dotEnvPathFile)) {
|
|
313
|
+
if (!this.get("dotEnvPath")) {
|
|
314
|
+
const examplesPath = (0, import_path.resolve)(dotEnvPath, "examples");
|
|
315
|
+
const examplesEnvFile = (0, import_path.resolve)(examplesPath, dotEnvFile);
|
|
316
|
+
if ((0, import_fs.existsSync)(examplesEnvFile)) {
|
|
317
|
+
dotEnvPathFile = examplesEnvFile;
|
|
318
|
+
} else {
|
|
319
|
+
dotEnvPathFile = (0, import_path.resolve)(dotEnvPath, "..", dotEnvFile);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (dotEnvPathFile && (0, import_fs.existsSync)(dotEnvPathFile)) {
|
|
325
|
+
(0, import_dotenv.config)({ path: dotEnvPathFile, quiet: true });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Load configuration files
|
|
330
|
+
*/
|
|
331
|
+
loadConfigFiles() {
|
|
332
|
+
this.configsLoaded = [];
|
|
333
|
+
this.configValues = {};
|
|
334
|
+
const _defaultConfigExtension = this.get("defaultConfigExtension") || "js";
|
|
335
|
+
const optConfigFiles = this.get("config") || this.get("configs") || "";
|
|
336
|
+
const configFiles = optConfigFiles ? optConfigFiles.split(/,\s*/) : [];
|
|
337
|
+
const optConfigFilePath = this.get("configPath");
|
|
338
|
+
if (configFiles.length > 0) {
|
|
339
|
+
for (const cfgFile of configFiles) {
|
|
340
|
+
let notLoaded = false;
|
|
341
|
+
let notLoadedEnvSpecific = false;
|
|
342
|
+
const cfgFileWithPath = this.resolveFileWithPath(optConfigFilePath, cfgFile);
|
|
343
|
+
try {
|
|
344
|
+
const cfgContents = this.requireConfigFile(cfgFileWithPath);
|
|
345
|
+
this.configValues = { ...this.configValues, ...cfgContents };
|
|
346
|
+
this.configsLoaded.push(cfgFileWithPath);
|
|
347
|
+
} catch {
|
|
348
|
+
notLoaded = true;
|
|
349
|
+
}
|
|
350
|
+
const cfgEnvFileWithPath = this.resolveFileWithPath(
|
|
351
|
+
optConfigFilePath,
|
|
352
|
+
cfgFile,
|
|
353
|
+
this.env
|
|
354
|
+
);
|
|
355
|
+
if (cfgEnvFileWithPath !== cfgFileWithPath) {
|
|
356
|
+
try {
|
|
357
|
+
const cfgContents = this.requireConfigFile(cfgEnvFileWithPath);
|
|
358
|
+
this.configValues = { ...this.configValues, ...cfgContents };
|
|
359
|
+
this.configsLoaded.push(cfgEnvFileWithPath);
|
|
360
|
+
} catch {
|
|
361
|
+
notLoadedEnvSpecific = true;
|
|
362
|
+
}
|
|
363
|
+
} else {
|
|
364
|
+
notLoadedEnvSpecific = true;
|
|
365
|
+
}
|
|
366
|
+
if (notLoaded && notLoadedEnvSpecific) {
|
|
367
|
+
throw new Error(`can't load config file "${cfgFileWithPath}"`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Resolve file path with environment-specific naming
|
|
374
|
+
*/
|
|
375
|
+
resolveFileWithPath(optConfigFilePath, cfgFile, env) {
|
|
376
|
+
let cfgFileWithPath = optConfigFilePath ? (0, import_path.isAbsolute)(optConfigFilePath) ? (0, import_path.resolve)(optConfigFilePath, cfgFile) : (0, import_path.resolve)(process.cwd(), optConfigFilePath, cfgFile) : (0, import_path.isAbsolute)(cfgFile) ? cfgFile : (0, import_path.resolve)(process.cwd(), cfgFile);
|
|
377
|
+
const { basePathWithName, extension } = this.splitPath(cfgFileWithPath);
|
|
378
|
+
if (env) {
|
|
379
|
+
cfgFileWithPath = `${basePathWithName}.${env}.${extension || "js"}`;
|
|
380
|
+
} else {
|
|
381
|
+
cfgFileWithPath = `${basePathWithName}.${extension || "js"}`;
|
|
382
|
+
}
|
|
383
|
+
return cfgFileWithPath;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Split file path into base path and extension
|
|
387
|
+
*/
|
|
388
|
+
splitPath(filePath) {
|
|
389
|
+
const basePathWithName = (0, import_path.join)((0, import_path.dirname)(filePath), (0, import_path.basename)(filePath, (0, import_path.extname)(filePath)));
|
|
390
|
+
const extension = (0, import_path.extname)(filePath).slice(1);
|
|
391
|
+
return { basePathWithName, extension };
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Require a configuration file (supports .js and .json)
|
|
395
|
+
*/
|
|
396
|
+
requireConfigFile(filePath) {
|
|
397
|
+
if (!(0, import_fs.existsSync)(filePath)) {
|
|
398
|
+
throw new Error(`Config file not found: ${filePath}`);
|
|
399
|
+
}
|
|
400
|
+
const ext = (0, import_path.extname)(filePath).toLowerCase();
|
|
401
|
+
if (ext === ".json") {
|
|
402
|
+
const content = (0, import_fs.readFileSync)(filePath, "utf8");
|
|
403
|
+
return JSON.parse(content);
|
|
404
|
+
} else if (ext === ".js") {
|
|
405
|
+
try {
|
|
406
|
+
delete require.cache[require.resolve(filePath)];
|
|
407
|
+
return require(filePath);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw new Error(`Failed to load JS config file: ${error instanceof Error ? error.message : String(error)}`);
|
|
410
|
+
}
|
|
411
|
+
} else {
|
|
412
|
+
throw new Error(`Unsupported file extension: ${ext}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Get all parsed data
|
|
417
|
+
*/
|
|
418
|
+
getParsed() {
|
|
419
|
+
return {
|
|
420
|
+
command: this.commands[0] || "",
|
|
421
|
+
flags: { ...this.flags },
|
|
422
|
+
options: { ...this.options },
|
|
423
|
+
usedKeys: Array.from(this.usedKeys)
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Set prefixes dynamically and re-parse arguments (like legacy)
|
|
428
|
+
*/
|
|
429
|
+
setPrefixes(prefixes) {
|
|
430
|
+
const arr = Array.isArray(prefixes) ? prefixes : prefixes.split(/,\s*/);
|
|
431
|
+
const sortedArr = arr.sort(
|
|
432
|
+
(a, b) => a.length < b.length ? 1 : a.length > b.length ? -1 : 0
|
|
433
|
+
);
|
|
434
|
+
this.prefixes = sortedArr.map((el) => el.toLowerCase());
|
|
435
|
+
const args = process.argv.slice(2);
|
|
436
|
+
this.parseArgs(args);
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/params/index.ts
|
|
441
|
+
var import_joi = __toESM(require("joi"), 1);
|
|
442
|
+
|
|
443
|
+
// src/errors.ts
|
|
444
|
+
var FrameworkError = class extends Error {
|
|
445
|
+
constructor(message) {
|
|
446
|
+
super(message);
|
|
447
|
+
this.name = "FrameworkError";
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
var ParamError = class extends FrameworkError {
|
|
451
|
+
constructor(message) {
|
|
452
|
+
super(message);
|
|
453
|
+
this.name = "ParamError";
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
var InitError = class extends FrameworkError {
|
|
457
|
+
constructor(message) {
|
|
458
|
+
super(message);
|
|
459
|
+
this.name = "InitError";
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
// src/params/custom-types.ts
|
|
464
|
+
var joiEdateType = (value, helpers) => {
|
|
465
|
+
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(value)) {
|
|
466
|
+
const testDate = new Date(value);
|
|
467
|
+
if (!isNaN(testDate.getTime())) {
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (value instanceof Date) {
|
|
472
|
+
return value.toISOString();
|
|
473
|
+
}
|
|
474
|
+
if (typeof value !== "string") {
|
|
475
|
+
value = String(value);
|
|
476
|
+
}
|
|
477
|
+
if (value.toLowerCase() === "now") {
|
|
478
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
479
|
+
}
|
|
480
|
+
const referenceRegex = /^@(\w+)([+-]\d+[smhdwy])$/i;
|
|
481
|
+
const referenceMatch = value.match(referenceRegex);
|
|
482
|
+
if (referenceMatch) {
|
|
483
|
+
const [, paramName, relativeExpr] = referenceMatch;
|
|
484
|
+
const context = helpers.prefs?.context;
|
|
485
|
+
if (!context || !context.params) {
|
|
486
|
+
throw new ParamError(`Cannot resolve cross-parameter reference @${paramName}: context not available. Ensure parameters are processed with proper context.`);
|
|
487
|
+
}
|
|
488
|
+
const referencedValue = context.params[paramName];
|
|
489
|
+
if (referencedValue === void 0 || referencedValue === null) {
|
|
490
|
+
throw new ParamError(`Cannot resolve @${paramName}: parameter "${paramName}" is not defined or has no value. Parameters are evaluated left-to-right.`);
|
|
491
|
+
}
|
|
492
|
+
let referenceDate;
|
|
493
|
+
if (referencedValue instanceof Date) {
|
|
494
|
+
referenceDate = referencedValue;
|
|
495
|
+
} else if (typeof referencedValue === "string") {
|
|
496
|
+
referenceDate = new Date(referencedValue);
|
|
497
|
+
if (isNaN(referenceDate.getTime())) {
|
|
498
|
+
throw new ParamError(`Referenced parameter @${paramName} has invalid date value: ${referencedValue}`);
|
|
499
|
+
}
|
|
500
|
+
} else {
|
|
501
|
+
throw new ParamError(`Referenced parameter @${paramName} is not a valid date type (found: ${typeof referencedValue})`);
|
|
502
|
+
}
|
|
503
|
+
const relativeMatch2 = relativeExpr.match(/^([+-])(\d+)([smhdwy])$/i);
|
|
504
|
+
if (!relativeMatch2) {
|
|
505
|
+
throw new ParamError(`Invalid relative time expression in @${paramName}${relativeExpr}`);
|
|
506
|
+
}
|
|
507
|
+
const [, sign, amount, unit] = relativeMatch2;
|
|
508
|
+
const offset = calculateTimeOffset(parseInt(amount, 10), unit, sign);
|
|
509
|
+
const resultDate = new Date(referenceDate.getTime() + offset);
|
|
510
|
+
return resultDate.toISOString();
|
|
511
|
+
}
|
|
512
|
+
const relativeTimeRegex = /^([+-])(\d+)([smhdwy])$/i;
|
|
513
|
+
const relativeMatch = value.match(relativeTimeRegex);
|
|
514
|
+
if (relativeMatch) {
|
|
515
|
+
const [, sign, amount, unit] = relativeMatch;
|
|
516
|
+
const numAmount = parseInt(amount, 10);
|
|
517
|
+
if (isNaN(numAmount)) {
|
|
518
|
+
throw new ParamError(`Invalid relative time amount: ${amount}`);
|
|
519
|
+
}
|
|
520
|
+
const offset = calculateTimeOffset(numAmount, unit, sign);
|
|
521
|
+
const resultDate = new Date(Date.now() + offset);
|
|
522
|
+
return resultDate.toISOString();
|
|
523
|
+
}
|
|
524
|
+
const parsedDate = new Date(value);
|
|
525
|
+
if (isNaN(parsedDate.getTime())) {
|
|
526
|
+
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")`);
|
|
527
|
+
}
|
|
528
|
+
return parsedDate.toISOString();
|
|
529
|
+
};
|
|
530
|
+
function calculateTimeOffset(amount, unit, sign) {
|
|
531
|
+
let multiplier = 1;
|
|
532
|
+
switch (unit.toLowerCase()) {
|
|
533
|
+
case "s":
|
|
534
|
+
multiplier = 1e3;
|
|
535
|
+
break;
|
|
536
|
+
case "m":
|
|
537
|
+
multiplier = 60 * 1e3;
|
|
538
|
+
break;
|
|
539
|
+
case "h":
|
|
540
|
+
multiplier = 60 * 60 * 1e3;
|
|
541
|
+
break;
|
|
542
|
+
case "d":
|
|
543
|
+
multiplier = 24 * 60 * 60 * 1e3;
|
|
544
|
+
break;
|
|
545
|
+
case "w":
|
|
546
|
+
multiplier = 7 * 24 * 60 * 60 * 1e3;
|
|
547
|
+
break;
|
|
548
|
+
case "y":
|
|
549
|
+
multiplier = 365 * 24 * 60 * 60 * 1e3;
|
|
550
|
+
break;
|
|
551
|
+
default:
|
|
552
|
+
throw new ParamError(`Invalid time unit: ${unit}. Supported units: s, m, h, d, w, y`);
|
|
553
|
+
}
|
|
554
|
+
return sign === "+" ? amount * multiplier : -amount * multiplier;
|
|
555
|
+
}
|
|
556
|
+
var joiStringArrayType = (type) => (value, helpers) => {
|
|
557
|
+
if (value === void 0 || typeof value === "function") {
|
|
558
|
+
return [];
|
|
559
|
+
}
|
|
560
|
+
const arr = value.split(/,\s*/).map((el) => {
|
|
561
|
+
if (type === "number") {
|
|
562
|
+
const v = parseInt(el, 10);
|
|
563
|
+
if (isNaN(v)) {
|
|
564
|
+
throw new ParamError(`array element "${el}" should be numeric`);
|
|
565
|
+
}
|
|
566
|
+
return v;
|
|
567
|
+
} else if (type === "boolean") {
|
|
568
|
+
const v = el.match(/true|t|yes|1/i) ? true : el.match(/false|f|no|0/i) ? false : null;
|
|
569
|
+
if (v === null) {
|
|
570
|
+
throw new ParamError(`array element "${el}" should be boolean`);
|
|
571
|
+
}
|
|
572
|
+
return v;
|
|
573
|
+
} else if (type === "string") {
|
|
574
|
+
return el;
|
|
575
|
+
} else {
|
|
576
|
+
throw new ParamError(`unknown type "${type}" for array elements`);
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
return arr;
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
// src/params/index.ts
|
|
583
|
+
var Params = class {
|
|
584
|
+
params = {};
|
|
585
|
+
definitions = {};
|
|
586
|
+
args;
|
|
587
|
+
paramSetters = [];
|
|
588
|
+
paramGetters = [];
|
|
589
|
+
constructor({ args }, opts = {}) {
|
|
590
|
+
this.args = args;
|
|
591
|
+
for (const [k, v] of Object.entries(opts)) {
|
|
592
|
+
this.params[k] = v;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Assign a parameter definition
|
|
597
|
+
*/
|
|
598
|
+
assignDefinition(key, definition) {
|
|
599
|
+
if (this.definitions[key] && !definition) {
|
|
600
|
+
return this.definitions[key];
|
|
601
|
+
}
|
|
602
|
+
let type;
|
|
603
|
+
if (!definition) {
|
|
604
|
+
type = import_joi.default.string();
|
|
605
|
+
} else if (import_joi.default.isSchema(definition)) {
|
|
606
|
+
type = definition;
|
|
607
|
+
} else if (import_joi.default.isSchema(definition.type)) {
|
|
608
|
+
type = definition.type;
|
|
609
|
+
} else if (typeof definition === "string") {
|
|
610
|
+
type = this.toJoi(definition);
|
|
611
|
+
} else if (typeof definition.type === "string") {
|
|
612
|
+
type = this.toJoi(definition.type);
|
|
613
|
+
} else if (!definition.type) {
|
|
614
|
+
type = import_joi.default.string();
|
|
615
|
+
} else {
|
|
616
|
+
type = import_joi.default.string();
|
|
617
|
+
}
|
|
618
|
+
if (!this.definitions[key]) {
|
|
619
|
+
this.definitions[key] = {};
|
|
620
|
+
}
|
|
621
|
+
this.definitions[key].type = type;
|
|
622
|
+
if (definition && definition.values) {
|
|
623
|
+
if (Array.isArray(definition.values)) {
|
|
624
|
+
this.definitions[key].values = definition.values;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return this.definitions[key];
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Convert string definition to Joi schema
|
|
631
|
+
*/
|
|
632
|
+
toJoi(str) {
|
|
633
|
+
let type;
|
|
634
|
+
if (str.match(/^string|^text/i)) {
|
|
635
|
+
type = import_joi.default.string();
|
|
636
|
+
} else if (str.match(/^number|^integer|^int/i)) {
|
|
637
|
+
type = import_joi.default.number();
|
|
638
|
+
} else if (str.match(/^boolean|^bool/i)) {
|
|
639
|
+
type = import_joi.default.boolean();
|
|
640
|
+
} else if (str.match(/^date/i)) {
|
|
641
|
+
type = import_joi.default.custom(joiEdateType);
|
|
642
|
+
} else if (str.match(/^duration/i)) {
|
|
643
|
+
type = import_joi.default.string().isoDuration();
|
|
644
|
+
} else if (str.match(/^array/i)) {
|
|
645
|
+
let elementTypes = "string";
|
|
646
|
+
const tmp = str.match(/\((.*)\)/);
|
|
647
|
+
if (tmp && tmp[1].match(/string/i)) {
|
|
648
|
+
elementTypes = "string";
|
|
649
|
+
} else if (tmp && tmp[1].match(/number|integer|int/i)) {
|
|
650
|
+
elementTypes = "number";
|
|
651
|
+
} else if (tmp && tmp[1].match(/boolean|bool/i)) {
|
|
652
|
+
elementTypes = "boolean";
|
|
653
|
+
}
|
|
654
|
+
type = import_joi.default.custom(joiStringArrayType(elementTypes));
|
|
655
|
+
} else {
|
|
656
|
+
type = import_joi.default.string();
|
|
657
|
+
}
|
|
658
|
+
const regexForDefault = /\bdefault\s+([^\s]+)/;
|
|
659
|
+
const matchForDefault = str.match(regexForDefault);
|
|
660
|
+
if (matchForDefault) {
|
|
661
|
+
const defValObj = type.validate(matchForDefault[1]);
|
|
662
|
+
if (defValObj.error) {
|
|
663
|
+
throw new ParamError(`default value "${defValObj.value}" type mismatch`);
|
|
664
|
+
}
|
|
665
|
+
type = type.default(defValObj.value);
|
|
666
|
+
} else if (str.match(/required/)) {
|
|
667
|
+
type = type.required();
|
|
668
|
+
}
|
|
669
|
+
return type;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Validate a value against a definition
|
|
673
|
+
*/
|
|
674
|
+
validate(key, val, def) {
|
|
675
|
+
const { value, error } = def.type.validate(val, { context: { params: this.params } });
|
|
676
|
+
if (error) {
|
|
677
|
+
const errs = error.details.map((el) => el.message).join(", ");
|
|
678
|
+
throw new ParamError(`"${key}" validation error: ${errs}`);
|
|
679
|
+
}
|
|
680
|
+
return value;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Get a parameter value with validation
|
|
684
|
+
*/
|
|
685
|
+
get(key, definition) {
|
|
686
|
+
const def = this.assignDefinition(key, definition);
|
|
687
|
+
let valFromGetters = void 0;
|
|
688
|
+
if (def.volatile || true) {
|
|
689
|
+
valFromGetters = this.runAllRegisteredGetters(key);
|
|
690
|
+
}
|
|
691
|
+
const valFromArgs = this.args.get(key);
|
|
692
|
+
const valFromParams = this.params[key];
|
|
693
|
+
const res = valFromGetters ? this.validate(key, valFromGetters, def) : valFromArgs ? this.validate(key, valFromArgs, def) : this.validate(key, valFromParams, def);
|
|
694
|
+
if (res !== void 0 && def.values && !def.values.includes(res)) {
|
|
695
|
+
throw new ParamError(`key ${key} should be one of ${def.values}`);
|
|
696
|
+
}
|
|
697
|
+
return res;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Set a parameter value with validation
|
|
701
|
+
*/
|
|
702
|
+
set(key, val, definition) {
|
|
703
|
+
if (val && val.type && val.value) {
|
|
704
|
+
definition = val;
|
|
705
|
+
val = val.value;
|
|
706
|
+
}
|
|
707
|
+
const def = this.assignDefinition(key, definition);
|
|
708
|
+
if (!this.runAllRegisteredSetters(key, val)) {
|
|
709
|
+
this.params[key] = val;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Get all parameters from definitions
|
|
714
|
+
* Processes parameters left-to-right to support cross-parameter references
|
|
715
|
+
*/
|
|
716
|
+
getAll(defs) {
|
|
717
|
+
const res = {};
|
|
718
|
+
for (const [k, def] of Object.entries(defs)) {
|
|
719
|
+
const value = this.get(k, def);
|
|
720
|
+
res[k] = value;
|
|
721
|
+
if (value !== void 0) {
|
|
722
|
+
this.params[k] = value;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
return res;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Run all registered getters for a key
|
|
729
|
+
*/
|
|
730
|
+
runAllRegisteredGetters(key) {
|
|
731
|
+
let val = null;
|
|
732
|
+
for (const getter of this.paramGetters) {
|
|
733
|
+
val = getter(key, this.definitions[key]);
|
|
734
|
+
if (val !== void 0) {
|
|
735
|
+
break;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return val;
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Run all registered setters for a key
|
|
742
|
+
*/
|
|
743
|
+
runAllRegisteredSetters(key, value) {
|
|
744
|
+
let setterUsed = false;
|
|
745
|
+
for (const setter of this.paramSetters) {
|
|
746
|
+
setterUsed = setter(key, value);
|
|
747
|
+
if (setterUsed) {
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return setterUsed;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Register a parameter getter
|
|
755
|
+
*/
|
|
756
|
+
registerParamGetter(fn) {
|
|
757
|
+
this.paramGetters.push(fn);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Register a parameter setter
|
|
761
|
+
*/
|
|
762
|
+
registerParamSetter(fn) {
|
|
763
|
+
this.paramSetters.push(fn);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
// src/logger/index.ts
|
|
768
|
+
var import_chalk = __toESM(require("chalk"), 1);
|
|
769
|
+
var import_util = __toESM(require("util"), 1);
|
|
770
|
+
|
|
771
|
+
// src/logger/transports.ts
|
|
772
|
+
var ConsoleTransport = class {
|
|
773
|
+
write(payload) {
|
|
774
|
+
console.info(payload);
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
var ParentProcessTransport = class {
|
|
778
|
+
write(payload) {
|
|
779
|
+
if (process.env.VITEST || process.env.NODE_ENV === "test") {
|
|
780
|
+
console.info(payload);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
if (typeof process.send === "function" && process.connected === true) {
|
|
784
|
+
process.send(payload);
|
|
785
|
+
} else {
|
|
786
|
+
console.info(payload);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
|
|
791
|
+
// src/logger/index.ts
|
|
792
|
+
var ALL_LEVELS = [
|
|
793
|
+
"silly",
|
|
794
|
+
"debug",
|
|
795
|
+
"logic",
|
|
796
|
+
"info",
|
|
797
|
+
"notice",
|
|
798
|
+
"warn",
|
|
799
|
+
"error",
|
|
800
|
+
"results",
|
|
801
|
+
"request",
|
|
802
|
+
"response",
|
|
803
|
+
"progress"
|
|
804
|
+
];
|
|
805
|
+
var LEVEL_COLORS = {
|
|
806
|
+
error: import_chalk.default.red.bold,
|
|
807
|
+
warn: import_chalk.default.rgb(255, 165, 0),
|
|
808
|
+
notice: import_chalk.default.cyan,
|
|
809
|
+
info: import_chalk.default.white.bold,
|
|
810
|
+
logic: import_chalk.default.gray,
|
|
811
|
+
debug: import_chalk.default.gray,
|
|
812
|
+
silly: import_chalk.default.gray,
|
|
813
|
+
request: import_chalk.default.green,
|
|
814
|
+
response: import_chalk.default.yellow,
|
|
815
|
+
progress: import_chalk.default.green,
|
|
816
|
+
results: import_chalk.default.magenta
|
|
817
|
+
};
|
|
818
|
+
var CliToolkitLogger = class {
|
|
819
|
+
options;
|
|
820
|
+
transport;
|
|
821
|
+
startTimes = {};
|
|
822
|
+
lastProgressTimes = {};
|
|
823
|
+
constructor(options = {}) {
|
|
824
|
+
this.options = this.normalizeOptions(options);
|
|
825
|
+
this.transport = this.options.route === "ipc" ? new ParentProcessTransport() : new ConsoleTransport();
|
|
826
|
+
}
|
|
827
|
+
setMode(mode) {
|
|
828
|
+
if (!this.isValidMode(mode)) {
|
|
829
|
+
throw new Error(`Unsupported logger mode: ${mode}`);
|
|
830
|
+
}
|
|
831
|
+
this.options.mode = mode;
|
|
832
|
+
}
|
|
833
|
+
debug(message, ...chunks) {
|
|
834
|
+
this.out({ level: "debug", message, chunks });
|
|
835
|
+
}
|
|
836
|
+
info(message, ...chunks) {
|
|
837
|
+
this.out({ level: "info", message, chunks });
|
|
838
|
+
}
|
|
839
|
+
notice(message, ...chunks) {
|
|
840
|
+
this.out({ level: "notice", message, chunks });
|
|
841
|
+
}
|
|
842
|
+
warn(message, ...chunks) {
|
|
843
|
+
this.out({ level: "warn", message, chunks });
|
|
844
|
+
}
|
|
845
|
+
error(message, ...chunks) {
|
|
846
|
+
this.out({ level: "error", message, chunks });
|
|
847
|
+
}
|
|
848
|
+
logic(message, ...chunks) {
|
|
849
|
+
this.out({ level: "logic", message, chunks });
|
|
850
|
+
}
|
|
851
|
+
silly(message, ...chunks) {
|
|
852
|
+
this.out({ level: "silly", message, chunks });
|
|
853
|
+
}
|
|
854
|
+
results(results) {
|
|
855
|
+
this.out({ level: "results", message: "results", results });
|
|
856
|
+
}
|
|
857
|
+
request(operation, ...chunks) {
|
|
858
|
+
const message = this.inspectChunks([operation, ...chunks]);
|
|
859
|
+
this.out({ level: "request", message });
|
|
860
|
+
}
|
|
861
|
+
response(operation, ...chunks) {
|
|
862
|
+
const message = this.inspectChunks([operation, ...chunks]);
|
|
863
|
+
this.out({ level: "response", message });
|
|
864
|
+
}
|
|
865
|
+
progress(message, opts) {
|
|
866
|
+
const { prefix, count, total } = opts;
|
|
867
|
+
const paddedTotal = String(total).length;
|
|
868
|
+
const paddedCount = String(count).padStart(paddedTotal, " ");
|
|
869
|
+
const payload = {
|
|
870
|
+
level: "progress",
|
|
871
|
+
message,
|
|
872
|
+
count: paddedCount,
|
|
873
|
+
total,
|
|
874
|
+
prefix
|
|
875
|
+
};
|
|
876
|
+
if (!this.startTimes[prefix ?? ""]) {
|
|
877
|
+
this.startTimes[prefix ?? ""] = Date.now();
|
|
878
|
+
}
|
|
879
|
+
if (this.options.progressTimes) {
|
|
880
|
+
const elapsedSeconds = (Date.now() - this.startTimes[prefix ?? ""]) / 1e3;
|
|
881
|
+
let remaining = -1;
|
|
882
|
+
if (count > 1) {
|
|
883
|
+
const rate = elapsedSeconds / (count - 1);
|
|
884
|
+
remaining = (total - count) * rate;
|
|
885
|
+
}
|
|
886
|
+
payload.elapsed = this.round(elapsedSeconds, 2);
|
|
887
|
+
payload.remaining = remaining >= 0 ? this.round(remaining, 2) : remaining;
|
|
888
|
+
}
|
|
889
|
+
if (count >= total) {
|
|
890
|
+
delete this.startTimes[prefix ?? ""];
|
|
891
|
+
delete this.lastProgressTimes[prefix ?? ""];
|
|
892
|
+
}
|
|
893
|
+
if (this.shouldOutputProgress(prefix ?? "", count, total)) {
|
|
894
|
+
this.out(payload);
|
|
895
|
+
if (this.options.progressThrottle && prefix) {
|
|
896
|
+
this.lastProgressTimes[prefix] = Date.now();
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
shouldOutputProgress(prefix, count, total) {
|
|
901
|
+
if (!this.options.progressThrottle) {
|
|
902
|
+
return true;
|
|
903
|
+
}
|
|
904
|
+
if (count === 1 || count === total || !prefix) {
|
|
905
|
+
return true;
|
|
906
|
+
}
|
|
907
|
+
const lastTime = this.lastProgressTimes[prefix];
|
|
908
|
+
if (!lastTime) {
|
|
909
|
+
return true;
|
|
910
|
+
}
|
|
911
|
+
return Date.now() - lastTime >= this.options.progressThrottle;
|
|
912
|
+
}
|
|
913
|
+
out(struct) {
|
|
914
|
+
if (this.options.silent) {
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
if (!this.options.levels.includes(struct.level)) {
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (this.options.prefix && !struct.prefix) {
|
|
921
|
+
struct.prefix = this.options.prefix;
|
|
922
|
+
}
|
|
923
|
+
const output = this.options.mode === "json" ? struct : this.formatLog(struct);
|
|
924
|
+
this.transport.write(output);
|
|
925
|
+
}
|
|
926
|
+
formatLog(struct) {
|
|
927
|
+
const parts = [];
|
|
928
|
+
const now = /* @__PURE__ */ new Date();
|
|
929
|
+
if (this.options.timestamp) {
|
|
930
|
+
parts.push(now.toISOString());
|
|
931
|
+
}
|
|
932
|
+
if (this.options.showLevel) {
|
|
933
|
+
parts.push(struct.level.toUpperCase());
|
|
934
|
+
}
|
|
935
|
+
if (struct.level === "progress") {
|
|
936
|
+
if (struct.prefix) {
|
|
937
|
+
parts.push(LEVEL_COLORS[struct.level].bold(struct.prefix));
|
|
938
|
+
}
|
|
939
|
+
if (struct.count !== void 0 && struct.total !== void 0) {
|
|
940
|
+
parts.push(LEVEL_COLORS[struct.level](`${struct.count}/${struct.total}`));
|
|
941
|
+
}
|
|
942
|
+
} else if (struct.prefix) {
|
|
943
|
+
parts.push(import_chalk.default.cyan(`[${struct.prefix}]`));
|
|
944
|
+
}
|
|
945
|
+
if (struct.message) {
|
|
946
|
+
const formatter = LEVEL_COLORS[struct.level] ?? import_chalk.default.white;
|
|
947
|
+
parts.push(formatter.bold(struct.message));
|
|
948
|
+
}
|
|
949
|
+
if (struct.level === "progress") {
|
|
950
|
+
if (struct.elapsed !== void 0 && struct.remaining !== void 0) {
|
|
951
|
+
const formatter = LEVEL_COLORS[struct.level];
|
|
952
|
+
parts.push(formatter(`${struct.elapsed}/${struct.remaining}`));
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (struct.chunks && struct.chunks.length) {
|
|
956
|
+
parts.push(this.inspectChunks(struct.chunks));
|
|
957
|
+
}
|
|
958
|
+
if (struct.results) {
|
|
959
|
+
const formatter = LEVEL_COLORS[struct.level] ?? import_chalk.default.white;
|
|
960
|
+
parts.push(formatter(JSON.stringify(struct.results, null, 4)));
|
|
961
|
+
}
|
|
962
|
+
return parts.join(" ");
|
|
963
|
+
}
|
|
964
|
+
inspectChunks(chunks) {
|
|
965
|
+
return chunks.map((chunk) => import_util.default.inspect(chunk, { colors: true, depth: null })).join(" ");
|
|
966
|
+
}
|
|
967
|
+
normalizeOptions(options) {
|
|
968
|
+
const { route, mode, prefix, silent, showLevel, timestamp, levels, progress } = options;
|
|
969
|
+
const shouldUseIpc = this.shouldUseIpcRoute();
|
|
970
|
+
const normalized = {
|
|
971
|
+
mode: this.isValidMode(mode) ? mode : "text",
|
|
972
|
+
route: route ?? (shouldUseIpc ? "ipc" : "console"),
|
|
973
|
+
prefix,
|
|
974
|
+
silent: silent ?? false,
|
|
975
|
+
showLevel: showLevel ?? true,
|
|
976
|
+
timestamp: timestamp ?? false,
|
|
977
|
+
levels: this.normalizeLevels(levels),
|
|
978
|
+
progressTimes: progress?.withTimes ?? false,
|
|
979
|
+
progressThrottle: progress?.throttleMs
|
|
980
|
+
};
|
|
981
|
+
return normalized;
|
|
982
|
+
}
|
|
983
|
+
shouldUseIpcRoute() {
|
|
984
|
+
if (process.env.VITEST || process.env.NODE_ENV === "test") {
|
|
985
|
+
return false;
|
|
986
|
+
}
|
|
987
|
+
return typeof process.send === "function" && process.connected === true;
|
|
988
|
+
}
|
|
989
|
+
normalizeLevels(levels) {
|
|
990
|
+
if (!levels || !levels.length) {
|
|
991
|
+
return ALL_LEVELS;
|
|
992
|
+
}
|
|
993
|
+
const includes = levels.filter((level) => !level.startsWith("-"));
|
|
994
|
+
const excludes = levels.filter((level) => level.startsWith("-")).map((level) => level.slice(1));
|
|
995
|
+
const unknown = [...includes, ...excludes].filter((level) => !ALL_LEVELS.includes(level));
|
|
996
|
+
if (unknown.length) {
|
|
997
|
+
console.warn(`[Logger] Unknown level(s): ${unknown.join(", ")}`);
|
|
998
|
+
}
|
|
999
|
+
const base = includes.length ? includes : ALL_LEVELS;
|
|
1000
|
+
return base.filter((level) => !excludes.includes(level));
|
|
1001
|
+
}
|
|
1002
|
+
isValidMode(mode) {
|
|
1003
|
+
return mode === void 0 || mode === null || mode === "text" || mode === "json";
|
|
1004
|
+
}
|
|
1005
|
+
round(value, places) {
|
|
1006
|
+
const factor = Math.pow(10, places);
|
|
1007
|
+
return Math.round(value * factor) / factor;
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
|
|
1011
|
+
// src/init/index.ts
|
|
1012
|
+
var import_events = require("events");
|
|
1013
|
+
function setup(opts = {}) {
|
|
1014
|
+
const args = new Args({
|
|
1015
|
+
overrides: opts.overrides || {},
|
|
1016
|
+
defaults: opts.defaults || {}
|
|
1017
|
+
});
|
|
1018
|
+
const params = new Params({ args }, opts.overrides || {});
|
|
1019
|
+
const loggerOptions = opts.logger || {};
|
|
1020
|
+
const logger = new CliToolkitLogger({
|
|
1021
|
+
mode: loggerOptions.mode || "text",
|
|
1022
|
+
route: loggerOptions.route || "console",
|
|
1023
|
+
prefix: loggerOptions.prefix,
|
|
1024
|
+
silent: loggerOptions.silent,
|
|
1025
|
+
showLevel: loggerOptions.showLevel,
|
|
1026
|
+
timestamp: loggerOptions.timestamp,
|
|
1027
|
+
levels: loggerOptions.levels
|
|
1028
|
+
});
|
|
1029
|
+
const cleanupFunctions = [];
|
|
1030
|
+
const context = {
|
|
1031
|
+
args,
|
|
1032
|
+
params,
|
|
1033
|
+
logger,
|
|
1034
|
+
emitter: new import_events.EventEmitter(),
|
|
1035
|
+
isStop: () => false,
|
|
1036
|
+
// Will be set in init function
|
|
1037
|
+
cleanupFunctions,
|
|
1038
|
+
registerCleanup: (fn) => {
|
|
1039
|
+
cleanupFunctions.push(fn);
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
logger.debug("[setup] completed successfully");
|
|
1043
|
+
return context;
|
|
1044
|
+
}
|
|
1045
|
+
async function setupModules(context, opts = {}) {
|
|
1046
|
+
if (opts.modules && opts.modules.length > 0) {
|
|
1047
|
+
context.logger.debug(`[setupModules] modules specified: ${opts.modules.join(", ")} (not yet implemented)`);
|
|
1048
|
+
}
|
|
1049
|
+
context.logger.debug("[setupModules] completed successfully");
|
|
1050
|
+
return context;
|
|
1051
|
+
}
|
|
1052
|
+
async function init(flow, opts = {}) {
|
|
1053
|
+
let stop = false;
|
|
1054
|
+
let context = null;
|
|
1055
|
+
try {
|
|
1056
|
+
context = setup(opts);
|
|
1057
|
+
context.isStop = () => stop;
|
|
1058
|
+
context = await setupModules(context, opts);
|
|
1059
|
+
process.on("SIGINT", async () => {
|
|
1060
|
+
if (stop) {
|
|
1061
|
+
context.logger.warn("[process] killed");
|
|
1062
|
+
process.exit(2);
|
|
1063
|
+
}
|
|
1064
|
+
stop = true;
|
|
1065
|
+
let allowance = 5;
|
|
1066
|
+
try {
|
|
1067
|
+
allowance = context.params.get("stopAllowance", "number default 5");
|
|
1068
|
+
} catch {
|
|
1069
|
+
}
|
|
1070
|
+
context.logger.info(`>> emitting stop with allowance ${allowance}`);
|
|
1071
|
+
context.emitter.emit("stop", allowance);
|
|
1072
|
+
});
|
|
1073
|
+
await flow(context);
|
|
1074
|
+
} catch (error) {
|
|
1075
|
+
const errorLocation = error instanceof Error && error.stack ? error.stack.split("\n")[1]?.trim() || "Unknown location" : "Unknown location";
|
|
1076
|
+
if (error instanceof ParamError) {
|
|
1077
|
+
context?.logger.error(`[params]: ${error.message} (${errorLocation})`);
|
|
1078
|
+
process.exitCode = 3;
|
|
1079
|
+
} else if (error instanceof InitError) {
|
|
1080
|
+
context?.logger.error(`[init]: ${error.message} (${errorLocation})`);
|
|
1081
|
+
process.exitCode = 4;
|
|
1082
|
+
} else {
|
|
1083
|
+
context?.logger.error(`[other] error:`, error, errorLocation);
|
|
1084
|
+
process.exitCode = 5;
|
|
1085
|
+
}
|
|
1086
|
+
} finally {
|
|
1087
|
+
if (context) {
|
|
1088
|
+
for (const fn of context.cleanupFunctions.reverse()) {
|
|
1089
|
+
try {
|
|
1090
|
+
await fn(context);
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
context.logger.warn("[cleanup] error in cleanup function:", error);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
const unusedArgs = context.args.getUnused();
|
|
1096
|
+
if (unusedArgs.length > 0) {
|
|
1097
|
+
context.logger.warn("Unused CLI args:", unusedArgs.join(", "));
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
function setupContext(opts = {}) {
|
|
1103
|
+
return setup(opts);
|
|
1104
|
+
}
|
|
1105
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1106
|
+
0 && (module.exports = {
|
|
1107
|
+
init,
|
|
1108
|
+
setupContext
|
|
1109
|
+
});
|
|
1110
|
+
//# sourceMappingURL=init.cjs.map
|