@master4n/master-cli 2.3.0 → 3.0.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 Master4Novice
3
+ Copyright (c) 2026 Master4Novice (dwivna)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,8 +1,16 @@
1
- # @master4n/master-cli
1
+ # @master4n/master-cli (`mfn`)
2
2
 
3
- ![Owner Badge](https://img.shields.io/badge/Owner-Master4Novice-orange?style=flat)
4
- ![Package License](https://img.shields.io/npm/l/%40master4n%2Fmaster-cli)
5
- ![Package Downloads](https://img.shields.io/npm/dm/%40master4n%2Fmaster-cli)
3
+ [![CI](https://github.com/Master4Novice/master-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/Master4Novice/master-cli/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/%40master4n%2Fmaster-cli)](https://www.npmjs.com/package/@master4n/master-cli)
5
+ ![npm downloads](https://img.shields.io/npm/dm/%40master4n%2Fmaster-cli)
6
+ ![License](https://img.shields.io/npm/l/%40master4n%2Fmaster-cli)
7
+ ![Owner](https://img.shields.io/badge/Owner-Master4Novice-orange?style=flat)
8
+
9
+ **Master CLI for developers and AI agents.** A set of headless, JSON-first
10
+ commands that replace the boilerplate agents otherwise regenerate on every
11
+ machine — timestamp/date conversion, JWT decoding, freeing ports, finding files,
12
+ and directory trees. Every command runs the same for a human at a terminal and
13
+ for an agent reading stdout.
6
14
 
7
15
  ## Installation
8
16
 
@@ -10,39 +18,77 @@
10
18
  npm install -g @master4n/master-cli
11
19
  ```
12
20
 
13
- ## Summary
21
+ This installs the `mfn` command.
14
22
 
15
- This package contains master-cli.
23
+ ## The contract (why it's agent-friendly)
16
24
 
17
- ## Details
25
+ - **Headless-first** — every command runs from flags/stdin. Interactive prompts
26
+ appear only on a TTY when required input is missing; with `--json` or when
27
+ piped, commands never block.
28
+ - **Machine-readable** — pass `--json` (or just pipe; non-TTY auto-emits) and you
29
+ get exactly one JSON object on stdout: `{ "ok": true, ... }` on success,
30
+ `{ "ok": false, "error", "message" }` on failure.
31
+ - **Stable exit codes** — `0` success · `1` runtime error · `2` usage error.
32
+ - **Clean channels** — the banner, spinners, and logs go to **stderr**; stdout
33
+ carries only data, so `mfn <cmd> --json | jq` always works.
34
+ - **Strict parsing** — unknown commands/flags and missing args fail loudly
35
+ (`{ok:false}`, exit 2), never a silent "success".
36
+ - **Self-describing** — `mfn capabilities --json` lists every command, and
37
+ [`llms.txt`](./llms.txt) documents the full agent contract.
18
38
 
19
- Use below command for help and options.
39
+ ## Quick start
20
40
 
21
- ```shell
22
- mfn -h # For help
23
- mfn -v # For installed version of master-cli
24
- mfn [command] -h # For help on specific command
41
+ ```sh
42
+ mfn -h # top-level help (lists every command)
43
+ mfn <command> -h # per-command help: flags + examples
44
+ mfn -v # version
45
+ mfn capabilities --json # machine-readable manifest of all commands
25
46
  ```
26
47
 
27
- ## Examples
28
-
29
- | Command | Option | Required | Description |
30
- | -------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
31
- | mfn md | -d myRootFolder | -d ( required ) | Make directory 'myRootFolder' inside current working directory |
32
- | mfn md | -d myRootFolder -s subFolder1 subFolder2 | -s ( optional ) | Make directory 'myRootFolder' inside current working directory and subdirectories [subFolder1, subFolder2] inside 'myRootFolder |
33
- | mfn cts | -t [svg/png/jpeg] | -t ( required ) | Save tree structure of content of current working directory in provided file type |
34
- | mfn cts | -t svg -l 300 -b 250 | -l & -b ( optional ) | Save file in a provided dimension |
35
- | mfn cts | -t svg -l 300 -b 250 -i .idea .bin node_modules package.json | -i ( optional ) | It will ignore provided files and folders while creating tree structure |
36
- | mfn sc | -i .idea .bin node_modules package.json | -i ( optional ) | It will help user to search the content of current working directory while ignoring provided files and folders from search list |
37
- | mfn hra | --mb 2000 --mr 800 --hr 750 --im true | -im ( optional ) | It will calculate your HRA. For India Exemption |
38
- | mfn sr | --mb 2000 --hr 750 --im true | -im ( optional ) | It will provide you calculated value of rent that will maximize your HRA. For India Exemption |
39
- | mfn decode | -t 'valid token' | | It will decode provided JWT token and display decoded result |
40
- | mfn date | | | Multiple date operations |
41
- | mfn create @apollo:express | | | This will create apollo graphql express template project. |
42
- | mfn kill | -p 8080 4000 | | This will kill process running on specific ports |
43
- | mfn update | | | This command update the CLI or a specified package to the latest version |
44
- | mfn epoch | | | Perform epoch converstions |
45
-
46
- ## Credits
47
-
48
- These definitions were written by [Master4Novice](https://github.com/Master4Novice).
48
+ ## Commands
49
+
50
+ | Command | What it does | Example |
51
+ | ------- | ------------ | ------- |
52
+ | `capabilities` | Self-describing manifest of every command | `mfn capabilities --json` |
53
+ | `id` | Generate IDs UUID v4, time-ordered UUID v7, or URL-safe nano | `mfn id --json` · `mfn id -t uuid7 -n 3 --json` |
54
+ | `hash` | Hash a string, file, or stdin (md5/sha1/sha256/sha512) | `mfn hash hello --json` · `mfn hash -f ./x --json` |
55
+ | `encode` | Encode/decode text base64, base64url, hex, url | `mfn encode hi --json` · `mfn encode aGk= -d --json` |
56
+ | `random` | Secure random bytes, or an unbiased password | `mfn random --json` · `mfn random -p -l 32 --json` |
57
+ | `port` | Find a free port, or check if one is available | `mfn port --json` · `mfn port -c 3000 --json` |
58
+ | `epoch` | Convert between epoch timestamps and dates (auto-detects s/ms/µs/ns) | `mfn epoch 1622547800 --json` · `mfn epoch --from 2021-06-01T11:43:20Z --json` |
59
+ | `date` | Convert/format a date across timezones (defaults to now) | `mfn date 2024-07-04T15:30:30Z --tz America/New_York --json` |
60
+ | `decode` | Decode a JWT (header + payload + expiry; signature **not** verified) | `mfn decode -t <jwt> --json` |
61
+ | `kill` | Kill the process(es) listening on given ports | `mfn kill -p 3000 8080 -y --json` |
62
+ | `sc` | Fuzzy-find files/folders under the current directory | `mfn sc service --json` |
63
+ | `cts` | Print (or export) a tree of the current directory | `mfn cts --json` · `mfn cts -t png` |
64
+ | `update` | Update the CLI (or a named package) to the latest version | `mfn update --json` |
65
+
66
+ Run `mfn <command> --help` for the full flag list and more examples.
67
+
68
+ ### Examples
69
+
70
+ ```sh
71
+ # Timestamps: any unit in, readable date out (parse cleanly in a script)
72
+ mfn epoch 1622547800000 --json | jq -r '.utc' # 2021-06-01 11:43:20.000
73
+
74
+ # Free the ports your dev server got stuck on
75
+ mfn kill -p 3000 5173 -y --json
76
+
77
+ # Inspect a JWT without a website
78
+ mfn decode -t "$TOKEN" --json | jq '.payload.exp'
79
+
80
+ # Hand an agent the repo layout
81
+ mfn cts --json | jq -r '.tree'
82
+ ```
83
+
84
+ ## Notes
85
+
86
+ - Date/time features are powered by
87
+ [`@master4n/temporal-transformer`](https://www.npmjs.com/package/@master4n/temporal-transformer)
88
+ v2 (Luxon-backed, integer epochs, `yyyy-MM-dd HH:mm:ss` tokens).
89
+ - Process/port/package operations use `execFile` (no shell), so inputs cannot
90
+ inject commands.
91
+
92
+ ## License
93
+
94
+ MIT © [Master4Novice](https://github.com/Master4Novice)
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Single source of truth for the command catalogue — consumed by the welcome
3
+ * banner (the "tools" line) and by `mfn capabilities` (the agent-facing
4
+ * manifest). Keep this in sync when adding a command.
5
+ */
6
+ export interface CommandInfo {
7
+ /** Invocation name, e.g. `epoch`. */
8
+ name: string;
9
+ /** One-line human summary. */
10
+ summary: string;
11
+ /** Copy-paste examples (headless, agent-friendly). */
12
+ examples: string[];
13
+ }
14
+ export declare const COMMANDS: readonly CommandInfo[];
@@ -0,0 +1,7 @@
1
+ declare const capabilities: {
2
+ command: string;
3
+ describe: string;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => void;
6
+ };
7
+ export default capabilities;
@@ -1,7 +1,7 @@
1
1
  declare const cts: {
2
2
  command: string;
3
3
  describe: string;
4
- builder: (yargs: any) => void;
4
+ builder: (yargs: any) => any;
5
5
  handler: (argv: any) => Promise<void>;
6
6
  };
7
7
  export default cts;
@@ -1,7 +1,7 @@
1
1
  declare const deco: {
2
2
  command: string;
3
3
  describe: string;
4
- builder: (yargs: any) => void;
5
- handler: (argv: any) => void;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => undefined;
6
6
  };
7
7
  export default deco;
@@ -0,0 +1,7 @@
1
+ declare const encodeCmd: {
2
+ command: string;
3
+ describe: string;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => Promise<undefined>;
6
+ };
7
+ export default encodeCmd;
@@ -0,0 +1,7 @@
1
+ declare const hash: {
2
+ command: string;
3
+ describe: string;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => Promise<undefined>;
6
+ };
7
+ export default hash;
@@ -0,0 +1,7 @@
1
+ declare const id: {
2
+ command: string;
3
+ describe: string;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => undefined;
6
+ };
7
+ export default id;
@@ -1,12 +1,14 @@
1
- import md from './md';
2
1
  import cts from './cts';
3
2
  import sc from './sc';
4
- import hra from './hra';
5
- import sr from './sr';
6
3
  import deco from './deco';
7
4
  import date from './date';
8
5
  import epoch from './epoch';
9
- import createApolloExpress from './create';
10
6
  import killProcess from './kill';
11
7
  import update from './update';
12
- export { md, cts, sc, hra, sr, deco, date, epoch, createApolloExpress, killProcess, update, };
8
+ import capabilities from './capabilities';
9
+ import id from './id';
10
+ import hash from './hash';
11
+ import encode from './encode';
12
+ import random from './random';
13
+ import port from './port';
14
+ export { cts, sc, deco, date, epoch, killProcess, update, capabilities, id, hash, encode, random, port, };
@@ -1,7 +1,7 @@
1
1
  declare const killProcess: {
2
2
  command: string;
3
3
  describe: string;
4
- builder: (yargs: any) => void;
4
+ builder: (yargs: any) => any;
5
5
  handler: (argv: any) => Promise<void>;
6
6
  };
7
7
  export default killProcess;
@@ -0,0 +1,10 @@
1
+ /** Resolve to a free port (0 lets the OS pick an available ephemeral port). */
2
+ declare function findFreePort(preferred?: number): Promise<number>;
3
+ export { findFreePort };
4
+ declare const port: {
5
+ command: string;
6
+ describe: string;
7
+ builder: (yargs: any) => any;
8
+ handler: (argv: any) => Promise<void>;
9
+ };
10
+ export default port;
@@ -0,0 +1,7 @@
1
+ declare const random: {
2
+ command: string;
3
+ describe: string;
4
+ builder: (yargs: any) => any;
5
+ handler: (argv: any) => void;
6
+ };
7
+ export default random;
@@ -1,7 +1,7 @@
1
1
  declare const sc: {
2
2
  command: string;
3
3
  describe: string;
4
- builder: (yargs: any) => void;
4
+ builder: (yargs: any) => any;
5
5
  handler: (argv: any) => Promise<void>;
6
6
  };
7
7
  export default sc;
@@ -1,7 +1,7 @@
1
1
  declare const update: {
2
2
  command: string;
3
3
  describe: string;
4
- builder: (yargs: any) => void;
4
+ builder: (yargs: any) => any;
5
5
  handler: (argv: any) => Promise<void>;
6
6
  };
7
7
  export default update;
package/bin/index.js CHANGED
@@ -1,35 +1,36 @@
1
1
  #!/usr/bin/env node
2
- import e from"yargs";import{format as t,inspect as o}from"util";import n,{normalize as r,resolve as s,dirname as i,basename as a,extname as c,relative as l}from"path";import u,{readFileSync as p,statSync as d,readdirSync as f,writeFile as m}from"fs";import{notStrictEqual as h,strictEqual as g}from"assert";import{fileURLToPath as y}from"url";import b from"chalk";import v from"figlet";import w from"boxen";import j from"inquirer";import S from"moment";import $ from"node:os";import x from"fs-extra";import{execSync as E,exec as O}from"node:child_process";import A from"sharp";import k from"inquirer-fuzzy-path";import M from"moment-timezone";import T from"inquirer-date-prompt";import D from"fuzzy";import Y from"inquirer-autocomplete-prompt";import{convertEpoch as N,convertDateToEpoch as R}from"@master4n/temporal-transformer";import _ from"ora";import{platform as F}from"os";Error;function L(){return process.versions.electron&&!process.defaultApp?0:1}
2
+ import e from"yargs";import{format as t}from"util";import n,{resolve as o,normalize as r}from"path";import s,{readFileSync as a,writeFile as i,statSync as c}from"fs";import"assert";import{fileURLToPath as l}from"url";import u from"chalk";import f from"figlet";import d from"boxen";import p from"node:os";import m from"fs-extra";import{execFile as h}from"node:child_process";import{getEpochNow as g,parseToEpoch as y,convertEpochToTimezone as b,convertEpoch as v}from"@master4n/temporal-transformer";import x from"sharp";import j from"inquirer";import w from"fuzzy";import{promisify as E}from"node:util";import{platform as $}from"os";import S from"ora";import{randomBytes as O,randomUUID as k,getHashes as N,createHash as I}from"node:crypto";import{readFile as A}from"node:fs/promises";import{createServer as T}from"node:net";function _(){return process.versions.electron&&!process.defaultApp?0:1}
3
3
  /**
4
4
  * @license
5
5
  * Copyright (c) 2016, Contributors
6
6
  * SPDX-License-Identifier: ISC
7
7
  */
8
- function I(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",o=!1;const n=e.match(/^-+/);for(let r=n?n[0].length:0;r<e.length;r++){let n=e.charAt(r);o&&(o=!1,n=n.toUpperCase()),0===r||"-"!==n&&"_"!==n?"-"!==n&&"_"!==n&&(t+=n):o=!0}return t}}function P(e,t){const o=e.toLowerCase();t=t||"-";let n="";for(let r=0;r<e.length;r++){const s=o.charAt(r),i=e.charAt(r);n+=s!==i&&r>0?`${t}${o.charAt(r)}`:i}return n}function B(e){return null!=e&&("number"==typeof e||(!!/^0x[0-9a-f]+$/i.test(e)||!/^0[^.]/.test(e)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)))}
8
+ function z(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",n=!1;const o=e.match(/^-+/);for(let r=o?o[0].length:0;r<e.length;r++){let o=e.charAt(r);n&&(n=!1,o=o.toUpperCase()),0===r||"-"!==o&&"_"!==o?"-"!==o&&"_"!==o&&(t+=o):n=!0}return t}}
9
9
  /**
10
10
  * @license
11
11
  * Copyright (c) 2016, Contributors
12
12
  * SPDX-License-Identifier: ISC
13
13
  */
14
+ var F;
14
15
  /**
15
16
  * @license
16
17
  * Copyright (c) 2016, Contributors
17
18
  * SPDX-License-Identifier: ISC
18
19
  */
19
- var z;
20
+ let L;!function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(F||(F={}));function B(e){return void 0!==e?e+1:1}function C(e){return"__proto__"===e?"___proto___":e}
20
21
  /**
22
+ * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
23
+ * CJS and ESM environments.
24
+ *
21
25
  * @license
22
26
  * Copyright (c) 2016, Contributors
23
27
  * SPDX-License-Identifier: ISC
24
28
  */
25
- let H;!function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(z||(z={}));function C(e){return void 0!==e?e+1:1}function q(e){return"__proto__"===e?"___proto___":e}
29
+ var D,M,U;const R=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,P=null!==(M=null===(D=null===process||void 0===process?void 0:process.versions)||void 0===D?void 0:D.node)&&void 0!==M?M:null===(U=null===process||void 0===process?void 0:process.version)||void 0===U?void 0:U.slice(1);if(P){if(Number(P.match(/^([^.]+)/)[1])<R)throw Error(`yargs parser supports a minimum Node.js version of ${R}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}const J=process?process.env:{};new class{constructor(e){L=e}parse(e,t){const n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=
26
30
  /**
27
- * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
28
- * CJS and ESM environments.
29
- *
30
31
  * @license
31
32
  * Copyright (c) 2016, Contributors
32
33
  * SPDX-License-Identifier: ISC
33
34
  */
34
- var U,J,W;const G=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Q=null!==(J=null===(U=null===process||void 0===process?void 0:process.versions)||void 0===U?void 0:U.node)&&void 0!==J?J:null===(W=null===process||void 0===process?void 0:process.version)||void 0===W?void 0:W.slice(1);if(Q){if(Number(Q.match(/^([^.]+)/)[1])<G)throw Error(`yargs parser supports a minimum Node.js version of ${G}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}const Z=process?process.env:{},V=new class{constructor(e){H=e}parse(e,t){const o=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),n=function(e){if(Array.isArray(e))return e.map((e=>"string"!=typeof e?e+"":e));e=e.trim();let t=0,o=null,n=null,r=null;const s=[];for(let i=0;i<e.length;i++)o=n,n=e.charAt(i)," "!==n||r?(n===r?r=null:"'"!==n&&'"'!==n||r||(r=n),s[t]||(s[t]=""),s[t]+=n):" "!==o&&t++;return s}(e),r="string"==typeof e,s=function(e){const t=[],o=Object.create(null);let n=!0;Object.keys(e).forEach((function(o){t.push([].concat(e[o],o))}));for(;n;){n=!1;for(let e=0;e<t.length;e++)for(let o=e+1;o<t.length;o++){if(t[e].filter((function(e){return-1!==t[o].indexOf(e)})).length){t[e]=t[e].concat(t[o]),t.splice(o,1),n=!0;break}}}return t.forEach((function(e){const t=(e=e.filter((function(e,t,o){return o.indexOf(e)===t}))).pop();void 0!==t&&"string"==typeof t&&(o[t]=e)})),o}(Object.assign(Object.create(null),o.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},o.configuration),a=Object.assign(Object.create(null),o.default),c=o.configObjects||[],l=o.envPrefix,u=i["populate--"],p=u?"--":"_",d=Object.create(null),f=Object.create(null),m=o.__||H.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,y=new RegExp("^--"+i["negation-prefix"]+"(.+)");[].concat(o.array||[]).filter(Boolean).forEach((function(e){const t="object"==typeof e?e.key:e,o=Object.keys(e).map((function(e){return{boolean:"bools",string:"strings",number:"numbers"}[e]})).filter(Boolean).pop();o&&(h[o][t]=!0),h.arrays[t]=!0,h.keys.push(t)})),[].concat(o.boolean||[]).filter(Boolean).forEach((function(e){h.bools[e]=!0,h.keys.push(e)})),[].concat(o.string||[]).filter(Boolean).forEach((function(e){h.strings[e]=!0,h.keys.push(e)})),[].concat(o.number||[]).filter(Boolean).forEach((function(e){h.numbers[e]=!0,h.keys.push(e)})),[].concat(o.count||[]).filter(Boolean).forEach((function(e){h.counts[e]=!0,h.keys.push(e)})),[].concat(o.normalize||[]).filter(Boolean).forEach((function(e){h.normalize[e]=!0,h.keys.push(e)})),"object"==typeof o.narg&&Object.entries(o.narg).forEach((([e,t])=>{"number"==typeof t&&(h.nargs[e]=t,h.keys.push(e))})),"object"==typeof o.coerce&&Object.entries(o.coerce).forEach((([e,t])=>{"function"==typeof t&&(h.coercions[e]=t,h.keys.push(e))})),void 0!==o.config&&(Array.isArray(o.config)||"string"==typeof o.config?[].concat(o.config).filter(Boolean).forEach((function(e){h.configs[e]=!0})):"object"==typeof o.config&&Object.entries(o.config).forEach((([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(h.configs[e]=t)}))),function(...e){e.forEach((function(e){Object.keys(e||{}).forEach((function(e){h.aliases[e]||(h.aliases[e]=[].concat(s[e]||[]),h.aliases[e].concat(e).forEach((function(t){if(/-/.test(t)&&i["camel-case-expansion"]){const o=I(t);o!==e&&-1===h.aliases[e].indexOf(o)&&(h.aliases[e].push(o),d[o]=!0)}})),h.aliases[e].concat(e).forEach((function(t){if(t.length>1&&/[A-Z]/.test(t)&&i["camel-case-expansion"]){const o=P(t,"-");o!==e&&-1===h.aliases[e].indexOf(o)&&(h.aliases[e].push(o),d[o]=!0)}})),h.aliases[e].forEach((function(t){h.aliases[t]=[e].concat(h.aliases[e].filter((function(e){return t!==e})))})))}))}))}(o.key,s,o.default,h.arrays),Object.keys(a).forEach((function(e){(h.aliases[e]||[]).forEach((function(t){a[t]=a[e]}))}));let b=null;Object.keys(h.counts).find((e=>R(e,h.arrays)?(b=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!R(e,h.nargs)&&(b=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0)));let v=[];const w=Object.assign(Object.create(null),{_:[]}),j={};for(let e=0;e<n.length;e++){const t=n[e],o=t.replace(/^-{3,}/,"---");let r,s,a,c,l,u;if("--"!==t&&/^-/.test(t)&&F(t))S(t);else{if(o.match(/^---+(=|$)/)){S(t);continue}if(t.match(/^--.+=/)||!i["short-option-groups"]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&(R(c[1],h.arrays)?e=x(e,c[1],n,c[2]):!1!==R(c[1],h.nargs)?e=$(e,c[1],n,c[2]):E(c[1],c[2],!0));else if(t.match(y)&&i["boolean-negation"])c=t.match(y),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],E(s,!!R(s,h.arrays)&&[!1]));else if(t.match(/^--.+/)||!i["short-option-groups"]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],R(s,h.arrays)?e=x(e,s,n):!1!==R(s,h.nargs)?e=$(e,s,n):(l=n[e+1],void 0===l||l.match(/^-/)&&!l.match(g)||R(s,h.bools)||R(s,h.counts)?/^(true|false)$/.test(l)?(E(s,l),e++):E(s,L(s)):(E(s,l),e++)));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&E(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(g))l=n[e+1],c=t.match(/^-(.\..+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],void 0===l||l.match(/^-/)||R(s,h.bools)||R(s,h.counts)?E(s,L(s)):(E(s,l),e++));else if(t.match(/^-[^-]+/)&&!t.match(g)){a=t.slice(1,-1).split(""),r=!1;for(let o=0;o<a.length;o++){if(l=t.slice(o+2),a[o+1]&&"="===a[o+1]){u=t.slice(o+3),s=a[o],R(s,h.arrays)?e=x(e,s,n,u):!1!==R(s,h.nargs)?e=$(e,s,n,u):E(s,u),r=!0;break}if("-"!==l){if(/[A-Za-z]/.test(a[o])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&!1===R(l,h.bools)){E(a[o],l),r=!0;break}if(a[o+1]&&a[o+1].match(/\W/)){E(a[o],l),r=!0;break}E(a[o],L(a[o]))}else E(a[o],l)}s=t.slice(-1)[0],r||"-"===s||(R(s,h.arrays)?e=x(e,s,n):!1!==R(s,h.nargs)?e=$(e,s,n):(l=n[e+1],void 0===l||/^(-|--)[^-]/.test(l)&&!l.match(g)||R(s,h.bools)||R(s,h.counts)?/^(true|false)$/.test(l)?(E(s,l),e++):E(s,L(s)):(E(s,l),e++)))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&R(t.slice(1),h.bools))s=t.slice(1),E(s,L(s));else{if("--"===t){v=n.slice(e+1);break}if(i["halt-at-non-option"]){v=n.slice(e);break}S(t)}}}function S(e){const t=k("_",e);"string"!=typeof t&&"number"!=typeof t||w._.push(t)}function $(e,t,o,n){let r,s=R(t,h.nargs);if(s="number"!=typeof s||isNaN(s)?1:s,0===s)return U(n)||(b=Error(m("Argument unexpected for: %s",t))),E(t,L(t)),e;let a=U(n)?0:1;if(i["nargs-eats-options"])o.length-(e+1)+a<s&&(b=Error(m("Not enough arguments following: %s",t))),a=s;else{for(r=e+1;r<o.length&&(!o[r].match(/^-[^0-9]/)||o[r].match(g)||F(o[r]));r++)a++;a<s&&(b=Error(m("Not enough arguments following: %s",t)))}let c=Math.min(a,s);for(!U(n)&&c>0&&(E(t,n),c--),r=e+1;r<c+e+1;r++)E(t,o[r]);return e+c}function x(e,t,o,n){let s=[],c=n||o[e+1];const l=R(t,h.nargs);if(R(t,h.bools)&&!/^(true|false)$/.test(c))s.push(!0);else if(U(c)||U(n)&&/^-/.test(c)&&!g.test(c)&&!F(c)){if(void 0!==a[t]){const e=a[t];s=Array.isArray(e)?e:[e]}}else{U(n)||s.push(A(t,n,!0));for(let n=e+1;n<o.length&&!(!i["greedy-arrays"]&&s.length>0||l&&"number"==typeof l&&s.length>=l)&&(c=o[n],!/^-/.test(c)||g.test(c)||F(c));n++)e=n,s.push(A(t,c,r))}return"number"==typeof l&&(l&&s.length<l||isNaN(l)&&0===s.length)&&(b=Error(m("Not enough arguments following: %s",t))),E(t,s),e}function E(e,t,o=r){if(/-/.test(e)&&i["camel-case-expansion"]){const t=e.split(".").map((function(e){return I(e)})).join(".");O(e,t)}const n=A(e,t,o),s=e.split(".");if(N(w,s,n),h.aliases[e]&&h.aliases[e].forEach((function(e){const t=e.split(".");N(w,t,n)})),s.length>1&&i["dot-notation"]&&(h.aliases[s[0]]||[]).forEach((function(t){let o=t.split(".");const r=[].concat(s);r.shift(),o=o.concat(r),(h.aliases[e]||[]).includes(o.join("."))||N(w,o,n)})),R(e,h.normalize)&&!R(e,h.arrays)){[e].concat(h.aliases[e]||[]).forEach((function(e){Object.defineProperty(j,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?H.normalize(e):e}})}))}}function O(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],d[t]=!0),h.aliases[t]&&h.aliases[t].length||O(t,e)}function A(e,t,o){o&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(R(e,h.bools)||R(e,h.counts))&&"string"==typeof t&&(t="true"===t);let n=Array.isArray(t)?t.map((function(t){return k(e,t)})):k(e,t);return R(e,h.counts)&&(U(n)||"boolean"==typeof n)&&(n=C()),R(e,h.normalize)&&R(e,h.arrays)&&(n=Array.isArray(t)?t.map((e=>H.normalize(e))):H.normalize(t)),n}function k(e,t){if(!i["parse-positional-numbers"]&&"_"===e)return t;if(!R(e,h.strings)&&!R(e,h.bools)&&!Array.isArray(t)){(B(t)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!U(t)&&R(e,h.numbers))&&(t=Number(t))}return t}function M(e,t){Object.keys(e).forEach((function(o){const n=e[o],r=t?t+"."+o:o;"object"==typeof n&&null!==n&&!Array.isArray(n)&&i["dot-notation"]?M(n,r):(!Y(w,r.split("."))||R(r,h.arrays)&&i["combine-arrays"])&&E(r,n)}))}function T(e,t){if(void 0===l)return;const o="string"==typeof l?l:"",n=H.env();Object.keys(n).forEach((function(r){if(""===o||0===r.lastIndexOf(o,0)){const s=r.split("__").map((function(e,t){return 0===t&&(e=e.substring(o.length)),I(e)}));(t&&h.configs[s.join(".")]||!t)&&!Y(e,s)&&E(s.join("."),n[r])}}))}function D(e,t,o,n=!1){Object.keys(o).forEach((function(r){Y(e,r.split("."))||(N(e,r.split("."),o[r]),n&&(f[r]=!0),(t[r]||[]).forEach((function(t){Y(e,t.split("."))||N(e,t.split("."),o[r])})))}))}function Y(e,t){let o=e;i["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){o=o[e]||{}}));const n=t[t.length-1];return"object"==typeof o&&n in o}function N(e,t,o){let n=e;i["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach((function(e){e=q(e),"object"==typeof n&&void 0===n[e]&&(n[e]={}),"object"!=typeof n[e]||Array.isArray(n[e])?(Array.isArray(n[e])?n[e].push({}):n[e]=[n[e],{}],n=n[e][n[e].length-1]):n=n[e]}));const r=q(t[t.length-1]),s=R(t.join("."),h.arrays),a=Array.isArray(o);let c=i["duplicate-arguments-array"];!c&&R(r,h.nargs)&&(c=!0,(!U(n[r])&&1===h.nargs[r]||Array.isArray(n[r])&&n[r].length===h.nargs[r])&&(n[r]=void 0)),o===C()?n[r]=C(n[r]):Array.isArray(n[r])?c&&s&&a?n[r]=i["flatten-duplicate-arrays"]?n[r].concat(o):(Array.isArray(n[r][0])?n[r]:[n[r]]).concat([o]):c||Boolean(s)!==Boolean(a)?n[r]=n[r].concat([o]):n[r]=o:void 0===n[r]&&s?n[r]=a?o:[o]:!c||void 0===n[r]||R(r,h.counts)||R(r,h.bools)?n[r]=o:n[r]=[n[r],o]}function R(e,t){const o=[].concat(h.aliases[e]||[],e),n=Object.keys(t),r=o.find((e=>n.includes(e)));return!!r&&t[r]}function _(e){const t=Object.keys(h);return[].concat(t.map((e=>h[e]))).some((function(t){return Array.isArray(t)?t.includes(e):t[e]}))}function F(e){return i["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(g))return!1;if(function(e){if(e.match(g)||!e.match(/^-[^-]+/))return!1;let t,o=!0;const n=e.slice(1).split("");for(let r=0;r<n.length;r++){if(t=e.slice(r+2),!_(n[r])){o=!1;break}if(n[r+1]&&"="===n[r+1]||"-"===t||/[A-Za-z]/.test(n[r])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(t)||n[r+1]&&n[r+1].match(/\W/))break}return o}(e))return!1;return!function(e,...t){return[].concat(...t).some((function(t){const o=e.match(t);return o&&_(o[1])}))}(e,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}(e)}function L(e){return R(e,h.bools)||R(e,h.counts)||!(`${e}`in a)?(t=function(e){let t=z.BOOLEAN;return R(e,h.strings)?t=z.STRING:R(e,h.numbers)?t=z.NUMBER:R(e,h.bools)?t=z.BOOLEAN:R(e,h.arrays)&&(t=z.ARRAY),t}(e),{[z.BOOLEAN]:!0,[z.STRING]:"",[z.NUMBER]:void 0,[z.ARRAY]:[]}[t]):a[e];var t}function U(e){return void 0===e}return T(w,!0),T(w,!1),function(e){const t=Object.create(null);D(t,h.aliases,a),Object.keys(h.configs).forEach((function(o){const n=e[o]||t[o];if(n)try{let e=null;const t=H.resolve(H.cwd(),n),r=h.configs[o];if("function"==typeof r){try{e=r(t)}catch(t){e=t}if(e instanceof Error)return void(b=e)}else e=H.require(t);M(e)}catch(t){"PermissionDenied"===t.name?b=t:e[o]&&(b=Error(m("Invalid JSON config file: %s",n)))}}))}(w),void 0!==c&&c.forEach((function(e){M(e)})),D(w,h.aliases,a,!0),function(e){let t;const o=new Set;Object.keys(e).forEach((function(n){if(!o.has(n)&&(t=R(n,h.coercions),"function"==typeof t))try{const r=k(n,t(e[n]));[].concat(h.aliases[n]||[],n).forEach((t=>{o.add(t),e[t]=r}))}catch(e){b=e}}))}(w),i["set-placeholder-key"]&&function(e){h.keys.forEach((t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)}))}(w),Object.keys(h.counts).forEach((function(e){Y(w,e.split("."))||E(e,0)})),u&&v.length&&(w[p]=[]),v.forEach((function(e){w[p].push(e)})),i["camel-case-expansion"]&&i["strip-dashed"]&&Object.keys(w).filter((e=>"--"!==e&&e.includes("-"))).forEach((e=>{delete w[e]})),i["strip-aliased"]&&[].concat(...Object.keys(s).map((e=>s[e]))).forEach((e=>{i["camel-case-expansion"]&&e.includes("-")&&delete w[e.split(".").map((e=>I(e))).join(".")],delete w[e]})),{aliases:Object.assign({},h.aliases),argv:Object.assign(j,w),configuration:i,defaulted:Object.assign({},f),error:b,newAliases:Object.assign({},d)}}}({cwd:process.cwd,env:()=>Z,format:t,normalize:r,resolve:s,require:e=>{if("undefined"!=typeof require)return require(e);if(e.match(/\.json$/))return JSON.parse(p(e,"utf8"));throw Error("only .json config files are supported in ESM")}}),K=function(e,t){return V.parse(e.slice(),t).argv};K.detailed=function(e,t){return V.parse(e.slice(),t)},K.camelCase=I,K.decamelize=P,K.looksLikeNumber=B;new RegExp("(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");var X={fs:{readFileSync:p,writeFile:m},format:t,resolve:s,exists:e=>{try{return d(e).isFile()}catch(e){return!1}}};let ee;class te{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let o=function(){};return"function"==typeof e[e.length-1]&&(o=e.pop()),o=o||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o})):o(),ee.format.apply(ee.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),o=e.shift(),n=e.shift();let r=function(){};"function"==typeof e[e.length-1]&&(r=e.pop()),this.cache[this.locale]||this._readLocaleFile();let s=1===n?t:o;if(this.cache[this.locale][t]){s=this.cache[this.locale][t][1===n?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:o},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r})):r();const i=[s];return~s.indexOf("%d")&&i.push(n),ee.format.apply(ee.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let o="";return e.forEach((function(e,n){const r=t[n+1];o+=e,void 0!==r&&(o+="%s")})),this.__.apply(this,[o].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],o=t.directory,n=t.locale,r=t.cb,s=this._resolveLocaleFile(o,n),i=JSON.stringify(this.cache[n],null,2);ee.fs.writeFile(s,i,"utf-8",(function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),r(t)}))}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{ee.fs.readFileSync&&(e=JSON.parse(ee.fs.readFileSync(t,"utf-8")))}catch(o){if(o instanceof SyntaxError&&(o.message="syntax error in "+t),"ENOENT"!==o.code)throw o;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let o=ee.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(o)&&~t.lastIndexOf("_")){const n=ee.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(n)&&(o=n)}return o}_fileExistsSync(e){return ee.exists(e)}}let oe;try{oe=y(import.meta.url)}catch(e){oe=process.cwd()}oe.substring(0,oe.lastIndexOf("node_modules"))||process.cwd(),process.cwd,process.exit,process.nextTick,void 0!==process.stdout.columns&&process.stdout.columns,function(e,t){ee=t;const o=new te(e);o.__.bind(o),o.__n.bind(o),o.setLocale.bind(o),o.getLocale.bind(o),o.updateLocale.bind(o),o.locale}({directory:s(oe,"../../../locales"),updateFiles:!1},X);function ne(){return{info:e=>{return console.log(`${b.blue("INFO")} [${b.magenta(S().format("YYYY/MM/DDTHH:mm:ss.SSSSSS"))}] ${t=e,b.white(t)}\n`);var t},warn:e=>{return console.log(`${b.yellow("WARN")} [${b.magenta(S().format("YYYY/MM/DDTHH:mm:ss.SSSSSS"))}] ${t=e,b.white(t)}`);var t},error:e=>{return console.log(`${b.red("ERROR")} [${b.magenta(S().format("YYYY/MM/DDTHH:mm:ss.SSSSSS"))}] ${t=e,b.white(t)}`);var t},debug:e=>{return console.log(`${b.cyan("DEBUG")} [${b.magenta(S().format("YYYY/MM/DDTHH:mm:ss.SSSSSS"))}] ${t=e,b.white(t)}`);var t}}}function re(e){return{add:(t,o,n,r)=>{e.command({command:t,describe:o,builder:n,handler:r})}}}function se(){const e=$.homedir();return n.join(e,".mfn","cache")}function ie(...e){for(const t of e)if(isNaN(t)||t<1)return!1;return!0}function ae(e,t="INR",o="en-IN"){return new Intl.NumberFormat(o,{style:"currency",currency:t}).format(e)}function ce(e){return E(`npm show ${e} version`).toString().trim()}const le=e=>b.green(e);async function ue(e,t){await x.writeJson(t,e,{spaces:2})}!function(){const e=$.homedir(),t=n.join(e,".mfn","cache");if(!u.existsSync(t))try{u.existsSync(n.join(e,".mfn"))||u.mkdirSync(n.join(e,".mfn")),u.mkdirSync(t,{recursive:!0})}catch(e){}}(),await(async()=>{const e=await(t="M4N-CLI",new Promise(((e,o)=>{v(t,((t,n)=>{t?o(t):e(n)}))})));var t;const o=w(b.hex("#27A244").bold(e),{padding:1,margin:1,dimBorder:!0,borderStyle:"round",borderColor:"#C1C110"}),n=function(){const e=$.platform();return"win32"===e?process.env.USERNAME||"User":"darwin"===e||"linux"===e?process.env.USER||"User":""}();console.log(b.whiteBright.bold("-------------------------------------------------------\n")),console.log(o),n&&n.length>0?console.log(b.magenta(`\n\tWelcome ${n} to the Master4Novice CLI Tool!\n`)):console.log(b.blue("\n\tWelcome to the Master4Novice CLI Tool!\n")),console.log(b.yellow("\tUse this tool to reduce your effort.\n")),console.log(b.white("-------------------------------------------------------\n"))})();const pe=e(process.argv.slice(L()+1));const de=b.hex("#44bcd8").bold("mfn");var fe=pe.scriptName(de);const me=ne(),he=(e,t)=>{me.info("Started creating subdirectories..."),t.forEach((t=>{const o=n.join(e,t);u.existsSync(o)?me.warn("Subdirectory already exists..."):(u.mkdirSync(o,{recursive:!0}),me.info(`Created subdirectory - /${t}`))}))},ge=(e,t)=>{me.info(`Current working directory: ${process.cwd()}`);const o=n.join(process.cwd(),e);u.existsSync(o)?(me.warn("Root directory already exist"),t&&t.length>0&&he(o,t)):(me.info("Started creating root directory inside current working directory..."),u.mkdirSync(o,{recursive:!0}),me.info(`Created root directory - /${e}`),t&&t.length>0&&he(o,t))},ye="md",be="Make directory and its subdirectories",ve=e=>{e.option("d",{alias:"directory",describe:"The root directory to create",type:"string",demandOption:!0}).option("s",{alias:"subdirectories",describe:"Subdirectories to create within the root directory",type:"array"})},we=e=>{if(e.directory&&e.directory.length>0){if(void 0===e.subdirectories)ge(e.directory,e.subdirectories);else{if(0===e.subdirectories.length)return void me.error("Invalid subdirectories name");ge(e.directory,e.subdirectories)}console.log("\n")}else me.error("Invalid directory name")},je=ne(),Se=n.join(se(),"cts_ignore.json");let $e="",xe=20;let Ee="";async function Oe(){try{return await x.readJson(Se)}catch(e){if("ENOENT"===e.code)return{ignores:[]};throw e}}function Ae(e,t,o="",r=0){const s=x.readdirSync(e);s.forEach(((i,a)=>{if(t&&t.includes(i))return;const c=n.join(e,i),l=a===s.length-1,u=x.statSync(c).isDirectory();Ee+=`${o}${l?"└── ":"├── "}${i}`+"\n",u&&Ae(c,t,`${o}${l?" ":"│ "}`,r+1)}))}function ke(e,t,o=0,r=new Array){const s=x.readdirSync(e);s.forEach(((i,a)=>{if(t&&t.includes(i))return;const c=n.join(e,i),l=a===s.length-1,u=x.statSync(c).isDirectory();let p="";r.forEach(((e,t)=>{p+=e?"\t".repeat(4):"│"+"\t".repeat(3)})),p+=l?"└── ":"├── ";if($e+=`<text style="white-space: pre;" x="${0*o}" y="${xe}">${`${p}${i}`}</text>`,xe+=20,u){const e=[...r,l];ke(c,t,o+1,e)}}))}function Me(e){return Buffer.from(e)}const Te=async(e,t,o,r)=>{je.info(`Processing current working directory: ${process.cwd()}`);const s=n.join(process.cwd()),i=n.basename(s);Ee+=i+"\n",Ae(s,t),$e+=`<text x="0" y="20">${i}</text>`,xe+=20,ke(s,t),$e=`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${o}"><rect width="100%" height="100%" fill="white"/><g fill="black" font-family="monospace" font-size="12">`+$e+"</g></svg>";const a=i+"."+e;switch(e){case"png":{const e=Me($e);await A(e).png().toFile(a),je.info(`Tree structure created for ${i} in file ${a}.`);break}case"jpeg":{const e=Me($e);await A(e).jpeg().toFile(a),je.info(`Tree structure created for ${i} in file ${a}.`);break}case"svg":x.outputFileSync(a,$e),je.info(`Tree structure created for ${i} in file ${a}.`);break;default:je.info("Unsupported type...")}je.debug(Ee)},De="cts",Ye="Create tree structure of current working directory and its contents",Ne=e=>{e.option("t",{alias:"fileType",describe:"Tree structure will be saved in file type",type:"string",choices:["svg","png","jpeg"],demandOption:!0}).option("i",{alias:"ignores",describe:"Folder list to be ignored in tree structure",type:"array"}).option("l",{alias:"length",describe:"Length of the image",type:"number",default:250}).option("b",{alias:"breadth",describe:"Breadth of the image",type:"number",default:200})},Re=async e=>{if(function(...e){for(const t of e)if(isNaN(t)||t<1||t>1e3)return!1;return!0}(e.length,e.breadth)){let t=e.ignores;if(t&&t.length>0){const e=await Oe();e.ignores=[],await ue(e,Se),e.ignores=[...t],await ue(e,Se),je.info(`Applying your ignore list: ${t.join(", ")}, updating ignore cache`)}else{const e=await Oe();e.ignores&&e.ignores.length>0&&(je.info(`Applying your cache ignore list: ${e.ignores.join(", ")}`),t=[...e.ignores])}Te(e.fileType,t,e.length,e.breadth)}else je.error("Length & Breadth must be valid number (1 to 1000)\n")},_e=ne(),Fe=n.join(se(),"sc_ignore.json");async function Le(){try{return await x.readJson(Fe)}catch(e){if("ENOENT"===e.code)return{ignores:[]};throw e}}async function Ie(e,t){if(t&&t.length>0){return await j.prompt([{type:"fuzzypath",name:"filePath",excludePath:e=>t.some((t=>e.includes(t))),excludeFilter:e=>"."==e,message:le("Select a folder/file:"),itemType:"any",depthLimit:5,rootPath:e}])}return await j.prompt([{type:"fuzzypath",name:"filePath",excludeFilter:e=>"."==e,message:le("Select a folder/file:"),itemType:"any",depthLimit:5,rootPath:e}])}async function Pe(){return await j.prompt([{type:"confirm",name:"exit",message:le("Do you want to exit?"),default:!0}])}j.registerPrompt("fuzzypath",k);const Be="sc",ze="Search content of current working directory",He=e=>{e.option("i",{alias:"ignores",describe:"List of directory content to ignore",type:"array"})},Ce=async e=>{let t=process.cwd();let o=e.ignores;if(o&&o.length>0){const e=await Le();e.ignores=[],await ue(e,Fe),e.ignores=[...o],await ue(e,Fe),_e.info(`Applying your ignore list: ${o.join(", ")}, updating ignore cache`)}else{const e=await Le();e.ignores&&e.ignores.length>0&&(_e.info(`Applying your cache ignore list: ${e.ignores.join(", ")}`),o=[...e.ignores])}for(;;){const{filePath:e}=await Ie(t,o),n=x.statSync(e);n.isFile()?(_e.info("Selected content is file..."),_e.info(`${e}`)):n.isDirectory()&&(_e.info("Selected content is directory..."),t=e,process.chdir(t),_e.warn(`${process.cwd()}`));const{exit:r}=await Pe();if(r){_e.warn("Exiting navigation..."),n.isDirectory()&&(_e.info("Use below command to change directory"),_e.info(`cd ${t}`));break}}},qe=ne();const Ue="hra",Je="Calculate HRA exemption",We=e=>{e.option("mb",{alias:"monthlyBasic",describe:"Monthly basic salary",type:"number",demandOption:!0}).option("mr",{alias:"monthlyRent",describe:"Monthly rent paid",type:"number",demandOption:!0}).option("hr",{alias:"hraReceived",describe:"Monthly HRA received from employer",type:"number",demandOption:!0}).option("im",{alias:"isMetro",describe:"Living in a metro city.",type:"boolean",choices:[!0,!1],default:!1})},Ge=e=>{if(!ie(e.monthlyBasic,e.monthlyRent,e.hraReceived))return void qe.error("Invalid Inputs\n");console.log("HRA exemption is calculated based on the following criteria:\n"),console.log("1. Actual HRA received from the employer."),console.log("2. 50% of salary (basic + DA) for those living in metro cities or 40% for non-metro cities."),console.log("3. Actual rent paid minus 10% of salary (basic + DA).\n");const t={monthlyBasic:e.monthlyBasic,monthlyRent:e.monthlyRent,hraReceived:e.hraReceived,isMetro:e.isMetro};console.log("\n"),qe.info("Provided Monthly Details:\n"),console.table([{MonthlyBasic:ae(e.monthlyBasic),MonthlyHRAReceived:ae(e.hraReceived),MonthlyRent:ae(e.monthlyRent),IsMetro:e.isMetro}]),console.log("\n");const o=function(e){const{monthlyBasic:t,monthlyRent:o,hraReceived:n,isMetro:r}=e,s=12*t,i=12*n,a=12*o-.1*s,c=(r?.5:.4)*s;return Math.min(i,a,c)}(t);console.log("\n"),qe.info("Calculated HRA Exemption Details:\n"),console.table([{Basic:ae(12*e.monthlyBasic),HRAReceived:ae(12*e.hraReceived),Rent:ae(12*e.monthlyRent),HRAExemption:ae(o)}]),console.log("\n")},Qe=ne();const Ze="sr",Ve="Suggest optimal rent for maximizing HRA exemption",Ke=e=>{e.option("mb",{alias:"monthlyBasic",describe:"Monthly basic salary",type:"number",demandOption:!0}).option("hr",{alias:"hraReceived",describe:"Monthly HRA received from employer",type:"number",demandOption:!0}).option("im",{alias:"isMetro",describe:"Living in a metro city.",type:"boolean",choices:[!0,!1],default:!1})},Xe=e=>{if(!ie(e.monthlyBasic,e.hraReceived))return void Qe.error("Invalid Inputs\n");console.log("\n"),Qe.info("Provided Details:\n"),console.table([{MonthlyBasic:ae(e.monthlyBasic),MonthlyHRAReceived:ae(e.hraReceived),IsMetro:e.isMetro}]),console.log("\n");const t=(o=e.monthlyBasic,n=e.hraReceived,e.isMetro,(12*o*.1+12*n)/12);var o,n;console.log("\n"),Qe.info("Suggested Rent Details For Maximise HRA Exemption:\n"),console.table([{MonthlyRent:ae(t),AnnualRent:ae(12*t)}]),console.log("\n"),Qe.warn("Suggestions are calculated based on inputs\n")},et=ne();const tt="decode",ot="Decode provided JWT token",nt=e=>{e.option("t",{alias:"token",describe:"JWT token to decode",type:"string",demandOption:!0})},rt=e=>{const t=function(e){try{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT structure");const o=t[1],n=Buffer.from(o,"base64").toString("utf-8");return JSON.parse(n)}catch(e){return et.error(`Error decoding JWT: ${e}`),null}}(e.token.replace(/^Bearer\s+/i,""));t&&(console.log("Decoded JWT Payload:\n"),console.log(b.cyanBright.bold("data:"),b.greenBright.bold(JSON.stringify(t,null,2))),console.log("\n"))};j.registerPrompt("date",T),j.registerPrompt("autocomplete",Y);const st=ne(),it=M.tz.names(),at=["YYYY-MM-DD","MM-DD-YYYY","DD-MM-YYYY","MMMM Do YYYY, h:mm:ss a","dddd, MMMM Do YYYY","YYYY-MM-DD HH:mm:ss","MMM DD, YYYY","hh:mm A","HH:mm:ss","MMMM Do YYYY, h:mm:ss a z","ddd, hA","YYYY-MM-DD[T]HH:mm:ss.SSS[Z]","YYYY-MM-DD[T]HH:mm:ssZ"];async function ct(){const{dateTime:e}=await j.prompt({type:"date",name:"dateTime",message:le("Choose a date to proceed"),clearable:!0});return console.log("\n"),st.info(`Provided date and time is: ${S(e).format("YYYY-MM-DD HH:mm:ss")}`),S(e)}async function lt(){const e=(await ct()).utc();console.log("\n"),st.info(`The UTC date and time is: ${e.format("YYYY-MM-DD HH:mm:ss")} UTC`)}async function ut(){const e=await ct(),t=await async function(){const{timezone:e}=await j.prompt([{type:"autocomplete",name:"timezone",message:le("Select a timezone:"),source:(e,t)=>(t=t||"",new Promise((e=>{e(D.filter(t,it).map((e=>e.original)))})))}]);return console.log("\n"),e}(),o=e.tz(t);console.log("\n"),st.info(`The date and time in ${t} is: ${o.format("YYYY-MM-DD HH:mm:ss")} ${t}`)}async function pt(){const e=await ct(),t=await async function(){const{format:e}=await j.prompt([{type:"autocomplete",name:"format",message:le("Select a date format:"),source:(e,t)=>(t=t||"",new Promise((e=>{e(D.filter(t,at).map((e=>e.original)))})))}]);return console.log("\n"),e}(),o=e.format(t);console.log("\n"),st.info(`The date in the selected format (${t}) is: ${o}`)}const dt="date",ft="Date conversion/operations",mt=e=>e,ht=async e=>{let t=!0,o=!1;do{console.log("\n");const{operation:e}=await j.prompt([{type:"rawlist",name:"operation",message:le("What do you want to do?"),choices:[{name:"Convert local datetime to UTC datetime",value:"localDateToUTC"},{name:"Convert local datetime to specific timezone datetime",value:"localDateToTimezone"},new j.Separator,{name:"Format date in string",value:"formatDate"},{name:"Exit",value:"exit"}]}]);if("exit"===e)t=!1,o=!1;else switch(console.log("\n"),e){case"localDateToUTC":o=!0,st.info("Operation Local Date To UTC Date\n"),await lt();break;case"localDateToTimezone":o=!0,st.info("Operation Local Date To Timezone\n"),await ut();break;case"formatDate":o=!0,st.info("Operation Format Date\n"),await pt();break;default:st.warn("Invalid option selected.")}if(t&&!o){console.log("\n");const{repeat:e}=await j.prompt([{type:"confirm",name:"repeat",message:le("Do you want to perform another operation?"),default:!1}]);t=e}}while(t);st.info("Exiting...\n")};j.registerPrompt("date",T),j.registerPrompt("autocomplete",Y);const gt=ne();async function yt(){try{const{epochValue:e}=await async function(){return console.log("\n"),await j.prompt({type:"input",name:"epochValue",message:le("Enter epoch time:"),validate:function(e){return!isNaN(e)||"Please enter a valid epoch time"}})}(),t=N(Number(e));console.log("\n"),gt.info("Epoch to date conversion details:\n"),console.table([{Epoch:`${t.epoch} is in ${t.epochUnit}`,LocalDateTime:t.dateTime,GMTDateTime:t.dateTimeInGMT,Relative:t.relative}])}catch(e){console.log("\n"),gt.error(`${e}`)}}async function bt(){try{const e=await async function(){console.log("\n");const{dateTime:e}=await j.prompt({type:"date",name:"dateTime",message:le("Choose a date to proceed"),clearable:!0});return gt.info(`Provided date and time is: ${S(e).format("YYYY-MM-DD HH:mm:ss")}`),S(e)}(),{epochInSeconds:t,epochInMilliseconds:o,dateTimeInGMT:n,dateTime:r,timezone:s}=R(e.toDate());console.log("\n"),gt.info("Epoch details:\n"),console.table([{Epochs:`${t} in seconds, ${o} in miliseconds`,LocalDateTime:r,GMTDateTime:n,DetectedTimezone:s}])}catch(e){console.log("\n"),gt.error(`${e}`)}}const vt="epoch",wt="Epoch conversions",jt=e=>e,St=async e=>{let t=!0,o=!1;do{console.log("\n");const{operation:e}=await j.prompt([{type:"rawlist",name:"operation",message:le("What do you want to do?"),choices:[{name:"Convert epoch to human-readable date",value:"epochToDate"},{name:"Convert human-readable date to epoch",value:"dateToEpoch"},{name:"Exit",value:"exit"}]}]);if("exit"===e)t=!1,o=!1;else switch(console.log("\n"),e){case"epochToDate":o=!0,gt.info("Operation Epoch To Date\n"),await yt();break;case"dateToEpoch":o=!0,gt.info("Operation Date To Epoch\n"),await bt();break;default:gt.warn("Invalid option selected.")}if(t&&!o){console.log("\n");const{repeat:e}=await j.prompt([{type:"confirm",name:"repeat",message:le("Do you want to perform another operation?"),default:!1}]);t=e}}while(t);gt.info("Exiting...\n")},$t="type Query {\n hello: String\n}\n",xt="const express = require('express');\nconst { ApolloServer } = require('@apollo/server');\nconst { expressMiddleware } = require('@apollo/server/express4');\nconst { readFileSync } = require('fs');\nconst { join } = require('path');\nconst cors = require('cors');\n \nconst getSchema = () => {\n const schemaPath = join(process.cwd(), `resources/schema.graphql`);\n return readFileSync(schemaPath, 'utf-8');\n};\n \nconst typeDefs = getSchema();\n \nconst resolvers = {\n Query: {\n hello: () => 'Hello world!',\n },\n};\n \nconst app = express();\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n});\n \nserver.start().then(() => {\n app.use('/graphql', cors(), express.json(), expressMiddleware(server));\n});\n \napp.listen(4000, () => {\n console.log('🚀 Server ready at http://localhost:4000/graphql');\n});\n",Et="import express from 'express';\nimport { ApolloServer } from '@apollo/server';\nimport { expressMiddleware } from '@apollo/server/express4';\nimport cors from 'cors';\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\n\nconst getSchema = (): string => {\n const schemaPath = join(process.cwd(), `resources/schema.graphql`);\n return readFileSync(schemaPath, 'utf-8');\n};\n\nconst typeDefs = getSchema();\n\nconst resolvers = {\n Query: {\n hello: () => 'Hello world!',\n },\n};\n\nconst app = express();\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers\n});\n\nawait server.start();\n\napp.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server));\n\napp.listen(4000, () => {\n console.log('🚀 Server ready at http://localhost:4000/graphql');\n});\n",Ot=ne(),At="create @apollo:express",kt="Create an Apollo GraphQL Express project",Mt=e=>e,Tt=async e=>{const{projectName:t,moduleType:o}=await async function(e){return await j.prompt(e)}([{type:"input",name:"projectName",message:le("Enter the project name:"),validate:e=>e.trim().length>0||"Please enter a valid project name."},{type:"expand",name:"moduleType",message:le("Choose module type:"),choices:[{key:"c",name:"CommonJS",value:"commonjs"},{key:"m",name:"ES Module",value:"module"}],default:0}]),r=S();console.log("\n");const s=_(b.green("@apollo:express:init")).start();try{const e=n.join(process.cwd(),t);u.mkdirSync(e);let i=!1;"module"===o&&(i=!0),function(e,t,o){u.writeFileSync(n.join(e,"package.json"),JSON.stringify(function(e,t,o){const n={"@apollo/server":ce("@apollo/server"),cors:ce("cors"),express:ce("express"),graphql:ce("graphql")};let r={},s={};return"module"===e?(r={"@types/cors":ce("@types/cors"),"@types/express":ce("@types/express"),"@types/node":ce("@types/node"),rimraf:ce("rimraf"),typescript:ce("typescript")},s={name:t.basename(o),version:"1.0.0",main:"./dist/index.js",type:e,scripts:{clean:"rimraf ./dist",build:"npm run clean && tsc",start:"node ./dist/index.js"},dependencies:n,devDependencies:r}):s={name:t.basename(o),version:"1.0.0",main:"src/index.js",type:e,scripts:{start:"node src/index.js"},dependencies:n},s}(o,n,e),null,2)),u.writeFileSync(n.join(e,"README.md"),((e,t)=>"module"===t?`# ${e}\n\nA starter project using apollo graphql and express. It is configured to use the '${t}' system.\n\n## Getting Started\n\n### Prerequisites\n\n- Node.js installed on your machine.\n\n### Build the application\n\nTo build the application, run the following command:\n\n\`\`\`bash\nnpm run build\n\`\`\`\n\n### Running the Server\n\nTo start the server, run the following command:\n\n\`\`\`bash\nnpm run start\n\`\`\`\n\nThe server will be running on [http://localhost:4000/graphql](http://localhost:4000/graphql).\n`:`# ${e}\n\nA starter project using apollo graphql and express. It is configured to use the '${t}' system.\n\n## Getting Started\n\n### Prerequisites\n\n- Node.js installed on your machine.\n\n### Running the Server\n\nTo start the server, run the following command:\n\n\`\`\`bash\nnpm run start\n\`\`\`\n\nThe server will be running on [http://localhost:4000/graphql](http://localhost:4000/graphql).\n`)(n.basename(e),o));const r=n.join(e,"src");u.mkdirSync(r);const s=n.join(e,"resources");u.mkdirSync(s);const i=t?"index.ts":"index.js";(function(e,t,o){u.writeFileSync(n.join(t,"schema.graphql"),$t);const r=o?Et:xt;u.writeFileSync(e,r)})(n.join(r,i),s,t),t&&function(e){const t={compilerOptions:{target:"es2020",module:"esnext",types:["node"],lib:["es2020"],strict:!0,esModuleInterop:!0,skipLibCheck:!0,outDir:"dist",rootDir:"src",moduleResolution:"node"},include:["./src/**/*"],exclude:["node_modules","dist"]};u.writeFileSync(n.join(e,"tsconfig.json"),JSON.stringify(t,null,2))}(e)}(e,i,o);const a=S(),c=S.duration(a.diff(r)),l=b.dim(`(${c.asSeconds().toFixed(3)})`);s.succeed(`${b.green("@apollo:express:init completed")} ${l}`),function(e,t,o){const n=S();o.start(b.green(`${e}:install`)),process.chdir(t),E("npm install");const r=S(),s=S.duration(r.diff(n)),i=b.dim(`(${s.asSeconds().toFixed(3)})`);o.succeed(`${b.green(`${e}:install completed`)} ${i}`)}("@apollo:express",e,s),console.log("\n"),console.log(b.green(`Project ${n.basename(e)} created successfully.\n`)),console.log("\n")}catch(e){Ot.error(`: ${e}`),s.fail("Failed to initialize project.")}};const Dt=ne(),Yt=n.join(se(),"ports.json");const Nt=e=>new Promise(((t,o)=>{const n="win32"===F()?`taskkill /PID ${e} /F`:`kill -9 ${e}`;O(n,((n,r,s)=>{if(n)return o(n);t(`Process ${e} killed successfully`)}))})),Rt=async e=>{try{const t=await Promise.all(e.map((e=>(e=>new Promise((t=>{const o="win32"===F()?`netstat -ano | findstr :${e}`:`lsof -i :${e} | grep LISTEN`;O(o,((o,n,r)=>{if(o||!n)return Dt.warn(`Port ${e} is not in use.\n`),void t(null);if("win32"===F()){const o=n.split("\n")[0],r=o?o.trim().split(/\s+/).pop():null;t(r?{port:e,pid:r}:null)}else{const o=n.split("\n")[0],r=o?o.trim().split(/\s+/)[1]:null;t(r?{port:e,pid:r}:null)}}))})))(e)))),o=t.filter((e=>null!==e));if(0===o.length)return console.log("\n"),void Dt.info("No processes found running on the specified ports\n");const n=o.map((e=>({name:`Port: ${e.port}, PID: ${e.pid}`,value:e.pid})));console.log("\n");const r=await j.prompt([{type:"checkbox",name:"pids",message:le("Select the processes you want to kill:"),choices:n}]);console.log("\n");for(const e of r.pids){const t=await Nt(e);Dt.info(t)}}catch(e){Dt.error(`${e}`)}},_t="kill",Ft="Kill process running on specific ports",Lt=e=>{e.option("p",{alias:"ports",describe:"List of port numbers",type:"array",coerce:e=>{if(!Array.isArray(e))throw new Error("Ports must be an array");for(const t of e)if(isNaN(Number(t)))throw new Error(`Invalid port number: ${t}`);return e.map(Number)}})},It=async e=>{const t=e.ports,o=await async function(){try{return await x.readJson(Yt)}catch(e){if("ENOENT"===e.code)return{ports:[]};throw e}}();t&&t.length>0?(o.ports=[],await ue(o,Yt),await Rt(t),o.ports=[...t],await ue(o,Yt)):o.ports&&o.ports.length>0?(Dt.info(`Using ports [${o.ports.join(", ")}] from cache\n`),await Rt(o.ports)):Dt.error("Ports are not provided\n")},Pt=ne();async function Bt(e){const t=S(),o=_();console.log("\n");try{o.start(b.green("@start updating/installing")),O(`npm install -g ${e}`,((n,r,s)=>{if(n)return o.fail(b.red("@fail updating/installing")),void Pt.error(`\nError updating package: ${n.message}`);if(s)return void Pt.error(`\nError output: ${s}\n`);const i=S(),a=S.duration(i.diff(t)),c=b.dim(`(${a.asSeconds().toFixed(3)})`);o.succeed(`${b.green("@success updating/installing")} ${c}`),async function(e,t){O(`npm view ${e} version`,((e,o,n)=>{t(e||n?null:o.trim())}))}(e,(t=>{null!==t&&(console.log("\n"),Pt.info(`${e} library updated/installed version -> ${b.green(t)}\n`))}))}))}catch(e){Pt.error(`${e}`)}}const zt="update [package]",Ht="Update the CLI or a specified package to the latest version",Ct=e=>{e.positional("package",{describe:"The name of the package to update",type:"string",default:"@master4n/master-cli"})},qt=async e=>{Bt(e.package)};re(fe).add(zt,Ht,Ct,qt),re(fe).add(vt,wt,jt,St),re(fe).add(dt,ft,mt,ht),re(fe).add(tt,ot,nt,rt),re(fe).add(At,kt,Mt,Tt),re(fe).add(Be,ze,He,Ce),re(fe).add(_t,Ft,Lt,It),re(fe).add(ye,be,ve,we),re(fe).add(De,Ye,Ne,Re),re(fe).add(Ue,Je,We,Ge),re(fe).add(Ze,Ve,Ke,Xe),fe.version().alias("version","v").help().alias("help","h").wrap(null).parse();
35
+ function(e){if(Array.isArray(e))return e.map(e=>"string"!=typeof e?e+"":e);e=e.trim();let t=0,n=null,o=null,r=null;const s=[];for(let a=0;a<e.length;a++)n=o,o=e.charAt(a)," "!==o||r?(o===r?r=null:"'"!==o&&'"'!==o||r||(r=o),s[t]||(s[t]=""),s[t]+=o):" "!==n&&t++;return s}(e),r="string"==typeof e,s=function(e){const t=[],n=Object.create(null);let o=!0;Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});for(;o;){o=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){if(t[e].filter(function(e){return-1!==t[n].indexOf(e)}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),o=!0;break}}}return t.forEach(function(e){const t=(e=e.filter(function(e,t,n){return n.indexOf(e)===t})).pop();void 0!==t&&"string"==typeof t&&(n[t]=e)}),n}(Object.assign(Object.create(null),n.alias)),a=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),i=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=a["populate--"],f=u?"--":"_",d=Object.create(null),p=Object.create(null),m=n.__||L.format,h={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,y=new RegExp("^--"+a["negation-prefix"]+"(.+)");[].concat(n.array||[]).filter(Boolean).forEach(function(e){const t="object"==typeof e?e.key:e,n=Object.keys(e).map(function(e){return{boolean:"bools",string:"strings",number:"numbers"}[e]}).filter(Boolean).pop();n&&(h[n][t]=!0),h.arrays[t]=!0,h.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){h.bools[e]=!0,h.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){h.strings[e]=!0,h.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){h.numbers[e]=!0,h.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){h.counts[e]=!0,h.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){h.normalize[e]=!0,h.keys.push(e)}),"object"==typeof n.narg&&Object.entries(n.narg).forEach(([e,t])=>{"number"==typeof t&&(h.nargs[e]=t,h.keys.push(e))}),"object"==typeof n.coerce&&Object.entries(n.coerce).forEach(([e,t])=>{"function"==typeof t&&(h.coercions[e]=t,h.keys.push(e))}),void 0!==n.config&&(Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach(function(e){h.configs[e]=!0}):"object"==typeof n.config&&Object.entries(n.config).forEach(([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(h.configs[e]=t)})),function(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){h.aliases[e]||(h.aliases[e]=[].concat(s[e]||[]),h.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&a["camel-case-expansion"]){const n=z(t);n!==e&&-1===h.aliases[e].indexOf(n)&&(h.aliases[e].push(n),d[n]=!0)}}),h.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&a["camel-case-expansion"]){const n=function(e,t){const n=e.toLowerCase();t=t||"-";let o="";for(let r=0;r<e.length;r++){const s=n.charAt(r),a=e.charAt(r);o+=s!==a&&r>0?`${t}${n.charAt(r)}`:a}return o}(t,"-");n!==e&&-1===h.aliases[e].indexOf(n)&&(h.aliases[e].push(n),d[n]=!0)}}),h.aliases[e].forEach(function(t){h.aliases[t]=[e].concat(h.aliases[e].filter(function(e){return t!==e}))}))})})}(n.key,s,n.default,h.arrays),Object.keys(i).forEach(function(e){(h.aliases[e]||[]).forEach(function(t){i[t]=i[e]})});let b=null;Object.keys(h.counts).find(e=>M(e,h.arrays)?(b=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!M(e,h.nargs)&&(b=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0));let v=[];const x=Object.assign(Object.create(null),{_:[]}),j={};for(let e=0;e<o.length;e++){const t=o[e],n=t.replace(/^-{3,}/,"---");let r,s,i,c,l,u;if("--"!==t&&/^-/.test(t)&&R(t))w(t);else{if(n.match(/^---+(=|$)/)){w(t);continue}if(t.match(/^--.+=/)||!a["short-option-groups"]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&(M(c[1],h.arrays)?e=$(e,c[1],o,c[2]):!1!==M(c[1],h.nargs)?e=E(e,c[1],o,c[2]):S(c[1],c[2],!0));else if(t.match(y)&&a["boolean-negation"])c=t.match(y),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],S(s,!!M(s,h.arrays)&&[!1]));else if(t.match(/^--.+/)||!a["short-option-groups"]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],M(s,h.arrays)?e=$(e,s,o):!1!==M(s,h.nargs)?e=E(e,s,o):(l=o[e+1],void 0===l||l.match(/^-/)&&!l.match(g)||M(s,h.bools)||M(s,h.counts)?/^(true|false)$/.test(l)?(S(s,l),e++):S(s,P(s)):(S(s,l),e++)));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&S(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(g))l=o[e+1],c=t.match(/^-(.\..+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(s=c[1],void 0===l||l.match(/^-/)||M(s,h.bools)||M(s,h.counts)?S(s,P(s)):(S(s,l),e++));else if(t.match(/^-[^-]+/)&&!t.match(g)){i=t.slice(1,-1).split(""),r=!1;for(let n=0;n<i.length;n++){if(l=t.slice(n+2),i[n+1]&&"="===i[n+1]){u=t.slice(n+3),s=i[n],M(s,h.arrays)?e=$(e,s,o,u):!1!==M(s,h.nargs)?e=E(e,s,o,u):S(s,u),r=!0;break}if("-"!==l){if(/[A-Za-z]/.test(i[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&!1===M(l,h.bools)){S(i[n],l),r=!0;break}if(i[n+1]&&i[n+1].match(/\W/)){S(i[n],l),r=!0;break}S(i[n],P(i[n]))}else S(i[n],l)}s=t.slice(-1)[0],r||"-"===s||(M(s,h.arrays)?e=$(e,s,o):!1!==M(s,h.nargs)?e=E(e,s,o):(l=o[e+1],void 0===l||/^(-|--)[^-]/.test(l)&&!l.match(g)||M(s,h.bools)||M(s,h.counts)?/^(true|false)$/.test(l)?(S(s,l),e++):S(s,P(s)):(S(s,l),e++)))}else if(t.match(/^-[0-9]$/)&&t.match(g)&&M(t.slice(1),h.bools))s=t.slice(1),S(s,P(s));else{if("--"===t){v=o.slice(e+1);break}if(a["halt-at-non-option"]){v=o.slice(e);break}w(t)}}}function w(e){const t=N("_",e);"string"!=typeof t&&"number"!=typeof t||x._.push(t)}function E(e,t,n,o){let r,s=M(t,h.nargs);if(s="number"!=typeof s||isNaN(s)?1:s,0===s)return J(o)||(b=Error(m("Argument unexpected for: %s",t))),S(t,P(t)),e;let i=J(o)?0:1;if(a["nargs-eats-options"])n.length-(e+1)+i<s&&(b=Error(m("Not enough arguments following: %s",t))),i=s;else{for(r=e+1;r<n.length&&(!n[r].match(/^-[^0-9]/)||n[r].match(g)||R(n[r]));r++)i++;i<s&&(b=Error(m("Not enough arguments following: %s",t)))}let c=Math.min(i,s);for(!J(o)&&c>0&&(S(t,o),c--),r=e+1;r<c+e+1;r++)S(t,n[r]);return e+c}function $(e,t,n,o){let s=[],c=o||n[e+1];const l=M(t,h.nargs);if(M(t,h.bools)&&!/^(true|false)$/.test(c))s.push(!0);else if(J(c)||J(o)&&/^-/.test(c)&&!g.test(c)&&!R(c)){if(void 0!==i[t]){const e=i[t];s=Array.isArray(e)?e:[e]}}else{J(o)||s.push(k(t,o,!0));for(let o=e+1;o<n.length&&!(!a["greedy-arrays"]&&s.length>0||l&&"number"==typeof l&&s.length>=l)&&(c=n[o],!/^-/.test(c)||g.test(c)||R(c));o++)e=o,s.push(k(t,c,r))}return"number"==typeof l&&(l&&s.length<l||isNaN(l)&&0===s.length)&&(b=Error(m("Not enough arguments following: %s",t))),S(t,s),e}function S(e,t,n=r){if(/-/.test(e)&&a["camel-case-expansion"]){const t=e.split(".").map(function(e){return z(e)}).join(".");O(e,t)}const o=k(e,t,n),s=e.split(".");if(D(x,s,o),h.aliases[e]&&h.aliases[e].forEach(function(e){const t=e.split(".");D(x,t,o)}),s.length>1&&a["dot-notation"]&&(h.aliases[s[0]]||[]).forEach(function(t){let n=t.split(".");const r=[].concat(s);r.shift(),n=n.concat(r),(h.aliases[e]||[]).includes(n.join("."))||D(x,n,o)}),M(e,h.normalize)&&!M(e,h.arrays)){[e].concat(h.aliases[e]||[]).forEach(function(e){Object.defineProperty(j,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?L.normalize(e):e}})})}}function O(e,t){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[t],d[t]=!0),h.aliases[t]&&h.aliases[t].length||O(t,e)}function k(e,t,n){n&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(M(e,h.bools)||M(e,h.counts))&&"string"==typeof t&&(t="true"===t);let o=Array.isArray(t)?t.map(function(t){return N(e,t)}):N(e,t);return M(e,h.counts)&&(J(o)||"boolean"==typeof o)&&(o=B()),M(e,h.normalize)&&M(e,h.arrays)&&(o=Array.isArray(t)?t.map(e=>L.normalize(e)):L.normalize(t)),o}function N(e,t){if(!a["parse-positional-numbers"]&&"_"===e)return t;if(!M(e,h.strings)&&!M(e,h.bools)&&!Array.isArray(t)){(null!=(n=t)&&("number"==typeof n||!!/^0x[0-9a-f]+$/i.test(n)||!/^0[^.]/.test(n)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(n))&&a["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!J(t)&&M(e,h.numbers))&&(t=Number(t))}var n;return t}function I(e,t){Object.keys(e).forEach(function(n){const o=e[n],r=t?t+"."+n:n;"object"==typeof o&&null!==o&&!Array.isArray(o)&&a["dot-notation"]?I(o,r):(!_(x,r.split("."))||M(r,h.arrays)&&a["combine-arrays"])&&S(r,o)})}function A(e,t){if(void 0===l)return;const n="string"==typeof l?l:"",o=L.env();Object.keys(o).forEach(function(r){if(""===n||0===r.lastIndexOf(n,0)){const s=r.split("__").map(function(e,t){return 0===t&&(e=e.substring(n.length)),z(e)});(t&&h.configs[s.join(".")]||!t)&&!_(e,s)&&S(s.join("."),o[r])}})}function T(e,t,n,o=!1){Object.keys(n).forEach(function(r){_(e,r.split("."))||(D(e,r.split("."),n[r]),o&&(p[r]=!0),(t[r]||[]).forEach(function(t){_(e,t.split("."))||D(e,t.split("."),n[r])}))})}function _(e,t){let n=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});const o=t[t.length-1];return"object"==typeof n&&o in n}function D(e,t,n){let o=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){e=C(e),"object"==typeof o&&void 0===o[e]&&(o[e]={}),"object"!=typeof o[e]||Array.isArray(o[e])?(Array.isArray(o[e])?o[e].push({}):o[e]=[o[e],{}],o=o[e][o[e].length-1]):o=o[e]});const r=C(t[t.length-1]),s=M(t.join("."),h.arrays),i=Array.isArray(n);let c=a["duplicate-arguments-array"];!c&&M(r,h.nargs)&&(c=!0,(!J(o[r])&&1===h.nargs[r]||Array.isArray(o[r])&&o[r].length===h.nargs[r])&&(o[r]=void 0)),n===B()?o[r]=B(o[r]):Array.isArray(o[r])?c&&s&&i?o[r]=a["flatten-duplicate-arrays"]?o[r].concat(n):(Array.isArray(o[r][0])?o[r]:[o[r]]).concat([n]):c||Boolean(s)!==Boolean(i)?o[r]=o[r].concat([n]):o[r]=n:void 0===o[r]&&s?o[r]=i?n:[n]:!c||void 0===o[r]||M(r,h.counts)||M(r,h.bools)?o[r]=n:o[r]=[o[r],n]}function M(e,t){const n=[].concat(h.aliases[e]||[],e),o=Object.keys(t),r=n.find(e=>o.includes(e));return!!r&&t[r]}function U(e){const t=Object.keys(h);return[].concat(t.map(e=>h[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function R(e){return a["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(g))return!1;if(function(e){if(e.match(g)||!e.match(/^-[^-]+/))return!1;let t,n=!0;const o=e.slice(1).split("");for(let r=0;r<o.length;r++){if(t=e.slice(r+2),!U(o[r])){n=!1;break}if(o[r+1]&&"="===o[r+1]||"-"===t||/[A-Za-z]/.test(o[r])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(t)||o[r+1]&&o[r+1].match(/\W/))break}return n}(e))return!1;return!function(e,...t){return[].concat(...t).some(function(t){const n=e.match(t);return n&&U(n[1])})}(e,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}(e)}function P(e){return M(e,h.bools)||M(e,h.counts)||!(`${e}`in i)?(t=function(e){let t=F.BOOLEAN;return M(e,h.strings)?t=F.STRING:M(e,h.numbers)?t=F.NUMBER:M(e,h.bools)?t=F.BOOLEAN:M(e,h.arrays)&&(t=F.ARRAY),t}(e),{[F.BOOLEAN]:!0,[F.STRING]:"",[F.NUMBER]:void 0,[F.ARRAY]:[]}[t]):i[e];var t}function J(e){return void 0===e}return A(x,!0),A(x,!1),function(e){const t=Object.create(null);T(t,h.aliases,i),Object.keys(h.configs).forEach(function(n){const o=e[n]||t[n];if(o)try{let e=null;const t=L.resolve(L.cwd(),o),r=h.configs[n];if("function"==typeof r){try{e=r(t)}catch(t){e=t}if(e instanceof Error)return void(b=e)}else e=L.require(t);I(e)}catch(t){"PermissionDenied"===t.name?b=t:e[n]&&(b=Error(m("Invalid JSON config file: %s",o)))}})}(x),void 0!==c&&c.forEach(function(e){I(e)}),T(x,h.aliases,i,!0),function(e){let t;const n=new Set;Object.keys(e).forEach(function(o){if(!n.has(o)&&(t=M(o,h.coercions),"function"==typeof t))try{const r=N(o,t(e[o]));[].concat(h.aliases[o]||[],o).forEach(t=>{n.add(t),e[t]=r})}catch(e){b=e}})}(x),a["set-placeholder-key"]&&function(e){h.keys.forEach(t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)})}(x),Object.keys(h.counts).forEach(function(e){_(x,e.split("."))||S(e,0)}),u&&v.length&&(x[f]=[]),v.forEach(function(e){x[f].push(e)}),a["camel-case-expansion"]&&a["strip-dashed"]&&Object.keys(x).filter(e=>"--"!==e&&e.includes("-")).forEach(e=>{delete x[e]}),a["strip-aliased"]&&[].concat(...Object.keys(s).map(e=>s[e])).forEach(e=>{a["camel-case-expansion"]&&e.includes("-")&&delete x[e.split(".").map(e=>z(e)).join(".")],delete x[e]}),{aliases:Object.assign({},h.aliases),argv:Object.assign(j,x),configuration:a,defaulted:Object.assign({},p),error:b,newAliases:Object.assign({},d)}}}({cwd:process.cwd,env:()=>J,format:t,normalize:r,resolve:o,require:e=>{if("undefined"!=typeof require)return require(e);if(e.match(/\.json$/))return JSON.parse(a(e,"utf8"));throw Error("only .json config files are supported in ESM")}});var G={fs:{readFileSync:a,writeFile:i},format:t,resolve:o,exists:e=>{try{return c(e).isFile()}catch(e){return!1}}};let W;class Y{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let n=function(){};return"function"==typeof e[e.length-1]&&(n=e.pop()),n=n||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),W.format.apply(W.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift();let r=function(){};"function"==typeof e[e.length-1]&&(r=e.pop()),this.cache[this.locale]||this._readLocaleFile();let s=1===o?t:n;if(this.cache[this.locale][t]){s=this.cache[this.locale][t][1===o?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r})):r();const a=[s];return~s.indexOf("%d")&&a.push(o),W.format.apply(W.format,a.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n="";return e.forEach(function(e,o){const r=t[o+1];n+=e,void 0!==r&&(n+="%s")}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],n=t.directory,o=t.locale,r=t.cb,s=this._resolveLocaleFile(n,o),a=JSON.stringify(this.cache[o],null,2);W.fs.writeFile(s,a,"utf-8",function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),r(t)})}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{W.fs.readFileSync&&(e=JSON.parse(W.fs.readFileSync(t,"utf-8")))}catch(n){if(n instanceof SyntaxError&&(n.message="syntax error in "+t),"ENOENT"!==n.code)throw n;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=W.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){const o=W.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(o)&&(n=o)}return n}_fileExistsSync(e){return W.exists(e)}}let Q;try{Q=l(import.meta.url)}catch(e){Q=process.cwd()}Q.substring(0,Q.lastIndexOf("node_modules"))||process.cwd(),process.cwd,process.exit,process.nextTick,void 0!==process.stdout.columns&&process.stdout.columns,function(e,t){W=t;const n=new Y(e);n.__.bind(n),n.__n.bind(n),n.setLocale.bind(n),n.getLocale.bind(n),n.updateLocale.bind(n),n.locale}({directory:o(Q,"../../../locales"),updateFiles:!1},G);const q=()=>(new Date).toISOString();function Z(){return{info:e=>console.error(`${u.blue("INFO")} [${u.magenta(q())}] ${u.white(e)}`),warn:e=>console.error(`${u.yellow("WARN")} [${u.magenta(q())}] ${u.white(e)}`),error:e=>console.error(`${u.red("ERROR")} [${u.magenta(q())}] ${u.white(e)}`),debug:e=>console.error(`${u.cyan("DEBUG")} [${u.magenta(q())}] ${u.white(e)}`)}}function H(){const e=p.homedir();return n.join(e,".mfn","cache")}const K=e=>u.green(e);async function V(e,t){await m.writeJson(t,e,{spaces:2})}const X=[{name:"capabilities",summary:"Self-describing manifest of every command an agent can call",examples:["mfn capabilities --json"]},{name:"epoch",summary:"Convert between epoch timestamps and dates (auto-detects unit)",examples:["mfn epoch 1622547800 --json","mfn epoch --from 2021-06-01T11:43:20Z --json"]},{name:"date",summary:"Convert/format a date across timezones (defaults to now)",examples:["mfn date --json","mfn date 2024-07-04T15:30:30Z --tz America/New_York --json"]},{name:"decode",summary:"Decode a JWT token (header + payload; signature not verified)",examples:["mfn decode -t <jwt> --json"]},{name:"kill",summary:"Kill the process(es) listening on specific ports",examples:["mfn kill -p 3000 8080 -y --json"]},{name:"sc",summary:"Find files/folders under the current directory (fuzzy match)",examples:["mfn sc service --json"]},{name:"cts",summary:"Print (or export) a tree of the current working directory",examples:["mfn cts --json","mfn cts -t png"]},{name:"update",summary:"Update the CLI or a specified package to the latest version",examples:["mfn update --json","mfn update <package> --json"]},{name:"id",summary:"Generate identifiers (UUID v4/v7 or URL-safe nano id)",examples:["mfn id --json","mfn id -t uuid7 -n 3 --json"]},{name:"hash",summary:"Hash a string, file, or stdin (md5/sha1/sha256/sha512)",examples:["mfn hash hello --json","mfn hash -a md5 -f ./file.txt --json"]},{name:"encode",summary:"Encode/decode text (base64, base64url, hex, url)",examples:["mfn encode hello --json","mfn encode aGVsbG8= -d --json"]},{name:"random",summary:"Generate secure random bytes or a password",examples:["mfn random --json","mfn random -p -l 32 --json"]},{name:"port",summary:"Find a free port, or check whether a specific port is available",examples:["mfn port --json","mfn port -c 3000 --json"]}];var ee="@master4n/master-cli",te="3.0.0";const ne=["add --json to any command for clean, machine-readable output","piping a command (no TTY) auto-emits JSON — great for agents & scripts","every command returns a stable exit code: 0 = ok, non-zero = failure","mfn <command> --help shows its flags and copy-paste examples","mfn capabilities --json lists every command an agent can call","mfn kill -p 3000 8080 -y frees stuck ports in one shot"],oe=e=>u.hex(e)("─".repeat(62));!function(){const e=p.homedir(),t=n.join(e,".mfn","cache");if(!s.existsSync(t))try{s.existsSync(n.join(e,".mfn"))||s.mkdirSync(n.join(e,".mfn")),s.mkdirSync(t,{recursive:!0})}catch{}}(),await(async()=>{if(!(Boolean(process.stdout.isTTY)&&!process.argv.includes("--json")))return;const e=await(t="M4N-CLI",new Promise((e,n)=>{f(t,(t,o)=>t?n(t):e(o??""))}));var t;const n=d(u.hex("#27A244").bold(e),{padding:1,margin:{top:1,bottom:0,left:1,right:1},borderStyle:"round",borderColor:"#C1C110",dimBorder:!0}),o=function(){const e=p.platform();return"win32"===e?process.env.USERNAME||"User":"darwin"===e||"linux"===e?process.env.USER||"User":""}(),r=u.dim(" • "),s=[u.hex("#44bcd8").bold(`mfn v${te}`),u.gray(`node ${process.version}`),u.gray(`${process.platform}/${process.arch}`),u.green.bold("AI-friendly")].join(r);let a="";try{const e=g();a=`${e.iso.replace("T"," ").slice(0,19)} ${u.dim(`(${e.timezone})`)}`}catch{}const i=X.map(e=>u.cyan(e.name)).join(u.dim(" · ")),c=ne[Math.floor(Math.random()*ne.length)],l=(e="")=>console.error(e);l(oe("#C1C110")),l(n),l(" "+(o?u.magenta(`👋 Welcome, ${u.bold(o)}`):u.magenta("👋 Welcome"))+r+s),a&&l(" "+u.gray("🕒 ")+u.white(a)),l(""),l(" "+u.yellow.bold("🧰 tools ")+i),l(" "+u.yellow.bold("💡 tip ")+u.white(c)),l(" "+u.yellow.bold("🤖 help ")+u.white("mfn <command> --help")),l(oe("#C1C110"))})();const re=e(process.argv.slice(_()+1));const se=u.hex("#44bcd8").bold("mfn");var ae=re.scriptName(se);const ie=()=>Boolean(process.stdout.isTTY),ce=e=>e.option("json",{type:"boolean",default:!1,describe:"Emit a single machine-readable JSON object on stdout"}),le=e=>Boolean(e?.json)||!ie(),ue=e=>{process.stdout.write(JSON.stringify(e)+"\n")};function fe(e,t,n){le(e)?ue({ok:!0,...t}):n()}function de(e,t,n,o=1){le(e)?ue({ok:!1,error:t,message:n}):console.error(n),process.exit(o)}const pe=e=>ie()&&!e?.json;async function me(){if(process.stdin.isTTY)return"";const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function he(e,t,n=2){process.argv.includes("--json")||!ie()?process.stdout.write(JSON.stringify({ok:!1,error:e,message:t})+"\n"):console.error(t),process.exit(n)}const ge=Z(),ye=n.join(H(),"cts_ignore.json"),be=["node_modules",".git",".nx"];function ve(e,t,o=""){let r,s="";try{r=m.readdirSync(e).filter(e=>!t.has(e)).sort()}catch{return`${o}└── [unreadable]\n`}return r.forEach((a,i)=>{const c=n.join(e,a),l=i===r.length-1;let u=!1;try{u=m.statSync(c).isDirectory()}catch{u=!1}s+=`${o}${l?"└── ":"├── "}${a}\n`,u&&(s+=ve(c,t,`${o}${l?" ":"│ "}`))}),s}const xe={command:"cts",describe:"Print (or export) a tree of the current working directory",builder:e=>ce(e).option("type",{alias:"t",describe:"Output format: text (stdout, default) or an image file",type:"string",choices:["text","svg","png","jpeg"],default:"text"}).option("ignore",{alias:"i",describe:"Folder names to ignore",type:"array"}).option("length",{alias:"l",describe:"Image height",type:"number",default:250}).option("breadth",{alias:"b",describe:"Image width",type:"number",default:200}).example("mfn cts","print the tree as text").example("mfn cts --json","tree as JSON").example("mfn cts -t png","export the tree to <dir>.png"),handler:async e=>{let t=e.ignore??[];t.length>0?await V({ignores:t},ye).catch(()=>{}):t=(await async function(){try{return await m.readJson(ye)}catch(e){if("ENOENT"===e.code)return{ignores:[]};throw e}}()).ignores??[];const o=new Set([...be,...t]),r=process.cwd(),s=n.basename(r);let a;try{a=s+"\n"+ve(r,o)}catch(t){return de(e,"TreeError",`Failed to build tree for ${r}: ${t instanceof Error?t.message:String(t)}`)}const i=String(e.type);if("text"===i)return fe(e,{root:s,path:r,format:"text",tree:a},()=>{process.stdout.write(a.endsWith("\n")?a:a+"\n")});if(!function(...e){for(const t of e)if(isNaN(t)||t<1||t>1e3)return!1;return!0}(e.length,e.breadth))return de(e,"InvalidDimensions","Length & breadth must be numbers in 1..1000.",2);const c=`${s}.${i}`;try{const t=function(e,t,n){return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${t}"><rect width="100%" height="100%" fill="white"/><g fill="black" font-family="monospace" font-size="12">${e.split("\n").map((e,t)=>`<text style="white-space: pre;" x="0" y="${20+20*t}">${e.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</text>`).join("")}</g></svg>`}(a,e.length,e.breadth);"svg"===i?m.outputFileSync(c,t):await x(Buffer.from(t))["png"===i?"png":"jpeg"]().toFile(c)}catch(t){const n=t instanceof Error?t.message:String(t);return de(e,"ExportFailed",`Failed to write ${c}: ${n}`)}fe(e,{root:s,path:r,format:i,file:c},()=>ge.info(`Tree for ${s} written to ${c}`))}},je=Z(),we=n.join(H(),"sc_ignore.json"),Ee=["node_modules",".git","dist","build",".nx","coverage"];function $e(e,t,o){const r=[],s=new Set([...Ee,...t]),a=(t,i)=>{if(i>o)return;let c;try{c=m.readdirSync(t,{withFileTypes:!0})}catch{return}for(const o of c){if(s.has(o.name))continue;const c=n.join(t,o.name),l=n.relative(e,c);r.push(o.isDirectory()?l+n.sep:l),o.isDirectory()&&a(c,i+1)}};return a(e,0),r}const Se={command:"sc [pattern]",describe:"Find files/folders under the current directory (fuzzy match)",builder:e=>ce(e).positional("pattern",{describe:"Fuzzy pattern to match against paths (omit to list all)",type:"string"}).option("ignore",{alias:"i",describe:"Additional directory names to ignore",type:"array"}).option("depth",{type:"number",default:6,describe:"Max recursion depth"}).option("limit",{type:"number",default:500,describe:"Max results returned"}).example("mfn sc service --json",'find paths matching "service"'),handler:async e=>{const t=process.cwd(),o=Number(e.depth),r=Number(e.limit);if(!Number.isInteger(o)||o<0)return de(e,"InvalidDepth","--depth must be a non-negative integer.",2);if(!Number.isInteger(r)||r<1)return de(e,"InvalidLimit","--limit must be a positive integer.",2);let s=e.ignore??[];if(s.length>0?await V({ignores:s},we).catch(()=>{}):s=(await async function(){try{return await m.readJson(we)}catch(e){if("ENOENT"===e.code)return{ignores:[]};throw e}}()).ignores??[],void 0===e.pattern&&pe(e))return async function(e,t,o,r,s){const a=$e(t,o,r),{pattern:i}=await j.prompt([{type:"input",name:"pattern",message:K("Filter (fuzzy, blank = all):")}]),c=String(i??"").trim(),l=(c?w.filter(c,a).map(e=>e.original):a).slice(0,s);if(0===l.length)return fe(e,{pattern:c||null,root:t,count:0,matches:[]},()=>je.warn("No matches."));const{selected:u}=await j.prompt([{type:"list",name:"selected",message:K("Select a path:"),choices:l,pageSize:15,loop:!1}]),f=m.statSync(n.join(t,u));fe(e,{path:u,type:f.isDirectory()?"directory":"file"},()=>{je.info(`${f.isDirectory()?"Directory":"File"}: ${u}`),f.isDirectory()&&je.info(`cd ${u}`)})}(e,t,s,o,r);const a=$e(t,s,o),i=e.pattern?w.filter(String(e.pattern),a).map(e=>e.original):a,c=i.slice(0,r);fe(e,{pattern:e.pattern??null,root:t,count:c.length,truncated:i.length>c.length,matches:c},()=>{je.info(`${c.length} match(es) under ${t}`);for(const e of c)console.log(e)})}},Oe=Z();function ke(e){const t=Buffer.from(e,"base64url").toString("utf-8");return JSON.parse(t)}const Ne={command:"decode",describe:"Decode a JWT token (header + payload; signature not verified)",builder:e=>ce(e).option("token",{alias:"t",describe:'JWT token to decode (a leading "Bearer " is stripped)',type:"string",demandOption:!0}).example("mfn decode -t <jwt> --json","decode a JWT"),handler:e=>{const t=String(e.token).replace(/^Bearer\s+/i,"").trim().split(".");if(3!==t.length)return de(e,"InvalidJWT","Invalid JWT structure: expected three dot-separated segments.");let n,o;try{n=ke(t[0]),o=ke(t[1])}catch(t){return de(e,"DecodeError",`Could not decode JWT: ${t instanceof Error?t.message:String(t)}`)}const r=o?.exp;let s;if("number"==typeof r&&Number.isFinite(r)){const e=Math.round(r-Date.now()/1e3);s={exp:r,expired:e<=0,expiresInSeconds:e}}fe(e,{header:n,payload:o,...s?{expiry:s}:{}},()=>{Oe.info("Decoded JWT (signature NOT verified)"),console.log(u.cyanBright.bold("header:")),console.log(u.greenBright(JSON.stringify(n,null,2))),console.log(u.cyanBright.bold("payload:")),console.log(u.greenBright(JSON.stringify(o,null,2))),s&&console.log(u.cyanBright.bold("expiry: ")+(s.expired?u.red(`expired ${-s.expiresInSeconds}s ago`):u.green(`valid for ${s.expiresInSeconds}s`)))})}},Ie=Z(),Ae="yyyy-MM-dd HH:mm:ss",Te=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";function _e(e){const t=e.format||Ae,n=e.tz||Te();let o,r,s;try{o=void 0!==e.from?y(String(e.from),e.inFormat,e.inTz).epochInMilliseconds:g().milliseconds}catch(t){const n=t instanceof Error?t.message:String(t);return de(e,t instanceof Error?t.name:"ParseError",n)}try{r=b(o,"UTC",t),s=b(o,n,t)}catch(t){const n=t instanceof Error?t.message:String(t);return de(e,t instanceof Error?t.name:"TimezoneError",n)}fe(e,{epochInSeconds:Math.floor(o/1e3),epochInMilliseconds:o,utc:r,zoned:s,timezone:n,format:t},()=>{Ie.info("Date conversion"),console.table([{UTC:r,[n]:s,Epoch_ms:o}])})}const ze={command:"date [from]",describe:"Convert/format a date across timezones (defaults to now)",builder:e=>ce(e).positional("from",{describe:"Date string to convert (ISO 8601 unless --in-format given). Omit for now.",type:"string"}).option("tz",{type:"string",describe:"Target output timezone (IANA; default: local)"}).option("format",{type:"string",describe:`Output format (default: ${Ae})`}).option("in-format",{type:"string",describe:"Luxon parse format for the input"}).option("in-tz",{type:"string",describe:"Timezone used to interpret the input"}).example("mfn date --json","now, in UTC + local").example("mfn date 2024-07-04T15:30:30Z --tz America/New_York --json","convert to a timezone"),handler:async e=>{const t={from:e.from,inFormat:e["in-format"],inTz:e["in-tz"],tz:e.tz,format:e.format,json:e.json};if(void 0===e.from&&void 0===e.tz&&void 0===e.format&&pe(e))return async function(e){const t=await j.prompt([{type:"input",name:"from",message:K("Date string (blank = now, ISO 8601):")},{type:"input",name:"tz",message:K(`Target timezone (blank = ${Te()}):`)},{type:"input",name:"format",message:K(`Output format (blank = ${Ae}):`)}]);_e({...e,from:t.from?.trim()||void 0,tz:t.tz?.trim()||void 0,format:t.format?.trim()||void 0})}(t);_e(t)}},Fe=Z();function Le(e,t){let n;try{n=v(t)}catch(t){const n=t instanceof Error?t.message:String(t);return de(e,t instanceof Error?t.name:"InvalidEpoch",n)}fe(e,{epoch:n.epoch,unit:n.epochUnit,utc:n.dateTimeInGMT,local:n.dateTime,timezone:n.timezone,relative:n.relative},()=>{Fe.info("Epoch → date"),console.table([{Epoch:`${n.epoch} (${n.epochUnit})`,Local:n.dateTime,GMT:n.dateTimeInGMT,Relative:n.relative}])})}function Be(e,t,n,o){let r,s;try{r=y(t,n,o)}catch(t){const n=t instanceof Error?t.message:String(t);return de(e,t instanceof Error?t.name:"ParseError",n)}try{s=v(r.epochInSeconds).relative}catch{s=void 0}fe(e,{epochInSeconds:r.epochInSeconds,epochInMilliseconds:r.epochInMilliseconds,utc:r.dateTimeInGMT,local:r.dateTime,timezone:r.timezone,relative:s},()=>{Fe.info("Date → epoch"),console.table([{Seconds:r.epochInSeconds,Milliseconds:r.epochInMilliseconds,Local:r.dateTime,GMT:r.dateTimeInGMT,Timezone:r.timezone}])})}const Ce={command:"epoch [value]",describe:"Convert between epoch timestamps and dates (auto-detects unit)",builder:e=>ce(e).positional("value",{describe:"Epoch value to convert to a date (s / ms / µs / ns auto-detected)",type:"number"}).option("from",{type:"string",describe:"A date string to convert TO epoch (ISO 8601 unless --format given)"}).option("format",{type:"string",describe:'Luxon parse format for --from (e.g. "dd/MM/yyyy")'}).option("tz",{type:"string",describe:"IANA timezone used to interpret --from (default: local)"}).example("mfn epoch 1622547800 --json","epoch → date").example("mfn epoch --from 2021-06-01T11:43:20Z --json","date → epoch"),handler:async e=>void 0!==e.from?Be(e,String(e.from),e.format,e.tz):void 0!==e.value&&null!==e.value?Le(e,Number(e.value)):pe(e)?async function(e){const{operation:t}=await j.prompt([{type:"rawlist",name:"operation",message:K("What do you want to do?"),choices:[{name:"Convert epoch → human-readable date",value:"epochToDate"},{name:"Convert date string → epoch",value:"dateToEpoch"}]}]);if("epochToDate"===t){const{value:t}=await j.prompt([{type:"input",name:"value",message:K("Enter epoch value:"),validate:e=>e.trim()&&!isNaN(Number(e))||"Enter a number"}]);Le(e,Number(t))}else{const{input:t}=await j.prompt([{type:"input",name:"input",message:K("Enter a date string (ISO 8601):"),validate:e=>Boolean(e.trim())||"Enter a date string"}]);Be(e,t,void 0,e.tz)}}(e):void de(e,"MissingInput","Provide an epoch <value>, or --from <dateString>. See `mfn epoch --help`.",2)},De=Z(),Me=E(h),Ue=n.join(H(),"ports.json"),Re="win32"===$();async function Pe(e){try{if(Re){const{stdout:t}=await Me("netstat",["-ano"]),n=t.split("\n").find(t=>t.includes(`:${e}`)&&/LISTENING/i.test(t)),o=n?n.trim().split(/\s+/).pop():null;return o?{port:e,pid:o}:null}const{stdout:t}=await Me("lsof",["-i",`:${e}`]),n=t.split("\n").find(e=>/LISTEN/.test(e)),o=n?n.trim().split(/\s+/)[1]:null;return o?{port:e,pid:o}:null}catch{return null}}async function Je(e){Re?await Me("taskkill",["/PID",e,"/F"]):await Me("kill",["-9",e])}const Ge={command:"kill",describe:"Kill the process(es) listening on specific ports",builder:e=>ce(e).option("ports",{alias:"p",describe:"Port number(s) to free",type:"array",coerce:e=>(Array.isArray(e)?e:[e]).map(e=>{const t=Number(e);if(isNaN(t))throw new Error(`Invalid port number: ${e}`);return t})}).option("yes",{alias:"y",type:"boolean",default:!1,describe:"Kill all matching processes without the interactive prompt"}).example("mfn kill -p 3000 8080 -y --json","free ports 3000 and 8080"),handler:async e=>{let t=e.ports??[];if(0===t.length){const n=pe(e)?await async function(){try{return await m.readJson(Ue)}catch(e){if("ENOENT"===e.code)return{ports:[]};throw e}}():{ports:[]};if(!n.ports?.length)return de(e,"NoPorts","No ports provided. Use -p <port...>. See `mfn kill --help`.",2);t=n.ports,De.info(`Using cached ports [${t.join(", ")}]`)}await V({ports:t},Ue).catch(()=>{});const n=(await Promise.all(t.map(Pe))).filter(e=>null!==e),o=t.filter(e=>!n.some(t=>t.port===e));if(0===n.length)return fe(e,{killed:[],failed:[],notFound:o},()=>De.info(`No processes listening on [${t.join(", ")}]`));let r=n;if(pe(e)&&!e.yes){const{pids:e}=await j.prompt([{type:"checkbox",name:"pids",message:K("Select the processes to kill:"),choices:n.map(e=>({name:`Port ${e.port} → PID ${e.pid}`,value:e.pid}))}]);r=n.filter(t=>e.includes(t.pid))}const s=[],a=[];for(const e of r)try{await Je(e.pid),s.push(e)}catch(t){a.push({...e,error:t instanceof Error?t.message:String(t)})}fe(e,{killed:s,failed:a,notFound:o},()=>{for(const e of s)De.info(`Killed PID ${e.pid} on port ${e.port}`);for(const e of a)De.error(`Failed to kill PID ${e.pid} (port ${e.port}): ${e.error}`);o.length&&De.warn(`No process on [${o.join(", ")}]`)}),a.length>0&&process.exit(1)}},We=Z(),Ye=E(h);const Qe={command:"update [package]",describe:"Update the CLI or a specified package to the latest version",builder:e=>ce(e).positional("package",{describe:"npm package to update globally (default: this CLI)",type:"string",default:"@master4n/master-cli"}).example("mfn update","update master-cli itself to the latest version").example("mfn update typescript --json","update a specific global package"),handler:async e=>{const t=String(e.package??"@master4n/master-cli"),n=pe(e)?S():null,o=Date.now();n?.start(u.green(`updating/installing ${t}`));try{await async function(e){await Ye("npm",["install","-g",e])}(t);const r=await async function(e){try{const{stdout:t}=await Ye("npm",["view",e,"version"]);return t.trim()||null}catch{return null}}(t),s=Date.now()-o;n?.succeed(`${u.green(`updated ${t}`)} ${u.dim(`(${(s/1e3).toFixed(3)}s)`)}`),fe(e,{package:t,version:r,durationMs:s},()=>{We.info(`${t} updated/installed${r?` -> ${u.green(r)}`:""}`)})}catch(o){n?.fail(u.red(`failed updating ${t}`));const r=o instanceof Error?o.message:String(o);de(e,"UpdateFailed",`Failed to update "${t}": ${r}`)}}},qe={command:"capabilities",describe:"List every command an agent can call (self-describing manifest)",builder:e=>ce(e).example("mfn capabilities --json","machine-readable manifest"),handler:e=>{fe(e,{name:ee,version:te,bin:"mfn",conventions:{json:"pass --json, or pipe (non-TTY auto-emits) — one {ok,...} object on stdout",exitCodes:{ok:0,error:1,usage:2},logs:"banners and logs go to stderr; stdout carries data only"},commands:X.map(e=>({name:e.name,summary:e.summary,examples:e.examples}))},()=>{console.log(`${ee} v${te} (bin: mfn)`),console.log("Commands an agent can call headlessly:");for(const e of X)console.log(` ${e.name.padEnd(10)} ${e.summary}`);console.log("\nConventions: --json for machine output · exit 0/1/2 · logs on stderr")})}};function Ze(e){switch(e){case"uuid":case"uuid4":return k();case"uuid7":return function(){const e=O(16);e.writeUIntBE(Date.now(),0,6),e[6]=15&e[6]|112,e[8]=63&e[8]|128;const t=e.toString("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}();default:return""}}const He={command:"id",describe:"Generate identifiers (UUID v4/v7 or URL-safe nano id)",builder:e=>ce(e).option("type",{alias:"t",describe:"Identifier type",type:"string",choices:["uuid","uuid4","uuid7","nano"],default:"uuid"}).option("count",{alias:"n",describe:"How many to generate",type:"number",default:1}).option("size",{describe:"Length for --type nano",type:"number",default:21}).example("mfn id --json","one UUID v4").example("mfn id -t uuid7 -n 3 --json","three time-ordered UUID v7").example("mfn id -t nano --size 12 --json","a 12-char URL-safe id"),handler:e=>{const t=String(e.type),n=Number(e.count),o=Number(e.size);if(!Number.isInteger(n)||n<1)return de(e,"InvalidCount","--count must be a positive integer.",2);if("nano"===t&&(!Number.isInteger(o)||o<1))return de(e,"InvalidSize","--size must be a positive integer.",2);const r=Array.from({length:n},()=>"nano"===t?function(e){let t="";for(;t.length<e;){const n=O(e);for(let o=0;o<n.length&&t.length<e;o++)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"[63&n[o]]}return t}(o):Ze(t));fe(e,{type:t,count:n,ids:r},()=>r.forEach(e=>console.log(e)))}},Ke=["md5","sha1","sha256","sha512"],Ve={command:"hash [text]",describe:"Hash a string, file, or stdin (md5/sha1/sha256/sha512)",builder:e=>ce(e).positional("text",{describe:"String to hash (or pipe via stdin, or use --file)",type:"string"}).option("algo",{alias:"a",describe:"Hash algorithm",type:"string",choices:Ke,default:"sha256"}).option("file",{alias:"f",describe:"Hash the contents of this file instead",type:"string"}).option("encoding",{alias:"e",describe:"Digest encoding",type:"string",choices:["hex","base64","base64url"],default:"hex"}).example("mfn hash hello --json",'sha256 of "hello"').example("mfn hash -a md5 -f ./file.txt --json","md5 of a file").example("cat file | mfn hash --json","hash piped stdin"),handler:async e=>{const t=String(e.algo),n=String(e.encoding);let o,r;try{if(void 0!==e.file)o=await A(String(e.file)),r=`file:${e.file}`;else if(void 0!==e.text)o=Buffer.from(String(e.text),"utf8"),r="text";else{const t=await me();if(!t)return de(e,"MissingInput","Provide a string, --file <path>, or pipe stdin.",2);o=Buffer.from(t,"utf8"),r="stdin"}}catch(t){return de(e,"ReadError",t instanceof Error?t.message:String(t))}if(!N().includes(t))return de(e,"UnsupportedAlgo",`Algorithm "${t}" is not available.`,2);const s=I(t).update(o).digest(n);fe(e,{algo:t,encoding:n,source:r,bytes:o.length,hash:s},()=>console.log(s))}};const Xe={command:"encode [text]",describe:"Encode/decode text (base64, base64url, hex, url)",builder:e=>ce(e).positional("text",{describe:"Text to (de/en)code (or pipe via stdin)",type:"string"}).option("as",{alias:"a",describe:"Codec",type:"string",choices:["base64","base64url","hex","url"],default:"base64"}).option("decode",{alias:"d",describe:"Decode instead of encode",type:"boolean",default:!1}).example("mfn encode hello --json",'base64-encode "hello"').example("mfn encode aGVsbG8= -d --json","base64-decode").example('mfn encode "a b&c" --as url --json',"url-encode"),handler:async e=>{const t=String(e.as),n=Boolean(e.decode);let o,r;if(void 0!==e.text)o=String(e.text);else if(o=(await me()).replace(/\n$/,""),!o)return de(e,"MissingInput","Provide text or pipe stdin.",2);try{r=n?function(e,t){switch(t){case"base64":return Buffer.from(e,"base64").toString("utf8");case"base64url":return Buffer.from(e,"base64url").toString("utf8");case"hex":return Buffer.from(e,"hex").toString("utf8");case"url":return decodeURIComponent(e)}}(o,t):function(e,t){switch(t){case"base64":return Buffer.from(e,"utf8").toString("base64");case"base64url":return Buffer.from(e,"utf8").toString("base64url");case"hex":return Buffer.from(e,"utf8").toString("hex");case"url":return encodeURIComponent(e)}}(o,t)}catch(o){return de(e,"CodecError",`Could not ${n?"decode":"encode"} as ${t}: ${o instanceof Error?o.message:String(o)}`)}fe(e,{operation:n?"decode":"encode",codec:t,input:o,output:r},()=>console.log(r))}};const et={command:"random",describe:"Generate cryptographically secure random bytes or a password",builder:e=>ce(e).option("bytes",{alias:"b",describe:"Number of random bytes",type:"number",default:32}).option("encoding",{alias:"e",describe:"Output encoding for bytes",type:"string",choices:["hex","base64","base64url"],default:"hex"}).option("password",{alias:"p",describe:"Generate a password instead of raw bytes",type:"boolean",default:!1}).option("length",{alias:"l",describe:"Password length",type:"number",default:24}).example("mfn random --json","32 secure random bytes as hex").example("mfn random -b 16 -e base64url --json","16 bytes, base64url").example("mfn random -p -l 32 --json","a 32-char password"),handler:e=>{if(e.password){const t=Number(e.length);if(!Number.isInteger(t)||t<1)return de(e,"InvalidLength","--length must be a positive integer.",2);const n=function(e,t){const n=t.length,o=Math.floor(256/n)*n;let r="";for(;r.length<e;)for(const s of O(2*e))if(s<o&&(r+=t[s%n],r.length===e))break;return r}(t,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*-_=+");return fe(e,{kind:"password",length:t,value:n},()=>console.log(n))}const t=Number(e.bytes);if(!Number.isInteger(t)||t<1)return de(e,"InvalidBytes","--bytes must be a positive integer.",2);const n=String(e.encoding),o=O(t).toString(n);fe(e,{kind:"bytes",bytes:t,encoding:n,value:o},()=>console.log(o))}};function tt(){return new Promise((e,t)=>{const n=T();n.unref(),n.on("error",t),n.listen(0,()=>{const t=n.address(),o="object"==typeof t&&t?t.port:0;e({port:o,close:()=>n.close()})})})}const nt={command:"port",describe:"Find a free port, or check whether a specific port is available",builder:e=>ce(e).option("check",{alias:"c",describe:"Check if this specific port is free",type:"number"}).option("count",{alias:"n",describe:"Return this many distinct free ports",type:"number",default:1}).example("mfn port --json","one free port").example("mfn port -n 3 --json","three free ports").example("mfn port -c 3000 --json","is port 3000 free?"),handler:async e=>{if(void 0!==e.check){const t=Number(e.check);if(!Number.isInteger(t)||t<1||t>65535)return de(e,"InvalidPort","--check must be an integer in 1..65535.",2);const n=await function(e){return new Promise(t=>{const n=T();n.unref(),n.on("error",()=>t(!1)),n.listen(e,()=>n.close(()=>t(!0)))})}(t);return fe(e,{port:t,available:n},()=>console.log(`${t} is ${n?"free":"in use"}`))}const t=Number(e.count);if(!Number.isInteger(t)||t<1)return de(e,"InvalidCount","--count must be a positive integer.",2);const n=[];try{for(;n.length<t;){const e=await tt();n.push(e)}}catch(t){n.forEach(e=>e.close());return de(e,"PortError",`Could not allocate a free port: ${t instanceof Error?t.message:String(t)}`)}const o=n.map(e=>e.port);n.forEach(e=>e.close()),fe(e,1===t?{port:o[0]}:{count:t,ports:o},()=>o.forEach(e=>console.log(e)))}},ot=e=>function(e){return{add:(t,n,o,r)=>{e.command({command:t,describe:n,builder:o,handler:r})}}}(ae).add(e.command,e.describe,e.builder,e.handler);ot(qe),ot(He),ot(Ve),ot(Xe),ot(et),ot(Ce),ot(ze),ot(Ne),ot(nt),ot(Ge),ot(Se),ot(xe),ot(Qe),ae.usage("mfn <command> [options]\n\nMaster CLI for developers and AI agents — headless, JSON-first commands that\nreplace boilerplate agents regenerate on every machine. Every command supports\n--json (machine output) and -h/--help (this text).").version(te).alias("version","v").help().alias("help","h").epilogue("Discover every command (machine-readable): mfn capabilities --json\nAgent contract & examples: see llms.txt in this package.\nDocs: https://github.com/Master4Novice/master-cli#readme").wrap(null).strict().demandCommand(1,"No command given. Run `mfn capabilities` to list commands.").fail((e,t)=>{t&&he("CommandError",t.message||String(t),1),he("UsageError",e||"Invalid command invocation.",2)}).parse();
35
36
  //# sourceMappingURL=index.js.map