@nmakarov/cli-toolkit 0.3.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.js CHANGED
@@ -2601,8 +2601,586 @@ var FileDatabase = class {
2601
2601
  return { ...this.metadata };
2602
2602
  }
2603
2603
  };
2604
+
2605
+ // src/db/index.ts
2606
+ import knex from "knex";
2607
+ var Db = class {
2608
+ knexInstance = null;
2609
+ config;
2610
+ logger;
2611
+ queriesLog = [];
2612
+ isConnected = false;
2613
+ constructor(config2) {
2614
+ if (!config2.connectionString) {
2615
+ throw new ParamError("Db: connectionString is required");
2616
+ }
2617
+ this.config = {
2618
+ testConnection: true,
2619
+ profile: false,
2620
+ pool: { min: 2, max: 10 },
2621
+ acquireConnectionTimeout: 1e4,
2622
+ ssl: { rejectUnauthorized: false },
2623
+ logger: console,
2624
+ name: "default",
2625
+ ...config2
2626
+ };
2627
+ this.logger = this.config.logger;
2628
+ const instance2 = this;
2629
+ const callableWrapper = function(...args) {
2630
+ throw new Error("This should never be called directly");
2631
+ };
2632
+ callableWrapper._instance = instance2;
2633
+ return new Proxy(callableWrapper, {
2634
+ // Intercept function calls: db('table')
2635
+ apply: (target, thisArg, argumentsList) => {
2636
+ const inst = target._instance;
2637
+ if (!inst.knexInstance) {
2638
+ throw new Error("Db: Not connected. Call connect() first.");
2639
+ }
2640
+ return inst.knexInstance(...argumentsList);
2641
+ },
2642
+ // Intercept property access: db.schema, db.raw, etc.
2643
+ get: (target, prop) => {
2644
+ if (prop === "_instance") {
2645
+ return target._instance;
2646
+ }
2647
+ const instance3 = target._instance;
2648
+ const ownMethods = [
2649
+ "connect",
2650
+ "disconnect",
2651
+ "testConnection",
2652
+ "tableExists",
2653
+ "getQueryLog",
2654
+ "getKnex",
2655
+ "isConnectedToDb",
2656
+ "getErrorMessage",
2657
+ "detectClient",
2658
+ "attachProfiler"
2659
+ ];
2660
+ if (prop in instance3) {
2661
+ const value = instance3[prop];
2662
+ if (typeof value === "function" && ownMethods.includes(prop)) {
2663
+ return value.bind(instance3);
2664
+ }
2665
+ if (typeof value !== "function") {
2666
+ return value;
2667
+ }
2668
+ }
2669
+ if (instance3.knexInstance) {
2670
+ const knexProp = instance3.knexInstance[prop];
2671
+ if (typeof knexProp === "function") {
2672
+ return knexProp.bind(instance3.knexInstance);
2673
+ }
2674
+ return knexProp;
2675
+ }
2676
+ if (prop in instance3) {
2677
+ const method = instance3[prop];
2678
+ if (typeof method === "function") {
2679
+ return method.bind(instance3);
2680
+ }
2681
+ return method;
2682
+ }
2683
+ return void 0;
2684
+ }
2685
+ });
2686
+ }
2687
+ /**
2688
+ * Detect database client type from connection string
2689
+ */
2690
+ detectClient(connectionString) {
2691
+ if (connectionString.match(/^postgresql/)) {
2692
+ return "pg";
2693
+ }
2694
+ if (connectionString.match(/^mysql/)) {
2695
+ return "mysql2";
2696
+ }
2697
+ return null;
2698
+ }
2699
+ /**
2700
+ * Connect to the database
2701
+ */
2702
+ async connect() {
2703
+ if (this.isConnected && this.knexInstance) {
2704
+ this.logger.warn?.("[Db] Already connected");
2705
+ return;
2706
+ }
2707
+ const client = this.detectClient(this.config.connectionString);
2708
+ if (!client) {
2709
+ throw new ParamError(
2710
+ `Db: Cannot determine client type from connection string. Expected postgresql:// or mysql://`
2711
+ );
2712
+ }
2713
+ try {
2714
+ const connectionConfig = {
2715
+ connectionString: this.config.connectionString,
2716
+ family: 4
2717
+ // Force IPv4 only (disable IPv6)
2718
+ };
2719
+ this.knexInstance = knex({
2720
+ client,
2721
+ connection: connectionConfig,
2722
+ pool: this.config.pool,
2723
+ acquireConnectionTimeout: this.config.acquireConnectionTimeout,
2724
+ ...this.config.ssl && { ssl: this.config.ssl }
2725
+ });
2726
+ if (this.config.profile) {
2727
+ this.attachProfiler();
2728
+ }
2729
+ if (this.config.testConnection) {
2730
+ await this.testConnection();
2731
+ }
2732
+ this.isConnected = true;
2733
+ this.logger.debug?.(`[Db] Connected to database "${this.config.name || this.config.connectionString}"`);
2734
+ } catch (error) {
2735
+ if (error instanceof ParamError) {
2736
+ throw error;
2737
+ }
2738
+ const errorMsg = this.getErrorMessage(error);
2739
+ throw new ParamError(`Db: Connection failed - ${errorMsg}`);
2740
+ }
2741
+ }
2742
+ /**
2743
+ * Disconnect from the database
2744
+ */
2745
+ async disconnect() {
2746
+ if (!this.knexInstance) {
2747
+ return;
2748
+ }
2749
+ try {
2750
+ await this.knexInstance.destroy();
2751
+ this.knexInstance = null;
2752
+ this.isConnected = false;
2753
+ this.queriesLog = [];
2754
+ this.logger.debug?.(`[Db] Disconnected from database "${this.config.name || this.config.connectionString}"`);
2755
+ } catch (error) {
2756
+ const errorMsg = this.getErrorMessage(error);
2757
+ this.logger.error?.(`[Db] Error disconnecting: ${errorMsg}`);
2758
+ throw error;
2759
+ }
2760
+ }
2761
+ /**
2762
+ * Extract error message from various error types
2763
+ */
2764
+ getErrorMessage(error) {
2765
+ if (error instanceof AggregateError) {
2766
+ const errors = error.errors || [];
2767
+ if (errors.length > 0) {
2768
+ const firstError = errors[0];
2769
+ const firstErrorMsg = firstError instanceof Error ? firstError.message : String(firstError);
2770
+ const allSimilar = errors.every((e) => {
2771
+ const msg = e instanceof Error ? e.message : String(e);
2772
+ const codeMatch = msg.match(/^(\w+)\s/);
2773
+ const firstCodeMatch = firstErrorMsg.match(/^(\w+)\s/);
2774
+ return codeMatch && firstCodeMatch && codeMatch[1] === firstCodeMatch[1];
2775
+ });
2776
+ if (allSimilar && errors.length > 1) {
2777
+ const addresses = errors.map((e) => {
2778
+ const msg = e instanceof Error ? e.message : String(e);
2779
+ const addrMatch = msg.match(/([:\d.]+:\d+)/);
2780
+ return addrMatch ? addrMatch[1] : null;
2781
+ }).filter(Boolean);
2782
+ if (addresses.length > 0) {
2783
+ const codeMatch = firstErrorMsg.match(/^(\w+)\s/);
2784
+ const code = codeMatch ? codeMatch[1] : "Connection error";
2785
+ return `${code} (tried: ${addresses.join(", ")})`;
2786
+ }
2787
+ }
2788
+ const uniqueMessages = [...new Set(errors.map((e) => {
2789
+ return e instanceof Error ? e.message : String(e);
2790
+ }))];
2791
+ if (uniqueMessages.length === 1) {
2792
+ return uniqueMessages[0];
2793
+ }
2794
+ return uniqueMessages.join("; ");
2795
+ }
2796
+ return error.message || "Multiple errors occurred";
2797
+ }
2798
+ if (error instanceof Error) {
2799
+ const errorWithCode = error;
2800
+ if (errorWithCode.code) {
2801
+ return `${errorWithCode.code}: ${error.message || String(error)}`;
2802
+ }
2803
+ return error.message || String(error);
2804
+ }
2805
+ if (typeof error === "string") {
2806
+ return error;
2807
+ }
2808
+ if (error?.message) {
2809
+ const msg = String(error.message);
2810
+ const errorWithCode = error;
2811
+ if (errorWithCode.code) {
2812
+ return `${errorWithCode.code}: ${msg}`;
2813
+ }
2814
+ return msg;
2815
+ }
2816
+ return String(error) || "Unknown error";
2817
+ }
2818
+ /**
2819
+ * Test database connection
2820
+ */
2821
+ async testConnection() {
2822
+ if (!this.knexInstance) {
2823
+ throw new Error("Db: Not connected. Call connect() first.");
2824
+ }
2825
+ try {
2826
+ const result = await this.knexInstance.raw("SELECT 2+3 AS result");
2827
+ const isOk = result.rows?.[0]?.result === 5 || result[0]?.[0]?.result === 5;
2828
+ this.logger.debug?.(`[Db] Connection test: ${isOk ? "OK" : "FAILED"}`);
2829
+ return isOk;
2830
+ } catch (error) {
2831
+ const errorMsg = this.getErrorMessage(error);
2832
+ this.logger.error?.(`[Db] Connection test failed: ${errorMsg}`);
2833
+ throw new ParamError(`Db: Connection test failed - ${errorMsg}`);
2834
+ }
2835
+ }
2836
+ /**
2837
+ * Attach query profiler to log all queries
2838
+ */
2839
+ attachProfiler() {
2840
+ if (!this.knexInstance) {
2841
+ return;
2842
+ }
2843
+ this.queriesLog = [];
2844
+ this.knexInstance.queriesLog = this.queriesLog;
2845
+ this.knexInstance.on("query", (query) => {
2846
+ query.__startTime = process.hrtime();
2847
+ });
2848
+ this.knexInstance.on("query-response", (response, query) => {
2849
+ const [seconds, nanoseconds] = process.hrtime(query.__startTime);
2850
+ const executionTimeMs = (seconds * 1e3 + nanoseconds / 1e6).toFixed(2);
2851
+ const logEntry = {
2852
+ sql: query.sql,
2853
+ bindings: query.bindings || [],
2854
+ executionTimeMs
2855
+ };
2856
+ this.queriesLog.push(logEntry);
2857
+ this.logger.debug?.(`[Db] Query: ${query.sql} | Duration: ${executionTimeMs}ms`);
2858
+ });
2859
+ this.knexInstance.on("query-error", (error, query) => {
2860
+ this.logger.error?.(`[Db] Query failed: ${query.sql}`, error);
2861
+ });
2862
+ }
2863
+ /**
2864
+ * Get query log (only available if profiling is enabled)
2865
+ */
2866
+ getQueryLog() {
2867
+ return [...this.queriesLog];
2868
+ }
2869
+ /**
2870
+ * Check if a table exists
2871
+ */
2872
+ async tableExists(tableName) {
2873
+ if (!this.knexInstance) {
2874
+ throw new Error("Db: Not connected. Call connect() first.");
2875
+ }
2876
+ try {
2877
+ return await this.knexInstance.schema.hasTable(tableName);
2878
+ } catch (error) {
2879
+ this.logger.error?.(`[Db] Error checking table existence: ${error.message}`);
2880
+ throw error;
2881
+ }
2882
+ }
2883
+ /**
2884
+ * Get the underlying Knex instance (for advanced usage)
2885
+ */
2886
+ getKnex() {
2887
+ if (!this.knexInstance) {
2888
+ throw new Error("Db: Not connected. Call connect() first.");
2889
+ }
2890
+ return this.knexInstance;
2891
+ }
2892
+ /**
2893
+ * Get connection status
2894
+ */
2895
+ isConnectedToDb() {
2896
+ return this.isConnected && this.knexInstance !== null;
2897
+ }
2898
+ };
2899
+
2900
+ // src/logger/index.ts
2901
+ import chalk from "chalk";
2902
+ import util from "util";
2903
+
2904
+ // src/logger/transports.ts
2905
+ var ConsoleTransport = class {
2906
+ write(payload) {
2907
+ console.info(payload);
2908
+ }
2909
+ };
2910
+ var ParentProcessTransport = class {
2911
+ write(payload) {
2912
+ if (process.env.VITEST || process.env.NODE_ENV === "test") {
2913
+ console.info(payload);
2914
+ return;
2915
+ }
2916
+ if (typeof process.send === "function" && process.connected === true) {
2917
+ process.send(payload);
2918
+ } else {
2919
+ console.info(payload);
2920
+ }
2921
+ }
2922
+ };
2923
+
2924
+ // src/logger/index.ts
2925
+ var ALL_LEVELS = [
2926
+ "silly",
2927
+ "debug",
2928
+ "logic",
2929
+ "info",
2930
+ "notice",
2931
+ "warn",
2932
+ "error",
2933
+ "results",
2934
+ "request",
2935
+ "response",
2936
+ "progress"
2937
+ ];
2938
+ var LEVEL_COLORS = {
2939
+ error: chalk.red.bold,
2940
+ warn: chalk.rgb(255, 165, 0),
2941
+ notice: chalk.cyan,
2942
+ info: chalk.white.bold,
2943
+ logic: chalk.gray,
2944
+ debug: chalk.gray,
2945
+ silly: chalk.gray,
2946
+ request: chalk.green,
2947
+ response: chalk.yellow,
2948
+ progress: chalk.green,
2949
+ results: chalk.magenta
2950
+ };
2951
+ var CliToolkitLogger = class {
2952
+ options;
2953
+ transport;
2954
+ startTimes = {};
2955
+ lastProgressTimes = {};
2956
+ constructor(options = {}) {
2957
+ this.options = this.normalizeOptions(options);
2958
+ this.transport = this.options.route === "ipc" ? new ParentProcessTransport() : new ConsoleTransport();
2959
+ }
2960
+ setMode(mode) {
2961
+ if (!this.isValidMode(mode)) {
2962
+ throw new Error(`Unsupported logger mode: ${mode}`);
2963
+ }
2964
+ this.options.mode = mode;
2965
+ }
2966
+ debug(message, ...chunks) {
2967
+ this.out({ level: "debug", message, chunks });
2968
+ }
2969
+ info(message, ...chunks) {
2970
+ this.out({ level: "info", message, chunks });
2971
+ }
2972
+ notice(message, ...chunks) {
2973
+ this.out({ level: "notice", message, chunks });
2974
+ }
2975
+ warn(message, ...chunks) {
2976
+ this.out({ level: "warn", message, chunks });
2977
+ }
2978
+ error(message, ...chunks) {
2979
+ this.out({ level: "error", message, chunks });
2980
+ }
2981
+ logic(message, ...chunks) {
2982
+ this.out({ level: "logic", message, chunks });
2983
+ }
2984
+ silly(message, ...chunks) {
2985
+ this.out({ level: "silly", message, chunks });
2986
+ }
2987
+ results(results) {
2988
+ this.out({ level: "results", message: "results", results });
2989
+ }
2990
+ request(operation, ...chunks) {
2991
+ const message = this.inspectChunks([operation, ...chunks]);
2992
+ this.out({ level: "request", message });
2993
+ }
2994
+ response(operation, ...chunks) {
2995
+ const message = this.inspectChunks([operation, ...chunks]);
2996
+ this.out({ level: "response", message });
2997
+ }
2998
+ progress(message, opts) {
2999
+ const { prefix, count, total } = opts;
3000
+ const paddedTotal = String(total).length;
3001
+ const paddedCount = String(count).padStart(paddedTotal, " ");
3002
+ const payload = {
3003
+ level: "progress",
3004
+ message,
3005
+ count: paddedCount,
3006
+ total,
3007
+ prefix
3008
+ };
3009
+ if (!this.startTimes[prefix ?? ""]) {
3010
+ this.startTimes[prefix ?? ""] = Date.now();
3011
+ }
3012
+ if (this.options.progressTimes) {
3013
+ const elapsedSeconds = (Date.now() - this.startTimes[prefix ?? ""]) / 1e3;
3014
+ let remaining = -1;
3015
+ if (count > 1) {
3016
+ const rate = elapsedSeconds / (count - 1);
3017
+ remaining = (total - count) * rate;
3018
+ }
3019
+ payload.elapsed = this.round(elapsedSeconds, 2);
3020
+ payload.remaining = remaining >= 0 ? this.round(remaining, 2) : remaining;
3021
+ }
3022
+ if (count >= total) {
3023
+ delete this.startTimes[prefix ?? ""];
3024
+ delete this.lastProgressTimes[prefix ?? ""];
3025
+ }
3026
+ if (this.shouldOutputProgress(prefix ?? "", count, total)) {
3027
+ this.out(payload);
3028
+ if (this.options.progressThrottle && prefix) {
3029
+ this.lastProgressTimes[prefix] = Date.now();
3030
+ }
3031
+ }
3032
+ }
3033
+ shouldOutputProgress(prefix, count, total) {
3034
+ if (!this.options.progressThrottle) {
3035
+ return true;
3036
+ }
3037
+ if (count === 1 || count === total || !prefix) {
3038
+ return true;
3039
+ }
3040
+ const lastTime = this.lastProgressTimes[prefix];
3041
+ if (!lastTime) {
3042
+ return true;
3043
+ }
3044
+ return Date.now() - lastTime >= this.options.progressThrottle;
3045
+ }
3046
+ out(struct) {
3047
+ if (this.options.silent) {
3048
+ return;
3049
+ }
3050
+ if (!this.options.levels.includes(struct.level)) {
3051
+ return;
3052
+ }
3053
+ if (this.options.prefix && !struct.prefix) {
3054
+ struct.prefix = this.options.prefix;
3055
+ }
3056
+ const output = this.options.mode === "json" ? struct : this.formatLog(struct);
3057
+ this.transport.write(output);
3058
+ }
3059
+ formatLog(struct) {
3060
+ const parts = [];
3061
+ const now = /* @__PURE__ */ new Date();
3062
+ if (this.options.timestamp) {
3063
+ parts.push(now.toISOString());
3064
+ }
3065
+ if (this.options.showLevel) {
3066
+ parts.push(struct.level.toUpperCase());
3067
+ }
3068
+ if (struct.level === "progress") {
3069
+ if (struct.prefix) {
3070
+ parts.push(LEVEL_COLORS[struct.level].bold(struct.prefix));
3071
+ }
3072
+ if (struct.count !== void 0 && struct.total !== void 0) {
3073
+ parts.push(LEVEL_COLORS[struct.level](`${struct.count}/${struct.total}`));
3074
+ }
3075
+ } else if (struct.prefix) {
3076
+ parts.push(chalk.cyan(`[${struct.prefix}]`));
3077
+ }
3078
+ if (struct.message) {
3079
+ const formatter = LEVEL_COLORS[struct.level] ?? chalk.white;
3080
+ parts.push(formatter.bold(struct.message));
3081
+ }
3082
+ if (struct.level === "progress") {
3083
+ if (struct.elapsed !== void 0 && struct.remaining !== void 0) {
3084
+ const formatter = LEVEL_COLORS[struct.level];
3085
+ parts.push(formatter(`${struct.elapsed}/${struct.remaining}`));
3086
+ }
3087
+ }
3088
+ if (struct.chunks && struct.chunks.length) {
3089
+ parts.push(this.inspectChunks(struct.chunks));
3090
+ }
3091
+ if (struct.results) {
3092
+ const formatter = LEVEL_COLORS[struct.level] ?? chalk.white;
3093
+ parts.push(formatter(JSON.stringify(struct.results, null, 4)));
3094
+ }
3095
+ return parts.join(" ");
3096
+ }
3097
+ inspectChunks(chunks) {
3098
+ return chunks.map((chunk) => util.inspect(chunk, { colors: true, depth: null })).join(" ");
3099
+ }
3100
+ normalizeOptions(options) {
3101
+ const { route, mode, prefix, silent, showLevel, timestamp, levels, progress } = options;
3102
+ const shouldUseIpc = this.shouldUseIpcRoute();
3103
+ const normalized = {
3104
+ mode: this.isValidMode(mode) ? mode : "text",
3105
+ route: route ?? (shouldUseIpc ? "ipc" : "console"),
3106
+ prefix,
3107
+ silent: silent ?? false,
3108
+ showLevel: showLevel ?? true,
3109
+ timestamp: timestamp ?? false,
3110
+ levels: this.normalizeLevels(levels),
3111
+ progressTimes: progress?.withTimes ?? false,
3112
+ progressThrottle: progress?.throttleMs
3113
+ };
3114
+ return normalized;
3115
+ }
3116
+ shouldUseIpcRoute() {
3117
+ if (process.env.VITEST || process.env.NODE_ENV === "test") {
3118
+ return false;
3119
+ }
3120
+ return typeof process.send === "function" && process.connected === true;
3121
+ }
3122
+ normalizeLevels(levels) {
3123
+ if (!levels || !levels.length) {
3124
+ return ALL_LEVELS;
3125
+ }
3126
+ const includes = levels.filter((level) => !level.startsWith("-"));
3127
+ const excludes = levels.filter((level) => level.startsWith("-")).map((level) => level.slice(1));
3128
+ const unknown = [...includes, ...excludes].filter((level) => !ALL_LEVELS.includes(level));
3129
+ if (unknown.length) {
3130
+ console.warn(`[Logger] Unknown level(s): ${unknown.join(", ")}`);
3131
+ }
3132
+ const base = includes.length ? includes : ALL_LEVELS;
3133
+ return base.filter((level) => !excludes.includes(level));
3134
+ }
3135
+ isValidMode(mode) {
3136
+ return mode === void 0 || mode === null || mode === "text" || mode === "json";
3137
+ }
3138
+ round(value, places) {
3139
+ const factor = Math.pow(10, places);
3140
+ return Math.round(value * factor) / factor;
3141
+ }
3142
+ };
3143
+
3144
+ // src/init/index.ts
3145
+ import { EventEmitter } from "events";
3146
+ function setup(opts = {}) {
3147
+ const args = new Args({
3148
+ overrides: opts.overrides || {},
3149
+ defaults: opts.defaults || {}
3150
+ });
3151
+ const params = new Params({ args }, opts.overrides || {});
3152
+ const loggerOptions = opts.logger || {};
3153
+ const logger = new CliToolkitLogger({
3154
+ mode: loggerOptions.mode || "text",
3155
+ route: loggerOptions.route || "console",
3156
+ prefix: loggerOptions.prefix,
3157
+ silent: loggerOptions.silent,
3158
+ showLevel: loggerOptions.showLevel,
3159
+ timestamp: loggerOptions.timestamp,
3160
+ levels: loggerOptions.levels
3161
+ });
3162
+ const cleanupFunctions = [];
3163
+ const context = {
3164
+ args,
3165
+ params,
3166
+ logger,
3167
+ emitter: new EventEmitter(),
3168
+ isStop: () => false,
3169
+ // Will be set in init function
3170
+ cleanupFunctions,
3171
+ registerCleanup: (fn) => {
3172
+ cleanupFunctions.push(fn);
3173
+ }
3174
+ };
3175
+ logger.debug("[setup] completed successfully");
3176
+ return context;
3177
+ }
3178
+ function setupContext(opts = {}) {
3179
+ return setup(opts);
3180
+ }
2604
3181
  export {
2605
3182
  Args,
3183
+ Db,
2606
3184
  Divider,
2607
3185
  FileDatabase,
2608
3186
  FileDatabaseError,
@@ -2631,6 +3209,7 @@ export {
2631
3209
  joiEdateType,
2632
3210
  joiStringArrayType,
2633
3211
  organizeFooterMessages,
3212
+ setupContext,
2634
3213
  showListScreen,
2635
3214
  showMenuScreen,
2636
3215
  showMultiColumnListScreen,