@newbeebox/newbeebox-debug-bridge 0.2.0 → 0.3.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/README.md +25 -10
- package/dist/cli.cjs +39 -33
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,27 +8,41 @@
|
|
|
8
8
|
npm i -g @newbeebox/newbeebox-debug-bridge # 或 npx @newbeebox/newbeebox-debug-bridge ...
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## 快速上手(adb 的心智)
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
ndb login --token ndbk_xxx # token 由服务端管理面板签发,落 ~/.ndb/config.json(600)
|
|
15
|
-
ndb
|
|
16
|
-
ndb
|
|
17
|
-
|
|
18
|
-
ndb
|
|
19
|
-
ndb
|
|
20
|
-
ndb
|
|
15
|
+
ndb connect 81268383 # 连上并设为当前设备
|
|
16
|
+
ndb devices # 看清单与状态:device / unauthorized / offline
|
|
17
|
+
|
|
18
|
+
ndb status # 之后的命令默认打在当前设备上
|
|
19
|
+
ndb exec -- ipconfig /all
|
|
20
|
+
ndb ls C:\logs
|
|
21
|
+
ndb get C:\logs\app.log --out app.log # >2MB 自动走资产桶异步下载
|
|
22
|
+
ndb screenshot --window "*.txt" --out shot.png
|
|
23
|
+
|
|
24
|
+
ndb -s 90011223 status # 临时打到别的设备
|
|
25
|
+
ndb disconnect # 断开当前设备(--all 全断)
|
|
21
26
|
```
|
|
22
27
|
|
|
28
|
+
连接码也可以照旧写在命令里:`ndb ls 81268383 C:\logs`、`ndb exec 81268383 -- ipconfig /all`
|
|
29
|
+
—— 判据是**位置参数个数**,不是"看着像不像连接码",所以 `ndb ls 12345678`(目录名恰好八位数字)
|
|
30
|
+
不会被误判。
|
|
31
|
+
|
|
23
32
|
## 全局选项
|
|
24
33
|
|
|
25
34
|
| 选项 | 说明 |
|
|
26
35
|
|------|------|
|
|
27
|
-
| `--base-url <url>` | 服务端地址(或
|
|
28
|
-
| `--token <token>` | 覆盖 token(或
|
|
36
|
+
| `--base-url <url>` | 服务端地址(或 `~/.ndb/config.json`,默认 `http://127.0.0.1:8080`) |
|
|
37
|
+
| `--token <token>` | 覆盖 token(或 `~/.ndb/config.json`) |
|
|
38
|
+
| `-s, --serial <code>` | 目标设备连接码,覆盖当前设备(同 `adb -s`) |
|
|
29
39
|
| `-o, --output <fmt>` | `text`(默认) \| `json` |
|
|
30
40
|
| `-c, --compact` | 紧凑单行 JSON(隐含 `-o json`) |
|
|
31
41
|
|
|
42
|
+
**不读任何环境变量**(0.3.0 起):`NDB_BASE_URL` / `NDB_TOKEN` 不再生效,改用上面的 flag 或
|
|
43
|
+
`ndb login`。**也不经任何系统代理**:走 `node:http/https` 显式 Agent,`HTTP_PROXY` 之类一律无效。
|
|
44
|
+
排障工具自己被中间人,比它要排的故障更难查。
|
|
45
|
+
|
|
32
46
|
## 给 LLM Agent
|
|
33
47
|
|
|
34
48
|
```bash
|
|
@@ -50,7 +64,8 @@ npm test
|
|
|
50
64
|
```
|
|
51
65
|
|
|
52
66
|
`npm test` 会拉起真实 server(内存后端) + 真实 desktop agent + 本 CLI,覆盖
|
|
53
|
-
login/
|
|
67
|
+
login/devices/connect/disconnect/`-s`/省略连接码/exec(放行+黑名单拦截)/ls/get(内联+资产)/
|
|
68
|
+
schema/未登录保护/环境变量不再生效。
|
|
54
69
|
|
|
55
70
|
命令定义是**单一数据结构**(`src/commands.ts`),一处定义同时驱动 human help、
|
|
56
71
|
JSON 输出与 `ndb schema`。协议契约见 `../docs/02-PROTOCOL.md`。
|
package/dist/cli.cjs
CHANGED
|
@@ -1,53 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(s))}let
|
|
4
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,i=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(e.match(o))return e;let a=t-n;if(a<i)return e;let
|
|
2
|
+
"use strict";var Ie=Object.create;var oe=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Me=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fe(e))!Ue.call(r,i)&&i!==t&&oe(r,i,{get:()=>e[i],enumerable:!(n=qe(e,i))||n.enumerable});return r};var We=(r,e,t)=>(t=r!=null?Ie(Be(r)):{},Me(e||!r||!r.__esModule?oe(t,"default",{value:r,enumerable:!0}):t,r));var E=A(B=>{var H=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},F=class extends H{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};B.CommanderError=H;B.InvalidArgumentError=F});var T=A(M=>{var{InvalidArgumentError:Le}=E(),U=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Le(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ze(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}M.Argument=U;M.humanReadableArgName=ze});var L=A(ae=>{var{humanReadableArgName:Ge}=T(),W=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,s)=>i.name().localeCompare(s.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Ge(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,t.subcommandTerm(i).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,t.optionTerm(i).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,t.optionTerm(i).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,t.argumentTerm(i).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth||80,s=2,o=2;function a(m,g){if(g){let y=`${m.padEnd(n+o)}${g}`;return t.wrap(y,i-s,n+o)}return m}function c(m){return m.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(s))}let u=[`Usage: ${t.commandUsage(e)}`,""],l=t.commandDescription(e);l.length>0&&(u=u.concat([t.wrap(l,i,0),""]));let h=t.visibleArguments(e).map(m=>a(t.argumentTerm(m),t.argumentDescription(m)));h.length>0&&(u=u.concat(["Arguments:",c(h),""]));let d=t.visibleOptions(e).map(m=>a(t.optionTerm(m),t.optionDescription(m)));if(d.length>0&&(u=u.concat(["Options:",c(d),""])),this.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));m.length>0&&(u=u.concat(["Global Options:",c(m),""]))}let _=t.visibleCommands(e).map(m=>a(t.subcommandTerm(m),t.subcommandDescription(m)));return _.length>0&&(u=u.concat(["Commands:",c(_),""])),u.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,i=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(e.match(o))return e;let a=t-n;if(a<i)return e;let c=e.slice(0,n),u=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${a-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),m=
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
6
|
+
`),l=" ".repeat(n),d="\\s\u200B",_=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),m=u.match(_)||[];return c+m.map((g,y)=>g===`
|
|
8
|
+
`?"":(y>0?l:"")+g.trimEnd()).join(`
|
|
9
|
+
`)}};ae.Help=W});var Q=A(J=>{var{InvalidArgumentError:Je}=E(),z=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ke(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Je(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Qe(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},G=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,s=i!==void 0?i:!1;return t.negate===(s===e)}};function Qe(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ke(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}J.Option=z;J.DualOptions=G});var ue=A(ce=>{function Xe(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=r.length;i++){let s=1;r[i-1]===e[n-1]?s=0:s=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+s),i>1&&n>1&&r[i-1]===e[n-2]&&r[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[r.length][e.length]}function Ye(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Xe(r,o),c=Math.max(r.length,o.length);(c-a)/c>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}ce.suggestSimilar=Ye});var pe=A(me=>{var Ze=require("node:events").EventEmitter,K=require("node:child_process"),O=require("node:path"),X=require("node:fs"),p=require("node:process"),{Argument:et,humanReadableArgName:tt}=T(),{CommanderError:Y}=E(),{Help:nt}=L(),{Option:le,DualOptions:it}=Q(),{suggestSimilar:he}=ue(),Z=class r extends Ze{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>p.stdout.write(t),writeErr:t=>p.stderr.write(t),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new r(e)}createHelp(){return Object.assign(new nt,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new et(e,t)}argument(e,t,n,i){let s=this.createArgument(e,t);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,i]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),i&&o.arguments(i),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Y(e,t,n)),p.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new le(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,t,n,i,s){if(typeof t=="object"&&t instanceof le)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,u)=>{let l=a.exec(c);return l?l[0]:u},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){p.versions?.electron&&(t.from="electron");let i=p.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=p.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":p.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(l,h){let d=O.resolve(l,h);if(X.existsSync(d))return d;if(i.includes(O.extname(h)))return;let _=i.find(m=>X.existsSync(`${d}${m}`));if(_)return`${d}${_}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let l;try{l=X.realpathSync(this._scriptPath)}catch{l=this._scriptPath}a=O.resolve(O.dirname(l),a)}if(a){let l=s(a,o);if(!l&&!e._executableFile&&this._scriptPath){let h=O.basename(this._scriptPath,O.extname(this._scriptPath));h!==this._name&&(l=s(a,`${h}-${e._name}`))}o=l||o}n=i.includes(O.extname(o));let c;p.platform!=="win32"?n?(t.unshift(o),t=de(p.execArgv).concat(t),c=K.spawn(p.argv[0],t,{stdio:"inherit"})):c=K.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=de(p.execArgv).concat(t),c=K.spawn(p.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{p.on(h,()=>{c.killed===!1&&c.exitCode===null&&c.kill(h)})});let u=this._exitCallback;c.on("close",l=>{l=l??1,u?u(new Y(l,"commander.executeSubCommandAsync","(close)")):p.exit(l)}),c.on("error",l=>{if(l.code==="ENOENT"){let h=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${h}`;throw new Error(d)}else if(
|
|
17
|
+
- ${h}`;throw new Error(d)}else if(l.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)p.exit(1);else{let h=new Y(1,"commander.executeSubCommandAsync","(error)");h.nestedError=l,u(h)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),t[i]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,s=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){i===n&&i.push(c),i.push(...s);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let l=s.shift();l===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,l)}else if(u.optional){let l=null;s.length>0&&!o(s[0])&&(l=s.shift()),this.emit(`option:${u.name()}`,l)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),l=this._findOption(c.slice(0,u));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,c.slice(u+1));continue}}if(o(c)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){i.push(c),s.length>0&&i.push(...s);break}i.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in p.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,p.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in p.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,p.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new it(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),c=this.getOptionValue(a),u=this.options.find(h=>h.negate&&a===h.attributeName()),l=this.options.find(h=>!h.negate&&a===h.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:l||o},i=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=he(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),t=he(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>tt(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=O.basename(e,O.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=i=>this._outputConfiguration.writeErr(i):n=i=>this._outputConfiguration.writeOut(i),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation(n);if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=p.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
24
|
-
`),
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function de(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}me.Command=Z});var be=A(b=>{var{Argument:fe}=T(),{Command:ee}=pe(),{CommanderError:st,InvalidArgumentError:ge}=E(),{Help:rt}=L(),{Option:_e}=Q();b.program=new ee;b.createCommand=r=>new ee(r);b.createOption=(r,e)=>new _e(r,e);b.createArgument=(r,e)=>new fe(r,e);b.Command=ee;b.Option=_e;b.Argument=fe;b.Help=rt;b.CommanderError=st;b.InvalidArgumentError=ge;b.InvalidOptionArgumentError=ge});var we=We(be(),1),{program:Nt,createCommand:Ht,createArgument:Tt,createOption:Dt,CommanderError:Vt,InvalidArgumentError:Pt,InvalidOptionArgumentError:jt,Command:ye,Argument:Rt,Option:It,Help:qt}=we.default;var j=require("node:fs");var D=require("node:http"),V=require("node:https"),v=require("node:zlib");function Oe(r){let e=r.replace(/\/+$/,"");return e.startsWith("wss://")?e="https://"+e.slice(6):e.startsWith("ws://")?e="http://"+e.slice(5):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="http://"+e),e}var $e=35e3,ot=300,at=3e4,ct=30*60*1e3,ut=1e4,lt=5,ht=r=>new Promise(e=>setTimeout(e,r));function dt(r,e){let t=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return!r.length||!t||t==="identity"?r:t==="gzip"?(0,v.gunzipSync)(r):t==="deflate"?(0,v.inflateSync)(r):t==="br"?(0,v.brotliDecompressSync)(r):r}var f=class extends Error{code;constructor(e){super(e.message),this.code=e.code}},k=class r{httpBase;token;agents={"http:":new D.Agent({keepAlive:!0}),"https:":new V.Agent({keepAlive:!0})};constructor(e){this.httpBase=Oe(e)}static async open(e){return new r(e)}close(){this.agents["http:"].destroy(),this.agents["https:"].destroy()}raw(e,t,n,i,s=lt){return new Promise((o,a)=>{let c=new URL(t),u=c.protocol==="https:";if(!u&&c.protocol!=="http:")return a(new Error(`\u4E0D\u652F\u6301\u7684\u534F\u8BAE ${c.protocol}`));let l=(u?V.request:D.request)({hostname:c.hostname,port:c.port||(u?443:80),path:c.pathname+c.search,method:e,headers:n,agent:this.agents[c.protocol],timeout:$e},h=>{let d=h.statusCode??0,_=h.headers.location;if(_&&d>=300&&d<400&&e==="GET"&&s>0){h.resume();let g=new URL(_,t),y={...n};return g.origin!==c.origin&&delete y.authorization,o(this.raw(e,g.toString(),y,i,s-1))}let m=[];h.on("data",g=>m.push(g)),h.on("error",a),h.on("end",()=>{try{o({status:d,headers:h.headers,body:dt(Buffer.concat(m),h.headers["content-encoding"])})}catch(g){a(new Error(`\u54CD\u5E94\u89E3\u538B\u5931\u8D25: ${g.message}`))}})});l.on("timeout",()=>l.destroy(new Error(`\u7A7A\u95F2\u8D85\u8FC7 ${$e}ms`))),l.on("error",a),i&&l.write(i),l.end()})}async request(e,t,n){let i=this.httpBase+t,s={accept:"application/json","accept-encoding":"gzip"};this.token&&(s.authorization=`Bearer ${this.token}`);let o=n!==void 0?Buffer.from(JSON.stringify(n),"utf8"):void 0;o&&(s["content-type"]="application/json",s["content-length"]=String(o.length));let a;try{a=await this.raw(e,i,s,o)}catch(l){let h=l.message,d=/空闲超过|ETIMEDOUT/.test(h)?"TIMEOUT":"INTERNAL";throw new f({code:d,message:`\u8BF7\u6C42\u5931\u8D25 ${i}: ${h}`})}let c=a.body.toString("utf8"),u;if(c)try{u=JSON.parse(c)}catch{}if(a.status<200||a.status>=300){let l=u?.error;throw l&&typeof l.code=="string"?new f({code:l.code,message:l.message??`HTTP ${a.status}`}):new f({code:"INTERNAL",message:`HTTP ${a.status}: ${c||"(\u7A7A\u54CD\u5E94)"}`})}return u}async login(e,t){return this.token=e,await this.request("GET","/api/whoami")}async connect(e){return this.request("GET",`/api/connect/${encodeURIComponent(e)}`)}async status(e){return this.request("GET",`/api/status/${encodeURIComponent(e)}`)}async exec(e,t,n,i){let o=(await this.request("POST","/api/exec",{code:e,cmd:t,args:n,timeout_ms:i}))?.job_id;if(!o)throw new f({code:"INTERNAL",message:"exec \u672A\u8FD4\u56DE job_id"});let a=Math.min((i??15e3)+at,ct),c=Date.now()+a+ut;for(;;){let u=await this.request("GET",`/api/jobs/${encodeURIComponent(o)}`);if(u?.status==="done")return u.result;if(u?.status==="error")throw new f({code:"AGENT_ERROR",message:u.error??"exec \u5931\u8D25"});if(Date.now()>c)throw new f({code:"TIMEOUT",message:"exec \u7ED3\u679C\u8F6E\u8BE2\u8D85\u65F6"});await ht(ot)}}async listDir(e,t){return this.request("POST","/api/list_dir",{code:e,path:t})}async newbeeboxDiag(e,t){return this.request("POST","/api/newbeebox_diag",{code:e,channel:t})}async readFile(e,t,n){let i=await this.request("POST","/api/read_file",{code:e,path:t,max_bytes:n});return i?.mode==="asset"?{kind:"asset",url:i.url,bytes:i.bytes,sha256:i.sha256}:{kind:"inline",bytes:Buffer.from(i?.data??"","base64"),total:i?.bytes??0}}async screenshot(e,t){let n=await this.request("POST","/api/screenshot",{code:e,...t});return n?.mode==="asset"?{kind:"asset",url:n.url,bytes:n.bytes,w:n.w,h:n.h}:{kind:"inline",bytes:Buffer.from(n?.data??"","base64"),total:n?.bytes??0}}async download(e){let t=e.startsWith("http")?e:this.httpBase+e,n=await this.raw("GET",t,{"accept-encoding":"identity"});if(n.status<200||n.status>=300)throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${n.status}: ${t}`);return n.body}};var Ce=require("node:os"),te=require("node:path"),w=require("node:fs"),mt="http://127.0.0.1:8080";function Ae(){return(0,te.join)((0,Ce.homedir)(),".ndb")}function P(){return(0,te.join)(Ae(),"config.json")}function $(){try{return JSON.parse((0,w.readFileSync)(P(),"utf8"))}catch{return{}}}function S(r){(0,w.mkdirSync)(Ae(),{recursive:!0}),(0,w.writeFileSync)(P(),JSON.stringify(r,null,2),{encoding:"utf8",mode:384});try{(0,w.chmodSync)(P(),384)}catch{}}function ve(){let r=$();return r.token===void 0?!1:(delete r.token,S(r),!0)}function xe(){return P()}function ne(){return $().devices??[]}function N(){return $().current}function Ee(r){let e=$(),t=(e.devices??[]).filter(n=>n.code!==r.code);t.push(r),S({...e,devices:t,current:r.code})}function ke(r){let e=$(),t=e.devices??[],n=t.filter(o=>r.includes(o.code)),i=t.filter(o=>!r.includes(o.code)),s=i.some(o=>o.code===e.current)?e.current:void 0;return S({...e,devices:i,current:s}),n}function Se(r){let e=$();return{baseUrl:r.baseUrl||e.base_url||mt,token:r.token||e.token}}var De=r=>`ndb/${r.version}`;async function ie(r,e){if(!r.token)throw new f({code:"UNAUTHORIZED",message:"\u672A\u767B\u5F55\uFF0C\u8BF7\u5148\u6267\u884C\uFF1Andb login --token <token>"});let t=await k.open(r.baseUrl);try{let n=await t.login(r.token,De(r));return await e(t,n)}finally{t.close()}}async function C(r,e){let t=r.device;if(!t)throw new f({code:"BAD_REQUEST",message:"\u672A\u6307\u5B9A\u8BBE\u5907\uFF1A\u5148 ndb connect <code>\uFF0C\u6216\u52A0\u5168\u5C40 -s <code>\uFF08ndb devices \u770B\u6E05\u5355\uFF09"});return ie(r,n=>e(n,t))}function pt(r){return r?r.online?r.authorized?"device":"unauthorized":"offline":"unknown"}async function Ne(r,e,t){try{return await r.newbeeboxDiag(e,t)}catch(n){throw n instanceof f&&n.code==="NOT_FOUND"&&/unsupported method/i.test(n.message)?new f({code:"NOT_FOUND",message:"\u5BA2\u6237\u673A agent \u7248\u672C\u8FC7\u4F4E\uFF0C\u4E0D\u652F\u6301 newbeebox \u91C7\u96C6\u3002\u8BF7\u8BA9\u5BA2\u6237\u91CD\u65B0\u4E0B\u8F7D\u5B89\u88C5\u6700\u65B0\u684C\u9762\u7AEF\u540E\u91CD\u8BD5\u3002"}):n}}function He(r,e,t,n){if(!e.length)return`${r} 0 \u4E2A`;let i=e.filter(t),s=i.length?i:e.slice(0,ft),o=e.length-s.length,a=s.map(u=>` - ${i.length?"\u26A0 ":""}${n(u)}`).join(`
|
|
24
|
+
`),c=o>0?`
|
|
25
25
|
\u2026 \u5176\u4F59 ${o} \u6761\u6B63\u5E38\uFF0C-o json \u770B\u5168\u91CF`:"";return`${r} ${e.length} \u4E2A${i.length?`\uFF08${i.length} \u4E2A\u6709\u95EE\u9898\uFF09`:""}:
|
|
26
|
-
${a}${
|
|
27
|
-
`)}var
|
|
28
|
-
\u914D\u7F6E\u5DF2\u4FDD\u5B58\uFF1A${r.saved}`},{name:"logout",summary:"\u6E05\u9664\u672C\u5730\u4FDD\u5B58\u7684 token",args:[],options:[],auth:"none",returns:"{ cleared }",async handler(){return{cleared:
|
|
29
|
-
\
|
|
30
|
-
\
|
|
26
|
+
${a}${c}`}var ft=12;function Te(r){return Object.entries(r).map(([e,t])=>`${e.padEnd(14)} ${t}`).join(`
|
|
27
|
+
`)}var R=[{name:"login",summary:"\u4FDD\u5B58 token \u5230 ~/.ndb/config.json \u5E76\u6821\u9A8C\u8EAB\u4EFD",description:"token \u7531\u670D\u52A1\u7AEF\u7BA1\u7406\u9762\u677F\u9884\u5148\u7B7E\u53D1\u3002\u6821\u9A8C\u901A\u8FC7\u540E\u843D\u672C\u5730\u914D\u7F6E\uFF08\u6743\u9650 600\uFF09\u3002",args:[],options:[{flag:"--token <token>",name:"token",type:"string",desc:"\u8981\u4FDD\u5B58\u7684 token\uFF08\u4E5F\u53EF\u7528\u5168\u5C40 --token\uFF09"}],auth:"none",returns:"{ saved, uid, username }",async handler(r,e,t){let n=t.token||r.token;if(!n)throw new f({code:"BAD_REQUEST",message:"\u7F3A\u5C11 token\uFF1Andb login --token <token>"});let i=await k.open(r.baseUrl),s;try{s=await i.login(n,De(r))}finally{i.close()}return S({...$(),base_url:r.baseUrl,token:n}),{saved:xe(),uid:s.uid,username:s.username}},render:r=>`\u5DF2\u767B\u5F55 ${r.username} (uid=${r.uid})
|
|
28
|
+
\u914D\u7F6E\u5DF2\u4FDD\u5B58\uFF1A${r.saved}`},{name:"logout",summary:"\u6E05\u9664\u672C\u5730\u4FDD\u5B58\u7684 token",args:[],options:[],auth:"none",returns:"{ cleared }",async handler(){return{cleared:ve()}},render:r=>r.cleared?"\u5DF2\u6E05\u9664\u672C\u5730 token":"\u672C\u5730\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684 token"},{name:"whoami",summary:"\u663E\u793A\u5F53\u524D\u8EAB\u4EFD\uFF08uid/username\uFF09",args:[],options:[],auth:"token",returns:"{ uid, username, session_expires }",async handler(r){return ie(r,async(e,t)=>({uid:t.uid,username:t.username,session_expires:t.session_expires}))},render:r=>Te(r)},{name:"devices",summary:"\u5217\u51FA\u5DF2\u8FDE\u63A5\u7684\u8BBE\u5907\uFF08\u8FDE\u63A5\u7801 / \u72B6\u6001 / \u4E3B\u673A\uFF09",description:`\u6E05\u5355\u6765\u81EA\u672C\u5730 ~/.ndb/config.json\uFF08connect \u843D\u5E93\uFF09\uFF0C\u72B6\u6001\u5B9E\u65F6\u5411\u670D\u52A1\u7AEF\u67E5\u3002
|
|
29
|
+
\u72B6\u6001\u8BCD\u540C adb\uFF1Adevice=\u5728\u7EBF\u4E14\u5DF2\u6388\u6743\uFF0Cunauthorized=\u5728\u7EBF\u4F46\u5BA2\u6237\u6CA1\u70B9\u6388\u6743\uFF0Coffline=\u4E0D\u5728\u7EBF\uFF0Cunknown=\u67E5\u4E0D\u5230\u3002`,args:[],options:[],auth:"token",returns:"{ current, devices: [{ code, state(device|unauthorized|offline|unknown), host, os, connected_at, current }] }",async handler(r){let e=ne(),t=N(),n=new Map;if(e.length)try{await ie(r,async i=>{(await Promise.all(e.map(o=>i.status(o.code).catch(()=>null)))).forEach((o,a)=>n.set(e[a].code,pt(o)))})}catch{}return{current:t,devices:e.map(i=>({...i,state:n.get(i.code)??"unknown",current:i.code===t}))}},render:r=>r.devices.length?["\u5DF2\u8FDE\u63A5\u8BBE\u5907\uFF1A",...r.devices.map(t=>`${t.code} ${String(t.state).padEnd(13)}${t.host??"-"}${t.os?` (${t.os})`:""}${t.current?" \u2190 \u5F53\u524D":""}`)].join(`
|
|
30
|
+
`):"\u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u8BBE\u5907\u3002\u5148\u6267\u884C\uFF1Andb connect <code>"},{name:"connect",summary:"\u8FDE\u63A5\u8BBE\u5907\uFF1A\u6821\u9A8C\u53EF\u8FBE\u5E76\u8BBE\u4E3A\u5F53\u524D\u8BBE\u5907",description:`\u8FDE\u4E0A\u540E\u8BE5\u8BBE\u5907\u6210\u4E3A\u9ED8\u8BA4\u76EE\u6807\uFF0C\u540E\u7EED\u547D\u4EE4\u4E0D\u5FC5\u518D\u8D34\u8FDE\u63A5\u7801\uFF1B\u4E34\u65F6\u6253\u5230\u522B\u7684\u8BBE\u5907\u7528\u5168\u5C40 -s <code>\u3002
|
|
31
|
+
\u4E0D\u5728\u7EBF\u7684\u7801\u4E0D\u5165\u5E93\uFF0C\u514D\u5F97\u62FC\u9519\u7684\u7801\u5E38\u9A7B\u6E05\u5355\u3002exec \u7B49\u9AD8\u5371\u64CD\u4F5C\u4ECD\u8981\u6C42 authorized=true\u3002`,device:!0,args:[],options:[],auth:"token",returns:"{ ok, code, online, authorized, host, os, saved }",async handler(r){return C(r,async(e,t)=>{let n=await e.connect(t),i=!!n?.online;return i&&Ee({code:t,host:n.host,os:n.os,connected_at:Date.now()}),{...n,code:t,saved:i}})},render:r=>`${r.host??"-"} (${r.os??"-"}) online=${r.online} authorized=${r.authorized}`+(r.online?r.authorized?`
|
|
32
|
+
\u5DF2\u8BBE\u4E3A\u5F53\u524D\u8BBE\u5907 ${r.code}\uFF0C\u540E\u7EED\u547D\u4EE4\u53EF\u7701\u7565\u8FDE\u63A5\u7801\u3002`:`
|
|
33
|
+
\u5DF2\u8BBE\u4E3A\u5F53\u524D\u8BBE\u5907 ${r.code}\uFF0C\u4F46\u5BA2\u6237\u5C1A\u672A\u70B9\u6388\u6743\uFF0C\u6682\u4E0D\u53EF\u6267\u884C\u8FDC\u7A0B\u64CD\u4F5C\u3002`:`
|
|
34
|
+
\u76EE\u6807\u4E0D\u5728\u7EBF\uFF0C\u672A\u52A0\u5165\u8BBE\u5907\u6E05\u5355\u3002`)},{name:"disconnect",summary:"\u65AD\u5F00\u8BBE\u5907\uFF08\u4ECE\u672C\u5730\u6E05\u5355\u79FB\u9664\uFF09",description:`\u7F3A\u7701\u65AD\u5F00\u5F53\u524D\u8BBE\u5907\uFF0C\u4E5F\u53EF\u6307\u5B9A\u8FDE\u63A5\u7801\u6216 --all\u3002
|
|
35
|
+
\u53EA\u6E05\u672C\u5730\u8BB0\u5F55\uFF0C\u4E0D\u52A8\u5BA2\u6237\u673A\u4E0A\u7684\u6388\u6743 \u2014\u2014 \u6388\u6743\u662F\u5BA2\u6237\u7ED9\u7684\uFF0C\u4E5F\u53EA\u80FD\u7531\u5BA2\u6237\u64A4\u9500\u3002`,device:!0,args:[],options:[{flag:"--all",name:"all",type:"boolean",desc:"\u65AD\u5F00\u5168\u90E8\u8BBE\u5907"}],auth:"none",returns:"{ removed: [code], current }",async handler(r,e,t){let n=t.all?ne().map(s=>s.code):r.device?[r.device]:[];if(!n.length)throw new f({code:"BAD_REQUEST",message:t.all?"\u6CA1\u6709\u5DF2\u8FDE\u63A5\u7684\u8BBE\u5907":"\u672A\u6307\u5B9A\u8BBE\u5907\uFF1Andb disconnect <code>\uFF0C\u6216 --all"});return{removed:ke(n).map(s=>s.code),current:N()}},render:r=>r.removed.length?`\u5DF2\u65AD\u5F00 ${r.removed.join(", ")}${r.current?`
|
|
36
|
+
\u5F53\u524D\u8BBE\u5907\uFF1A${r.current}`:""}`:"\u6E05\u5355\u91CC\u6CA1\u6709\u8FD9\u53F0\u8BBE\u5907"},{name:"status",summary:"\u67E5\u5BA2\u6237\u673A\u5728\u7EBF/\u6388\u6743\u72B6\u6001",device:!0,args:[],options:[],auth:"token",returns:"{ online, authorized, last_seen }",async handler(r){return C(r,(e,t)=>e.status(t))},render:r=>Te(r)},{name:"exec",summary:"\u5728\u6307\u5B9A\u5BA2\u6237\u673A\u6267\u884C\u4E00\u6761\u547D\u4EE4",description:"\u53D7\u670D\u52A1\u7AEF\u547D\u4EE4\u9ED1\u767D\u540D\u5355\u7EA6\u675F\uFF1B\u88AB\u62D2\u56DE FORBIDDEN\u3002\n\u547D\u4EE4\u4E00\u5F8B\u5199\u5728 -- \u4E4B\u540E\uFF1A`ndb exec -- ipconfig /all`\uFF08\u5F53\u524D\u8BBE\u5907\uFF09\u3001`ndb exec <code> -- ipconfig /all`\uFF08\u6307\u5B9A\u8BBE\u5907\uFF09\u3002",device:!0,args:[{name:"cmd",required:!0,variadic:!0,desc:"\u547D\u4EE4\u4E0E\u53C2\u6570\uFF0C\u5982 -- ipconfig /all"}],options:[{flag:"--timeout <ms>",name:"timeout",type:"number",desc:"\u6267\u884C\u8D85\u65F6(\u6BEB\u79D2)",default:15e3}],auth:"token+authorized",returns:"{ exit_code, stdout, stderr, duration_ms, truncated }",async handler(r,e,t){if(e.length===0)throw new f({code:"BAD_REQUEST",message:"\u7F3A\u5C11\u547D\u4EE4\uFF1A\u5F53\u524D\u8BBE\u5907\u5199 `ndb exec -- ipconfig /all`\uFF0C\u6307\u5B9A\u8BBE\u5907\u5199 `ndb exec <code> -- ipconfig /all`"});let n=t.timeout!=null?Number(t.timeout):void 0;return C(r,(i,s)=>i.exec(s,e[0],e.slice(1),n))},render:r=>{let e=`exit=${r.exit_code} (${r.duration_ms}ms)${r.truncated?" [truncated]":""}`,t=r.stdout?`
|
|
31
37
|
${r.stdout.replace(/\n$/,"")}`:"",n=r.stderr?`
|
|
32
38
|
[stderr]
|
|
33
|
-
${r.stderr.replace(/\n$/,"")}`:"";return e+t+n}},{name:"ls",summary:"\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\uFF08\u4FBF\u4E8E\u5B9A\u4F4D\u6587\u4EF6\uFF09",
|
|
34
|
-
`):"(\u7A7A\u76EE\u5F55)"}},{name:"get",summary:"\u8BFB\u53D6/\u4E0B\u8F7D\u8FDC\u7A0B\u6587\u4EF6",description:"\u5C0F\u6587\u4EF6\u5185\u8054\u56DE\u4F20\uFF1B\u5927\u6587\u4EF6(>\u670D\u52A1\u7AEF\u9608\u503C,\u9ED8\u8BA42MB)\u81EA\u52A8\u843D\u8D44\u4EA7\u6876\u5E76 HTTP \u5F02\u6B65\u4E0B\u8F7D\u3002--out \u5B58\u6587\u4EF6\uFF0C\u5426\u5219\u5199 stdout\u3002",
|
|
35
|
-
\u4E0D\u542B\u4EFB\u4F55\u51ED\u636E\uFF08token/\u5BC6\u7801\u4E00\u5F8B\u4E0D\u91C7\u96C6\uFF0C\u624B\u673A\u53F7\u6253\u7801\uFF09\u3002\u65E5\u5FD7\u6B63\u6587\u4E0D\u5728\u6B64\u547D\u4EE4\u5185\uFF0C\u7528
|
|
39
|
+
${r.stderr.replace(/\n$/,"")}`:"";return e+t+n}},{name:"ls",summary:"\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\uFF08\u4FBF\u4E8E\u5B9A\u4F4D\u6587\u4EF6\uFF09",device:!0,args:[{name:"path",required:!0,desc:"\u76EE\u5F55\u8DEF\u5F84"}],options:[],auth:"token+authorized",returns:"{ entries: [{ name, size, dir, mtime }] }",async handler(r,e){return C(r,(t,n)=>t.listDir(n,e[0]))},render:r=>{let e=r.entries.map(t=>{let n=t.dir?"D":"-",i=t.dir?"":String(t.size);return`${n} ${i.padStart(10)} ${t.name}`});return e.length?e.join(`
|
|
40
|
+
`):"(\u7A7A\u76EE\u5F55)"}},{name:"get",summary:"\u8BFB\u53D6/\u4E0B\u8F7D\u8FDC\u7A0B\u6587\u4EF6",description:"\u5C0F\u6587\u4EF6\u5185\u8054\u56DE\u4F20\uFF1B\u5927\u6587\u4EF6(>\u670D\u52A1\u7AEF\u9608\u503C,\u9ED8\u8BA42MB)\u81EA\u52A8\u843D\u8D44\u4EA7\u6876\u5E76 HTTP \u5F02\u6B65\u4E0B\u8F7D\u3002--out \u5B58\u6587\u4EF6\uFF0C\u5426\u5219\u5199 stdout\u3002",device:!0,args:[{name:"path",required:!0,desc:"\u8FDC\u7A0B\u6587\u4EF6\u8DEF\u5F84"}],options:[{flag:"--out <file>",name:"out",type:"string",desc:"\u4FDD\u5B58\u5230\u672C\u5730\u6587\u4EF6\uFF08\u7F3A\u7701\u5199 stdout\uFF09"},{flag:"--max-bytes <n>",name:"maxBytes",type:"number",desc:"\u6700\u5927\u8BFB\u53D6\u5B57\u8282\u6570"}],auth:"token+authorized",returns:"{ mode: inline|asset, bytes, sha256?, out? }",async handler(r,e,t){let n=t.maxBytes!=null?Number(t.maxBytes):void 0;return C(r,async(i,s)=>{let o=await i.readFile(s,e[0],n),a=o.kind==="inline"?o.bytes:await i.download(o.url),c={mode:o.kind,bytes:a.length,...o.kind==="asset"?{sha256:o.sha256,url:o.url}:{}};return t.out?((0,j.writeFileSync)(t.out,a),c.out=t.out):r.output==="json"?c.base64=a.toString("base64"):process.stdout.write(a),c})},render:r=>r.out?`\u5DF2\u4FDD\u5B58 ${r.bytes} \u5B57\u8282\u5230 ${r.out} (${r.mode})`:""},{name:"screenshot",summary:"\u8FDC\u7A0B\u622A\u56FE\u5E76\u4E0B\u8F7D\u5230\u672C\u5730",description:"\u9ED8\u8BA4\u5168\u5C4F\uFF1B--window/--app \u6307\u5B9A\u7A97\u53E3\u3002\u5927\u56FE\u540C\u6837\u8D70\u8D44\u4EA7\u6876\u3002\u8FD4\u56DE\u56FE\u7247\u4FDD\u5B58\u8DEF\u5F84\u3002",device:!0,args:[],options:[{flag:"--out <file>",name:"out",type:"string",desc:"\u4FDD\u5B58\u8DEF\u5F84\uFF08\u7F3A\u7701 ndb-shot-<code>.png\uFF09"},{flag:"--app <name>",name:"app",type:"string",desc:"\u76EE\u6807\u5E94\u7528\u540D\uFF08\u7A97\u53E3\u622A\u56FE\uFF09"},{flag:"--window <title>",name:"window",type:"string",desc:"\u7A97\u53E3\u6807\u9898\u5339\u914D"},{flag:"--monitor <n>",name:"monitor",type:"number",desc:"\u663E\u793A\u5668\u5E8F\u53F7\uFF08\u5168\u5C4F\uFF09"}],auth:"token+authorized",returns:"{ bytes, out }",async handler(r,e,t){let n=t.app||t.window?"window":"screen";return C(r,async(i,s)=>{let o=await i.screenshot(s,{target:n,app:t.app,window_title:t.window,monitor:t.monitor!=null?Number(t.monitor):void 0}),a=o.kind==="inline"?o.bytes:await i.download(o.url),c=t.out||`ndb-shot-${s}.png`;return(0,j.writeFileSync)(c,a),{bytes:a.length,out:c,mode:o.kind}})},render:r=>`\u5DF2\u4FDD\u5B58\u622A\u56FE ${r.bytes} \u5B57\u8282 \u2192 ${r.out}`},{name:"newbeebox-diag",summary:"\u91C7\u96C6\u65B0\u624B\u76D2\u5B50\u7684\u5B89\u88C5/\u7528\u6237/\u8BBE\u7F6E/\u65E5\u5FD7\u6E05\u5355\uFF08\u6545\u969C\u6392\u67E5\u7B2C\u4E00\u6B65\uFF09",description:`\u5BA2\u6237\u673A\u4FA7\u81EA\u52A8\u53D1\u73B0\u6E20\u9053(\u6B63\u5F0F/Dev/Beta)\u4E0E\u5B89\u88C5\u8DEF\u5F84\uFF0C\u56DE\u4E00\u4EFD\u7ED3\u6784\u5316\u62A5\u544A\u3002
|
|
41
|
+
\u4E0D\u542B\u4EFB\u4F55\u51ED\u636E\uFF08token/\u5BC6\u7801\u4E00\u5F8B\u4E0D\u91C7\u96C6\uFF0C\u624B\u673A\u53F7\u6253\u7801\uFF09\u3002\u65E5\u5FD7\u6B63\u6587\u4E0D\u5728\u6B64\u547D\u4EE4\u5185\uFF0C\u7528 newbeebox-logs \u53D6\u3002
|
|
36
42
|
\u6392\u969C\u770B\u70B9\uFF1Aapps[].local_path_exists / launcher_exists=false \u2192 \u5BA2\u6237\u7AEF\u8BC6\u522B\u4E0D\u4E86\uFF1B
|
|
37
|
-
settings.cdn/download_mode/cache_dir_exists \u2192 \u6A21\u7EC4\u4E0B\u8F7D\u4E0E\u7F51\u7EDC\u7C7B\u6545\u969C\u3002`,
|
|
38
|
-
`),
|
|
43
|
+
settings.cdn/download_mode/cache_dir_exists \u2192 \u6A21\u7EC4\u4E0B\u8F7D\u4E0E\u7F51\u7EDC\u7C7B\u6545\u969C\u3002`,device:!0,args:[],options:[{flag:"--channel <name>",name:"channel",type:"string",desc:"\u53EA\u91C7\u6307\u5B9A\u6E20\u9053 NewBeeBox|NewBeeBoxDev|NewBeeBoxBeta\uFF08\u7F3A\u7701\u5168\u91C7\uFF09"}],auth:"token+authorized",returns:"{ collected_at, installs: [{ channel, data_dir, install_dir, version, user: { uid, nickname, phone_masked, client_id, vip, logged_in }, apps: [{ id, name, kind(game|app|store_app), version, local_path, local_path_exists, launcher_path, launcher_exists, mod_count }], settings: { cdn, download_mode(speed|diff), cache_dir, cache_dir_exists, cache_size, auto_start, wmic_compatible, game_paths: [{ key, path, exists }], disks: [{ target, fstype, size, avail, pcent }], pending_downloads }, logs: [{ name, path, bytes, mtime }] }] }",async handler(r,e,t){return C(r,(n,i)=>Ne(n,i,t.channel))},render:r=>r.installs?.length?r.installs.map(e=>{let t=e.user,n=[`\u6E20\u9053 ${e.channel}${e.version?` v${e.version}`:""}`,`\u6570\u636E\u76EE\u5F55 ${e.data_dir}`,`\u5B89\u88C5\u76EE\u5F55 ${e.install_dir??"(\u672A\u627E\u5230)"}`,t?`\u7528\u6237 uid=${t.uid??"-"} ${t.nickname??""} ${t.phone_masked??""} ${t.vip?`\u4F1A\u5458${t.vip} `:""}\u8BBE\u5907=${t.client_id??"-"} ${t.logged_in?"\u5DF2\u767B\u5F55":"\u672A\u767B\u5F55"}`:"\u7528\u6237 (\u65E0\u767B\u5F55\u75D5\u8FF9)"],i=e.settings??{},s=a=>`${(a/1024**3).toFixed(1)}G`;n.push(`\u8BBE\u7F6E cdn=${i.cdn??"-"} \u4E0B\u8F7D\u6A21\u5F0F=${i.download_mode??"-"}${i.wmic_compatible===!0?" wmic\u517C\u5BB9\u6A21\u5F0F=\u5F00":""}${i.pending_downloads!=null?` \u5F85\u4E0B\u8F7D=${i.pending_downloads}`:""}`,`\u7F13\u5B58 ${i.cache_dir??"-"}${i.cache_dir?i.cache_dir_exists?" [\u5B58\u5728]":" [\u7F3A\u5931!]":""}${i.cache_size!=null?` \u5DF2\u5360 ${s(i.cache_size)}`:""}`),i.disks?.length&&n.push(`\u78C1\u76D8 ${i.disks.map(a=>`${a.target}${a.avail!=null?` \u4F59${s(a.avail)}`:""}${a.pcent?`(${a.pcent})`:""}`).join(" ")}`),i.game_paths?.length&&n.push(He("\u6E38\u620F\u8DEF\u5F84",i.game_paths,a=>!a.exists,a=>`${a.key} ${a.path}`));let o=(e.logs??[]).map(a=>` - ${a.name.padEnd(13)} ${String(a.bytes).padStart(9)} B ${a.path}`);return[n.join(`
|
|
44
|
+
`),He("\u5B9E\u4F8B",e.apps??[],a=>!a.local_path_exists||!a.launcher_exists,a=>{let c=[a.local_path_exists?"":"\u76EE\u5F55\u7F3A\u5931",a.launcher_exists?"":"\u542F\u52A8\u5668\u7F3A\u5931"].filter(Boolean).join("/");return`[${a.kind}] ${a.name}${a.version?` v${a.version}`:""}${a.mod_count!=null?` \u6A21\u7EC4${a.mod_count}`:""}${c?` ${c}`:""}
|
|
39
45
|
${a.local_path??"-"}`}),`\u65E5\u5FD7 ${o.length} \u4E2A${o.length?`:
|
|
40
46
|
`+o.join(`
|
|
41
47
|
`):""}`].join(`
|
|
42
48
|
`)}).join(`
|
|
43
49
|
|
|
44
|
-
`):"\u672A\u68C0\u6D4B\u5230\u65B0\u624B\u76D2\u5B50\uFF08\u4E09\u4E2A\u6E20\u9053\u7684\u6570\u636E\u76EE\u5F55\u90FD\u4E0D\u5B58\u5728\uFF09"},{name:"
|
|
50
|
+
`):"\u672A\u68C0\u6D4B\u5230\u65B0\u624B\u76D2\u5B50\uFF08\u4E09\u4E2A\u6E20\u9053\u7684\u6570\u636E\u76EE\u5F55\u90FD\u4E0D\u5B58\u5728\uFF09"},{name:"newbeebox-logs",summary:"\u53D6\u65B0\u624B\u76D2\u5B50\u65E5\u5FD7\u6B63\u6587\uFF08\u81EA\u52A8\u5B9A\u4F4D\u8DEF\u5F84\uFF0C\u53EF\u7B5B\u53EF\u622A\u5C3E\uFF09",description:`\u5148\u8DD1\u4E00\u6B21 newbeebox-diag \u5B9A\u4F4D\u65E5\u5FD7\u8DEF\u5F84\uFF0C\u518D\u8BFB\u56DE\u6B63\u6587\u2014\u2014\u65E0\u9700\u624B\u6572\u8DEF\u5F84\u3002
|
|
45
51
|
main=\u4E3B\u8FDB\u7A0B\uFF1A\u4E0B\u8F7D/\u89E3\u538B(commonHttpDownload)\u3001\u70ED\u66F4\u3001\u767B\u5F55\u5237\u65B0(Auth.refresh)\u3001\u7EBF\u8DEF\u68C0\u6D4B\uFF1B
|
|
46
52
|
view=\u6E32\u67D3\u8FDB\u7A0B\uFF1A\u63A5\u53E3\u7F51\u5173\u5F02\u5E38(V2/Auth \u7F51\u5173)\u3001\u6E38\u620F\u8DEF\u5F84\u4E0E\u8BC6\u522B\u3001\u624B\u52A8\u6DFB\u52A0\u6E38\u620F\u3002
|
|
47
|
-
\u884C\u683C\u5F0F \`[\u65F6\u95F4] [\u6807\u7B7E] [\u7EA7\u522B] \u6B63\u6587\`\uFF0C\u7EA7\u522B\u5C0F\u5199\u3002--grep \u5148\u7B5B\u540E\u622A\u5C3E\uFF0C\u6700\u9002\u5408\u627E\u62A5\u9519\u3002`,
|
|
48
|
-
`),
|
|
49
|
-
${r.text}`},{name:"schema",summary:"\u5BFC\u51FA\u5168\u90E8\u547D\u4EE4\u7684\u673A\u5668\u53EF\u8BFB schema\uFF08\u7ED9 LLM Agent\uFF09",description:"\u8F93\u51FA function-calling \u53CB\u597D\u7684\u5DE5\u5177\u63CF\u8FF0\u3002\u914D\u5408 -c \u8F93\u51FA\u7D27\u51D1\u5355\u884C JSON\u3002",args:[],options:[],auth:"none",async handler(r){return
|
|
50
|
-
`);process.exitCode=1}function
|
|
51
|
-
${
|
|
53
|
+
\u884C\u683C\u5F0F \`[\u65F6\u95F4] [\u6807\u7B7E] [\u7EA7\u522B] \u6B63\u6587\`\uFF0C\u7EA7\u522B\u5C0F\u5199\u3002--grep \u5148\u7B5B\u540E\u622A\u5C3E\uFF0C\u6700\u9002\u5408\u627E\u62A5\u9519\u3002`,device:!0,args:[],options:[{flag:"--which <name>",name:"which",type:"string",desc:"\u65E5\u5FD7\u7C7B\u578B view|main|view.old|main.old",default:"view"},{flag:"--tail <n>",name:"tail",type:"number",desc:"\u53EA\u53D6\u672B\u5C3E N \u884C",default:200},{flag:"--grep <re>",name:"grep",type:"string",desc:"\u5148\u6309\u6B63\u5219(\u4E0D\u533A\u5206\u5927\u5C0F\u5199)\u7B5B\u884C\uFF0C\u518D\u622A\u5C3E"},{flag:"--channel <name>",name:"channel",type:"string",desc:"\u6307\u5B9A\u6E20\u9053\uFF08\u591A\u6E20\u9053\u5E76\u5B58\u65F6\uFF09"},{flag:"--out <file>",name:"out",type:"string",desc:"\u4FDD\u5B58\u5230\u672C\u5730\u6587\u4EF6"}],auth:"token+authorized",returns:"{ channel, name, path, bytes, matched, lines, text?, out? }",async handler(r,e,t){let n=String(t.which??"view"),i=n.endsWith(".log")?n:`${n}.log`;return C(r,async(s,o)=>{let c=(await Ne(s,o,t.channel)).installs?.[0];if(!c)throw new f({code:"NOT_FOUND",message:"\u672A\u68C0\u6D4B\u5230\u65B0\u624B\u76D2\u5B50\u5B89\u88C5"});let u=(c.logs??[]).find(x=>x.name===i);if(!u){let x=(c.logs??[]).map(q=>q.name).join(", ")||"(\u65E0)";throw new f({code:"NOT_FOUND",message:`\u65E5\u5FD7 ${i} \u4E0D\u5B58\u5728\uFF0C\u73B0\u6709\uFF1A${x}`})}let l=await s.readFile(o,u.path),d=(l.kind==="inline"?l.bytes:await s.download(l.url)).toString("utf8").split(/\r?\n/),_=d.length;if(t.grep){let x=new RegExp(String(t.grep),"i");d=d.filter(q=>x.test(q))}let m=d.length,g=Number(t.tail??200);g>0&&d.length>g&&(d=d.slice(-g));let y=d.join(`
|
|
54
|
+
`),I={channel:c.channel,name:u.name,path:u.path,bytes:u.bytes,total_lines:_,matched:m,lines:d.length};return t.out?((0,j.writeFileSync)(t.out,y),I.out=t.out):I.text=y,I})},render:r=>r.out?`\u5DF2\u4FDD\u5B58 ${r.lines} \u884C\u5230 ${r.out}\uFF08${r.name}\uFF0C\u5171 ${r.total_lines} \u884C\uFF0C\u547D\u4E2D ${r.matched}\uFF09`:`# ${r.path}\uFF08\u5171 ${r.total_lines} \u884C\uFF0C\u547D\u4E2D ${r.matched}\uFF0C\u663E\u793A\u672B ${r.lines} \u884C\uFF09
|
|
55
|
+
${r.text}`},{name:"schema",summary:"\u5BFC\u51FA\u5168\u90E8\u547D\u4EE4\u7684\u673A\u5668\u53EF\u8BFB schema\uFF08\u7ED9 LLM Agent\uFF09",description:"\u8F93\u51FA function-calling \u53CB\u597D\u7684\u5DE5\u5177\u63CF\u8FF0\u3002\u914D\u5408 -c \u8F93\u51FA\u7D27\u51D1\u5355\u884C JSON\u3002",args:[],options:[],auth:"none",async handler(r){return gt(r.version)},returns:"{ tool, version, commands: [...] }"}];function gt(r){let e=R.filter(t=>t.name!=="schema").map(t=>{let n={},i=[];t.device&&(n.code={type:"string",description:"\u76EE\u6807\u8BBE\u5907\u8FDE\u63A5\u7801\uFF1B\u7F3A\u7701\u7528 ndb connect \u5EFA\u7ACB\u7684\u5F53\u524D\u8BBE\u5907\uFF08ndb devices \u53EF\u67E5\uFF09"});for(let s of t.args)n[s.name]={type:"string",description:s.desc+(s.variadic?"\uFF08\u53EF\u591A\u503C\uFF09":"")},s.required&&i.push(s.name);for(let s of t.options)n[s.name]={type:s.type,description:s.desc,...s.default!=null?{default:s.default}:{}};return n.output={type:"string",enum:["text","json"],default:"text",description:"\u8F93\u51FA\u683C\u5F0F"},{name:t.name,summary:t.summary,description:t.description??t.summary,parameters:{type:"object",properties:n,required:i},returns:t.returns,auth:t.auth}});return{tool:"ndb",version:r,commands:e}}var je="0.3.0",Re=process.argv.slice(2),Ve=Re.indexOf("--"),Pe=Ve<0?-1:Re.length-Ve-1;function se(r){let e=r.args.map(t=>{let n=t.variadic?`${t.name}...`:t.name;return t.required?`<${n}>`:`[${n}]`});return r.device&&e.unshift("[code]"),e.join(" ")}function re(r){return[r.name,se(r)].filter(Boolean).join(" ")}function _t(r,e){if(r.args.some(n=>n.variadic)){if(Pe<0)return{code:e[0],args:e.slice(1)};let n=e.length-Pe;if(n===0)return{args:e};if(n===1)return{code:e[0],args:e.slice(1)};throw new f({code:"BAD_REQUEST",message:`-- \u4E4B\u524D\u53EA\u80FD\u6709\u8FDE\u63A5\u7801\u3002\u7528\u6CD5\uFF1Andb ${re(r)}`})}let t=e.length-r.args.length;if(t===0)return{args:e};if(t===1)return{code:e[0],args:e.slice(1)};throw new f({code:"BAD_REQUEST",message:`\u53C2\u6570\u4E2A\u6570\u4E0D\u5BF9\uFF08\u7ED9\u4E86 ${e.length} \u4E2A\uFF09\u3002\u7528\u6CD5\uFF1Andb ${re(r)}`})}function bt(r){let e=r.opts(),{baseUrl:t,token:n}=Se({baseUrl:e.baseUrl,token:e.token}),i=!!e.compact,s=i||e.output==="json"?"json":"text";return{baseUrl:t,token:n,output:s,compact:i,version:je}}function wt(r,e,t){if(r.output==="json"){let i={ok:!0,data:t};console.log(r.compact?JSON.stringify(i):JSON.stringify(i,null,2));return}let n=e.render?e.render(t):t===void 0?"":JSON.stringify(t,null,2);n&&console.log(n)}function yt(r,e){let t=e instanceof f?e.code:e?.code??"INTERNAL",n=e?.message??String(e);if(r.output==="json"){let i={ok:!1,error:{code:t,message:n}};console.log(r.compact?JSON.stringify(i):JSON.stringify(i,null,2))}else process.stderr.write(`error: [${t}] ${n}
|
|
56
|
+
`);process.exitCode=1}function Ot(){let r=new ye;r.name("ndb").description("NewBeeDebugBridge \u5DE5\u7A0B\u5E08\u7AEF CLI \u2014\u2014 \u8FDC\u7A0B\u8FD0\u7EF4(\u622A\u56FE/\u6267\u884C/\u8BFB\u6587\u4EF6/\u76D2\u5B50\u91C7\u96C6)\uFF0C\u5BF9 LLM Agent \u53CB\u597D\u3002").version(je,"-V, --version").option("--base-url <url>","\u670D\u52A1\u7AEF\u5730\u5740\uFF08\u6216 ~/.ndb/config.json\uFF09").option("--token <token>","token\uFF08\u6216 ~/.ndb/config.json\uFF09").option("-s, --serial <code>","\u76EE\u6807\u8BBE\u5907\u8FDE\u63A5\u7801\uFF0C\u8986\u76D6\u5F53\u524D\u8BBE\u5907\uFF08\u540C adb -s\uFF09").option("-o, --output <fmt>","\u8F93\u51FA\u683C\u5F0F text|json","text").option("-c, --compact","\u7D27\u51D1\u5355\u884C JSON\uFF08\u9690\u542B -o json\uFF09").showHelpAfterError();let e=new Map(R.map(t=>[t.name,t]));r.configureHelp({subcommandTerm(t){let n=e.get(t.name()),i=t.options.length?" [options]":"",s=n?se(n):t.registeredArguments.map(o=>o.required?`<${o.name()}>`:`[${o.name()}]`).join(" ");return`${t.name()}${i}${s?` ${s}`:""}`}});for(let t of R){let n=r.command(t.device?`${t.name} [args...]`:re(t));t.device&&n.usage(`[options] ${se(t)}`.trim()),n.summary(t.summary);let i=[t.summary,t.description,`\u8F93\u51FA\uFF08-o json \u7684\u5B57\u6BB5\uFF09\uFF1A
|
|
57
|
+
${t.returns}`].filter(Boolean);n.description(i.join(`
|
|
52
58
|
|
|
53
|
-
`));for(let
|
|
59
|
+
`));for(let s of t.options)n.option(s.flag,s.desc,s.default);n.action(async(...s)=>{let o=bt(r);try{let a=t.device?1:t.args.length,c=s[a]??{},l=s.slice(0,a).flatMap(d=>Array.isArray(d)?d:d==null?[]:[d]);if(t.device){let d=_t(t,l);l=d.args,o.device=d.code??r.opts().serial??N()}let h=await t.handler(o,l,c);wt(o,t,h)}catch(a){yt(o,a)}})}return r}Ot().parseAsync(process.argv);
|