flightdesk 0.1.2 → 0.1.4

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.
Files changed (3) hide show
  1. package/main.js +4312 -71
  2. package/main.js.map +2 -2
  3. package/package.json +1 -1
package/main.js CHANGED
@@ -1,40 +1,3471 @@
1
1
  #!/usr/bin/env node
2
- #!/usr/bin/env node
3
- var Gt=Object.create;var ct=Object.defineProperty;var Bt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var P=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Qt=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Kt(t))!Yt.call(s,i)&&i!==e&&ct(s,i,{get:()=>t[i],enumerable:!(n=Bt(t,i))||n.enumerable});return s};var C=(s,t,e)=>(e=s!=null?Gt(Jt(s)):{},Qt(t||!s||!s.__esModule?ct(e,"default",{value:s,enumerable:!0}):e,s));var S=P(W=>{var V=class extends Error{constructor(t,e,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},L=class extends V{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};W.CommanderError=V;W.InvalidArgumentError=L});var z=P(B=>{var{InvalidArgumentError:Zt}=S(),G=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:e.concat(t)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new Zt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Xt(s){let t=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+t+">":"["+t+"]"}B.Argument=G;B.humanReadableArgName=Xt});var J=P(ut=>{var{humanReadableArgName:te}=z(),K=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(t){let e=t.commands.filter(i=>!i._hidden),n=t._getHelpCommand();return n&&!n._hidden&&e.push(n),this.sortSubcommands&&e.sort((i,o)=>i.name().localeCompare(o.name())),e}compareOptions(t,e){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(t).localeCompare(n(e))}visibleOptions(t){let e=t.options.filter(i=>!i.hidden),n=t._getHelpOption();if(n&&!n.hidden){let i=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!i&&!o?e.push(n):n.long&&!o?e.push(t.createOption(n.long,n.description)):n.short&&!i&&e.push(t.createOption(n.short,n.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let n=t.parent;n;n=n.parent){let i=n.options.filter(o=>!o.hidden);e.push(...i)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(n=>te(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((n,i)=>Math.max(n,e.subcommandTerm(i).length),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((n,i)=>Math.max(n,e.optionTerm(i).length),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((n,i)=>Math.max(n,e.optionTerm(i).length),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((n,i)=>Math.max(n,e.argumentTerm(i).length),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let n="";for(let i=t.parent;i;i=i.parent)n=i.name()+" "+n;return n+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];return t.argChoices&&e.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0?`${t.description} (${e.join(", ")})`:t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let n=`(${e.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,e){let n=e.padWidth(t,e),i=e.helpWidth||80,o=2,r=2;function l(p,A){if(A){let M=`${p.padEnd(n+r)}${A}`;return e.wrap(M,i-o,n+r)}return p}function a(p){return p.join(`
4
- `).replace(/^/gm," ".repeat(o))}let c=[`Usage: ${e.commandUsage(t)}`,""],u=e.commandDescription(t);u.length>0&&(c=c.concat([e.wrap(u,i,0),""]));let h=e.visibleArguments(t).map(p=>l(e.argumentTerm(p),e.argumentDescription(p)));h.length>0&&(c=c.concat(["Arguments:",a(h),""]));let m=e.visibleOptions(t).map(p=>l(e.optionTerm(p),e.optionDescription(p)));if(m.length>0&&(c=c.concat(["Options:",a(m),""])),this.showGlobalOptions){let p=e.visibleGlobalOptions(t).map(A=>l(e.optionTerm(A),e.optionDescription(A)));p.length>0&&(c=c.concat(["Global Options:",a(p),""]))}let $=e.visibleCommands(t).map(p=>l(e.subcommandTerm(p),e.subcommandDescription(p)));return $.length>0&&(c=c.concat(["Commands:",a($),""])),c.join(`
5
- `)}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}wrap(t,e,n,i=40){let o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",r=new RegExp(`[\\n][${o}]+`);if(t.match(r))return t;let l=e-n;if(l<i)return t;let a=t.slice(0,n),c=t.slice(n).replace(`\r
6
- `,`
7
- `),u=" ".repeat(n),m="\\s\u200B",$=new RegExp(`
8
- |.{1,${l-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),p=c.match($)||[];return a+p.map((A,M)=>A===`
9
- `?"":(M>0?u:"")+A.trimEnd()).join(`
10
- `)}};ut.Help=K});var X=P(Z=>{var{InvalidArgumentError:ee}=S(),Y=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let n=ie(t);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(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:e.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new ee(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ne(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Q=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(t,e){let n=e.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,o=i!==void 0?i:!1;return e.negate===(o===t)}};function ne(s){return s.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function ie(s){let t,e,n=s.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(t=n.shift()),e=n.shift(),!t&&/^-[^-]$/.test(e)&&(t=e,e=void 0),{shortFlag:t,longFlag:e}}Z.Option=Y;Z.DualOptions=Q});var dt=P(ht=>{function oe(s,t){if(Math.abs(s.length-t.length)>3)return Math.max(s.length,t.length);let e=[];for(let n=0;n<=s.length;n++)e[n]=[n];for(let n=0;n<=t.length;n++)e[0][n]=n;for(let n=1;n<=t.length;n++)for(let i=1;i<=s.length;i++){let o=1;s[i-1]===t[n-1]?o=0:o=1,e[i][n]=Math.min(e[i-1][n]+1,e[i][n-1]+1,e[i-1][n-1]+o),i>1&&n>1&&s[i-1]===t[n-2]&&s[i-2]===t[n-1]&&(e[i][n]=Math.min(e[i][n],e[i-2][n-2]+1))}return e[s.length][t.length]}function se(s,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=s.startsWith("--");e&&(s=s.slice(2),t=t.map(r=>r.slice(2)));let n=[],i=3,o=.4;return t.forEach(r=>{if(r.length<=1)return;let l=oe(s,r),a=Math.max(s.length,r.length);(a-l)/a>o&&(l<i?(i=l,n=[r]):l===i&&n.push(r))}),n.sort((r,l)=>r.localeCompare(l)),e&&(n=n.map(r=>`--${r}`)),n.length>1?`
11
- (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
12
- (Did you mean ${n[0]}?)`:""}ht.suggestSimilar=se});var _t=P(ft=>{var re=require("node:events").EventEmitter,tt=require("node:child_process"),k=require("node:path"),et=require("node:fs"),d=require("node:process"),{Argument:ae,humanReadableArgName:le}=z(),{CommanderError:nt}=S(),{Help:ce}=J(),{Option:pt,DualOptions:ue}=X(),{suggestSimilar:gt}=dt(),it=class s extends re{constructor(t){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=t||"",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:e=>d.stdout.write(e),writeErr:e=>d.stderr.write(e),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,outputError:(e,n)=>n(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,n){let i=e,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,r,l]=t.match(/([^ ]+) *(.*)/),a=this.createCommand(r);return i&&(a.description(i),a._executableHandler=!0),o.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(o.noHelp||o.hidden),a._executableFile=o.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i?this:a}createCommand(t){return new s(t)}createHelp(){return Object.assign(new ce,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
13
- - specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new ae(t,e)}argument(t,e,n,i){let o=this.createArgument(t,e);return typeof n=="function"?o.default(i).argParser(n):o.default(n),this.addArgument(o),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,n,i]=t.match(/([^ ]+) *(.*)/),o=e??"display help for command",r=this.createCommand(n);return r.helpOption(!1),i&&r.arguments(i),o&&r.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,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(t,e){let n=["preSubcommand","preAction","postAction"];if(!n.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
14
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,n){this._exitCallback&&this._exitCallback(new nt(t,e,n)),d.exit(t)}action(t){let e=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),t.apply(this,o)};return this._actionHandler=e,this}createOption(t,e){return new pt(t,e)}_callParseArg(t,e,n,i){try{return t.parseArg(e,n)}catch(o){if(o.code==="commander.invalidArgument"){let r=`${i} ${o.message}`;this.error(r,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let n=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
15
- - already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){let e=i=>[i.name()].concat(i.aliases()),n=e(t).find(i=>this._findCommand(i));if(n){let i=e(this._findCommand(n)).join("|"),o=e(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),n=t.attributeName();if(t.negate){let o=t.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(n,t.defaultValue,"default");let i=(o,r,l)=>{o==null&&t.presetArg!==void 0&&(o=t.presetArg);let a=this.getOptionValue(n);o!==null&&t.parseArg?o=this._callParseArg(t,o,a,r):o!==null&&t.variadic&&(o=t._concatValue(o,a)),o==null&&(t.negate?o=!1:t.isBoolean()||t.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,l)};return this.on("option:"+e,o=>{let r=`error: option '${t.flags}' argument '${o}' is invalid.`;i(o,r,"cli")}),t.envVar&&this.on("optionEnv:"+e,o=>{let r=`error: option '${t.flags}' value '${o}' from env '${t.envVar}' is invalid.`;i(o,r,"env")}),this}_optionEx(t,e,n,i,o){if(typeof e=="object"&&e instanceof pt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,n);if(r.makeOptionMandatory(!!t.mandatory),typeof i=="function")r.default(o).argParser(i);else if(i instanceof RegExp){let l=i;i=(a,c)=>{let u=l.exec(a);return u?u[0]:c},r.default(o).argParser(i)}else r.default(i);return this.addOption(r)}option(t,e,n,i){return this._optionEx({},t,e,n,i)}requiredOption(t,e,n,i){return this._optionEx({mandatory:!0},t,e,n,i)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,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(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,n){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=n,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(t)!==void 0&&(e=n.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){d.versions?.electron&&(e.from="electron");let i=d.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(e.from="eval")}t===void 0&&(t=d.argv),this.rawArgs=t.slice();let n;switch(e.from){case void 0:case"node":this._scriptPath=t[1],n=t.slice(2);break;case"electron":d.defaultApp?(this._scriptPath=t[1],n=t.slice(2)):n=t.slice(1);break;case"user":n=t.slice(0);break;case"eval":n=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(t,e){let n=this._prepareUserArgs(t,e);return this._parseCommand([],n),this}async parseAsync(t,e){let n=this._prepareUserArgs(t,e);return await this._parseCommand([],n),this}_executeSubCommand(t,e){e=e.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(u,h){let m=k.resolve(u,h);if(et.existsSync(m))return m;if(i.includes(k.extname(h)))return;let $=i.find(p=>et.existsSync(`${m}${p}`));if($)return`${m}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=t._executableFile||`${this._name}-${t._name}`,l=this._executableDir||"";if(this._scriptPath){let u;try{u=et.realpathSync(this._scriptPath)}catch{u=this._scriptPath}l=k.resolve(k.dirname(u),l)}if(l){let u=o(l,r);if(!u&&!t._executableFile&&this._scriptPath){let h=k.basename(this._scriptPath,k.extname(this._scriptPath));h!==this._name&&(u=o(l,`${h}-${t._name}`))}r=u||r}n=i.includes(k.extname(r));let a;d.platform!=="win32"?n?(e.unshift(r),e=mt(d.execArgv).concat(e),a=tt.spawn(d.argv[0],e,{stdio:"inherit"})):a=tt.spawn(r,e,{stdio:"inherit"}):(e.unshift(r),e=mt(d.execArgv).concat(e),a=tt.spawn(d.execPath,e,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{d.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let c=this._exitCallback;a.on("close",u=>{u=u??1,c?c(new nt(u,"commander.executeSubCommandAsync","(close)")):d.exit(u)}),a.on("error",u=>{if(u.code==="ENOENT"){let h=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",m=`'${r}' does not exist
16
- - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+
28
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js
29
+ var require_error = __commonJS({
30
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js"(exports2) {
31
+ var CommanderError2 = class extends Error {
32
+ /**
33
+ * Constructs the CommanderError class
34
+ * @param {number} exitCode suggested exit code which could be used with process.exit
35
+ * @param {string} code an id string representing the error
36
+ * @param {string} message human-readable description of the error
37
+ */
38
+ constructor(exitCode, code, message) {
39
+ super(message);
40
+ Error.captureStackTrace(this, this.constructor);
41
+ this.name = this.constructor.name;
42
+ this.code = code;
43
+ this.exitCode = exitCode;
44
+ this.nestedError = void 0;
45
+ }
46
+ };
47
+ var InvalidArgumentError2 = class extends CommanderError2 {
48
+ /**
49
+ * Constructs the InvalidArgumentError class
50
+ * @param {string} [message] explanation of why argument is invalid
51
+ */
52
+ constructor(message) {
53
+ super(1, "commander.invalidArgument", message);
54
+ Error.captureStackTrace(this, this.constructor);
55
+ this.name = this.constructor.name;
56
+ }
57
+ };
58
+ exports2.CommanderError = CommanderError2;
59
+ exports2.InvalidArgumentError = InvalidArgumentError2;
60
+ }
61
+ });
62
+
63
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js
64
+ var require_argument = __commonJS({
65
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js"(exports2) {
66
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
67
+ var Argument2 = class {
68
+ /**
69
+ * Initialize a new command argument with the given name and description.
70
+ * The default is that the argument is required, and you can explicitly
71
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
72
+ *
73
+ * @param {string} name
74
+ * @param {string} [description]
75
+ */
76
+ constructor(name, description) {
77
+ this.description = description || "";
78
+ this.variadic = false;
79
+ this.parseArg = void 0;
80
+ this.defaultValue = void 0;
81
+ this.defaultValueDescription = void 0;
82
+ this.argChoices = void 0;
83
+ switch (name[0]) {
84
+ case "<":
85
+ this.required = true;
86
+ this._name = name.slice(1, -1);
87
+ break;
88
+ case "[":
89
+ this.required = false;
90
+ this._name = name.slice(1, -1);
91
+ break;
92
+ default:
93
+ this.required = true;
94
+ this._name = name;
95
+ break;
96
+ }
97
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
98
+ this.variadic = true;
99
+ this._name = this._name.slice(0, -3);
100
+ }
101
+ }
102
+ /**
103
+ * Return argument name.
104
+ *
105
+ * @return {string}
106
+ */
107
+ name() {
108
+ return this._name;
109
+ }
110
+ /**
111
+ * @package
112
+ */
113
+ _concatValue(value, previous) {
114
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
115
+ return [value];
116
+ }
117
+ return previous.concat(value);
118
+ }
119
+ /**
120
+ * Set the default value, and optionally supply the description to be displayed in the help.
121
+ *
122
+ * @param {*} value
123
+ * @param {string} [description]
124
+ * @return {Argument}
125
+ */
126
+ default(value, description) {
127
+ this.defaultValue = value;
128
+ this.defaultValueDescription = description;
129
+ return this;
130
+ }
131
+ /**
132
+ * Set the custom handler for processing CLI command arguments into argument values.
133
+ *
134
+ * @param {Function} [fn]
135
+ * @return {Argument}
136
+ */
137
+ argParser(fn) {
138
+ this.parseArg = fn;
139
+ return this;
140
+ }
141
+ /**
142
+ * Only allow argument value to be one of choices.
143
+ *
144
+ * @param {string[]} values
145
+ * @return {Argument}
146
+ */
147
+ choices(values) {
148
+ this.argChoices = values.slice();
149
+ this.parseArg = (arg, previous) => {
150
+ if (!this.argChoices.includes(arg)) {
151
+ throw new InvalidArgumentError2(
152
+ `Allowed choices are ${this.argChoices.join(", ")}.`
153
+ );
154
+ }
155
+ if (this.variadic) {
156
+ return this._concatValue(arg, previous);
157
+ }
158
+ return arg;
159
+ };
160
+ return this;
161
+ }
162
+ /**
163
+ * Make argument required.
164
+ *
165
+ * @returns {Argument}
166
+ */
167
+ argRequired() {
168
+ this.required = true;
169
+ return this;
170
+ }
171
+ /**
172
+ * Make argument optional.
173
+ *
174
+ * @returns {Argument}
175
+ */
176
+ argOptional() {
177
+ this.required = false;
178
+ return this;
179
+ }
180
+ };
181
+ function humanReadableArgName(arg) {
182
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
183
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
184
+ }
185
+ exports2.Argument = Argument2;
186
+ exports2.humanReadableArgName = humanReadableArgName;
187
+ }
188
+ });
189
+
190
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js
191
+ var require_help = __commonJS({
192
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js"(exports2) {
193
+ var { humanReadableArgName } = require_argument();
194
+ var Help2 = class {
195
+ constructor() {
196
+ this.helpWidth = void 0;
197
+ this.sortSubcommands = false;
198
+ this.sortOptions = false;
199
+ this.showGlobalOptions = false;
200
+ }
201
+ /**
202
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
203
+ *
204
+ * @param {Command} cmd
205
+ * @returns {Command[]}
206
+ */
207
+ visibleCommands(cmd) {
208
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
209
+ const helpCommand = cmd._getHelpCommand();
210
+ if (helpCommand && !helpCommand._hidden) {
211
+ visibleCommands.push(helpCommand);
212
+ }
213
+ if (this.sortSubcommands) {
214
+ visibleCommands.sort((a, b) => {
215
+ return a.name().localeCompare(b.name());
216
+ });
217
+ }
218
+ return visibleCommands;
219
+ }
220
+ /**
221
+ * Compare options for sort.
222
+ *
223
+ * @param {Option} a
224
+ * @param {Option} b
225
+ * @returns {number}
226
+ */
227
+ compareOptions(a, b) {
228
+ const getSortKey = (option) => {
229
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
230
+ };
231
+ return getSortKey(a).localeCompare(getSortKey(b));
232
+ }
233
+ /**
234
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
235
+ *
236
+ * @param {Command} cmd
237
+ * @returns {Option[]}
238
+ */
239
+ visibleOptions(cmd) {
240
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
241
+ const helpOption = cmd._getHelpOption();
242
+ if (helpOption && !helpOption.hidden) {
243
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
244
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
245
+ if (!removeShort && !removeLong) {
246
+ visibleOptions.push(helpOption);
247
+ } else if (helpOption.long && !removeLong) {
248
+ visibleOptions.push(
249
+ cmd.createOption(helpOption.long, helpOption.description)
250
+ );
251
+ } else if (helpOption.short && !removeShort) {
252
+ visibleOptions.push(
253
+ cmd.createOption(helpOption.short, helpOption.description)
254
+ );
255
+ }
256
+ }
257
+ if (this.sortOptions) {
258
+ visibleOptions.sort(this.compareOptions);
259
+ }
260
+ return visibleOptions;
261
+ }
262
+ /**
263
+ * Get an array of the visible global options. (Not including help.)
264
+ *
265
+ * @param {Command} cmd
266
+ * @returns {Option[]}
267
+ */
268
+ visibleGlobalOptions(cmd) {
269
+ if (!this.showGlobalOptions) return [];
270
+ const globalOptions = [];
271
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
272
+ const visibleOptions = ancestorCmd.options.filter(
273
+ (option) => !option.hidden
274
+ );
275
+ globalOptions.push(...visibleOptions);
276
+ }
277
+ if (this.sortOptions) {
278
+ globalOptions.sort(this.compareOptions);
279
+ }
280
+ return globalOptions;
281
+ }
282
+ /**
283
+ * Get an array of the arguments if any have a description.
284
+ *
285
+ * @param {Command} cmd
286
+ * @returns {Argument[]}
287
+ */
288
+ visibleArguments(cmd) {
289
+ if (cmd._argsDescription) {
290
+ cmd.registeredArguments.forEach((argument) => {
291
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
292
+ });
293
+ }
294
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
295
+ return cmd.registeredArguments;
296
+ }
297
+ return [];
298
+ }
299
+ /**
300
+ * Get the command term to show in the list of subcommands.
301
+ *
302
+ * @param {Command} cmd
303
+ * @returns {string}
304
+ */
305
+ subcommandTerm(cmd) {
306
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
307
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
308
+ (args ? " " + args : "");
309
+ }
310
+ /**
311
+ * Get the option term to show in the list of options.
312
+ *
313
+ * @param {Option} option
314
+ * @returns {string}
315
+ */
316
+ optionTerm(option) {
317
+ return option.flags;
318
+ }
319
+ /**
320
+ * Get the argument term to show in the list of arguments.
321
+ *
322
+ * @param {Argument} argument
323
+ * @returns {string}
324
+ */
325
+ argumentTerm(argument) {
326
+ return argument.name();
327
+ }
328
+ /**
329
+ * Get the longest command term length.
330
+ *
331
+ * @param {Command} cmd
332
+ * @param {Help} helper
333
+ * @returns {number}
334
+ */
335
+ longestSubcommandTermLength(cmd, helper) {
336
+ return helper.visibleCommands(cmd).reduce((max, command) => {
337
+ return Math.max(max, helper.subcommandTerm(command).length);
338
+ }, 0);
339
+ }
340
+ /**
341
+ * Get the longest option term length.
342
+ *
343
+ * @param {Command} cmd
344
+ * @param {Help} helper
345
+ * @returns {number}
346
+ */
347
+ longestOptionTermLength(cmd, helper) {
348
+ return helper.visibleOptions(cmd).reduce((max, option) => {
349
+ return Math.max(max, helper.optionTerm(option).length);
350
+ }, 0);
351
+ }
352
+ /**
353
+ * Get the longest global option term length.
354
+ *
355
+ * @param {Command} cmd
356
+ * @param {Help} helper
357
+ * @returns {number}
358
+ */
359
+ longestGlobalOptionTermLength(cmd, helper) {
360
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
361
+ return Math.max(max, helper.optionTerm(option).length);
362
+ }, 0);
363
+ }
364
+ /**
365
+ * Get the longest argument term length.
366
+ *
367
+ * @param {Command} cmd
368
+ * @param {Help} helper
369
+ * @returns {number}
370
+ */
371
+ longestArgumentTermLength(cmd, helper) {
372
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
373
+ return Math.max(max, helper.argumentTerm(argument).length);
374
+ }, 0);
375
+ }
376
+ /**
377
+ * Get the command usage to be displayed at the top of the built-in help.
378
+ *
379
+ * @param {Command} cmd
380
+ * @returns {string}
381
+ */
382
+ commandUsage(cmd) {
383
+ let cmdName = cmd._name;
384
+ if (cmd._aliases[0]) {
385
+ cmdName = cmdName + "|" + cmd._aliases[0];
386
+ }
387
+ let ancestorCmdNames = "";
388
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
389
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
390
+ }
391
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
392
+ }
393
+ /**
394
+ * Get the description for the command.
395
+ *
396
+ * @param {Command} cmd
397
+ * @returns {string}
398
+ */
399
+ commandDescription(cmd) {
400
+ return cmd.description();
401
+ }
402
+ /**
403
+ * Get the subcommand summary to show in the list of subcommands.
404
+ * (Fallback to description for backwards compatibility.)
405
+ *
406
+ * @param {Command} cmd
407
+ * @returns {string}
408
+ */
409
+ subcommandDescription(cmd) {
410
+ return cmd.summary() || cmd.description();
411
+ }
412
+ /**
413
+ * Get the option description to show in the list of options.
414
+ *
415
+ * @param {Option} option
416
+ * @return {string}
417
+ */
418
+ optionDescription(option) {
419
+ const extraInfo = [];
420
+ if (option.argChoices) {
421
+ extraInfo.push(
422
+ // use stringify to match the display of the default value
423
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
424
+ );
425
+ }
426
+ if (option.defaultValue !== void 0) {
427
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
428
+ if (showDefault) {
429
+ extraInfo.push(
430
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
431
+ );
432
+ }
433
+ }
434
+ if (option.presetArg !== void 0 && option.optional) {
435
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
436
+ }
437
+ if (option.envVar !== void 0) {
438
+ extraInfo.push(`env: ${option.envVar}`);
439
+ }
440
+ if (extraInfo.length > 0) {
441
+ return `${option.description} (${extraInfo.join(", ")})`;
442
+ }
443
+ return option.description;
444
+ }
445
+ /**
446
+ * Get the argument description to show in the list of arguments.
447
+ *
448
+ * @param {Argument} argument
449
+ * @return {string}
450
+ */
451
+ argumentDescription(argument) {
452
+ const extraInfo = [];
453
+ if (argument.argChoices) {
454
+ extraInfo.push(
455
+ // use stringify to match the display of the default value
456
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
457
+ );
458
+ }
459
+ if (argument.defaultValue !== void 0) {
460
+ extraInfo.push(
461
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
462
+ );
463
+ }
464
+ if (extraInfo.length > 0) {
465
+ const extraDescripton = `(${extraInfo.join(", ")})`;
466
+ if (argument.description) {
467
+ return `${argument.description} ${extraDescripton}`;
468
+ }
469
+ return extraDescripton;
470
+ }
471
+ return argument.description;
472
+ }
473
+ /**
474
+ * Generate the built-in help text.
475
+ *
476
+ * @param {Command} cmd
477
+ * @param {Help} helper
478
+ * @returns {string}
479
+ */
480
+ formatHelp(cmd, helper) {
481
+ const termWidth = helper.padWidth(cmd, helper);
482
+ const helpWidth = helper.helpWidth || 80;
483
+ const itemIndentWidth = 2;
484
+ const itemSeparatorWidth = 2;
485
+ function formatItem(term, description) {
486
+ if (description) {
487
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
488
+ return helper.wrap(
489
+ fullText,
490
+ helpWidth - itemIndentWidth,
491
+ termWidth + itemSeparatorWidth
492
+ );
493
+ }
494
+ return term;
495
+ }
496
+ function formatList(textArray) {
497
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
498
+ }
499
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
500
+ const commandDescription = helper.commandDescription(cmd);
501
+ if (commandDescription.length > 0) {
502
+ output = output.concat([
503
+ helper.wrap(commandDescription, helpWidth, 0),
504
+ ""
505
+ ]);
506
+ }
507
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
508
+ return formatItem(
509
+ helper.argumentTerm(argument),
510
+ helper.argumentDescription(argument)
511
+ );
512
+ });
513
+ if (argumentList.length > 0) {
514
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
515
+ }
516
+ const optionList = helper.visibleOptions(cmd).map((option) => {
517
+ return formatItem(
518
+ helper.optionTerm(option),
519
+ helper.optionDescription(option)
520
+ );
521
+ });
522
+ if (optionList.length > 0) {
523
+ output = output.concat(["Options:", formatList(optionList), ""]);
524
+ }
525
+ if (this.showGlobalOptions) {
526
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
527
+ return formatItem(
528
+ helper.optionTerm(option),
529
+ helper.optionDescription(option)
530
+ );
531
+ });
532
+ if (globalOptionList.length > 0) {
533
+ output = output.concat([
534
+ "Global Options:",
535
+ formatList(globalOptionList),
536
+ ""
537
+ ]);
538
+ }
539
+ }
540
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
541
+ return formatItem(
542
+ helper.subcommandTerm(cmd2),
543
+ helper.subcommandDescription(cmd2)
544
+ );
545
+ });
546
+ if (commandList.length > 0) {
547
+ output = output.concat(["Commands:", formatList(commandList), ""]);
548
+ }
549
+ return output.join("\n");
550
+ }
551
+ /**
552
+ * Calculate the pad width from the maximum term length.
553
+ *
554
+ * @param {Command} cmd
555
+ * @param {Help} helper
556
+ * @returns {number}
557
+ */
558
+ padWidth(cmd, helper) {
559
+ return Math.max(
560
+ helper.longestOptionTermLength(cmd, helper),
561
+ helper.longestGlobalOptionTermLength(cmd, helper),
562
+ helper.longestSubcommandTermLength(cmd, helper),
563
+ helper.longestArgumentTermLength(cmd, helper)
564
+ );
565
+ }
566
+ /**
567
+ * Wrap the given string to width characters per line, with lines after the first indented.
568
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
569
+ *
570
+ * @param {string} str
571
+ * @param {number} width
572
+ * @param {number} indent
573
+ * @param {number} [minColumnWidth=40]
574
+ * @return {string}
575
+ *
576
+ */
577
+ wrap(str, width, indent, minColumnWidth = 40) {
578
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
579
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
580
+ if (str.match(manualIndent)) return str;
581
+ const columnWidth = width - indent;
582
+ if (columnWidth < minColumnWidth) return str;
583
+ const leadingStr = str.slice(0, indent);
584
+ const columnText = str.slice(indent).replace("\r\n", "\n");
585
+ const indentString = " ".repeat(indent);
586
+ const zeroWidthSpace = "\u200B";
587
+ const breaks = `\\s${zeroWidthSpace}`;
588
+ const regex = new RegExp(
589
+ `
590
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
591
+ "g"
592
+ );
593
+ const lines = columnText.match(regex) || [];
594
+ return leadingStr + lines.map((line, i) => {
595
+ if (line === "\n") return "";
596
+ return (i > 0 ? indentString : "") + line.trimEnd();
597
+ }).join("\n");
598
+ }
599
+ };
600
+ exports2.Help = Help2;
601
+ }
602
+ });
603
+
604
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js
605
+ var require_option = __commonJS({
606
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js"(exports2) {
607
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
608
+ var Option2 = class {
609
+ /**
610
+ * Initialize a new `Option` with the given `flags` and `description`.
611
+ *
612
+ * @param {string} flags
613
+ * @param {string} [description]
614
+ */
615
+ constructor(flags, description) {
616
+ this.flags = flags;
617
+ this.description = description || "";
618
+ this.required = flags.includes("<");
619
+ this.optional = flags.includes("[");
620
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
621
+ this.mandatory = false;
622
+ const optionFlags = splitOptionFlags(flags);
623
+ this.short = optionFlags.shortFlag;
624
+ this.long = optionFlags.longFlag;
625
+ this.negate = false;
626
+ if (this.long) {
627
+ this.negate = this.long.startsWith("--no-");
628
+ }
629
+ this.defaultValue = void 0;
630
+ this.defaultValueDescription = void 0;
631
+ this.presetArg = void 0;
632
+ this.envVar = void 0;
633
+ this.parseArg = void 0;
634
+ this.hidden = false;
635
+ this.argChoices = void 0;
636
+ this.conflictsWith = [];
637
+ this.implied = void 0;
638
+ }
639
+ /**
640
+ * Set the default value, and optionally supply the description to be displayed in the help.
641
+ *
642
+ * @param {*} value
643
+ * @param {string} [description]
644
+ * @return {Option}
645
+ */
646
+ default(value, description) {
647
+ this.defaultValue = value;
648
+ this.defaultValueDescription = description;
649
+ return this;
650
+ }
651
+ /**
652
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
653
+ * The custom processing (parseArg) is called.
654
+ *
655
+ * @example
656
+ * new Option('--color').default('GREYSCALE').preset('RGB');
657
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
658
+ *
659
+ * @param {*} arg
660
+ * @return {Option}
661
+ */
662
+ preset(arg) {
663
+ this.presetArg = arg;
664
+ return this;
665
+ }
666
+ /**
667
+ * Add option name(s) that conflict with this option.
668
+ * An error will be displayed if conflicting options are found during parsing.
669
+ *
670
+ * @example
671
+ * new Option('--rgb').conflicts('cmyk');
672
+ * new Option('--js').conflicts(['ts', 'jsx']);
673
+ *
674
+ * @param {(string | string[])} names
675
+ * @return {Option}
676
+ */
677
+ conflicts(names) {
678
+ this.conflictsWith = this.conflictsWith.concat(names);
679
+ return this;
680
+ }
681
+ /**
682
+ * Specify implied option values for when this option is set and the implied options are not.
683
+ *
684
+ * The custom processing (parseArg) is not called on the implied values.
685
+ *
686
+ * @example
687
+ * program
688
+ * .addOption(new Option('--log', 'write logging information to file'))
689
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
690
+ *
691
+ * @param {object} impliedOptionValues
692
+ * @return {Option}
693
+ */
694
+ implies(impliedOptionValues) {
695
+ let newImplied = impliedOptionValues;
696
+ if (typeof impliedOptionValues === "string") {
697
+ newImplied = { [impliedOptionValues]: true };
698
+ }
699
+ this.implied = Object.assign(this.implied || {}, newImplied);
700
+ return this;
701
+ }
702
+ /**
703
+ * Set environment variable to check for option value.
704
+ *
705
+ * An environment variable is only used if when processed the current option value is
706
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
707
+ *
708
+ * @param {string} name
709
+ * @return {Option}
710
+ */
711
+ env(name) {
712
+ this.envVar = name;
713
+ return this;
714
+ }
715
+ /**
716
+ * Set the custom handler for processing CLI option arguments into option values.
717
+ *
718
+ * @param {Function} [fn]
719
+ * @return {Option}
720
+ */
721
+ argParser(fn) {
722
+ this.parseArg = fn;
723
+ return this;
724
+ }
725
+ /**
726
+ * Whether the option is mandatory and must have a value after parsing.
727
+ *
728
+ * @param {boolean} [mandatory=true]
729
+ * @return {Option}
730
+ */
731
+ makeOptionMandatory(mandatory = true) {
732
+ this.mandatory = !!mandatory;
733
+ return this;
734
+ }
735
+ /**
736
+ * Hide option in help.
737
+ *
738
+ * @param {boolean} [hide=true]
739
+ * @return {Option}
740
+ */
741
+ hideHelp(hide = true) {
742
+ this.hidden = !!hide;
743
+ return this;
744
+ }
745
+ /**
746
+ * @package
747
+ */
748
+ _concatValue(value, previous) {
749
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
750
+ return [value];
751
+ }
752
+ return previous.concat(value);
753
+ }
754
+ /**
755
+ * Only allow option value to be one of choices.
756
+ *
757
+ * @param {string[]} values
758
+ * @return {Option}
759
+ */
760
+ choices(values) {
761
+ this.argChoices = values.slice();
762
+ this.parseArg = (arg, previous) => {
763
+ if (!this.argChoices.includes(arg)) {
764
+ throw new InvalidArgumentError2(
765
+ `Allowed choices are ${this.argChoices.join(", ")}.`
766
+ );
767
+ }
768
+ if (this.variadic) {
769
+ return this._concatValue(arg, previous);
770
+ }
771
+ return arg;
772
+ };
773
+ return this;
774
+ }
775
+ /**
776
+ * Return option name.
777
+ *
778
+ * @return {string}
779
+ */
780
+ name() {
781
+ if (this.long) {
782
+ return this.long.replace(/^--/, "");
783
+ }
784
+ return this.short.replace(/^-/, "");
785
+ }
786
+ /**
787
+ * Return option name, in a camelcase format that can be used
788
+ * as a object attribute key.
789
+ *
790
+ * @return {string}
791
+ */
792
+ attributeName() {
793
+ return camelcase(this.name().replace(/^no-/, ""));
794
+ }
795
+ /**
796
+ * Check if `arg` matches the short or long flag.
797
+ *
798
+ * @param {string} arg
799
+ * @return {boolean}
800
+ * @package
801
+ */
802
+ is(arg) {
803
+ return this.short === arg || this.long === arg;
804
+ }
805
+ /**
806
+ * Return whether a boolean option.
807
+ *
808
+ * Options are one of boolean, negated, required argument, or optional argument.
809
+ *
810
+ * @return {boolean}
811
+ * @package
812
+ */
813
+ isBoolean() {
814
+ return !this.required && !this.optional && !this.negate;
815
+ }
816
+ };
817
+ var DualOptions = class {
818
+ /**
819
+ * @param {Option[]} options
820
+ */
821
+ constructor(options) {
822
+ this.positiveOptions = /* @__PURE__ */ new Map();
823
+ this.negativeOptions = /* @__PURE__ */ new Map();
824
+ this.dualOptions = /* @__PURE__ */ new Set();
825
+ options.forEach((option) => {
826
+ if (option.negate) {
827
+ this.negativeOptions.set(option.attributeName(), option);
828
+ } else {
829
+ this.positiveOptions.set(option.attributeName(), option);
830
+ }
831
+ });
832
+ this.negativeOptions.forEach((value, key) => {
833
+ if (this.positiveOptions.has(key)) {
834
+ this.dualOptions.add(key);
835
+ }
836
+ });
837
+ }
838
+ /**
839
+ * Did the value come from the option, and not from possible matching dual option?
840
+ *
841
+ * @param {*} value
842
+ * @param {Option} option
843
+ * @returns {boolean}
844
+ */
845
+ valueFromOption(value, option) {
846
+ const optionKey = option.attributeName();
847
+ if (!this.dualOptions.has(optionKey)) return true;
848
+ const preset = this.negativeOptions.get(optionKey).presetArg;
849
+ const negativeValue = preset !== void 0 ? preset : false;
850
+ return option.negate === (negativeValue === value);
851
+ }
852
+ };
853
+ function camelcase(str) {
854
+ return str.split("-").reduce((str2, word) => {
855
+ return str2 + word[0].toUpperCase() + word.slice(1);
856
+ });
857
+ }
858
+ function splitOptionFlags(flags) {
859
+ let shortFlag;
860
+ let longFlag;
861
+ const flagParts = flags.split(/[ |,]+/);
862
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
863
+ shortFlag = flagParts.shift();
864
+ longFlag = flagParts.shift();
865
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
866
+ shortFlag = longFlag;
867
+ longFlag = void 0;
868
+ }
869
+ return { shortFlag, longFlag };
870
+ }
871
+ exports2.Option = Option2;
872
+ exports2.DualOptions = DualOptions;
873
+ }
874
+ });
875
+
876
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js
877
+ var require_suggestSimilar = __commonJS({
878
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js"(exports2) {
879
+ var maxDistance = 3;
880
+ function editDistance(a, b) {
881
+ if (Math.abs(a.length - b.length) > maxDistance)
882
+ return Math.max(a.length, b.length);
883
+ const d = [];
884
+ for (let i = 0; i <= a.length; i++) {
885
+ d[i] = [i];
886
+ }
887
+ for (let j = 0; j <= b.length; j++) {
888
+ d[0][j] = j;
889
+ }
890
+ for (let j = 1; j <= b.length; j++) {
891
+ for (let i = 1; i <= a.length; i++) {
892
+ let cost = 1;
893
+ if (a[i - 1] === b[j - 1]) {
894
+ cost = 0;
895
+ } else {
896
+ cost = 1;
897
+ }
898
+ d[i][j] = Math.min(
899
+ d[i - 1][j] + 1,
900
+ // deletion
901
+ d[i][j - 1] + 1,
902
+ // insertion
903
+ d[i - 1][j - 1] + cost
904
+ // substitution
905
+ );
906
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
907
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
908
+ }
909
+ }
910
+ }
911
+ return d[a.length][b.length];
912
+ }
913
+ function suggestSimilar(word, candidates) {
914
+ if (!candidates || candidates.length === 0) return "";
915
+ candidates = Array.from(new Set(candidates));
916
+ const searchingOptions = word.startsWith("--");
917
+ if (searchingOptions) {
918
+ word = word.slice(2);
919
+ candidates = candidates.map((candidate) => candidate.slice(2));
920
+ }
921
+ let similar = [];
922
+ let bestDistance = maxDistance;
923
+ const minSimilarity = 0.4;
924
+ candidates.forEach((candidate) => {
925
+ if (candidate.length <= 1) return;
926
+ const distance = editDistance(word, candidate);
927
+ const length = Math.max(word.length, candidate.length);
928
+ const similarity = (length - distance) / length;
929
+ if (similarity > minSimilarity) {
930
+ if (distance < bestDistance) {
931
+ bestDistance = distance;
932
+ similar = [candidate];
933
+ } else if (distance === bestDistance) {
934
+ similar.push(candidate);
935
+ }
936
+ }
937
+ });
938
+ similar.sort((a, b) => a.localeCompare(b));
939
+ if (searchingOptions) {
940
+ similar = similar.map((candidate) => `--${candidate}`);
941
+ }
942
+ if (similar.length > 1) {
943
+ return `
944
+ (Did you mean one of ${similar.join(", ")}?)`;
945
+ }
946
+ if (similar.length === 1) {
947
+ return `
948
+ (Did you mean ${similar[0]}?)`;
949
+ }
950
+ return "";
951
+ }
952
+ exports2.suggestSimilar = suggestSimilar;
953
+ }
954
+ });
955
+
956
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js
957
+ var require_command = __commonJS({
958
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js"(exports2) {
959
+ var EventEmitter = require("node:events").EventEmitter;
960
+ var childProcess = require("node:child_process");
961
+ var path3 = require("node:path");
962
+ var fs3 = require("node:fs");
963
+ var process2 = require("node:process");
964
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
965
+ var { CommanderError: CommanderError2 } = require_error();
966
+ var { Help: Help2 } = require_help();
967
+ var { Option: Option2, DualOptions } = require_option();
968
+ var { suggestSimilar } = require_suggestSimilar();
969
+ var Command2 = class _Command extends EventEmitter {
970
+ /**
971
+ * Initialize a new `Command`.
972
+ *
973
+ * @param {string} [name]
974
+ */
975
+ constructor(name) {
976
+ super();
977
+ this.commands = [];
978
+ this.options = [];
979
+ this.parent = null;
980
+ this._allowUnknownOption = false;
981
+ this._allowExcessArguments = true;
982
+ this.registeredArguments = [];
983
+ this._args = this.registeredArguments;
984
+ this.args = [];
985
+ this.rawArgs = [];
986
+ this.processedArgs = [];
987
+ this._scriptPath = null;
988
+ this._name = name || "";
989
+ this._optionValues = {};
990
+ this._optionValueSources = {};
991
+ this._storeOptionsAsProperties = false;
992
+ this._actionHandler = null;
993
+ this._executableHandler = false;
994
+ this._executableFile = null;
995
+ this._executableDir = null;
996
+ this._defaultCommandName = null;
997
+ this._exitCallback = null;
998
+ this._aliases = [];
999
+ this._combineFlagAndOptionalValue = true;
1000
+ this._description = "";
1001
+ this._summary = "";
1002
+ this._argsDescription = void 0;
1003
+ this._enablePositionalOptions = false;
1004
+ this._passThroughOptions = false;
1005
+ this._lifeCycleHooks = {};
1006
+ this._showHelpAfterError = false;
1007
+ this._showSuggestionAfterError = true;
1008
+ this._outputConfiguration = {
1009
+ writeOut: (str) => process2.stdout.write(str),
1010
+ writeErr: (str) => process2.stderr.write(str),
1011
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1012
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1013
+ outputError: (str, write) => write(str)
1014
+ };
1015
+ this._hidden = false;
1016
+ this._helpOption = void 0;
1017
+ this._addImplicitHelpCommand = void 0;
1018
+ this._helpCommand = void 0;
1019
+ this._helpConfiguration = {};
1020
+ }
1021
+ /**
1022
+ * Copy settings that are useful to have in common across root command and subcommands.
1023
+ *
1024
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1025
+ *
1026
+ * @param {Command} sourceCommand
1027
+ * @return {Command} `this` command for chaining
1028
+ */
1029
+ copyInheritedSettings(sourceCommand) {
1030
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1031
+ this._helpOption = sourceCommand._helpOption;
1032
+ this._helpCommand = sourceCommand._helpCommand;
1033
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1034
+ this._exitCallback = sourceCommand._exitCallback;
1035
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1036
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1037
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1038
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1039
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1040
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1041
+ return this;
1042
+ }
1043
+ /**
1044
+ * @returns {Command[]}
1045
+ * @private
1046
+ */
1047
+ _getCommandAndAncestors() {
1048
+ const result = [];
1049
+ for (let command = this; command; command = command.parent) {
1050
+ result.push(command);
1051
+ }
1052
+ return result;
1053
+ }
1054
+ /**
1055
+ * Define a command.
1056
+ *
1057
+ * There are two styles of command: pay attention to where to put the description.
1058
+ *
1059
+ * @example
1060
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1061
+ * program
1062
+ * .command('clone <source> [destination]')
1063
+ * .description('clone a repository into a newly created directory')
1064
+ * .action((source, destination) => {
1065
+ * console.log('clone command called');
1066
+ * });
1067
+ *
1068
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1069
+ * program
1070
+ * .command('start <service>', 'start named service')
1071
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1072
+ *
1073
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1074
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1075
+ * @param {object} [execOpts] - configuration options (for executable)
1076
+ * @return {Command} returns new command for action handler, or `this` for executable command
1077
+ */
1078
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1079
+ let desc = actionOptsOrExecDesc;
1080
+ let opts = execOpts;
1081
+ if (typeof desc === "object" && desc !== null) {
1082
+ opts = desc;
1083
+ desc = null;
1084
+ }
1085
+ opts = opts || {};
1086
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1087
+ const cmd = this.createCommand(name);
1088
+ if (desc) {
1089
+ cmd.description(desc);
1090
+ cmd._executableHandler = true;
1091
+ }
1092
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1093
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1094
+ cmd._executableFile = opts.executableFile || null;
1095
+ if (args) cmd.arguments(args);
1096
+ this._registerCommand(cmd);
1097
+ cmd.parent = this;
1098
+ cmd.copyInheritedSettings(this);
1099
+ if (desc) return this;
1100
+ return cmd;
1101
+ }
1102
+ /**
1103
+ * Factory routine to create a new unattached command.
1104
+ *
1105
+ * See .command() for creating an attached subcommand, which uses this routine to
1106
+ * create the command. You can override createCommand to customise subcommands.
1107
+ *
1108
+ * @param {string} [name]
1109
+ * @return {Command} new command
1110
+ */
1111
+ createCommand(name) {
1112
+ return new _Command(name);
1113
+ }
1114
+ /**
1115
+ * You can customise the help with a subclass of Help by overriding createHelp,
1116
+ * or by overriding Help properties using configureHelp().
1117
+ *
1118
+ * @return {Help}
1119
+ */
1120
+ createHelp() {
1121
+ return Object.assign(new Help2(), this.configureHelp());
1122
+ }
1123
+ /**
1124
+ * You can customise the help by overriding Help properties using configureHelp(),
1125
+ * or with a subclass of Help by overriding createHelp().
1126
+ *
1127
+ * @param {object} [configuration] - configuration options
1128
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1129
+ */
1130
+ configureHelp(configuration) {
1131
+ if (configuration === void 0) return this._helpConfiguration;
1132
+ this._helpConfiguration = configuration;
1133
+ return this;
1134
+ }
1135
+ /**
1136
+ * The default output goes to stdout and stderr. You can customise this for special
1137
+ * applications. You can also customise the display of errors by overriding outputError.
1138
+ *
1139
+ * The configuration properties are all functions:
1140
+ *
1141
+ * // functions to change where being written, stdout and stderr
1142
+ * writeOut(str)
1143
+ * writeErr(str)
1144
+ * // matching functions to specify width for wrapping help
1145
+ * getOutHelpWidth()
1146
+ * getErrHelpWidth()
1147
+ * // functions based on what is being written out
1148
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1149
+ *
1150
+ * @param {object} [configuration] - configuration options
1151
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1152
+ */
1153
+ configureOutput(configuration) {
1154
+ if (configuration === void 0) return this._outputConfiguration;
1155
+ Object.assign(this._outputConfiguration, configuration);
1156
+ return this;
1157
+ }
1158
+ /**
1159
+ * Display the help or a custom message after an error occurs.
1160
+ *
1161
+ * @param {(boolean|string)} [displayHelp]
1162
+ * @return {Command} `this` command for chaining
1163
+ */
1164
+ showHelpAfterError(displayHelp = true) {
1165
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1166
+ this._showHelpAfterError = displayHelp;
1167
+ return this;
1168
+ }
1169
+ /**
1170
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1171
+ *
1172
+ * @param {boolean} [displaySuggestion]
1173
+ * @return {Command} `this` command for chaining
1174
+ */
1175
+ showSuggestionAfterError(displaySuggestion = true) {
1176
+ this._showSuggestionAfterError = !!displaySuggestion;
1177
+ return this;
1178
+ }
1179
+ /**
1180
+ * Add a prepared subcommand.
1181
+ *
1182
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1183
+ *
1184
+ * @param {Command} cmd - new subcommand
1185
+ * @param {object} [opts] - configuration options
1186
+ * @return {Command} `this` command for chaining
1187
+ */
1188
+ addCommand(cmd, opts) {
1189
+ if (!cmd._name) {
1190
+ throw new Error(`Command passed to .addCommand() must have a name
1191
+ - specify the name in Command constructor or using .name()`);
1192
+ }
1193
+ opts = opts || {};
1194
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1195
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1196
+ this._registerCommand(cmd);
1197
+ cmd.parent = this;
1198
+ cmd._checkForBrokenPassThrough();
1199
+ return this;
1200
+ }
1201
+ /**
1202
+ * Factory routine to create a new unattached argument.
1203
+ *
1204
+ * See .argument() for creating an attached argument, which uses this routine to
1205
+ * create the argument. You can override createArgument to return a custom argument.
1206
+ *
1207
+ * @param {string} name
1208
+ * @param {string} [description]
1209
+ * @return {Argument} new argument
1210
+ */
1211
+ createArgument(name, description) {
1212
+ return new Argument2(name, description);
1213
+ }
1214
+ /**
1215
+ * Define argument syntax for command.
1216
+ *
1217
+ * The default is that the argument is required, and you can explicitly
1218
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1219
+ *
1220
+ * @example
1221
+ * program.argument('<input-file>');
1222
+ * program.argument('[output-file]');
1223
+ *
1224
+ * @param {string} name
1225
+ * @param {string} [description]
1226
+ * @param {(Function|*)} [fn] - custom argument processing function
1227
+ * @param {*} [defaultValue]
1228
+ * @return {Command} `this` command for chaining
1229
+ */
1230
+ argument(name, description, fn, defaultValue) {
1231
+ const argument = this.createArgument(name, description);
1232
+ if (typeof fn === "function") {
1233
+ argument.default(defaultValue).argParser(fn);
1234
+ } else {
1235
+ argument.default(fn);
1236
+ }
1237
+ this.addArgument(argument);
1238
+ return this;
1239
+ }
1240
+ /**
1241
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1242
+ *
1243
+ * See also .argument().
1244
+ *
1245
+ * @example
1246
+ * program.arguments('<cmd> [env]');
1247
+ *
1248
+ * @param {string} names
1249
+ * @return {Command} `this` command for chaining
1250
+ */
1251
+ arguments(names) {
1252
+ names.trim().split(/ +/).forEach((detail) => {
1253
+ this.argument(detail);
1254
+ });
1255
+ return this;
1256
+ }
1257
+ /**
1258
+ * Define argument syntax for command, adding a prepared argument.
1259
+ *
1260
+ * @param {Argument} argument
1261
+ * @return {Command} `this` command for chaining
1262
+ */
1263
+ addArgument(argument) {
1264
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1265
+ if (previousArgument && previousArgument.variadic) {
1266
+ throw new Error(
1267
+ `only the last argument can be variadic '${previousArgument.name()}'`
1268
+ );
1269
+ }
1270
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1271
+ throw new Error(
1272
+ `a default value for a required argument is never used: '${argument.name()}'`
1273
+ );
1274
+ }
1275
+ this.registeredArguments.push(argument);
1276
+ return this;
1277
+ }
1278
+ /**
1279
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1280
+ *
1281
+ * @example
1282
+ * program.helpCommand('help [cmd]');
1283
+ * program.helpCommand('help [cmd]', 'show help');
1284
+ * program.helpCommand(false); // suppress default help command
1285
+ * program.helpCommand(true); // add help command even if no subcommands
1286
+ *
1287
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1288
+ * @param {string} [description] - custom description
1289
+ * @return {Command} `this` command for chaining
1290
+ */
1291
+ helpCommand(enableOrNameAndArgs, description) {
1292
+ if (typeof enableOrNameAndArgs === "boolean") {
1293
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1294
+ return this;
1295
+ }
1296
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1297
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1298
+ const helpDescription = description ?? "display help for command";
1299
+ const helpCommand = this.createCommand(helpName);
1300
+ helpCommand.helpOption(false);
1301
+ if (helpArgs) helpCommand.arguments(helpArgs);
1302
+ if (helpDescription) helpCommand.description(helpDescription);
1303
+ this._addImplicitHelpCommand = true;
1304
+ this._helpCommand = helpCommand;
1305
+ return this;
1306
+ }
1307
+ /**
1308
+ * Add prepared custom help command.
1309
+ *
1310
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1311
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1312
+ * @return {Command} `this` command for chaining
1313
+ */
1314
+ addHelpCommand(helpCommand, deprecatedDescription) {
1315
+ if (typeof helpCommand !== "object") {
1316
+ this.helpCommand(helpCommand, deprecatedDescription);
1317
+ return this;
1318
+ }
1319
+ this._addImplicitHelpCommand = true;
1320
+ this._helpCommand = helpCommand;
1321
+ return this;
1322
+ }
1323
+ /**
1324
+ * Lazy create help command.
1325
+ *
1326
+ * @return {(Command|null)}
1327
+ * @package
1328
+ */
1329
+ _getHelpCommand() {
1330
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1331
+ if (hasImplicitHelpCommand) {
1332
+ if (this._helpCommand === void 0) {
1333
+ this.helpCommand(void 0, void 0);
1334
+ }
1335
+ return this._helpCommand;
1336
+ }
1337
+ return null;
1338
+ }
1339
+ /**
1340
+ * Add hook for life cycle event.
1341
+ *
1342
+ * @param {string} event
1343
+ * @param {Function} listener
1344
+ * @return {Command} `this` command for chaining
1345
+ */
1346
+ hook(event, listener) {
1347
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1348
+ if (!allowedValues.includes(event)) {
1349
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1350
+ Expecting one of '${allowedValues.join("', '")}'`);
1351
+ }
1352
+ if (this._lifeCycleHooks[event]) {
1353
+ this._lifeCycleHooks[event].push(listener);
1354
+ } else {
1355
+ this._lifeCycleHooks[event] = [listener];
1356
+ }
1357
+ return this;
1358
+ }
1359
+ /**
1360
+ * Register callback to use as replacement for calling process.exit.
1361
+ *
1362
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1363
+ * @return {Command} `this` command for chaining
1364
+ */
1365
+ exitOverride(fn) {
1366
+ if (fn) {
1367
+ this._exitCallback = fn;
1368
+ } else {
1369
+ this._exitCallback = (err) => {
1370
+ if (err.code !== "commander.executeSubCommandAsync") {
1371
+ throw err;
1372
+ } else {
1373
+ }
1374
+ };
1375
+ }
1376
+ return this;
1377
+ }
1378
+ /**
1379
+ * Call process.exit, and _exitCallback if defined.
1380
+ *
1381
+ * @param {number} exitCode exit code for using with process.exit
1382
+ * @param {string} code an id string representing the error
1383
+ * @param {string} message human-readable description of the error
1384
+ * @return never
1385
+ * @private
1386
+ */
1387
+ _exit(exitCode, code, message) {
1388
+ if (this._exitCallback) {
1389
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1390
+ }
1391
+ process2.exit(exitCode);
1392
+ }
1393
+ /**
1394
+ * Register callback `fn` for the command.
1395
+ *
1396
+ * @example
1397
+ * program
1398
+ * .command('serve')
1399
+ * .description('start service')
1400
+ * .action(function() {
1401
+ * // do work here
1402
+ * });
1403
+ *
1404
+ * @param {Function} fn
1405
+ * @return {Command} `this` command for chaining
1406
+ */
1407
+ action(fn) {
1408
+ const listener = (args) => {
1409
+ const expectedArgsCount = this.registeredArguments.length;
1410
+ const actionArgs = args.slice(0, expectedArgsCount);
1411
+ if (this._storeOptionsAsProperties) {
1412
+ actionArgs[expectedArgsCount] = this;
1413
+ } else {
1414
+ actionArgs[expectedArgsCount] = this.opts();
1415
+ }
1416
+ actionArgs.push(this);
1417
+ return fn.apply(this, actionArgs);
1418
+ };
1419
+ this._actionHandler = listener;
1420
+ return this;
1421
+ }
1422
+ /**
1423
+ * Factory routine to create a new unattached option.
1424
+ *
1425
+ * See .option() for creating an attached option, which uses this routine to
1426
+ * create the option. You can override createOption to return a custom option.
1427
+ *
1428
+ * @param {string} flags
1429
+ * @param {string} [description]
1430
+ * @return {Option} new option
1431
+ */
1432
+ createOption(flags, description) {
1433
+ return new Option2(flags, description);
1434
+ }
1435
+ /**
1436
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1437
+ *
1438
+ * @param {(Option | Argument)} target
1439
+ * @param {string} value
1440
+ * @param {*} previous
1441
+ * @param {string} invalidArgumentMessage
1442
+ * @private
1443
+ */
1444
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1445
+ try {
1446
+ return target.parseArg(value, previous);
1447
+ } catch (err) {
1448
+ if (err.code === "commander.invalidArgument") {
1449
+ const message = `${invalidArgumentMessage} ${err.message}`;
1450
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1451
+ }
1452
+ throw err;
1453
+ }
1454
+ }
1455
+ /**
1456
+ * Check for option flag conflicts.
1457
+ * Register option if no conflicts found, or throw on conflict.
1458
+ *
1459
+ * @param {Option} option
1460
+ * @private
1461
+ */
1462
+ _registerOption(option) {
1463
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1464
+ if (matchingOption) {
1465
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1466
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1467
+ - already used by option '${matchingOption.flags}'`);
1468
+ }
1469
+ this.options.push(option);
1470
+ }
1471
+ /**
1472
+ * Check for command name and alias conflicts with existing commands.
1473
+ * Register command if no conflicts found, or throw on conflict.
1474
+ *
1475
+ * @param {Command} command
1476
+ * @private
1477
+ */
1478
+ _registerCommand(command) {
1479
+ const knownBy = (cmd) => {
1480
+ return [cmd.name()].concat(cmd.aliases());
1481
+ };
1482
+ const alreadyUsed = knownBy(command).find(
1483
+ (name) => this._findCommand(name)
1484
+ );
1485
+ if (alreadyUsed) {
1486
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1487
+ const newCmd = knownBy(command).join("|");
1488
+ throw new Error(
1489
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1490
+ );
1491
+ }
1492
+ this.commands.push(command);
1493
+ }
1494
+ /**
1495
+ * Add an option.
1496
+ *
1497
+ * @param {Option} option
1498
+ * @return {Command} `this` command for chaining
1499
+ */
1500
+ addOption(option) {
1501
+ this._registerOption(option);
1502
+ const oname = option.name();
1503
+ const name = option.attributeName();
1504
+ if (option.negate) {
1505
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1506
+ if (!this._findOption(positiveLongFlag)) {
1507
+ this.setOptionValueWithSource(
1508
+ name,
1509
+ option.defaultValue === void 0 ? true : option.defaultValue,
1510
+ "default"
1511
+ );
1512
+ }
1513
+ } else if (option.defaultValue !== void 0) {
1514
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1515
+ }
1516
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1517
+ if (val == null && option.presetArg !== void 0) {
1518
+ val = option.presetArg;
1519
+ }
1520
+ const oldValue = this.getOptionValue(name);
1521
+ if (val !== null && option.parseArg) {
1522
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1523
+ } else if (val !== null && option.variadic) {
1524
+ val = option._concatValue(val, oldValue);
1525
+ }
1526
+ if (val == null) {
1527
+ if (option.negate) {
1528
+ val = false;
1529
+ } else if (option.isBoolean() || option.optional) {
1530
+ val = true;
1531
+ } else {
1532
+ val = "";
1533
+ }
1534
+ }
1535
+ this.setOptionValueWithSource(name, val, valueSource);
1536
+ };
1537
+ this.on("option:" + oname, (val) => {
1538
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1539
+ handleOptionValue(val, invalidValueMessage, "cli");
1540
+ });
1541
+ if (option.envVar) {
1542
+ this.on("optionEnv:" + oname, (val) => {
1543
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1544
+ handleOptionValue(val, invalidValueMessage, "env");
1545
+ });
1546
+ }
1547
+ return this;
1548
+ }
1549
+ /**
1550
+ * Internal implementation shared by .option() and .requiredOption()
1551
+ *
1552
+ * @return {Command} `this` command for chaining
1553
+ * @private
1554
+ */
1555
+ _optionEx(config, flags, description, fn, defaultValue) {
1556
+ if (typeof flags === "object" && flags instanceof Option2) {
1557
+ throw new Error(
1558
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1559
+ );
1560
+ }
1561
+ const option = this.createOption(flags, description);
1562
+ option.makeOptionMandatory(!!config.mandatory);
1563
+ if (typeof fn === "function") {
1564
+ option.default(defaultValue).argParser(fn);
1565
+ } else if (fn instanceof RegExp) {
1566
+ const regex = fn;
1567
+ fn = (val, def) => {
1568
+ const m = regex.exec(val);
1569
+ return m ? m[0] : def;
1570
+ };
1571
+ option.default(defaultValue).argParser(fn);
1572
+ } else {
1573
+ option.default(fn);
1574
+ }
1575
+ return this.addOption(option);
1576
+ }
1577
+ /**
1578
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1579
+ *
1580
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1581
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1582
+ *
1583
+ * See the README for more details, and see also addOption() and requiredOption().
1584
+ *
1585
+ * @example
1586
+ * program
1587
+ * .option('-p, --pepper', 'add pepper')
1588
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1589
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1590
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1591
+ *
1592
+ * @param {string} flags
1593
+ * @param {string} [description]
1594
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1595
+ * @param {*} [defaultValue]
1596
+ * @return {Command} `this` command for chaining
1597
+ */
1598
+ option(flags, description, parseArg, defaultValue) {
1599
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1600
+ }
1601
+ /**
1602
+ * Add a required option which must have a value after parsing. This usually means
1603
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1604
+ *
1605
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1606
+ *
1607
+ * @param {string} flags
1608
+ * @param {string} [description]
1609
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1610
+ * @param {*} [defaultValue]
1611
+ * @return {Command} `this` command for chaining
1612
+ */
1613
+ requiredOption(flags, description, parseArg, defaultValue) {
1614
+ return this._optionEx(
1615
+ { mandatory: true },
1616
+ flags,
1617
+ description,
1618
+ parseArg,
1619
+ defaultValue
1620
+ );
1621
+ }
1622
+ /**
1623
+ * Alter parsing of short flags with optional values.
1624
+ *
1625
+ * @example
1626
+ * // for `.option('-f,--flag [value]'):
1627
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1628
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1629
+ *
1630
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1631
+ * @return {Command} `this` command for chaining
1632
+ */
1633
+ combineFlagAndOptionalValue(combine = true) {
1634
+ this._combineFlagAndOptionalValue = !!combine;
1635
+ return this;
1636
+ }
1637
+ /**
1638
+ * Allow unknown options on the command line.
1639
+ *
1640
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1641
+ * @return {Command} `this` command for chaining
1642
+ */
1643
+ allowUnknownOption(allowUnknown = true) {
1644
+ this._allowUnknownOption = !!allowUnknown;
1645
+ return this;
1646
+ }
1647
+ /**
1648
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1649
+ *
1650
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1651
+ * @return {Command} `this` command for chaining
1652
+ */
1653
+ allowExcessArguments(allowExcess = true) {
1654
+ this._allowExcessArguments = !!allowExcess;
1655
+ return this;
1656
+ }
1657
+ /**
1658
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1659
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1660
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1661
+ *
1662
+ * @param {boolean} [positional]
1663
+ * @return {Command} `this` command for chaining
1664
+ */
1665
+ enablePositionalOptions(positional = true) {
1666
+ this._enablePositionalOptions = !!positional;
1667
+ return this;
1668
+ }
1669
+ /**
1670
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1671
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1672
+ * positional options to have been enabled on the program (parent commands).
1673
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1674
+ *
1675
+ * @param {boolean} [passThrough] for unknown options.
1676
+ * @return {Command} `this` command for chaining
1677
+ */
1678
+ passThroughOptions(passThrough = true) {
1679
+ this._passThroughOptions = !!passThrough;
1680
+ this._checkForBrokenPassThrough();
1681
+ return this;
1682
+ }
1683
+ /**
1684
+ * @private
1685
+ */
1686
+ _checkForBrokenPassThrough() {
1687
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1688
+ throw new Error(
1689
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1690
+ );
1691
+ }
1692
+ }
1693
+ /**
1694
+ * Whether to store option values as properties on command object,
1695
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1696
+ *
1697
+ * @param {boolean} [storeAsProperties=true]
1698
+ * @return {Command} `this` command for chaining
1699
+ */
1700
+ storeOptionsAsProperties(storeAsProperties = true) {
1701
+ if (this.options.length) {
1702
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1703
+ }
1704
+ if (Object.keys(this._optionValues).length) {
1705
+ throw new Error(
1706
+ "call .storeOptionsAsProperties() before setting option values"
1707
+ );
1708
+ }
1709
+ this._storeOptionsAsProperties = !!storeAsProperties;
1710
+ return this;
1711
+ }
1712
+ /**
1713
+ * Retrieve option value.
1714
+ *
1715
+ * @param {string} key
1716
+ * @return {object} value
1717
+ */
1718
+ getOptionValue(key) {
1719
+ if (this._storeOptionsAsProperties) {
1720
+ return this[key];
1721
+ }
1722
+ return this._optionValues[key];
1723
+ }
1724
+ /**
1725
+ * Store option value.
1726
+ *
1727
+ * @param {string} key
1728
+ * @param {object} value
1729
+ * @return {Command} `this` command for chaining
1730
+ */
1731
+ setOptionValue(key, value) {
1732
+ return this.setOptionValueWithSource(key, value, void 0);
1733
+ }
1734
+ /**
1735
+ * Store option value and where the value came from.
1736
+ *
1737
+ * @param {string} key
1738
+ * @param {object} value
1739
+ * @param {string} source - expected values are default/config/env/cli/implied
1740
+ * @return {Command} `this` command for chaining
1741
+ */
1742
+ setOptionValueWithSource(key, value, source) {
1743
+ if (this._storeOptionsAsProperties) {
1744
+ this[key] = value;
1745
+ } else {
1746
+ this._optionValues[key] = value;
1747
+ }
1748
+ this._optionValueSources[key] = source;
1749
+ return this;
1750
+ }
1751
+ /**
1752
+ * Get source of option value.
1753
+ * Expected values are default | config | env | cli | implied
1754
+ *
1755
+ * @param {string} key
1756
+ * @return {string}
1757
+ */
1758
+ getOptionValueSource(key) {
1759
+ return this._optionValueSources[key];
1760
+ }
1761
+ /**
1762
+ * Get source of option value. See also .optsWithGlobals().
1763
+ * Expected values are default | config | env | cli | implied
1764
+ *
1765
+ * @param {string} key
1766
+ * @return {string}
1767
+ */
1768
+ getOptionValueSourceWithGlobals(key) {
1769
+ let source;
1770
+ this._getCommandAndAncestors().forEach((cmd) => {
1771
+ if (cmd.getOptionValueSource(key) !== void 0) {
1772
+ source = cmd.getOptionValueSource(key);
1773
+ }
1774
+ });
1775
+ return source;
1776
+ }
1777
+ /**
1778
+ * Get user arguments from implied or explicit arguments.
1779
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1780
+ *
1781
+ * @private
1782
+ */
1783
+ _prepareUserArgs(argv, parseOptions) {
1784
+ if (argv !== void 0 && !Array.isArray(argv)) {
1785
+ throw new Error("first parameter to parse must be array or undefined");
1786
+ }
1787
+ parseOptions = parseOptions || {};
1788
+ if (argv === void 0 && parseOptions.from === void 0) {
1789
+ if (process2.versions?.electron) {
1790
+ parseOptions.from = "electron";
1791
+ }
1792
+ const execArgv = process2.execArgv ?? [];
1793
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1794
+ parseOptions.from = "eval";
1795
+ }
1796
+ }
1797
+ if (argv === void 0) {
1798
+ argv = process2.argv;
1799
+ }
1800
+ this.rawArgs = argv.slice();
1801
+ let userArgs;
1802
+ switch (parseOptions.from) {
1803
+ case void 0:
1804
+ case "node":
1805
+ this._scriptPath = argv[1];
1806
+ userArgs = argv.slice(2);
1807
+ break;
1808
+ case "electron":
1809
+ if (process2.defaultApp) {
1810
+ this._scriptPath = argv[1];
1811
+ userArgs = argv.slice(2);
1812
+ } else {
1813
+ userArgs = argv.slice(1);
1814
+ }
1815
+ break;
1816
+ case "user":
1817
+ userArgs = argv.slice(0);
1818
+ break;
1819
+ case "eval":
1820
+ userArgs = argv.slice(1);
1821
+ break;
1822
+ default:
1823
+ throw new Error(
1824
+ `unexpected parse option { from: '${parseOptions.from}' }`
1825
+ );
1826
+ }
1827
+ if (!this._name && this._scriptPath)
1828
+ this.nameFromFilename(this._scriptPath);
1829
+ this._name = this._name || "program";
1830
+ return userArgs;
1831
+ }
1832
+ /**
1833
+ * Parse `argv`, setting options and invoking commands when defined.
1834
+ *
1835
+ * Use parseAsync instead of parse if any of your action handlers are async.
1836
+ *
1837
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1838
+ *
1839
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1840
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1841
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1842
+ * - `'user'`: just user arguments
1843
+ *
1844
+ * @example
1845
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1846
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1847
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1848
+ *
1849
+ * @param {string[]} [argv] - optional, defaults to process.argv
1850
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1851
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1852
+ * @return {Command} `this` command for chaining
1853
+ */
1854
+ parse(argv, parseOptions) {
1855
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1856
+ this._parseCommand([], userArgs);
1857
+ return this;
1858
+ }
1859
+ /**
1860
+ * Parse `argv`, setting options and invoking commands when defined.
1861
+ *
1862
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1863
+ *
1864
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1865
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1866
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1867
+ * - `'user'`: just user arguments
1868
+ *
1869
+ * @example
1870
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1871
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1872
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1873
+ *
1874
+ * @param {string[]} [argv]
1875
+ * @param {object} [parseOptions]
1876
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1877
+ * @return {Promise}
1878
+ */
1879
+ async parseAsync(argv, parseOptions) {
1880
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1881
+ await this._parseCommand([], userArgs);
1882
+ return this;
1883
+ }
1884
+ /**
1885
+ * Execute a sub-command executable.
1886
+ *
1887
+ * @private
1888
+ */
1889
+ _executeSubCommand(subcommand, args) {
1890
+ args = args.slice();
1891
+ let launchWithNode = false;
1892
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1893
+ function findFile(baseDir, baseName) {
1894
+ const localBin = path3.resolve(baseDir, baseName);
1895
+ if (fs3.existsSync(localBin)) return localBin;
1896
+ if (sourceExt.includes(path3.extname(baseName))) return void 0;
1897
+ const foundExt = sourceExt.find(
1898
+ (ext) => fs3.existsSync(`${localBin}${ext}`)
1899
+ );
1900
+ if (foundExt) return `${localBin}${foundExt}`;
1901
+ return void 0;
1902
+ }
1903
+ this._checkForMissingMandatoryOptions();
1904
+ this._checkForConflictingOptions();
1905
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1906
+ let executableDir = this._executableDir || "";
1907
+ if (this._scriptPath) {
1908
+ let resolvedScriptPath;
1909
+ try {
1910
+ resolvedScriptPath = fs3.realpathSync(this._scriptPath);
1911
+ } catch (err) {
1912
+ resolvedScriptPath = this._scriptPath;
1913
+ }
1914
+ executableDir = path3.resolve(
1915
+ path3.dirname(resolvedScriptPath),
1916
+ executableDir
1917
+ );
1918
+ }
1919
+ if (executableDir) {
1920
+ let localFile = findFile(executableDir, executableFile);
1921
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1922
+ const legacyName = path3.basename(
1923
+ this._scriptPath,
1924
+ path3.extname(this._scriptPath)
1925
+ );
1926
+ if (legacyName !== this._name) {
1927
+ localFile = findFile(
1928
+ executableDir,
1929
+ `${legacyName}-${subcommand._name}`
1930
+ );
1931
+ }
1932
+ }
1933
+ executableFile = localFile || executableFile;
1934
+ }
1935
+ launchWithNode = sourceExt.includes(path3.extname(executableFile));
1936
+ let proc;
1937
+ if (process2.platform !== "win32") {
1938
+ if (launchWithNode) {
1939
+ args.unshift(executableFile);
1940
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1941
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1942
+ } else {
1943
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1944
+ }
1945
+ } else {
1946
+ args.unshift(executableFile);
1947
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1948
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1949
+ }
1950
+ if (!proc.killed) {
1951
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1952
+ signals.forEach((signal) => {
1953
+ process2.on(signal, () => {
1954
+ if (proc.killed === false && proc.exitCode === null) {
1955
+ proc.kill(signal);
1956
+ }
1957
+ });
1958
+ });
1959
+ }
1960
+ const exitCallback = this._exitCallback;
1961
+ proc.on("close", (code) => {
1962
+ code = code ?? 1;
1963
+ if (!exitCallback) {
1964
+ process2.exit(code);
1965
+ } else {
1966
+ exitCallback(
1967
+ new CommanderError2(
1968
+ code,
1969
+ "commander.executeSubCommandAsync",
1970
+ "(close)"
1971
+ )
1972
+ );
1973
+ }
1974
+ });
1975
+ proc.on("error", (err) => {
1976
+ if (err.code === "ENOENT") {
1977
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1978
+ const executableMissing = `'${executableFile}' does not exist
1979
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
1980
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${h}`;throw new Error(m)}else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!c)d.exit(1);else{let h=new nt(1,"commander.executeSubCommandAsync","(error)");h.nestedError=u,c(h)}}),this.runningCommand=a}_dispatchSubcommand(t,e,n){let i=this._findCommand(t);i||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,e.concat(n));else return i._parseCommand(e,n)}),o}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(n,i,o)=>{let r=i;if(i!==null&&n.parseArg){let l=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;r=this._callParseArg(n,i,o,l)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((r,l)=>t(n,l,r),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=t(n,o,n.defaultValue))),e[i]=o}),this.processedArgs=e}_chainOrCall(t,e){return t&&t.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let n=t,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[e]!==void 0).forEach(o=>{o._lifeCycleHooks[e].forEach(r=>{i.push({hookedCommand:o,callback:r})})}),e==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(t,e,n){let i=t;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(this,e))}),i}_parseCommand(t,e){let n=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(n.operands),e=n.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);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])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(o,t,e)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});t.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=t.find(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],n=[],i=e,o=t.slice();function r(a){return a.length>1&&a[0]==="-"}let l=null;for(;o.length;){let a=o.shift();if(a==="--"){i===n&&i.push(a),i.push(...o);break}if(l&&!r(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,r(a)){let c=this._findOption(a);if(c){if(c.required){let u=o.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;o.length>0&&!r(o[0])&&(u=o.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),o.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),u=this._findOption(a.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,a.slice(c+1));continue}}if(r(a)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&n.length===0){if(this._findCommand(a)){e.push(a),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){e.push(a),o.length>0&&e.push(...o);break}else if(this._defaultCommandName){n.push(a),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){i.push(a),o.length>0&&i.push(...o);break}i.push(a)}return{operands:e,unknown:n}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let n=0;n<e;n++){let i=this.options[n].attributeName();t[i]=i===this._versionOptionName?this._version:this[i]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
19
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
- `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let n=e||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in d.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,d.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new ue(this.options),e=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&e(n.attributeName())&&t.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!e(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let n=r=>{let l=r.attributeName(),a=this.getOptionValue(l),c=this.options.find(h=>h.negate&&l===h.attributeName()),u=this.options.find(h=>!h.negate&&l===h.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:u||r},i=r=>{let l=n(r),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},o=`error: ${i(t)} cannot be used with ${i(e)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let r=o.createHelp().visibleOptions(o).filter(l=>l.long).map(l=>l.long);i=i.concat(r),o=o.parent}while(o&&!o._enablePositionalOptions);e=gt(t,i)}let n=`error: unknown option '${t}'${e}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,n=e===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${n} but got ${t.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),e=gt(t,i)}let n=`error: unknown command '${t}'${e}`;this.error(n,{code:"commander.unknownCommand"})}version(t,e,n){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",n=n||"output the version number";let i=this.createOption(e,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${t}
22
- `),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(t);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${i}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(n=>le(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=k.basename(t,k.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp();return e.helpWidth===void 0&&(e.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),e.formatHelp(this,e)}_getHelpContext(t){t=t||{};let e={error:!!t.error},n;return e.error?n=i=>this._outputConfiguration.writeErr(i):n=i=>this._outputConfiguration.writeOut(i),e.write=t.write||n,e.command=this,e}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let n=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation(n);if(e&&(i=e(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(o=>o.emit("afterAllHelp",n))}helpOption(t,e){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",e=e??"display help for command",this._helpOption=this.createOption(t,e),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let e=d.exitCode||0;e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let n=["beforeAll","before","after","afterAll"];if(!n.includes(t))throw new Error(`Unexpected value for position to addHelpText.
23
- Expecting one of '${n.join("', '")}'`);let i=`${t}Help`;return this.on(i,o=>{let r;typeof e=="function"?r=e({error:o.error,command:o.command}):r=e,r&&o.write(`${r}
24
- `)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(i=>e.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function mt(s){return s.map(t=>{if(!t.startsWith("--inspect"))return t;let e,n="127.0.0.1",i="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?e=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=o[1],n=o[3],i=o[4]),e&&i!=="0"?`${e}=${n}:${parseInt(i)+1}`:t})}ft.Command=it});var yt=P(w=>{var{Argument:wt}=z(),{Command:ot}=_t(),{CommanderError:he,InvalidArgumentError:Ct}=S(),{Help:de}=J(),{Option:Ot}=X();w.program=new ot;w.createCommand=s=>new ot(s);w.createOption=(s,t)=>new Ot(s,t);w.createArgument=(s,t)=>new wt(s,t);w.Command=ot;w.Option=Ot;w.Argument=wt;w.Help=de;w.CommanderError=he;w.InvalidArgumentError=Ct;w.InvalidOptionArgumentError=Ct});var kt=C(yt(),1),{program:Se,createCommand:De,createArgument:Re,createOption:Ne,CommanderError:Ue,InvalidArgumentError:Ve,InvalidOptionArgumentError:ze,Command:bt,Argument:He,Option:je,Help:qe}=kt.default;var vt=C(require("readline"));var v=C(require("fs")),At=C(require("path")),$t=C(require("os")),D=At.join($t.homedir(),".flightdeskrc"),x="https://flightdesk.dev/api";function g(){try{if(v.existsSync(D)){let s=v.readFileSync(D,"utf-8");return JSON.parse(s)}}catch(s){console.error("Warning: Failed to load config file:",s)}return{organizations:[],repoMapping:{}}}function b(s){v.writeFileSync(D,JSON.stringify(s,null,2))}function O(){let s=g();return s.defaultOrganization?s.organizations.find(t=>t.id===s.defaultOrganization)||null:s.organizations.length===1?s.organizations[0]:null}function Pt(s){let t=g(),e=t.repoMapping[s];return e&&t.organizations.find(n=>n.id===e)||null}function H(s){let t=g(),e=t.organizations.findIndex(n=>n.id===s.id);e>=0?t.organizations[e]=s:t.organizations.push(s),t.organizations.length===1&&(t.defaultOrganization=s.id),b(t)}function Et(s){let t=g();t.organizations=t.organizations.filter(e=>e.id!==s);for(let[e,n]of Object.entries(t.repoMapping))n===s&&delete t.repoMapping[e];t.defaultOrganization===s&&(t.defaultOrganization=t.organizations[0]?.id),b(t)}function y(){return g().organizations.length>0}function I(s,t){return new Promise(e=>{s.question(t,n=>{e(n.trim())})})}async function xt(){let s=vt.createInterface({input:process.stdin,output:process.stdout});console.log(`
25
- \u{1F6EB} FlightDesk CLI Setup
26
- `);try{let t=g();if(t.organizations.length>0&&(console.log("Existing organizations configured:"),t.organizations.forEach((u,h)=>{console.log(` ${h+1}. ${u.name} (${u.id})`)}),console.log(""),(await I(s,"Add another organization? (y/N): ")).toLowerCase()!=="y")){console.log(`
27
- Configuration unchanged.`),s.close();return}let e=await I(s,"Organization name: ");if(!e){console.error("Organization name is required"),s.close();return}let n=await I(s,"API Key: ");if(!n){console.error("API Key is required"),s.close();return}let o=await I(s,`API URL (${x}): `)||x,r,l=n.match(/^fd_key_([^_]+)_/);l?r=l[1]:r=`org_${Date.now()}`;let a={id:r,name:e,apiKey:n,apiUrl:o};console.log(`
28
- Testing connection...`);try{let c=await fetch(`${o}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:"{ __typename }"})});if(!c.ok)throw new Error(`API returned ${c.status}`);console.log("\u2705 Connection successful!")}catch(c){if(console.error(`\u274C Connection failed: ${c}`),(await I(s,"Save configuration anyway? (y/N): ")).toLowerCase()!=="y"){s.close();return}}if(H(a),t.organizations.length>0&&(await I(s,"Set as default organization? (y/N): ")).toLowerCase()==="y"){let u=g();u.defaultOrganization=r,b(u)}console.log(`
29
- \u2705 Configuration saved to ${D}`),console.log(`
30
- You can now use:`),console.log(' flightdesk task create -p <project-id> -t "Task title"'),console.log(" flightdesk status"),console.log(" flightdesk watch")}finally{s.close()}}var It=C(require("path")),Tt=C(require("os")),j=C(require("fs")),st=null,R=It.join(Tt.homedir(),".flightdesk","chromium-profile");async function E(){try{return st=await import("playwright"),!0}catch{return!1}}function pe(){j.existsSync(R)||j.mkdirSync(R,{recursive:!0})}async function rt(s){if(!st)throw new Error("Playwright not available");pe();let t=await st.chromium.launchPersistentContext(R,{headless:s,viewport:{width:1280,height:720},userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"});return{browser:t.browser(),context:t}}async function N(){if(!await E())throw new Error("Playwright not installed");let{context:s}=await rt(!0);try{let t=await s.newPage();await t.goto("https://claude.ai/",{waitUntil:"domcontentloaded"});let e=t.url();return!e.includes("/login")&&!e.includes("/oauth")}finally{await s.close()}}async function St(){if(!await E())throw new Error("Playwright not installed");console.log("Opening browser for Claude login..."),console.log("Please log in, then close the browser window.");let{context:s}=await rt(!1);try{await(await s.newPage()).goto("https://claude.ai/",{waitUntil:"domcontentloaded"}),await new Promise(e=>{s.on("close",()=>e())}),console.log("Browser closed. Checking login status...")}finally{try{await s.close()}catch{}}}async function Dt(s,t={}){if(!await E())return{status:"error",error:"Playwright not installed"};let{headless:e=!0,timeout:n=3e4,autoPr:i=!1}=t,{context:o}=await rt(e);try{let r=await o.newPage();r.setDefaultTimeout(n),await r.goto(s,{waitUntil:"domcontentloaded"}),await r.waitForTimeout(2e3);let l={status:"active"};if(await r.$("text=This session has been archived"))return{status:"archived"};let c=r.url();if(c.includes("/login")||c.includes("/oauth"))return{status:"error",error:"Not logged in to Claude. Run: flightdesk auth"};let u=await ge(r);u&&(l.branchName=u);let h=await r.$('button:has-text("Create PR"), button:has-text("Create Pull Request"), button:has-text("Open PR")');if(l.hasPrButton=!!h,i&&h){console.log(' Clicking "Create PR" button...'),await h.click(),await r.waitForTimeout(5e3);let m=await me(r);m&&(l.prUrl=m)}return l}catch(r){return{status:"error",error:r instanceof Error?r.message:String(r)}}finally{await o.close()}}async function ge(s){let t=['[data-testid="branch-name"]',".branch-name","text=/\\b(feature|fix|bugfix|hotfix|release|develop|main|master)\\/[\\w-]+/i"];for(let e of t)try{let n=await s.$(e);if(n){let i=await n.textContent();if(i){let o=i.trim();if(o&&!o.includes(" "))return o}}}catch{}try{let e=await s.content(),n=[/(?:branch|checkout|switched to)[:\s]+['"]?([a-zA-Z0-9/_-]+)['"]?/i,/(?:On branch|HEAD -> )\s*([a-zA-Z0-9/_-]+)/i,/\[([a-zA-Z0-9/_-]+)\]/];for(let i of n){let o=e.match(i);if(o&&o[1]){let r=o[1].trim();if(r.length>2&&r.length<100&&!r.includes("<"))return r}}}catch{}return null}async function me(s){let t=['a[href*="github.com"][href*="/pull/"]','a[href*="gitlab.com"][href*="/merge_requests/"]','a[href*="bitbucket.org"][href*="/pull-requests/"]'];for(let e of t)try{let n=await s.$(e);if(n){let i=await n.getAttribute("href");if(i)return i}}catch{}try{let e=await s.content(),n=[/(https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/,/(https:\/\/gitlab\.com\/[^/]+\/[^/]+\/-\/merge_requests\/\d+)/];for(let i of n){let o=e.match(i);if(o&&o[1])return o[1]}}catch{}return null}async function Rt(){if(console.log(`\u{1F510} FlightDesk Authentication
31
- `),await E()||(console.error("Playwright is not installed."),console.error("Install with: pnpm add playwright && npx playwright install chromium"),process.exit(1)),console.log(`Profile directory: ${R}
32
- `),console.log("Checking current authentication status..."),await N()){console.log("\u2705 Already logged in to Claude!"),console.log(`
33
- The watch daemon will be able to monitor your sessions.`);return}console.log(`\u274C Not logged in to Claude.
34
- `),console.log("Opening browser for login..."),console.log(`Please log in to your Claude account, then close the browser.
35
- `),await St(),console.log(`
36
- Verifying login...`),await N()?(console.log("\u2705 Successfully logged in!"),console.log(`
37
- The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u274C Login was not detected."),console.log("Please try again with: flightdesk auth"))}var _=class{constructor(t){this.apiUrl=t.apiUrl,this.apiKey=t.apiKey}async graphql(t,e){let n=await fetch(`${this.apiUrl}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({query:t,variables:e})});if(!n.ok)throw new Error(`API request failed: ${n.status} ${n.statusText}`);let i=await n.json();if(i.errors&&i.errors.length>0)throw new Error(`GraphQL error: ${i.errors.map(o=>o.message).join(", ")}`);return i.data}async createTask(t){return(await this.graphql(`
1981
+ - ${executableDirMessage}`;
1982
+ throw new Error(executableMissing);
1983
+ } else if (err.code === "EACCES") {
1984
+ throw new Error(`'${executableFile}' not executable`);
1985
+ }
1986
+ if (!exitCallback) {
1987
+ process2.exit(1);
1988
+ } else {
1989
+ const wrappedError = new CommanderError2(
1990
+ 1,
1991
+ "commander.executeSubCommandAsync",
1992
+ "(error)"
1993
+ );
1994
+ wrappedError.nestedError = err;
1995
+ exitCallback(wrappedError);
1996
+ }
1997
+ });
1998
+ this.runningCommand = proc;
1999
+ }
2000
+ /**
2001
+ * @private
2002
+ */
2003
+ _dispatchSubcommand(commandName, operands, unknown) {
2004
+ const subCommand = this._findCommand(commandName);
2005
+ if (!subCommand) this.help({ error: true });
2006
+ let promiseChain;
2007
+ promiseChain = this._chainOrCallSubCommandHook(
2008
+ promiseChain,
2009
+ subCommand,
2010
+ "preSubcommand"
2011
+ );
2012
+ promiseChain = this._chainOrCall(promiseChain, () => {
2013
+ if (subCommand._executableHandler) {
2014
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2015
+ } else {
2016
+ return subCommand._parseCommand(operands, unknown);
2017
+ }
2018
+ });
2019
+ return promiseChain;
2020
+ }
2021
+ /**
2022
+ * Invoke help directly if possible, or dispatch if necessary.
2023
+ * e.g. help foo
2024
+ *
2025
+ * @private
2026
+ */
2027
+ _dispatchHelpCommand(subcommandName) {
2028
+ if (!subcommandName) {
2029
+ this.help();
2030
+ }
2031
+ const subCommand = this._findCommand(subcommandName);
2032
+ if (subCommand && !subCommand._executableHandler) {
2033
+ subCommand.help();
2034
+ }
2035
+ return this._dispatchSubcommand(
2036
+ subcommandName,
2037
+ [],
2038
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2039
+ );
2040
+ }
2041
+ /**
2042
+ * Check this.args against expected this.registeredArguments.
2043
+ *
2044
+ * @private
2045
+ */
2046
+ _checkNumberOfArguments() {
2047
+ this.registeredArguments.forEach((arg, i) => {
2048
+ if (arg.required && this.args[i] == null) {
2049
+ this.missingArgument(arg.name());
2050
+ }
2051
+ });
2052
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2053
+ return;
2054
+ }
2055
+ if (this.args.length > this.registeredArguments.length) {
2056
+ this._excessArguments(this.args);
2057
+ }
2058
+ }
2059
+ /**
2060
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2061
+ *
2062
+ * @private
2063
+ */
2064
+ _processArguments() {
2065
+ const myParseArg = (argument, value, previous) => {
2066
+ let parsedValue = value;
2067
+ if (value !== null && argument.parseArg) {
2068
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2069
+ parsedValue = this._callParseArg(
2070
+ argument,
2071
+ value,
2072
+ previous,
2073
+ invalidValueMessage
2074
+ );
2075
+ }
2076
+ return parsedValue;
2077
+ };
2078
+ this._checkNumberOfArguments();
2079
+ const processedArgs = [];
2080
+ this.registeredArguments.forEach((declaredArg, index) => {
2081
+ let value = declaredArg.defaultValue;
2082
+ if (declaredArg.variadic) {
2083
+ if (index < this.args.length) {
2084
+ value = this.args.slice(index);
2085
+ if (declaredArg.parseArg) {
2086
+ value = value.reduce((processed, v) => {
2087
+ return myParseArg(declaredArg, v, processed);
2088
+ }, declaredArg.defaultValue);
2089
+ }
2090
+ } else if (value === void 0) {
2091
+ value = [];
2092
+ }
2093
+ } else if (index < this.args.length) {
2094
+ value = this.args[index];
2095
+ if (declaredArg.parseArg) {
2096
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2097
+ }
2098
+ }
2099
+ processedArgs[index] = value;
2100
+ });
2101
+ this.processedArgs = processedArgs;
2102
+ }
2103
+ /**
2104
+ * Once we have a promise we chain, but call synchronously until then.
2105
+ *
2106
+ * @param {(Promise|undefined)} promise
2107
+ * @param {Function} fn
2108
+ * @return {(Promise|undefined)}
2109
+ * @private
2110
+ */
2111
+ _chainOrCall(promise, fn) {
2112
+ if (promise && promise.then && typeof promise.then === "function") {
2113
+ return promise.then(() => fn());
2114
+ }
2115
+ return fn();
2116
+ }
2117
+ /**
2118
+ *
2119
+ * @param {(Promise|undefined)} promise
2120
+ * @param {string} event
2121
+ * @return {(Promise|undefined)}
2122
+ * @private
2123
+ */
2124
+ _chainOrCallHooks(promise, event) {
2125
+ let result = promise;
2126
+ const hooks = [];
2127
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2128
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2129
+ hooks.push({ hookedCommand, callback });
2130
+ });
2131
+ });
2132
+ if (event === "postAction") {
2133
+ hooks.reverse();
2134
+ }
2135
+ hooks.forEach((hookDetail) => {
2136
+ result = this._chainOrCall(result, () => {
2137
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2138
+ });
2139
+ });
2140
+ return result;
2141
+ }
2142
+ /**
2143
+ *
2144
+ * @param {(Promise|undefined)} promise
2145
+ * @param {Command} subCommand
2146
+ * @param {string} event
2147
+ * @return {(Promise|undefined)}
2148
+ * @private
2149
+ */
2150
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2151
+ let result = promise;
2152
+ if (this._lifeCycleHooks[event] !== void 0) {
2153
+ this._lifeCycleHooks[event].forEach((hook) => {
2154
+ result = this._chainOrCall(result, () => {
2155
+ return hook(this, subCommand);
2156
+ });
2157
+ });
2158
+ }
2159
+ return result;
2160
+ }
2161
+ /**
2162
+ * Process arguments in context of this command.
2163
+ * Returns action result, in case it is a promise.
2164
+ *
2165
+ * @private
2166
+ */
2167
+ _parseCommand(operands, unknown) {
2168
+ const parsed = this.parseOptions(unknown);
2169
+ this._parseOptionsEnv();
2170
+ this._parseOptionsImplied();
2171
+ operands = operands.concat(parsed.operands);
2172
+ unknown = parsed.unknown;
2173
+ this.args = operands.concat(unknown);
2174
+ if (operands && this._findCommand(operands[0])) {
2175
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2176
+ }
2177
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2178
+ return this._dispatchHelpCommand(operands[1]);
2179
+ }
2180
+ if (this._defaultCommandName) {
2181
+ this._outputHelpIfRequested(unknown);
2182
+ return this._dispatchSubcommand(
2183
+ this._defaultCommandName,
2184
+ operands,
2185
+ unknown
2186
+ );
2187
+ }
2188
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2189
+ this.help({ error: true });
2190
+ }
2191
+ this._outputHelpIfRequested(parsed.unknown);
2192
+ this._checkForMissingMandatoryOptions();
2193
+ this._checkForConflictingOptions();
2194
+ const checkForUnknownOptions = () => {
2195
+ if (parsed.unknown.length > 0) {
2196
+ this.unknownOption(parsed.unknown[0]);
2197
+ }
2198
+ };
2199
+ const commandEvent = `command:${this.name()}`;
2200
+ if (this._actionHandler) {
2201
+ checkForUnknownOptions();
2202
+ this._processArguments();
2203
+ let promiseChain;
2204
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2205
+ promiseChain = this._chainOrCall(
2206
+ promiseChain,
2207
+ () => this._actionHandler(this.processedArgs)
2208
+ );
2209
+ if (this.parent) {
2210
+ promiseChain = this._chainOrCall(promiseChain, () => {
2211
+ this.parent.emit(commandEvent, operands, unknown);
2212
+ });
2213
+ }
2214
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2215
+ return promiseChain;
2216
+ }
2217
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2218
+ checkForUnknownOptions();
2219
+ this._processArguments();
2220
+ this.parent.emit(commandEvent, operands, unknown);
2221
+ } else if (operands.length) {
2222
+ if (this._findCommand("*")) {
2223
+ return this._dispatchSubcommand("*", operands, unknown);
2224
+ }
2225
+ if (this.listenerCount("command:*")) {
2226
+ this.emit("command:*", operands, unknown);
2227
+ } else if (this.commands.length) {
2228
+ this.unknownCommand();
2229
+ } else {
2230
+ checkForUnknownOptions();
2231
+ this._processArguments();
2232
+ }
2233
+ } else if (this.commands.length) {
2234
+ checkForUnknownOptions();
2235
+ this.help({ error: true });
2236
+ } else {
2237
+ checkForUnknownOptions();
2238
+ this._processArguments();
2239
+ }
2240
+ }
2241
+ /**
2242
+ * Find matching command.
2243
+ *
2244
+ * @private
2245
+ * @return {Command | undefined}
2246
+ */
2247
+ _findCommand(name) {
2248
+ if (!name) return void 0;
2249
+ return this.commands.find(
2250
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2251
+ );
2252
+ }
2253
+ /**
2254
+ * Return an option matching `arg` if any.
2255
+ *
2256
+ * @param {string} arg
2257
+ * @return {Option}
2258
+ * @package
2259
+ */
2260
+ _findOption(arg) {
2261
+ return this.options.find((option) => option.is(arg));
2262
+ }
2263
+ /**
2264
+ * Display an error message if a mandatory option does not have a value.
2265
+ * Called after checking for help flags in leaf subcommand.
2266
+ *
2267
+ * @private
2268
+ */
2269
+ _checkForMissingMandatoryOptions() {
2270
+ this._getCommandAndAncestors().forEach((cmd) => {
2271
+ cmd.options.forEach((anOption) => {
2272
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2273
+ cmd.missingMandatoryOptionValue(anOption);
2274
+ }
2275
+ });
2276
+ });
2277
+ }
2278
+ /**
2279
+ * Display an error message if conflicting options are used together in this.
2280
+ *
2281
+ * @private
2282
+ */
2283
+ _checkForConflictingLocalOptions() {
2284
+ const definedNonDefaultOptions = this.options.filter((option) => {
2285
+ const optionKey = option.attributeName();
2286
+ if (this.getOptionValue(optionKey) === void 0) {
2287
+ return false;
2288
+ }
2289
+ return this.getOptionValueSource(optionKey) !== "default";
2290
+ });
2291
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2292
+ (option) => option.conflictsWith.length > 0
2293
+ );
2294
+ optionsWithConflicting.forEach((option) => {
2295
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2296
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2297
+ );
2298
+ if (conflictingAndDefined) {
2299
+ this._conflictingOption(option, conflictingAndDefined);
2300
+ }
2301
+ });
2302
+ }
2303
+ /**
2304
+ * Display an error message if conflicting options are used together.
2305
+ * Called after checking for help flags in leaf subcommand.
2306
+ *
2307
+ * @private
2308
+ */
2309
+ _checkForConflictingOptions() {
2310
+ this._getCommandAndAncestors().forEach((cmd) => {
2311
+ cmd._checkForConflictingLocalOptions();
2312
+ });
2313
+ }
2314
+ /**
2315
+ * Parse options from `argv` removing known options,
2316
+ * and return argv split into operands and unknown arguments.
2317
+ *
2318
+ * Examples:
2319
+ *
2320
+ * argv => operands, unknown
2321
+ * --known kkk op => [op], []
2322
+ * op --known kkk => [op], []
2323
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2324
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2325
+ *
2326
+ * @param {string[]} argv
2327
+ * @return {{operands: string[], unknown: string[]}}
2328
+ */
2329
+ parseOptions(argv) {
2330
+ const operands = [];
2331
+ const unknown = [];
2332
+ let dest = operands;
2333
+ const args = argv.slice();
2334
+ function maybeOption(arg) {
2335
+ return arg.length > 1 && arg[0] === "-";
2336
+ }
2337
+ let activeVariadicOption = null;
2338
+ while (args.length) {
2339
+ const arg = args.shift();
2340
+ if (arg === "--") {
2341
+ if (dest === unknown) dest.push(arg);
2342
+ dest.push(...args);
2343
+ break;
2344
+ }
2345
+ if (activeVariadicOption && !maybeOption(arg)) {
2346
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2347
+ continue;
2348
+ }
2349
+ activeVariadicOption = null;
2350
+ if (maybeOption(arg)) {
2351
+ const option = this._findOption(arg);
2352
+ if (option) {
2353
+ if (option.required) {
2354
+ const value = args.shift();
2355
+ if (value === void 0) this.optionMissingArgument(option);
2356
+ this.emit(`option:${option.name()}`, value);
2357
+ } else if (option.optional) {
2358
+ let value = null;
2359
+ if (args.length > 0 && !maybeOption(args[0])) {
2360
+ value = args.shift();
2361
+ }
2362
+ this.emit(`option:${option.name()}`, value);
2363
+ } else {
2364
+ this.emit(`option:${option.name()}`);
2365
+ }
2366
+ activeVariadicOption = option.variadic ? option : null;
2367
+ continue;
2368
+ }
2369
+ }
2370
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2371
+ const option = this._findOption(`-${arg[1]}`);
2372
+ if (option) {
2373
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2374
+ this.emit(`option:${option.name()}`, arg.slice(2));
2375
+ } else {
2376
+ this.emit(`option:${option.name()}`);
2377
+ args.unshift(`-${arg.slice(2)}`);
2378
+ }
2379
+ continue;
2380
+ }
2381
+ }
2382
+ if (/^--[^=]+=/.test(arg)) {
2383
+ const index = arg.indexOf("=");
2384
+ const option = this._findOption(arg.slice(0, index));
2385
+ if (option && (option.required || option.optional)) {
2386
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2387
+ continue;
2388
+ }
2389
+ }
2390
+ if (maybeOption(arg)) {
2391
+ dest = unknown;
2392
+ }
2393
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2394
+ if (this._findCommand(arg)) {
2395
+ operands.push(arg);
2396
+ if (args.length > 0) unknown.push(...args);
2397
+ break;
2398
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2399
+ operands.push(arg);
2400
+ if (args.length > 0) operands.push(...args);
2401
+ break;
2402
+ } else if (this._defaultCommandName) {
2403
+ unknown.push(arg);
2404
+ if (args.length > 0) unknown.push(...args);
2405
+ break;
2406
+ }
2407
+ }
2408
+ if (this._passThroughOptions) {
2409
+ dest.push(arg);
2410
+ if (args.length > 0) dest.push(...args);
2411
+ break;
2412
+ }
2413
+ dest.push(arg);
2414
+ }
2415
+ return { operands, unknown };
2416
+ }
2417
+ /**
2418
+ * Return an object containing local option values as key-value pairs.
2419
+ *
2420
+ * @return {object}
2421
+ */
2422
+ opts() {
2423
+ if (this._storeOptionsAsProperties) {
2424
+ const result = {};
2425
+ const len = this.options.length;
2426
+ for (let i = 0; i < len; i++) {
2427
+ const key = this.options[i].attributeName();
2428
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2429
+ }
2430
+ return result;
2431
+ }
2432
+ return this._optionValues;
2433
+ }
2434
+ /**
2435
+ * Return an object containing merged local and global option values as key-value pairs.
2436
+ *
2437
+ * @return {object}
2438
+ */
2439
+ optsWithGlobals() {
2440
+ return this._getCommandAndAncestors().reduce(
2441
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2442
+ {}
2443
+ );
2444
+ }
2445
+ /**
2446
+ * Display error message and exit (or call exitOverride).
2447
+ *
2448
+ * @param {string} message
2449
+ * @param {object} [errorOptions]
2450
+ * @param {string} [errorOptions.code] - an id string representing the error
2451
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2452
+ */
2453
+ error(message, errorOptions) {
2454
+ this._outputConfiguration.outputError(
2455
+ `${message}
2456
+ `,
2457
+ this._outputConfiguration.writeErr
2458
+ );
2459
+ if (typeof this._showHelpAfterError === "string") {
2460
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2461
+ `);
2462
+ } else if (this._showHelpAfterError) {
2463
+ this._outputConfiguration.writeErr("\n");
2464
+ this.outputHelp({ error: true });
2465
+ }
2466
+ const config = errorOptions || {};
2467
+ const exitCode = config.exitCode || 1;
2468
+ const code = config.code || "commander.error";
2469
+ this._exit(exitCode, code, message);
2470
+ }
2471
+ /**
2472
+ * Apply any option related environment variables, if option does
2473
+ * not have a value from cli or client code.
2474
+ *
2475
+ * @private
2476
+ */
2477
+ _parseOptionsEnv() {
2478
+ this.options.forEach((option) => {
2479
+ if (option.envVar && option.envVar in process2.env) {
2480
+ const optionKey = option.attributeName();
2481
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2482
+ this.getOptionValueSource(optionKey)
2483
+ )) {
2484
+ if (option.required || option.optional) {
2485
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2486
+ } else {
2487
+ this.emit(`optionEnv:${option.name()}`);
2488
+ }
2489
+ }
2490
+ }
2491
+ });
2492
+ }
2493
+ /**
2494
+ * Apply any implied option values, if option is undefined or default value.
2495
+ *
2496
+ * @private
2497
+ */
2498
+ _parseOptionsImplied() {
2499
+ const dualHelper = new DualOptions(this.options);
2500
+ const hasCustomOptionValue = (optionKey) => {
2501
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2502
+ };
2503
+ this.options.filter(
2504
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2505
+ this.getOptionValue(option.attributeName()),
2506
+ option
2507
+ )
2508
+ ).forEach((option) => {
2509
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2510
+ this.setOptionValueWithSource(
2511
+ impliedKey,
2512
+ option.implied[impliedKey],
2513
+ "implied"
2514
+ );
2515
+ });
2516
+ });
2517
+ }
2518
+ /**
2519
+ * Argument `name` is missing.
2520
+ *
2521
+ * @param {string} name
2522
+ * @private
2523
+ */
2524
+ missingArgument(name) {
2525
+ const message = `error: missing required argument '${name}'`;
2526
+ this.error(message, { code: "commander.missingArgument" });
2527
+ }
2528
+ /**
2529
+ * `Option` is missing an argument.
2530
+ *
2531
+ * @param {Option} option
2532
+ * @private
2533
+ */
2534
+ optionMissingArgument(option) {
2535
+ const message = `error: option '${option.flags}' argument missing`;
2536
+ this.error(message, { code: "commander.optionMissingArgument" });
2537
+ }
2538
+ /**
2539
+ * `Option` does not have a value, and is a mandatory option.
2540
+ *
2541
+ * @param {Option} option
2542
+ * @private
2543
+ */
2544
+ missingMandatoryOptionValue(option) {
2545
+ const message = `error: required option '${option.flags}' not specified`;
2546
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2547
+ }
2548
+ /**
2549
+ * `Option` conflicts with another option.
2550
+ *
2551
+ * @param {Option} option
2552
+ * @param {Option} conflictingOption
2553
+ * @private
2554
+ */
2555
+ _conflictingOption(option, conflictingOption) {
2556
+ const findBestOptionFromValue = (option2) => {
2557
+ const optionKey = option2.attributeName();
2558
+ const optionValue = this.getOptionValue(optionKey);
2559
+ const negativeOption = this.options.find(
2560
+ (target) => target.negate && optionKey === target.attributeName()
2561
+ );
2562
+ const positiveOption = this.options.find(
2563
+ (target) => !target.negate && optionKey === target.attributeName()
2564
+ );
2565
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2566
+ return negativeOption;
2567
+ }
2568
+ return positiveOption || option2;
2569
+ };
2570
+ const getErrorMessage = (option2) => {
2571
+ const bestOption = findBestOptionFromValue(option2);
2572
+ const optionKey = bestOption.attributeName();
2573
+ const source = this.getOptionValueSource(optionKey);
2574
+ if (source === "env") {
2575
+ return `environment variable '${bestOption.envVar}'`;
2576
+ }
2577
+ return `option '${bestOption.flags}'`;
2578
+ };
2579
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2580
+ this.error(message, { code: "commander.conflictingOption" });
2581
+ }
2582
+ /**
2583
+ * Unknown option `flag`.
2584
+ *
2585
+ * @param {string} flag
2586
+ * @private
2587
+ */
2588
+ unknownOption(flag) {
2589
+ if (this._allowUnknownOption) return;
2590
+ let suggestion = "";
2591
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2592
+ let candidateFlags = [];
2593
+ let command = this;
2594
+ do {
2595
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2596
+ candidateFlags = candidateFlags.concat(moreFlags);
2597
+ command = command.parent;
2598
+ } while (command && !command._enablePositionalOptions);
2599
+ suggestion = suggestSimilar(flag, candidateFlags);
2600
+ }
2601
+ const message = `error: unknown option '${flag}'${suggestion}`;
2602
+ this.error(message, { code: "commander.unknownOption" });
2603
+ }
2604
+ /**
2605
+ * Excess arguments, more than expected.
2606
+ *
2607
+ * @param {string[]} receivedArgs
2608
+ * @private
2609
+ */
2610
+ _excessArguments(receivedArgs) {
2611
+ if (this._allowExcessArguments) return;
2612
+ const expected = this.registeredArguments.length;
2613
+ const s = expected === 1 ? "" : "s";
2614
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2615
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2616
+ this.error(message, { code: "commander.excessArguments" });
2617
+ }
2618
+ /**
2619
+ * Unknown command.
2620
+ *
2621
+ * @private
2622
+ */
2623
+ unknownCommand() {
2624
+ const unknownName = this.args[0];
2625
+ let suggestion = "";
2626
+ if (this._showSuggestionAfterError) {
2627
+ const candidateNames = [];
2628
+ this.createHelp().visibleCommands(this).forEach((command) => {
2629
+ candidateNames.push(command.name());
2630
+ if (command.alias()) candidateNames.push(command.alias());
2631
+ });
2632
+ suggestion = suggestSimilar(unknownName, candidateNames);
2633
+ }
2634
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2635
+ this.error(message, { code: "commander.unknownCommand" });
2636
+ }
2637
+ /**
2638
+ * Get or set the program version.
2639
+ *
2640
+ * This method auto-registers the "-V, --version" option which will print the version number.
2641
+ *
2642
+ * You can optionally supply the flags and description to override the defaults.
2643
+ *
2644
+ * @param {string} [str]
2645
+ * @param {string} [flags]
2646
+ * @param {string} [description]
2647
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2648
+ */
2649
+ version(str, flags, description) {
2650
+ if (str === void 0) return this._version;
2651
+ this._version = str;
2652
+ flags = flags || "-V, --version";
2653
+ description = description || "output the version number";
2654
+ const versionOption = this.createOption(flags, description);
2655
+ this._versionOptionName = versionOption.attributeName();
2656
+ this._registerOption(versionOption);
2657
+ this.on("option:" + versionOption.name(), () => {
2658
+ this._outputConfiguration.writeOut(`${str}
2659
+ `);
2660
+ this._exit(0, "commander.version", str);
2661
+ });
2662
+ return this;
2663
+ }
2664
+ /**
2665
+ * Set the description.
2666
+ *
2667
+ * @param {string} [str]
2668
+ * @param {object} [argsDescription]
2669
+ * @return {(string|Command)}
2670
+ */
2671
+ description(str, argsDescription) {
2672
+ if (str === void 0 && argsDescription === void 0)
2673
+ return this._description;
2674
+ this._description = str;
2675
+ if (argsDescription) {
2676
+ this._argsDescription = argsDescription;
2677
+ }
2678
+ return this;
2679
+ }
2680
+ /**
2681
+ * Set the summary. Used when listed as subcommand of parent.
2682
+ *
2683
+ * @param {string} [str]
2684
+ * @return {(string|Command)}
2685
+ */
2686
+ summary(str) {
2687
+ if (str === void 0) return this._summary;
2688
+ this._summary = str;
2689
+ return this;
2690
+ }
2691
+ /**
2692
+ * Set an alias for the command.
2693
+ *
2694
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2695
+ *
2696
+ * @param {string} [alias]
2697
+ * @return {(string|Command)}
2698
+ */
2699
+ alias(alias) {
2700
+ if (alias === void 0) return this._aliases[0];
2701
+ let command = this;
2702
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2703
+ command = this.commands[this.commands.length - 1];
2704
+ }
2705
+ if (alias === command._name)
2706
+ throw new Error("Command alias can't be the same as its name");
2707
+ const matchingCommand = this.parent?._findCommand(alias);
2708
+ if (matchingCommand) {
2709
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2710
+ throw new Error(
2711
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2712
+ );
2713
+ }
2714
+ command._aliases.push(alias);
2715
+ return this;
2716
+ }
2717
+ /**
2718
+ * Set aliases for the command.
2719
+ *
2720
+ * Only the first alias is shown in the auto-generated help.
2721
+ *
2722
+ * @param {string[]} [aliases]
2723
+ * @return {(string[]|Command)}
2724
+ */
2725
+ aliases(aliases) {
2726
+ if (aliases === void 0) return this._aliases;
2727
+ aliases.forEach((alias) => this.alias(alias));
2728
+ return this;
2729
+ }
2730
+ /**
2731
+ * Set / get the command usage `str`.
2732
+ *
2733
+ * @param {string} [str]
2734
+ * @return {(string|Command)}
2735
+ */
2736
+ usage(str) {
2737
+ if (str === void 0) {
2738
+ if (this._usage) return this._usage;
2739
+ const args = this.registeredArguments.map((arg) => {
2740
+ return humanReadableArgName(arg);
2741
+ });
2742
+ return [].concat(
2743
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2744
+ this.commands.length ? "[command]" : [],
2745
+ this.registeredArguments.length ? args : []
2746
+ ).join(" ");
2747
+ }
2748
+ this._usage = str;
2749
+ return this;
2750
+ }
2751
+ /**
2752
+ * Get or set the name of the command.
2753
+ *
2754
+ * @param {string} [str]
2755
+ * @return {(string|Command)}
2756
+ */
2757
+ name(str) {
2758
+ if (str === void 0) return this._name;
2759
+ this._name = str;
2760
+ return this;
2761
+ }
2762
+ /**
2763
+ * Set the name of the command from script filename, such as process.argv[1],
2764
+ * or require.main.filename, or __filename.
2765
+ *
2766
+ * (Used internally and public although not documented in README.)
2767
+ *
2768
+ * @example
2769
+ * program.nameFromFilename(require.main.filename);
2770
+ *
2771
+ * @param {string} filename
2772
+ * @return {Command}
2773
+ */
2774
+ nameFromFilename(filename) {
2775
+ this._name = path3.basename(filename, path3.extname(filename));
2776
+ return this;
2777
+ }
2778
+ /**
2779
+ * Get or set the directory for searching for executable subcommands of this command.
2780
+ *
2781
+ * @example
2782
+ * program.executableDir(__dirname);
2783
+ * // or
2784
+ * program.executableDir('subcommands');
2785
+ *
2786
+ * @param {string} [path]
2787
+ * @return {(string|null|Command)}
2788
+ */
2789
+ executableDir(path4) {
2790
+ if (path4 === void 0) return this._executableDir;
2791
+ this._executableDir = path4;
2792
+ return this;
2793
+ }
2794
+ /**
2795
+ * Return program help documentation.
2796
+ *
2797
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2798
+ * @return {string}
2799
+ */
2800
+ helpInformation(contextOptions) {
2801
+ const helper = this.createHelp();
2802
+ if (helper.helpWidth === void 0) {
2803
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2804
+ }
2805
+ return helper.formatHelp(this, helper);
2806
+ }
2807
+ /**
2808
+ * @private
2809
+ */
2810
+ _getHelpContext(contextOptions) {
2811
+ contextOptions = contextOptions || {};
2812
+ const context = { error: !!contextOptions.error };
2813
+ let write;
2814
+ if (context.error) {
2815
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2816
+ } else {
2817
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2818
+ }
2819
+ context.write = contextOptions.write || write;
2820
+ context.command = this;
2821
+ return context;
2822
+ }
2823
+ /**
2824
+ * Output help information for this command.
2825
+ *
2826
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2827
+ *
2828
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2829
+ */
2830
+ outputHelp(contextOptions) {
2831
+ let deprecatedCallback;
2832
+ if (typeof contextOptions === "function") {
2833
+ deprecatedCallback = contextOptions;
2834
+ contextOptions = void 0;
2835
+ }
2836
+ const context = this._getHelpContext(contextOptions);
2837
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2838
+ this.emit("beforeHelp", context);
2839
+ let helpInformation = this.helpInformation(context);
2840
+ if (deprecatedCallback) {
2841
+ helpInformation = deprecatedCallback(helpInformation);
2842
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2843
+ throw new Error("outputHelp callback must return a string or a Buffer");
2844
+ }
2845
+ }
2846
+ context.write(helpInformation);
2847
+ if (this._getHelpOption()?.long) {
2848
+ this.emit(this._getHelpOption().long);
2849
+ }
2850
+ this.emit("afterHelp", context);
2851
+ this._getCommandAndAncestors().forEach(
2852
+ (command) => command.emit("afterAllHelp", context)
2853
+ );
2854
+ }
2855
+ /**
2856
+ * You can pass in flags and a description to customise the built-in help option.
2857
+ * Pass in false to disable the built-in help option.
2858
+ *
2859
+ * @example
2860
+ * program.helpOption('-?, --help' 'show help'); // customise
2861
+ * program.helpOption(false); // disable
2862
+ *
2863
+ * @param {(string | boolean)} flags
2864
+ * @param {string} [description]
2865
+ * @return {Command} `this` command for chaining
2866
+ */
2867
+ helpOption(flags, description) {
2868
+ if (typeof flags === "boolean") {
2869
+ if (flags) {
2870
+ this._helpOption = this._helpOption ?? void 0;
2871
+ } else {
2872
+ this._helpOption = null;
2873
+ }
2874
+ return this;
2875
+ }
2876
+ flags = flags ?? "-h, --help";
2877
+ description = description ?? "display help for command";
2878
+ this._helpOption = this.createOption(flags, description);
2879
+ return this;
2880
+ }
2881
+ /**
2882
+ * Lazy create help option.
2883
+ * Returns null if has been disabled with .helpOption(false).
2884
+ *
2885
+ * @returns {(Option | null)} the help option
2886
+ * @package
2887
+ */
2888
+ _getHelpOption() {
2889
+ if (this._helpOption === void 0) {
2890
+ this.helpOption(void 0, void 0);
2891
+ }
2892
+ return this._helpOption;
2893
+ }
2894
+ /**
2895
+ * Supply your own option to use for the built-in help option.
2896
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2897
+ *
2898
+ * @param {Option} option
2899
+ * @return {Command} `this` command for chaining
2900
+ */
2901
+ addHelpOption(option) {
2902
+ this._helpOption = option;
2903
+ return this;
2904
+ }
2905
+ /**
2906
+ * Output help information and exit.
2907
+ *
2908
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2909
+ *
2910
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2911
+ */
2912
+ help(contextOptions) {
2913
+ this.outputHelp(contextOptions);
2914
+ let exitCode = process2.exitCode || 0;
2915
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2916
+ exitCode = 1;
2917
+ }
2918
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2919
+ }
2920
+ /**
2921
+ * Add additional text to be displayed with the built-in help.
2922
+ *
2923
+ * Position is 'before' or 'after' to affect just this command,
2924
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2925
+ *
2926
+ * @param {string} position - before or after built-in help
2927
+ * @param {(string | Function)} text - string to add, or a function returning a string
2928
+ * @return {Command} `this` command for chaining
2929
+ */
2930
+ addHelpText(position, text) {
2931
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2932
+ if (!allowedValues.includes(position)) {
2933
+ throw new Error(`Unexpected value for position to addHelpText.
2934
+ Expecting one of '${allowedValues.join("', '")}'`);
2935
+ }
2936
+ const helpEvent = `${position}Help`;
2937
+ this.on(helpEvent, (context) => {
2938
+ let helpStr;
2939
+ if (typeof text === "function") {
2940
+ helpStr = text({ error: context.error, command: context.command });
2941
+ } else {
2942
+ helpStr = text;
2943
+ }
2944
+ if (helpStr) {
2945
+ context.write(`${helpStr}
2946
+ `);
2947
+ }
2948
+ });
2949
+ return this;
2950
+ }
2951
+ /**
2952
+ * Output help information if help flags specified
2953
+ *
2954
+ * @param {Array} args - array of options to search for help flags
2955
+ * @private
2956
+ */
2957
+ _outputHelpIfRequested(args) {
2958
+ const helpOption = this._getHelpOption();
2959
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2960
+ if (helpRequested) {
2961
+ this.outputHelp();
2962
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2963
+ }
2964
+ }
2965
+ };
2966
+ function incrementNodeInspectorPort(args) {
2967
+ return args.map((arg) => {
2968
+ if (!arg.startsWith("--inspect")) {
2969
+ return arg;
2970
+ }
2971
+ let debugOption;
2972
+ let debugHost = "127.0.0.1";
2973
+ let debugPort = "9229";
2974
+ let match;
2975
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2976
+ debugOption = match[1];
2977
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2978
+ debugOption = match[1];
2979
+ if (/^\d+$/.test(match[3])) {
2980
+ debugPort = match[3];
2981
+ } else {
2982
+ debugHost = match[3];
2983
+ }
2984
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2985
+ debugOption = match[1];
2986
+ debugHost = match[3];
2987
+ debugPort = match[4];
2988
+ }
2989
+ if (debugOption && debugPort !== "0") {
2990
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2991
+ }
2992
+ return arg;
2993
+ });
2994
+ }
2995
+ exports2.Command = Command2;
2996
+ }
2997
+ });
2998
+
2999
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js
3000
+ var require_commander = __commonJS({
3001
+ "node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js"(exports2) {
3002
+ var { Argument: Argument2 } = require_argument();
3003
+ var { Command: Command2 } = require_command();
3004
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3005
+ var { Help: Help2 } = require_help();
3006
+ var { Option: Option2 } = require_option();
3007
+ exports2.program = new Command2();
3008
+ exports2.createCommand = (name) => new Command2(name);
3009
+ exports2.createOption = (flags, description) => new Option2(flags, description);
3010
+ exports2.createArgument = (name, description) => new Argument2(name, description);
3011
+ exports2.Command = Command2;
3012
+ exports2.Option = Option2;
3013
+ exports2.Argument = Argument2;
3014
+ exports2.Help = Help2;
3015
+ exports2.CommanderError = CommanderError2;
3016
+ exports2.InvalidArgumentError = InvalidArgumentError2;
3017
+ exports2.InvalidOptionArgumentError = InvalidArgumentError2;
3018
+ }
3019
+ });
3020
+
3021
+ // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
3022
+ var import_index = __toESM(require_commander(), 1);
3023
+ var {
3024
+ program,
3025
+ createCommand,
3026
+ createArgument,
3027
+ createOption,
3028
+ CommanderError,
3029
+ InvalidArgumentError,
3030
+ InvalidOptionArgumentError,
3031
+ // deprecated old name
3032
+ Command,
3033
+ Argument,
3034
+ Option,
3035
+ Help
3036
+ } = import_index.default;
3037
+
3038
+ // apps/cli/src/commands/init.ts
3039
+ var readline = __toESM(require("readline"));
3040
+
3041
+ // apps/cli/src/lib/config.ts
3042
+ var fs = __toESM(require("fs"));
3043
+ var path = __toESM(require("path"));
3044
+ var os = __toESM(require("os"));
3045
+ var CONFIG_FILE = path.join(os.homedir(), ".flightdeskrc");
3046
+ var DEFAULT_API_URL = "https://flightdesk.dev/api";
3047
+ function loadConfig() {
3048
+ try {
3049
+ if (fs.existsSync(CONFIG_FILE)) {
3050
+ const content = fs.readFileSync(CONFIG_FILE, "utf-8");
3051
+ return JSON.parse(content);
3052
+ }
3053
+ } catch (error) {
3054
+ console.error("Warning: Failed to load config file:", error);
3055
+ }
3056
+ return {
3057
+ organizations: [],
3058
+ repoMapping: {}
3059
+ };
3060
+ }
3061
+ function saveConfig(config) {
3062
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
3063
+ }
3064
+ function getDefaultOrganization() {
3065
+ const config = loadConfig();
3066
+ if (config.defaultOrganization) {
3067
+ return config.organizations.find((o) => o.id === config.defaultOrganization) || null;
3068
+ }
3069
+ if (config.organizations.length === 1) {
3070
+ return config.organizations[0];
3071
+ }
3072
+ return null;
3073
+ }
3074
+ function getOrganizationByRepo(repoFullName) {
3075
+ const config = loadConfig();
3076
+ const orgId = config.repoMapping[repoFullName];
3077
+ if (orgId) {
3078
+ return config.organizations.find((o) => o.id === orgId) || null;
3079
+ }
3080
+ return null;
3081
+ }
3082
+ function addOrganization(org2) {
3083
+ const config = loadConfig();
3084
+ const existingIndex = config.organizations.findIndex((o) => o.id === org2.id);
3085
+ if (existingIndex >= 0) {
3086
+ config.organizations[existingIndex] = org2;
3087
+ } else {
3088
+ config.organizations.push(org2);
3089
+ }
3090
+ if (config.organizations.length === 1) {
3091
+ config.defaultOrganization = org2.id;
3092
+ }
3093
+ saveConfig(config);
3094
+ }
3095
+ function removeOrganization(orgId) {
3096
+ const config = loadConfig();
3097
+ config.organizations = config.organizations.filter((o) => o.id !== orgId);
3098
+ for (const [repo, mappedOrgId] of Object.entries(config.repoMapping)) {
3099
+ if (mappedOrgId === orgId) {
3100
+ delete config.repoMapping[repo];
3101
+ }
3102
+ }
3103
+ if (config.defaultOrganization === orgId) {
3104
+ config.defaultOrganization = config.organizations[0]?.id;
3105
+ }
3106
+ saveConfig(config);
3107
+ }
3108
+ function isConfigured() {
3109
+ const config = loadConfig();
3110
+ return config.organizations.length > 0;
3111
+ }
3112
+
3113
+ // apps/cli/src/commands/init.ts
3114
+ function question(rl, prompt) {
3115
+ return new Promise((resolve) => {
3116
+ rl.question(prompt, (answer) => {
3117
+ resolve(answer.trim());
3118
+ });
3119
+ });
3120
+ }
3121
+ async function initCommand() {
3122
+ const rl = readline.createInterface({
3123
+ input: process.stdin,
3124
+ output: process.stdout
3125
+ });
3126
+ console.log("\n\u{1F6EB} FlightDesk CLI Setup\n");
3127
+ try {
3128
+ const config = loadConfig();
3129
+ if (config.organizations.length > 0) {
3130
+ console.log("Existing organizations configured:");
3131
+ config.organizations.forEach((org3, i) => {
3132
+ console.log(` ${i + 1}. ${org3.name} (${org3.id})`);
3133
+ });
3134
+ console.log("");
3135
+ const addMore = await question(rl, "Add another organization? (y/N): ");
3136
+ if (addMore.toLowerCase() !== "y") {
3137
+ console.log("\nConfiguration unchanged.");
3138
+ rl.close();
3139
+ return;
3140
+ }
3141
+ }
3142
+ const orgName = await question(rl, "Organization name: ");
3143
+ if (!orgName) {
3144
+ console.error("Organization name is required");
3145
+ rl.close();
3146
+ return;
3147
+ }
3148
+ const apiKey = await question(rl, "API Key: ");
3149
+ if (!apiKey) {
3150
+ console.error("API Key is required");
3151
+ rl.close();
3152
+ return;
3153
+ }
3154
+ const apiUrlInput = await question(rl, `API URL (${DEFAULT_API_URL}): `);
3155
+ const apiUrl = apiUrlInput || DEFAULT_API_URL;
3156
+ let orgId;
3157
+ const keyMatch = apiKey.match(/^fd_key_([^_]+)_/);
3158
+ if (keyMatch) {
3159
+ orgId = keyMatch[1];
3160
+ } else {
3161
+ orgId = `org_${Date.now()}`;
3162
+ }
3163
+ const org2 = {
3164
+ id: orgId,
3165
+ name: orgName,
3166
+ apiKey,
3167
+ apiUrl
3168
+ };
3169
+ console.log("\nTesting connection...");
3170
+ try {
3171
+ const response = await fetch(`${apiUrl}/graphql`, {
3172
+ method: "POST",
3173
+ headers: {
3174
+ "Content-Type": "application/json",
3175
+ "Authorization": `Bearer ${apiKey}`
3176
+ },
3177
+ body: JSON.stringify({
3178
+ query: "{ __typename }"
3179
+ })
3180
+ });
3181
+ if (!response.ok) {
3182
+ throw new Error(`API returned ${response.status}`);
3183
+ }
3184
+ console.log("\u2705 Connection successful!");
3185
+ } catch (error) {
3186
+ console.error(`\u274C Connection failed: ${error}`);
3187
+ const proceed = await question(rl, "Save configuration anyway? (y/N): ");
3188
+ if (proceed.toLowerCase() !== "y") {
3189
+ rl.close();
3190
+ return;
3191
+ }
3192
+ }
3193
+ addOrganization(org2);
3194
+ if (config.organizations.length > 0) {
3195
+ const setDefault = await question(rl, "Set as default organization? (y/N): ");
3196
+ if (setDefault.toLowerCase() === "y") {
3197
+ const updatedConfig = loadConfig();
3198
+ updatedConfig.defaultOrganization = orgId;
3199
+ saveConfig(updatedConfig);
3200
+ }
3201
+ }
3202
+ console.log(`
3203
+ \u2705 Configuration saved to ${CONFIG_FILE}`);
3204
+ console.log("\nYou can now use:");
3205
+ console.log(' flightdesk task create -p <project-id> -t "Task title"');
3206
+ console.log(" flightdesk status");
3207
+ console.log(" flightdesk watch");
3208
+ } finally {
3209
+ rl.close();
3210
+ }
3211
+ }
3212
+
3213
+ // apps/cli/src/lib/session-monitor.ts
3214
+ var path2 = __toESM(require("path"));
3215
+ var os2 = __toESM(require("os"));
3216
+ var fs2 = __toESM(require("fs"));
3217
+ var playwright = null;
3218
+ var USER_DATA_DIR = path2.join(os2.homedir(), ".flightdesk", "chromium-profile");
3219
+ async function isPlaywrightAvailable() {
3220
+ try {
3221
+ playwright = await import("playwright");
3222
+ return true;
3223
+ } catch {
3224
+ return false;
3225
+ }
3226
+ }
3227
+ function ensureUserDataDir() {
3228
+ if (!fs2.existsSync(USER_DATA_DIR)) {
3229
+ fs2.mkdirSync(USER_DATA_DIR, { recursive: true });
3230
+ }
3231
+ }
3232
+ async function launchBrowser(headless) {
3233
+ if (!playwright) {
3234
+ throw new Error("Playwright not available");
3235
+ }
3236
+ ensureUserDataDir();
3237
+ const context = await playwright.chromium.launchPersistentContext(USER_DATA_DIR, {
3238
+ headless,
3239
+ viewport: { width: 1280, height: 720 },
3240
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
3241
+ });
3242
+ const browser = context.browser();
3243
+ return { browser, context };
3244
+ }
3245
+ async function checkAuth() {
3246
+ if (!await isPlaywrightAvailable()) {
3247
+ throw new Error("Playwright not installed");
3248
+ }
3249
+ const { context } = await launchBrowser(true);
3250
+ try {
3251
+ const page = await context.newPage();
3252
+ await page.goto("https://claude.ai/", { waitUntil: "domcontentloaded" });
3253
+ const url = page.url();
3254
+ const isLoggedIn = !url.includes("/login") && !url.includes("/oauth");
3255
+ return isLoggedIn;
3256
+ } finally {
3257
+ await context.close();
3258
+ }
3259
+ }
3260
+ async function openForLogin() {
3261
+ if (!await isPlaywrightAvailable()) {
3262
+ throw new Error("Playwright not installed");
3263
+ }
3264
+ console.log("Opening browser for Claude login...");
3265
+ console.log("Please log in, then close the browser window.");
3266
+ const { context } = await launchBrowser(false);
3267
+ try {
3268
+ const page = await context.newPage();
3269
+ await page.goto("https://claude.ai/", { waitUntil: "domcontentloaded" });
3270
+ await new Promise((resolve) => {
3271
+ context.on("close", () => resolve());
3272
+ });
3273
+ console.log("Browser closed. Checking login status...");
3274
+ } finally {
3275
+ try {
3276
+ await context.close();
3277
+ } catch {
3278
+ }
3279
+ }
3280
+ }
3281
+ async function monitorSession(sessionUrl, options = {}) {
3282
+ if (!await isPlaywrightAvailable()) {
3283
+ return { status: "error", error: "Playwright not installed" };
3284
+ }
3285
+ const { headless = true, timeout = 3e4, autoPr = false } = options;
3286
+ const { context } = await launchBrowser(headless);
3287
+ try {
3288
+ const page = await context.newPage();
3289
+ page.setDefaultTimeout(timeout);
3290
+ await page.goto(sessionUrl, { waitUntil: "domcontentloaded" });
3291
+ await page.waitForTimeout(2e3);
3292
+ const result = { status: "active" };
3293
+ const archiveIndicator = await page.$("text=This session has been archived");
3294
+ if (archiveIndicator) {
3295
+ return { status: "archived" };
3296
+ }
3297
+ const url = page.url();
3298
+ if (url.includes("/login") || url.includes("/oauth")) {
3299
+ return {
3300
+ status: "error",
3301
+ error: "Not logged in to Claude. Run: flightdesk auth"
3302
+ };
3303
+ }
3304
+ const branchName = await extractBranchName(page);
3305
+ if (branchName) {
3306
+ result.branchName = branchName;
3307
+ }
3308
+ const prButton = await page.$('button:has-text("Create PR"), button:has-text("Create Pull Request"), button:has-text("Open PR")');
3309
+ result.hasPrButton = !!prButton;
3310
+ if (autoPr && prButton) {
3311
+ console.log(' Clicking "Create PR" button...');
3312
+ await prButton.click();
3313
+ await page.waitForTimeout(5e3);
3314
+ const prUrl = await extractPrUrl(page);
3315
+ if (prUrl) {
3316
+ result.prUrl = prUrl;
3317
+ }
3318
+ }
3319
+ return result;
3320
+ } catch (error) {
3321
+ return {
3322
+ status: "error",
3323
+ error: error instanceof Error ? error.message : String(error)
3324
+ };
3325
+ } finally {
3326
+ await context.close();
3327
+ }
3328
+ }
3329
+ async function extractBranchName(page) {
3330
+ const selectors = [
3331
+ // Look for git branch indicators
3332
+ '[data-testid="branch-name"]',
3333
+ ".branch-name",
3334
+ // Look for text patterns
3335
+ "text=/\\b(feature|fix|bugfix|hotfix|release|develop|main|master)\\/[\\w-]+/i"
3336
+ ];
3337
+ for (const selector of selectors) {
3338
+ try {
3339
+ const element = await page.$(selector);
3340
+ if (element) {
3341
+ const text = await element.textContent();
3342
+ if (text) {
3343
+ const cleaned = text.trim();
3344
+ if (cleaned && !cleaned.includes(" ")) {
3345
+ return cleaned;
3346
+ }
3347
+ }
3348
+ }
3349
+ } catch {
3350
+ }
3351
+ }
3352
+ try {
3353
+ const pageContent = await page.content();
3354
+ const branchPatterns = [
3355
+ /(?:branch|checkout|switched to)[:\s]+['"]?([a-zA-Z0-9/_-]+)['"]?/i,
3356
+ /(?:On branch|HEAD -> )\s*([a-zA-Z0-9/_-]+)/i,
3357
+ /\[([a-zA-Z0-9/_-]+)\]/
3358
+ ];
3359
+ for (const pattern of branchPatterns) {
3360
+ const match = pageContent.match(pattern);
3361
+ if (match && match[1]) {
3362
+ const branch = match[1].trim();
3363
+ if (branch.length > 2 && branch.length < 100 && !branch.includes("<")) {
3364
+ return branch;
3365
+ }
3366
+ }
3367
+ }
3368
+ } catch {
3369
+ }
3370
+ return null;
3371
+ }
3372
+ async function extractPrUrl(page) {
3373
+ const selectors = [
3374
+ 'a[href*="github.com"][href*="/pull/"]',
3375
+ 'a[href*="gitlab.com"][href*="/merge_requests/"]',
3376
+ 'a[href*="bitbucket.org"][href*="/pull-requests/"]'
3377
+ ];
3378
+ for (const selector of selectors) {
3379
+ try {
3380
+ const element = await page.$(selector);
3381
+ if (element) {
3382
+ const href = await element.getAttribute("href");
3383
+ if (href) {
3384
+ return href;
3385
+ }
3386
+ }
3387
+ } catch {
3388
+ }
3389
+ }
3390
+ try {
3391
+ const pageContent = await page.content();
3392
+ const prPatterns = [
3393
+ /(https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/,
3394
+ /(https:\/\/gitlab\.com\/[^/]+\/[^/]+\/-\/merge_requests\/\d+)/
3395
+ ];
3396
+ for (const pattern of prPatterns) {
3397
+ const match = pageContent.match(pattern);
3398
+ if (match && match[1]) {
3399
+ return match[1];
3400
+ }
3401
+ }
3402
+ } catch {
3403
+ }
3404
+ return null;
3405
+ }
3406
+
3407
+ // apps/cli/src/commands/auth.ts
3408
+ async function authCommand() {
3409
+ console.log("\u{1F510} FlightDesk Authentication\n");
3410
+ const playwrightAvailable = await isPlaywrightAvailable();
3411
+ if (!playwrightAvailable) {
3412
+ console.error("Playwright is not installed.");
3413
+ console.error("Install with: pnpm add playwright && npx playwright install chromium");
3414
+ process.exit(1);
3415
+ }
3416
+ console.log(`Profile directory: ${USER_DATA_DIR}
3417
+ `);
3418
+ console.log("Checking current authentication status...");
3419
+ const isAuthenticated = await checkAuth();
3420
+ if (isAuthenticated) {
3421
+ console.log("\u2705 Already logged in to Claude!");
3422
+ console.log("\nThe watch daemon will be able to monitor your sessions.");
3423
+ return;
3424
+ }
3425
+ console.log("\u274C Not logged in to Claude.\n");
3426
+ console.log("Opening browser for login...");
3427
+ console.log("Please log in to your Claude account, then close the browser.\n");
3428
+ await openForLogin();
3429
+ console.log("\nVerifying login...");
3430
+ const nowAuthenticated = await checkAuth();
3431
+ if (nowAuthenticated) {
3432
+ console.log("\u2705 Successfully logged in!");
3433
+ console.log("\nThe watch daemon can now monitor your Claude Code sessions.");
3434
+ } else {
3435
+ console.log("\u274C Login was not detected.");
3436
+ console.log("Please try again with: flightdesk auth");
3437
+ }
3438
+ }
3439
+
3440
+ // apps/cli/src/lib/api.ts
3441
+ var FlightDeskAPI = class {
3442
+ constructor(org2) {
3443
+ this.apiUrl = org2.apiUrl;
3444
+ this.apiKey = org2.apiKey;
3445
+ }
3446
+ async graphql(query, variables) {
3447
+ const response = await fetch(`${this.apiUrl}/graphql`, {
3448
+ method: "POST",
3449
+ headers: {
3450
+ "Content-Type": "application/json",
3451
+ "Authorization": `Bearer ${this.apiKey}`
3452
+ },
3453
+ body: JSON.stringify({ query, variables })
3454
+ });
3455
+ if (!response.ok) {
3456
+ throw new Error(`API request failed: ${response.status} ${response.statusText}`);
3457
+ }
3458
+ const result = await response.json();
3459
+ if (result.errors && result.errors.length > 0) {
3460
+ throw new Error(`GraphQL error: ${result.errors.map((e) => e.message).join(", ")}`);
3461
+ }
3462
+ return result.data;
3463
+ }
3464
+ // ============================================================================
3465
+ // Task Operations
3466
+ // ============================================================================
3467
+ async createTask(input) {
3468
+ const query = `
38
3469
  mutation CreateTask($input: UserCreateTaskInput!) {
39
3470
  userCreateTask(input: $input) {
40
3471
  id
@@ -43,7 +3474,12 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
43
3474
  createdAt
44
3475
  }
45
3476
  }
46
- `,{input:t})).userCreateTask}async updateTask(t,e){return(await this.graphql(`
3477
+ `;
3478
+ const result = await this.graphql(query, { input });
3479
+ return result.userCreateTask;
3480
+ }
3481
+ async updateTask(taskId, input) {
3482
+ const query = `
47
3483
  mutation UpdateTask($taskId: String!, $input: UserUpdateTaskInput!) {
48
3484
  userUpdateTask(taskId: $taskId, input: $input) {
49
3485
  id
@@ -53,7 +3489,12 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
53
3489
  prUrl
54
3490
  }
55
3491
  }
56
- `,{taskId:t,input:e})).userUpdateTask}async getTask(t){return(await this.graphql(`
3492
+ `;
3493
+ const result = await this.graphql(query, { taskId, input });
3494
+ return result.userUpdateTask;
3495
+ }
3496
+ async getTask(taskId) {
3497
+ const query = `
57
3498
  query GetTask($taskId: String!) {
58
3499
  userTask(taskId: $taskId) {
59
3500
  id
@@ -74,9 +3515,14 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
74
3515
  }
75
3516
  }
76
3517
  }
77
- `,{taskId:t})).userTask}async listTasks(t){return(await this.graphql(`
78
- query ListTasks($projectId: String, $status: String) {
79
- userTasks(projectId: $projectId, status: $status) {
3518
+ `;
3519
+ const result = await this.graphql(query, { taskId });
3520
+ return result.userTask;
3521
+ }
3522
+ async listTasks(options) {
3523
+ const query = `
3524
+ query ListTasks($input: ListTasksInput!) {
3525
+ userTasks(input: $input) {
80
3526
  id
81
3527
  title
82
3528
  status
@@ -89,7 +3535,22 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
89
3535
  }
90
3536
  }
91
3537
  }
92
- `,t)).userTasks}async listProjects(){return(await this.graphql(`
3538
+ `;
3539
+ const input = {};
3540
+ if (options?.projectId) {
3541
+ input.projectId = options.projectId;
3542
+ }
3543
+ if (options?.status) {
3544
+ input.status = [options.status];
3545
+ }
3546
+ const result = await this.graphql(query, { input });
3547
+ return result.userTasks;
3548
+ }
3549
+ // ============================================================================
3550
+ // Project Operations
3551
+ // ============================================================================
3552
+ async listProjects() {
3553
+ const query = `
93
3554
  query ListProjects {
94
3555
  userProjects {
95
3556
  id
@@ -97,7 +3558,12 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
97
3558
  githubRepo
98
3559
  }
99
3560
  }
100
- `)).userProjects}async getProject(t){return(await this.graphql(`
3561
+ `;
3562
+ const result = await this.graphql(query);
3563
+ return result.userProjects;
3564
+ }
3565
+ async getProject(projectId) {
3566
+ const query = `
101
3567
  query GetProject($projectId: String!) {
102
3568
  userProject(projectId: $projectId) {
103
3569
  id
@@ -106,14 +3572,30 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
106
3572
  tokenTtlHours
107
3573
  }
108
3574
  }
109
- `,{projectId:t})).userProject}async createTaskToken(t){return(await this.graphql(`
3575
+ `;
3576
+ const result = await this.graphql(query, { projectId });
3577
+ return result.userProject;
3578
+ }
3579
+ // ============================================================================
3580
+ // Task Token Operations (for agent authentication)
3581
+ // ============================================================================
3582
+ async createTaskToken(taskId) {
3583
+ const query = `
110
3584
  mutation CreateTaskToken($taskId: String!) {
111
3585
  userCreateTaskToken(taskId: $taskId) {
112
3586
  token
113
3587
  expiresAt
114
3588
  }
115
3589
  }
116
- `,{taskId:t})).userCreateTaskToken}async getTaskPrompts(t){return(await this.graphql(`
3590
+ `;
3591
+ const result = await this.graphql(query, { taskId });
3592
+ return result.userCreateTaskToken;
3593
+ }
3594
+ // ============================================================================
3595
+ // Prompt Operations
3596
+ // ============================================================================
3597
+ async getTaskPrompts(taskId) {
3598
+ const query = `
117
3599
  query GetTaskPrompts($taskId: String!) {
118
3600
  userTaskPrompts(taskId: $taskId) {
119
3601
  type
@@ -122,32 +3604,791 @@ The watch daemon can now monitor your Claude Code sessions.`)):(console.log("\u2
122
3604
  reason
123
3605
  }
124
3606
  }
125
- `,{taskId:t})).userTaskPrompts}};async function Nt(s,t,e){y()||(console.error("FlightDesk is not configured. Run: flightdesk init"),process.exit(1));let n=O();n||(console.error("No organization configured. Run: flightdesk init"),process.exit(1));let i=new _(n);try{let o=e.viewUrl,r=e.teleportId;if(!process.stdin.isTTY){let a=await fe(),c=_e(a);o=o||c.viewUrl,r=r||c.teleportId}let l=t;if(!l){e.title||(console.error('Task title required when creating a new task. Use --title "..."'),process.exit(1)),console.log(`Creating task: ${e.title}`);let a=await i.createTask({projectId:s,title:e.title,description:e.description});l=a.id,console.log(`\u2705 Created task: ${a.id}`)}(o||r)&&(console.log("Registering session with task..."),await i.updateTask(l,{sessionViewUrl:o,sessionTeleportId:r,status:"DISPATCHED"}),console.log("\u2705 Session registered")),console.log(`
126
- Task ID: ${l}`),o&&console.log(`Session: ${o}`),r&&console.log(`Resume: claude --teleport ${r}`)}catch(o){console.error(`Error: ${o}`),process.exit(1)}}function fe(){return new Promise(s=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e}),process.stdin.on("end",()=>{s(t)}),setTimeout(()=>s(t),100)})}function _e(s){let t={},e=s.match(/View:\s+(https:\/\/claude\.ai\/code\/session_[^\s]+)/);e&&(t.viewUrl=e[1]);let n=s.match(/--teleport\s+(session_[^\s]+)/);return n&&(t.teleportId=n[1]),t}async function Ut(s){y()||(console.error("FlightDesk is not configured. Run: flightdesk init"),process.exit(1));let t=O();t||(console.error("No organization configured. Run: flightdesk init"),process.exit(1));let e=new _(t);try{let n=await e.listTasks({projectId:s.project});if(n.length===0){console.log("No tasks found.");return}let i={};for(let r of n)i[r.status]||(i[r.status]=[]),i[r.status].push(r);let o=["PENDING","DISPATCHED","IN_PROGRESS","BRANCH_CREATED","PR_OPEN","PREVIEW_STARTING","PREVIEW_READY","REVIEW_RUNNING","REVIEW_DONE","QA_READY","QA_APPROVED","MERGED","ARCHIVED"];console.log(`
127
- \u{1F4CB} FlightDesk Tasks
128
- `);for(let r of o){let l=i[r];if(!(!l||l.length===0)){console.log(`${we(r)} ${r} (${l.length})`);for(let a of l)console.log(` ${a.id.slice(0,8)} - ${a.title}`),a.branchName&&console.log(` Branch: ${a.branchName}`),a.prUrl&&console.log(` PR: ${a.prUrl}`);console.log("")}}}catch(n){console.error(`Error: ${n}`),process.exit(1)}}function we(s){switch(s){case"PENDING":return"\u2B1C";case"DISPATCHED":return"\u{1F680}";case"IN_PROGRESS":return"\u{1F504}";case"BRANCH_CREATED":return"\u{1F33F}";case"PR_OPEN":return"\u{1F4DD}";case"PREVIEW_STARTING":return"\u23F3";case"PREVIEW_READY":return"\u{1F310}";case"REVIEW_RUNNING":return"\u{1F50D}";case"REVIEW_DONE":return"\u2705";case"QA_READY":return"\u{1F9EA}";case"QA_APPROVED":return"\u{1F44D}";case"MERGED":return"\u{1F389}";case"ARCHIVED":return"\u{1F4E6}";default:return"\u2753"}}async function Vt(s){y()||(console.error("FlightDesk is not configured. Run: flightdesk init"),process.exit(1));let t=O();t||(console.error("No organization configured. Run: flightdesk init"),process.exit(1));let e=parseInt(s.interval,10);(isNaN(e)||e<1)&&(console.error("Invalid interval. Must be a positive number of minutes."),process.exit(1)),console.log("\u{1F6EB} FlightDesk Watch Daemon"),console.log(` Organization: ${t.name}`),console.log(` Interval: ${e} minutes`),console.log(` Auto-PR: ${s.autoPr?"enabled":"disabled"}`),console.log("");let n=await E();n?await N()?(console.log("\u2705 Playwright ready, Claude authenticated"),console.log("")):(console.log("\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth"),console.log("")):(console.log("\u26A0\uFE0F Playwright not installed. Session monitoring disabled."),console.log(" Install with: pnpm add playwright && npx playwright install chromium"),console.log(""));let i=new _(t);async function o(){let l=new Date().toLocaleTimeString();console.log(`[${l}] Checking tasks...`);try{let c=(await i.listTasks()).filter(u=>["DISPATCHED","IN_PROGRESS","BRANCH_CREATED"].includes(u.status));if(c.length===0){console.log(" No active tasks to monitor");return}console.log(` Found ${c.length} active task(s)`);for(let u of c)if(console.log(`
129
- \u{1F4CB} ${u.title}`),console.log(` Status: ${u.status}`),u.sessionViewUrl&&n){console.log(" Checking session...");let h=await Dt(u.sessionViewUrl,{headless:s.headless!==!1,autoPr:s.autoPr&&!u.prUrl});await Ce(i,u,h)}else u.sessionViewUrl||console.log(" No session URL registered")}catch(a){console.error(` Error: ${a}`)}}if(await o(),s.once){console.log(`
130
- Done (--once flag specified)`);return}console.log(`
3607
+ `;
3608
+ const result = await this.graphql(query, { taskId });
3609
+ return result.userTaskPrompts;
3610
+ }
3611
+ };
3612
+
3613
+ // apps/cli/src/commands/register.ts
3614
+ async function registerCommand(projectId, taskId, options) {
3615
+ if (!isConfigured()) {
3616
+ console.error("FlightDesk is not configured. Run: flightdesk init");
3617
+ process.exit(1);
3618
+ }
3619
+ const org2 = getDefaultOrganization();
3620
+ if (!org2) {
3621
+ console.error("No organization configured. Run: flightdesk init");
3622
+ process.exit(1);
3623
+ }
3624
+ const api = new FlightDeskAPI(org2);
3625
+ try {
3626
+ let viewUrl = options.viewUrl;
3627
+ let teleportId = options.teleportId;
3628
+ if (!process.stdin.isTTY) {
3629
+ const input = await readStdin();
3630
+ const parsed = parseClaudeOutput(input);
3631
+ viewUrl = viewUrl || parsed.viewUrl;
3632
+ teleportId = teleportId || parsed.teleportId;
3633
+ }
3634
+ let actualTaskId = taskId;
3635
+ if (!actualTaskId) {
3636
+ if (!options.title) {
3637
+ console.error('Task title required when creating a new task. Use --title "..."');
3638
+ process.exit(1);
3639
+ }
3640
+ console.log(`Creating task: ${options.title}`);
3641
+ const task2 = await api.createTask({
3642
+ projectId,
3643
+ title: options.title,
3644
+ description: options.description
3645
+ });
3646
+ actualTaskId = task2.id;
3647
+ console.log(`\u2705 Created task: ${task2.id}`);
3648
+ }
3649
+ if (viewUrl || teleportId) {
3650
+ console.log("Registering session with task...");
3651
+ await api.updateTask(actualTaskId, {
3652
+ sessionViewUrl: viewUrl,
3653
+ sessionTeleportId: teleportId,
3654
+ status: "DISPATCHED"
3655
+ });
3656
+ console.log("\u2705 Session registered");
3657
+ }
3658
+ console.log(`
3659
+ Task ID: ${actualTaskId}`);
3660
+ if (viewUrl) {
3661
+ console.log(`Session: ${viewUrl}`);
3662
+ }
3663
+ if (teleportId) {
3664
+ console.log(`Resume: claude --teleport ${teleportId}`);
3665
+ }
3666
+ } catch (error) {
3667
+ console.error(`Error: ${error}`);
3668
+ process.exit(1);
3669
+ }
3670
+ }
3671
+ function readStdin() {
3672
+ return new Promise((resolve) => {
3673
+ let data = "";
3674
+ process.stdin.setEncoding("utf8");
3675
+ process.stdin.on("data", (chunk) => {
3676
+ data += chunk;
3677
+ });
3678
+ process.stdin.on("end", () => {
3679
+ resolve(data);
3680
+ });
3681
+ setTimeout(() => resolve(data), 100);
3682
+ });
3683
+ }
3684
+ function parseClaudeOutput(output) {
3685
+ const result = {};
3686
+ const viewMatch = output.match(/View:\s+(https:\/\/claude\.ai\/code\/session_[^\s]+)/);
3687
+ if (viewMatch) {
3688
+ result.viewUrl = viewMatch[1];
3689
+ }
3690
+ const teleportMatch = output.match(/--teleport\s+(session_[^\s]+)/);
3691
+ if (teleportMatch) {
3692
+ result.teleportId = teleportMatch[1];
3693
+ }
3694
+ return result;
3695
+ }
3696
+
3697
+ // apps/cli/src/commands/status.ts
3698
+ async function statusCommand(options) {
3699
+ if (!isConfigured()) {
3700
+ console.error("FlightDesk is not configured. Run: flightdesk init");
3701
+ process.exit(1);
3702
+ }
3703
+ const org2 = getDefaultOrganization();
3704
+ if (!org2) {
3705
+ console.error("No organization configured. Run: flightdesk init");
3706
+ process.exit(1);
3707
+ }
3708
+ const api = new FlightDeskAPI(org2);
3709
+ try {
3710
+ const tasks = await api.listTasks({ projectId: options.project });
3711
+ if (tasks.length === 0) {
3712
+ console.log("No tasks found.");
3713
+ return;
3714
+ }
3715
+ const byStatus = {};
3716
+ for (const task2 of tasks) {
3717
+ if (!byStatus[task2.status]) {
3718
+ byStatus[task2.status] = [];
3719
+ }
3720
+ byStatus[task2.status].push(task2);
3721
+ }
3722
+ const statusOrder = [
3723
+ "PENDING",
3724
+ "DISPATCHED",
3725
+ "IN_PROGRESS",
3726
+ "BRANCH_CREATED",
3727
+ "PR_OPEN",
3728
+ "PREVIEW_STARTING",
3729
+ "PREVIEW_READY",
3730
+ "REVIEW_RUNNING",
3731
+ "REVIEW_DONE",
3732
+ "QA_READY",
3733
+ "QA_APPROVED",
3734
+ "MERGED",
3735
+ "ARCHIVED"
3736
+ ];
3737
+ console.log("\n\u{1F4CB} FlightDesk Tasks\n");
3738
+ for (const status of statusOrder) {
3739
+ const statusTasks = byStatus[status];
3740
+ if (!statusTasks || statusTasks.length === 0) continue;
3741
+ console.log(`${getStatusEmoji(status)} ${status} (${statusTasks.length})`);
3742
+ for (const task2 of statusTasks) {
3743
+ console.log(` ${task2.id.slice(0, 8)} - ${task2.title}`);
3744
+ if (task2.branchName) {
3745
+ console.log(` Branch: ${task2.branchName}`);
3746
+ }
3747
+ if (task2.prUrl) {
3748
+ console.log(` PR: ${task2.prUrl}`);
3749
+ }
3750
+ }
3751
+ console.log("");
3752
+ }
3753
+ } catch (error) {
3754
+ console.error(`Error: ${error}`);
3755
+ process.exit(1);
3756
+ }
3757
+ }
3758
+ function getStatusEmoji(status) {
3759
+ switch (status) {
3760
+ case "PENDING":
3761
+ return "\u2B1C";
3762
+ case "DISPATCHED":
3763
+ return "\u{1F680}";
3764
+ case "IN_PROGRESS":
3765
+ return "\u{1F504}";
3766
+ case "BRANCH_CREATED":
3767
+ return "\u{1F33F}";
3768
+ case "PR_OPEN":
3769
+ return "\u{1F4DD}";
3770
+ case "PREVIEW_STARTING":
3771
+ return "\u23F3";
3772
+ case "PREVIEW_READY":
3773
+ return "\u{1F310}";
3774
+ case "REVIEW_RUNNING":
3775
+ return "\u{1F50D}";
3776
+ case "REVIEW_DONE":
3777
+ return "\u2705";
3778
+ case "QA_READY":
3779
+ return "\u{1F9EA}";
3780
+ case "QA_APPROVED":
3781
+ return "\u{1F44D}";
3782
+ case "MERGED":
3783
+ return "\u{1F389}";
3784
+ case "ARCHIVED":
3785
+ return "\u{1F4E6}";
3786
+ default:
3787
+ return "\u2753";
3788
+ }
3789
+ }
3790
+
3791
+ // apps/cli/src/commands/watch.ts
3792
+ async function watchCommand(options) {
3793
+ if (!isConfigured()) {
3794
+ console.error("FlightDesk is not configured. Run: flightdesk init");
3795
+ process.exit(1);
3796
+ }
3797
+ const org2 = getDefaultOrganization();
3798
+ if (!org2) {
3799
+ console.error("No organization configured. Run: flightdesk init");
3800
+ process.exit(1);
3801
+ }
3802
+ const intervalMinutes = parseInt(options.interval, 10);
3803
+ if (isNaN(intervalMinutes) || intervalMinutes < 1) {
3804
+ console.error("Invalid interval. Must be a positive number of minutes.");
3805
+ process.exit(1);
3806
+ }
3807
+ console.log("\u{1F6EB} FlightDesk Watch Daemon");
3808
+ console.log(` Organization: ${org2.name}`);
3809
+ console.log(` Interval: ${intervalMinutes} minutes`);
3810
+ console.log(` Auto-PR: ${options.autoPr ? "enabled" : "disabled"}`);
3811
+ console.log("");
3812
+ const playwrightAvailable = await isPlaywrightAvailable();
3813
+ if (!playwrightAvailable) {
3814
+ console.log("\u26A0\uFE0F Playwright not installed. Session monitoring disabled.");
3815
+ console.log(" Install with: pnpm add playwright && npx playwright install chromium");
3816
+ console.log("");
3817
+ } else {
3818
+ const isAuthenticated = await checkAuth();
3819
+ if (!isAuthenticated) {
3820
+ console.log("\u26A0\uFE0F Not logged into Claude. Run: flightdesk auth");
3821
+ console.log("");
3822
+ } else {
3823
+ console.log("\u2705 Playwright ready, Claude authenticated");
3824
+ console.log("");
3825
+ }
3826
+ }
3827
+ const api = new FlightDeskAPI(org2);
3828
+ async function runCheck() {
3829
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
3830
+ console.log(`[${timestamp}] Checking tasks...`);
3831
+ try {
3832
+ const tasks = await api.listTasks();
3833
+ const activeTasks = tasks.filter(
3834
+ (t) => ["DISPATCHED", "IN_PROGRESS", "BRANCH_CREATED"].includes(t.status)
3835
+ );
3836
+ if (activeTasks.length === 0) {
3837
+ console.log(" No active tasks to monitor");
3838
+ return;
3839
+ }
3840
+ console.log(` Found ${activeTasks.length} active task(s)`);
3841
+ for (const task2 of activeTasks) {
3842
+ console.log(`
3843
+ \u{1F4CB} ${task2.title}`);
3844
+ console.log(` Status: ${task2.status}`);
3845
+ if (task2.sessionViewUrl && playwrightAvailable) {
3846
+ console.log(` Checking session...`);
3847
+ const sessionInfo = await monitorSession(task2.sessionViewUrl, {
3848
+ headless: options.headless !== false,
3849
+ autoPr: options.autoPr && !task2.prUrl
3850
+ // Only auto-PR if no PR exists
3851
+ });
3852
+ await processSessionInfo(api, task2, sessionInfo);
3853
+ } else if (!task2.sessionViewUrl) {
3854
+ console.log(" No session URL registered");
3855
+ }
3856
+ }
3857
+ } catch (error) {
3858
+ console.error(` Error: ${error}`);
3859
+ }
3860
+ }
3861
+ await runCheck();
3862
+ if (options.once) {
3863
+ console.log("\nDone (--once flag specified)");
3864
+ return;
3865
+ }
3866
+ console.log(`
131
3867
  Watching... (Ctrl+C to stop)
132
- `);let r=setInterval(o,e*60*1e3);process.on("SIGINT",()=>{console.log(`
133
- Shutting down...`),clearInterval(r),process.exit(0)}),await new Promise(()=>{})}async function Ce(s,t,e){if(e.status==="error"){console.log(` \u274C Error: ${e.error}`);return}if(e.status==="archived"){console.log(" \u{1F4E6} Session archived");return}let n={};if(e.branchName&&e.branchName!==t.branchName&&(console.log(` \u{1F33F} Branch detected: ${e.branchName}`),n.branchName=e.branchName,t.status==="DISPATCHED"&&(n.status="IN_PROGRESS")),e.prUrl&&e.prUrl!==t.prUrl){console.log(` \u{1F517} PR detected: ${e.prUrl}`),n.prUrl=e.prUrl;let i=e.prUrl.match(/\/pull\/(\d+)/);i&&(n.prNumber=parseInt(i[1],10)),n.status="PR_OPEN"}if(e.hasPrButton&&!e.prUrl&&!t.prUrl&&console.log(' \u{1F4DD} "Create PR" button available'),Object.keys(n).length>0)try{await s.updateTask(t.id,n),console.log(" \u2705 Task updated")}catch(i){console.log(` \u274C Failed to update task: ${i}`)}else console.log(" No changes detected")}async function U(s,t){y()||(console.error("FlightDesk is not configured. Run: flightdesk init"),process.exit(1));let e=O();e||(console.error("No organization configured. Run: flightdesk init"),process.exit(1));let n=new _(e);try{switch(s){case"create":await Oe(n,t);break;case"list":await ye(n,t);break;case"status":await ke(n,t);break;case"update":await be(n,t);break}}catch(i){console.error(`Error: ${i}`),process.exit(1)}}async function Oe(s,t){console.log(`Creating task: ${t.title}`);let e=await s.createTask({projectId:t.project,title:t.title,description:t.description});console.log(`
134
- \u2705 Task created`),console.log(` ID: ${e.id}`),console.log(` Title: ${e.title}`),console.log(` Status: ${e.status}`)}async function ye(s,t){let e=await s.listTasks({projectId:t.project,status:t.status});if(e.length===0){console.log("No tasks found.");return}console.log(`
135
- Tasks:
136
- `);for(let n of e){let i=zt(n.status);console.log(`${i} ${n.id.slice(0,8)} - ${n.title}`),console.log(` Project: ${n.project.name}`),console.log(` Status: ${n.status}`),n.branchName&&console.log(` Branch: ${n.branchName}`),n.prUrl&&console.log(` PR: ${n.prUrl}`),console.log("")}}async function ke(s,t){let e=await s.getTask(t.taskId);e||(console.error("Task not found"),process.exit(1)),console.log(`
137
- \u{1F4CB} Task: ${e.title}
138
- `),console.log(`ID: ${e.id}`),console.log(`Status: ${zt(e.status)} ${e.status}`),console.log(`Project: ${e.project.name} (${e.project.githubRepo})`),e.description&&console.log(`
3868
+ `);
3869
+ const intervalId = setInterval(runCheck, intervalMinutes * 60 * 1e3);
3870
+ process.on("SIGINT", () => {
3871
+ console.log("\nShutting down...");
3872
+ clearInterval(intervalId);
3873
+ process.exit(0);
3874
+ });
3875
+ await new Promise(() => {
3876
+ });
3877
+ }
3878
+ async function processSessionInfo(api, task2, info) {
3879
+ if (info.status === "error") {
3880
+ console.log(` \u274C Error: ${info.error}`);
3881
+ return;
3882
+ }
3883
+ if (info.status === "archived") {
3884
+ console.log(" \u{1F4E6} Session archived");
3885
+ return;
3886
+ }
3887
+ const updates = {};
3888
+ if (info.branchName && info.branchName !== task2.branchName) {
3889
+ console.log(` \u{1F33F} Branch detected: ${info.branchName}`);
3890
+ updates.branchName = info.branchName;
3891
+ if (task2.status === "DISPATCHED") {
3892
+ updates.status = "IN_PROGRESS";
3893
+ }
3894
+ }
3895
+ if (info.prUrl && info.prUrl !== task2.prUrl) {
3896
+ console.log(` \u{1F517} PR detected: ${info.prUrl}`);
3897
+ updates.prUrl = info.prUrl;
3898
+ const prMatch = info.prUrl.match(/\/pull\/(\d+)/);
3899
+ if (prMatch) {
3900
+ updates.prNumber = parseInt(prMatch[1], 10);
3901
+ }
3902
+ updates.status = "PR_OPEN";
3903
+ }
3904
+ if (info.hasPrButton && !info.prUrl && !task2.prUrl) {
3905
+ console.log(' \u{1F4DD} "Create PR" button available');
3906
+ }
3907
+ if (Object.keys(updates).length > 0) {
3908
+ try {
3909
+ await api.updateTask(task2.id, updates);
3910
+ console.log(" \u2705 Task updated");
3911
+ } catch (error) {
3912
+ console.log(` \u274C Failed to update task: ${error}`);
3913
+ }
3914
+ } else {
3915
+ console.log(" No changes detected");
3916
+ }
3917
+ }
3918
+
3919
+ // apps/cli/src/commands/task.ts
3920
+ async function taskCommand(action, options) {
3921
+ if (!isConfigured()) {
3922
+ console.error("FlightDesk is not configured. Run: flightdesk init");
3923
+ process.exit(1);
3924
+ }
3925
+ const org2 = getDefaultOrganization();
3926
+ if (!org2) {
3927
+ console.error("No organization configured. Run: flightdesk init");
3928
+ process.exit(1);
3929
+ }
3930
+ const api = new FlightDeskAPI(org2);
3931
+ try {
3932
+ switch (action) {
3933
+ case "create":
3934
+ await handleCreate(api, options);
3935
+ break;
3936
+ case "list":
3937
+ await handleList(api, options);
3938
+ break;
3939
+ case "status":
3940
+ await handleStatus(api, options);
3941
+ break;
3942
+ case "update":
3943
+ await handleUpdate(api, options);
3944
+ break;
3945
+ }
3946
+ } catch (error) {
3947
+ console.error(`Error: ${error}`);
3948
+ process.exit(1);
3949
+ }
3950
+ }
3951
+ async function handleCreate(api, options) {
3952
+ console.log(`Creating task: ${options.title}`);
3953
+ const task2 = await api.createTask({
3954
+ projectId: options.project,
3955
+ title: options.title,
3956
+ description: options.description
3957
+ });
3958
+ console.log(`
3959
+ \u2705 Task created`);
3960
+ console.log(` ID: ${task2.id}`);
3961
+ console.log(` Title: ${task2.title}`);
3962
+ console.log(` Status: ${task2.status}`);
3963
+ }
3964
+ async function handleList(api, options) {
3965
+ const tasks = await api.listTasks({
3966
+ projectId: options.project,
3967
+ status: options.status
3968
+ });
3969
+ if (tasks.length === 0) {
3970
+ console.log("No tasks found.");
3971
+ return;
3972
+ }
3973
+ console.log("\nTasks:\n");
3974
+ for (const task2 of tasks) {
3975
+ const statusEmoji = getStatusEmoji2(task2.status);
3976
+ console.log(`${statusEmoji} ${task2.id.slice(0, 8)} - ${task2.title}`);
3977
+ if (task2.project?.name) console.log(` Project: ${task2.project.name}`);
3978
+ console.log(` Status: ${task2.status}`);
3979
+ if (task2.branchName) console.log(` Branch: ${task2.branchName}`);
3980
+ if (task2.prUrl) console.log(` PR: ${task2.prUrl}`);
3981
+ console.log("");
3982
+ }
3983
+ }
3984
+ async function handleStatus(api, options) {
3985
+ const task2 = await api.getTask(options.taskId);
3986
+ if (!task2) {
3987
+ console.error("Task not found");
3988
+ process.exit(1);
3989
+ }
3990
+ console.log(`
3991
+ \u{1F4CB} Task: ${task2.title}
3992
+ `);
3993
+ console.log(`ID: ${task2.id}`);
3994
+ console.log(`Status: ${getStatusEmoji2(task2.status)} ${task2.status}`);
3995
+ if (task2.project) {
3996
+ console.log(`Project: ${task2.project.name}${task2.project.githubRepo ? ` (${task2.project.githubRepo})` : ""}`);
3997
+ }
3998
+ if (task2.description) {
3999
+ console.log(`
139
4000
  Description:
140
- ${e.description}`),console.log(""),e.branchName&&console.log(`Branch: ${e.branchName}`),e.prUrl&&console.log(`PR: ${e.prUrl}`),e.sessionViewUrl&&console.log(`Session: ${e.sessionViewUrl}`),e.sessionTeleportId&&console.log(`Resume: claude --teleport ${e.sessionTeleportId}`),console.log(`
141
- Created: ${new Date(e.createdAt).toLocaleString()}`),console.log(`Updated: ${new Date(e.updatedAt).toLocaleString()}`)}async function be(s,t){let e={};t.status&&(e.status=t.status),t.branch&&(e.branchName=t.branch),t.prUrl&&(e.prUrl=t.prUrl),Object.keys(e).length===0&&(console.error("No updates specified. Use --status, --branch, or --pr-url"),process.exit(1)),console.log(`Updating task ${t.taskId}...`);let n=await s.updateTask(t.taskId,e);console.log(`
142
- \u2705 Task updated`),console.log(` Status: ${n.status}`),n.branchName&&console.log(` Branch: ${n.branchName}`),n.prUrl&&console.log(` PR: ${n.prUrl}`)}function zt(s){switch(s){case"PENDING":return"\u2B1C";case"DISPATCHED":return"\u{1F680}";case"IN_PROGRESS":return"\u{1F504}";case"BRANCH_CREATED":return"\u{1F33F}";case"PR_OPEN":return"\u{1F4DD}";case"PREVIEW_STARTING":return"\u23F3";case"PREVIEW_READY":return"\u{1F310}";case"REVIEW_RUNNING":return"\u{1F50D}";case"REVIEW_DONE":return"\u2705";case"QA_READY":return"\u{1F9EA}";case"QA_APPROVED":return"\u{1F44D}";case"MERGED":return"\u{1F389}";case"ARCHIVED":return"\u{1F4E6}";default:return"\u2753"}}async function Ht(s,t){y()||(console.error("FlightDesk is not configured. Run: flightdesk init"),process.exit(1));let e=O();e||(console.error("No organization configured. Run: flightdesk init"),process.exit(1));let n=new _(e),i=["review","test_plan","summary","handoff"];i.includes(t.type)||(console.error(`Invalid prompt type: ${t.type}`),console.error(`Valid types: ${i.join(", ")}`),process.exit(1));try{let r=(await n.getTaskPrompts(s)).find(l=>l.type===t.type);r||(console.error(`Prompt type "${t.type}" not found for this task`),process.exit(1)),r.available||(console.error(`Prompt not available: ${r.reason||"Unknown reason"}`),process.exit(1)),console.log(r.content)}catch(o){console.error(`Error: ${o}`),process.exit(1)}}var at=C(require("readline"));function T(s,t){return new Promise(e=>{s.question(t,n=>{e(n.trim())})})}async function jt(){let s=g();if(s.organizations.length===0){console.log("No organizations configured."),console.log("Run: flightdesk init");return}console.log(`
143
- \u{1F4CB} Connected Organizations
144
- `);for(let e of s.organizations){let i=e.id===s.defaultOrganization?" (default)":"";console.log(` ${e.name}${i}`),console.log(` ID: ${e.id}`),console.log(` API: ${e.apiUrl}`),console.log("")}let t=Object.entries(s.repoMapping);if(t.length>0){console.log(`\u{1F4C1} Repository Mappings
145
- `);for(let[e,n]of t){let i=s.organizations.find(o=>o.id===n);console.log(` ${e} \u2192 ${i?.name||n}`)}console.log("")}}async function qt(){let s=at.createInterface({input:process.stdin,output:process.stdout});console.log(`
146
- \u{1F517} Add Organization
147
- `);try{let t=await T(s,"Organization name: ");if(!t){console.error("Organization name is required");return}let e=await T(s,"API Key: ");if(!e){console.error("API Key is required");return}let i=await T(s,`API URL (${x}): `)||x,o,r=e.match(/^fd_key_([^_]+)_/);r?o=r[1]:o=`org_${Date.now()}`;let l={id:o,name:t,apiKey:e,apiUrl:i};console.log(`
148
- Testing connection...`);try{let c=await fetch(`${i}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({query:"{ __typename }"})});if(!c.ok)throw new Error(`API returned ${c.status}`);console.log("\u2705 Connection successful!")}catch(c){if(console.error(`\u274C Connection failed: ${c}`),(await T(s,"Save anyway? (y/N): ")).toLowerCase()!=="y")return}H(l),console.log(`
149
- \u2705 Added organization: ${t}`);let a=g();a.organizations.length>1&&(await T(s,"Set as default? (y/N): ")).toLowerCase()==="y"&&(a.defaultOrganization=o,b(a),console.log("Set as default organization"))}finally{s.close()}}async function Ft(s){let t=g(),e=t.organizations.find(i=>i.id===s||i.name.toLowerCase()===s.toLowerCase());if(!e){console.error(`Organization not found: ${s}`),console.log(`
150
- Available organizations:`);for(let i of t.organizations)console.log(` - ${i.name} (${i.id})`);process.exit(1)}let n=at.createInterface({input:process.stdin,output:process.stdout});try{if((await T(n,`Remove "${e.name}"? (y/N): `)).toLowerCase()!=="y"){console.log("Cancelled");return}Et(e.id),console.log(`\u2705 Removed organization: ${e.name}`)}finally{n.close()}}async function Mt(s){let t=g(),e=t.organizations.find(n=>n.id===s||n.name.toLowerCase()===s.toLowerCase());e||(console.error(`Organization not found: ${s}`),process.exit(1)),t.defaultOrganization=e.id,b(t),console.log(`\u2705 Default organization set to: ${e.name}`)}var lt=require("child_process");async function Lt(){console.log(`
151
- \u{1F50D} Current Context
152
- `);let s={};try{let e=(0,lt.execSync)("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),n=null,i=e.match(/git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);i&&(n=i[1]);let o=e.match(/https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);o&&(n=o[1]),n&&(s.remote=n);let r=(0,lt.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();s.branch=r}catch{}if(!s.remote){console.log("\u{1F4C1} Not in a git repository (or no remote configured)"),console.log("");let e=g();if(e.organizations.length>0){console.log("Connected organizations:");for(let n of e.organizations){let i=n.id===e.defaultOrganization;console.log(` - ${n.name}${i?" (default)":""}`)}}else console.log("No organizations configured. Run: flightdesk init");return}console.log(`\u{1F4C1} Repository: ${s.remote}`),console.log(`\u{1F33F} Branch: ${s.branch}`),console.log("");let t=Pt(s.remote);if(t)console.log(`\u{1F3E2} Organization: ${t.name}`),console.log(` API: ${t.apiUrl}`),console.log(""),console.log("This repository is mapped to the above organization."),console.log("Commands will use this organization automatically.");else{console.log("\u26A0\uFE0F This repository is not mapped to any organization."),console.log("");let e=g();if(e.organizations.length>0){console.log("Connected organizations:");for(let n of e.organizations){let i=n.id===e.defaultOrganization;console.log(` - ${n.name}${i?" (default)":""}`)}console.log(""),console.log("Run: flightdesk sync to refresh repository mappings")}else console.log("No organizations configured. Run: flightdesk init")}}async function Wt(){let s=g();s.organizations.length===0&&(console.error("No organizations configured. Run: flightdesk init"),process.exit(1)),console.log(`\u{1F504} Syncing repository mappings...
153
- `);let t=0,e={};for(let n of s.organizations){console.log(` ${n.name}...`);try{let o=await new _(n).listProjects();console.log(` Found ${o.length} project(s)`);for(let r of o)r.githubRepo&&(e[r.githubRepo]=n.id,t++)}catch(i){console.log(` \u274C Error: ${i}`)}}if(s.repoMapping=e,b(s),console.log(""),console.log(`\u2705 Synced ${t} project(s)`),t>0){console.log(""),console.log("Repository mappings:");for(let[n,i]of Object.entries(e)){let o=s.organizations.find(r=>r.id===i);console.log(` ${n} \u2192 ${o?.name||i}`)}}}var f=new bt;f.name("flightdesk").description("FlightDesk CLI - AI task management for Claude Code sessions").version("0.1.0");f.command("init").description("Configure FlightDesk CLI with your API credentials").action(xt);f.command("auth").description("Log in to Claude for session monitoring").action(Rt);f.command("register <project-id> [task-id]").description("Register a Claude Code session with a FlightDesk task").option("--view-url <url>","Claude Code session view URL").option("--teleport-id <id>","Claude Code teleport ID").option("--title <title>","Task title (creates new task if task-id not provided)").option("--description <description>","Task description").action(Nt);var q=f.command("task").description("Task management commands");q.command("create").description("Create a new task").requiredOption("-p, --project <id>","Project ID").requiredOption("-t, --title <title>","Task title").option("-d, --description <description>","Task description").action(s=>U("create",s));q.command("list").description("List tasks").option("-p, --project <id>","Filter by project ID").option("--status <status>","Filter by status").action(s=>U("list",s));q.command("status <task-id>").description("Get task status").action(s=>U("status",{taskId:s}));q.command("update <task-id>").description("Update task").option("-s, --status <status>","New status").option("--branch <branch>","Branch name").option("--pr-url <url>","Pull request URL").action((s,t)=>U("update",{taskId:s,...t}));f.command("watch").description("Start the Playwright daemon to monitor Claude Code sessions").option("--interval <minutes>","Check interval in minutes","5").option("--once","Run once and exit").option("--auto-pr",'Automatically click "Create PR" button when found').option("--no-headless","Run browser in visible mode (for debugging)").action(Vt);f.command("status").description("Show status of all active tasks").option("-p, --project <id>","Filter by project").action(Ut);f.command("prompt <task-id>").description("Get a prompt for a task (ready to paste into Claude)").option("--type <type>","Prompt type: review, test_plan, summary, handoff","review").action(Ht);var F=f.command("org").description("Organization management");F.command("list").description("List connected organizations").action(jt);F.command("add").description("Connect to a new organization").action(qt);F.command("remove <org-id>").description("Disconnect from an organization").action(Ft);F.command("default <org-id>").description("Set default organization").action(Mt);f.command("context").description("Show current repository context and mapped organization").action(Lt);f.command("sync").description("Refresh project-to-repository mappings from all organizations").action(Wt);f.command("mount <task-id>").description("Mount preview environment filesystem via SSHFS").option("--vscode","Open in VS Code after mounting").action(s=>{console.log("\u26A0\uFE0F Mount command requires preview environments (Phase 9)"),console.log(` Task ID: ${s}`),console.log(""),console.log("Preview environments are not yet implemented."),console.log("This feature will be available in a future release.")});f.command("unmount <task-id>").description("Unmount a task filesystem").action(s=>{console.log("\u26A0\uFE0F Unmount command requires preview environments (Phase 9)"),console.log(` Task ID: ${s}`)});f.command("logs <task-id>").description("Stream logs from a preview environment").option("-f, --follow","Follow log output").option("--process <name>","Filter by process name").action(s=>{console.log("\u26A0\uFE0F Logs command requires preview environments (Phase 9)"),console.log(` Task ID: ${s}`)});f.parse();
4001
+ ${task2.description}`);
4002
+ }
4003
+ console.log("");
4004
+ if (task2.branchName) console.log(`Branch: ${task2.branchName}`);
4005
+ if (task2.prUrl) console.log(`PR: ${task2.prUrl}`);
4006
+ if (task2.sessionViewUrl) console.log(`Session: ${task2.sessionViewUrl}`);
4007
+ if (task2.sessionTeleportId) {
4008
+ console.log(`Resume: claude --teleport ${task2.sessionTeleportId}`);
4009
+ }
4010
+ console.log(`
4011
+ Created: ${new Date(task2.createdAt).toLocaleString()}`);
4012
+ console.log(`Updated: ${new Date(task2.updatedAt).toLocaleString()}`);
4013
+ }
4014
+ async function handleUpdate(api, options) {
4015
+ const input = {};
4016
+ if (options.status) input.status = options.status;
4017
+ if (options.branch) input.branchName = options.branch;
4018
+ if (options.prUrl) input.prUrl = options.prUrl;
4019
+ if (Object.keys(input).length === 0) {
4020
+ console.error("No updates specified. Use --status, --branch, or --pr-url");
4021
+ process.exit(1);
4022
+ }
4023
+ console.log(`Updating task ${options.taskId}...`);
4024
+ const task2 = await api.updateTask(options.taskId, input);
4025
+ console.log(`
4026
+ \u2705 Task updated`);
4027
+ console.log(` Status: ${task2.status}`);
4028
+ if (task2.branchName) console.log(` Branch: ${task2.branchName}`);
4029
+ if (task2.prUrl) console.log(` PR: ${task2.prUrl}`);
4030
+ }
4031
+ function getStatusEmoji2(status) {
4032
+ switch (status) {
4033
+ case "PENDING":
4034
+ return "\u2B1C";
4035
+ case "DISPATCHED":
4036
+ return "\u{1F680}";
4037
+ case "IN_PROGRESS":
4038
+ return "\u{1F504}";
4039
+ case "BRANCH_CREATED":
4040
+ return "\u{1F33F}";
4041
+ case "PR_OPEN":
4042
+ return "\u{1F4DD}";
4043
+ case "PREVIEW_STARTING":
4044
+ return "\u23F3";
4045
+ case "PREVIEW_READY":
4046
+ return "\u{1F310}";
4047
+ case "REVIEW_RUNNING":
4048
+ return "\u{1F50D}";
4049
+ case "REVIEW_DONE":
4050
+ return "\u2705";
4051
+ case "QA_READY":
4052
+ return "\u{1F9EA}";
4053
+ case "QA_APPROVED":
4054
+ return "\u{1F44D}";
4055
+ case "MERGED":
4056
+ return "\u{1F389}";
4057
+ case "ARCHIVED":
4058
+ return "\u{1F4E6}";
4059
+ default:
4060
+ return "\u2753";
4061
+ }
4062
+ }
4063
+
4064
+ // apps/cli/src/commands/prompt.ts
4065
+ async function promptCommand(taskId, options) {
4066
+ if (!isConfigured()) {
4067
+ console.error("FlightDesk is not configured. Run: flightdesk init");
4068
+ process.exit(1);
4069
+ }
4070
+ const org2 = getDefaultOrganization();
4071
+ if (!org2) {
4072
+ console.error("No organization configured. Run: flightdesk init");
4073
+ process.exit(1);
4074
+ }
4075
+ const api = new FlightDeskAPI(org2);
4076
+ const validTypes = ["review", "test_plan", "summary", "handoff"];
4077
+ if (!validTypes.includes(options.type)) {
4078
+ console.error(`Invalid prompt type: ${options.type}`);
4079
+ console.error(`Valid types: ${validTypes.join(", ")}`);
4080
+ process.exit(1);
4081
+ }
4082
+ try {
4083
+ const prompts = await api.getTaskPrompts(taskId);
4084
+ const prompt = prompts.find((p) => p.type === options.type);
4085
+ if (!prompt) {
4086
+ console.error(`Prompt type "${options.type}" not found for this task`);
4087
+ process.exit(1);
4088
+ }
4089
+ if (!prompt.available) {
4090
+ console.error(`Prompt not available: ${prompt.reason || "Unknown reason"}`);
4091
+ process.exit(1);
4092
+ }
4093
+ console.log(prompt.content);
4094
+ } catch (error) {
4095
+ console.error(`Error: ${error}`);
4096
+ process.exit(1);
4097
+ }
4098
+ }
4099
+
4100
+ // apps/cli/src/commands/org.ts
4101
+ var readline2 = __toESM(require("readline"));
4102
+ function question2(rl, prompt) {
4103
+ return new Promise((resolve) => {
4104
+ rl.question(prompt, (answer) => {
4105
+ resolve(answer.trim());
4106
+ });
4107
+ });
4108
+ }
4109
+ async function orgListCommand() {
4110
+ const config = loadConfig();
4111
+ if (config.organizations.length === 0) {
4112
+ console.log("No organizations configured.");
4113
+ console.log("Run: flightdesk init");
4114
+ return;
4115
+ }
4116
+ console.log("\n\u{1F4CB} Connected Organizations\n");
4117
+ for (const org2 of config.organizations) {
4118
+ const isDefault = org2.id === config.defaultOrganization;
4119
+ const defaultTag = isDefault ? " (default)" : "";
4120
+ console.log(` ${org2.name}${defaultTag}`);
4121
+ console.log(` ID: ${org2.id}`);
4122
+ console.log(` API: ${org2.apiUrl}`);
4123
+ console.log("");
4124
+ }
4125
+ const mappings = Object.entries(config.repoMapping);
4126
+ if (mappings.length > 0) {
4127
+ console.log("\u{1F4C1} Repository Mappings\n");
4128
+ for (const [repo, orgId] of mappings) {
4129
+ const org2 = config.organizations.find((o) => o.id === orgId);
4130
+ console.log(` ${repo} \u2192 ${org2?.name || orgId}`);
4131
+ }
4132
+ console.log("");
4133
+ }
4134
+ }
4135
+ async function orgAddCommand() {
4136
+ const rl = readline2.createInterface({
4137
+ input: process.stdin,
4138
+ output: process.stdout
4139
+ });
4140
+ console.log("\n\u{1F517} Add Organization\n");
4141
+ try {
4142
+ const orgName = await question2(rl, "Organization name: ");
4143
+ if (!orgName) {
4144
+ console.error("Organization name is required");
4145
+ return;
4146
+ }
4147
+ const apiKey = await question2(rl, "API Key: ");
4148
+ if (!apiKey) {
4149
+ console.error("API Key is required");
4150
+ return;
4151
+ }
4152
+ const apiUrlInput = await question2(rl, `API URL (${DEFAULT_API_URL}): `);
4153
+ const apiUrl = apiUrlInput || DEFAULT_API_URL;
4154
+ let orgId;
4155
+ const keyMatch = apiKey.match(/^fd_key_([^_]+)_/);
4156
+ if (keyMatch) {
4157
+ orgId = keyMatch[1];
4158
+ } else {
4159
+ orgId = `org_${Date.now()}`;
4160
+ }
4161
+ const org2 = {
4162
+ id: orgId,
4163
+ name: orgName,
4164
+ apiKey,
4165
+ apiUrl
4166
+ };
4167
+ console.log("\nTesting connection...");
4168
+ try {
4169
+ const response = await fetch(`${apiUrl}/graphql`, {
4170
+ method: "POST",
4171
+ headers: {
4172
+ "Content-Type": "application/json",
4173
+ "Authorization": `Bearer ${apiKey}`
4174
+ },
4175
+ body: JSON.stringify({
4176
+ query: "{ __typename }"
4177
+ })
4178
+ });
4179
+ if (!response.ok) {
4180
+ throw new Error(`API returned ${response.status}`);
4181
+ }
4182
+ console.log("\u2705 Connection successful!");
4183
+ } catch (error) {
4184
+ console.error(`\u274C Connection failed: ${error}`);
4185
+ const proceed = await question2(rl, "Save anyway? (y/N): ");
4186
+ if (proceed.toLowerCase() !== "y") {
4187
+ return;
4188
+ }
4189
+ }
4190
+ addOrganization(org2);
4191
+ console.log(`
4192
+ \u2705 Added organization: ${orgName}`);
4193
+ const config = loadConfig();
4194
+ if (config.organizations.length > 1) {
4195
+ const setDefault = await question2(rl, "Set as default? (y/N): ");
4196
+ if (setDefault.toLowerCase() === "y") {
4197
+ config.defaultOrganization = orgId;
4198
+ saveConfig(config);
4199
+ console.log("Set as default organization");
4200
+ }
4201
+ }
4202
+ } finally {
4203
+ rl.close();
4204
+ }
4205
+ }
4206
+ async function orgRemoveCommand(orgId) {
4207
+ const config = loadConfig();
4208
+ const org2 = config.organizations.find((o) => o.id === orgId || o.name.toLowerCase() === orgId.toLowerCase());
4209
+ if (!org2) {
4210
+ console.error(`Organization not found: ${orgId}`);
4211
+ console.log("\nAvailable organizations:");
4212
+ for (const o of config.organizations) {
4213
+ console.log(` - ${o.name} (${o.id})`);
4214
+ }
4215
+ process.exit(1);
4216
+ }
4217
+ const rl = readline2.createInterface({
4218
+ input: process.stdin,
4219
+ output: process.stdout
4220
+ });
4221
+ try {
4222
+ const confirm = await question2(rl, `Remove "${org2.name}"? (y/N): `);
4223
+ if (confirm.toLowerCase() !== "y") {
4224
+ console.log("Cancelled");
4225
+ return;
4226
+ }
4227
+ removeOrganization(org2.id);
4228
+ console.log(`\u2705 Removed organization: ${org2.name}`);
4229
+ } finally {
4230
+ rl.close();
4231
+ }
4232
+ }
4233
+ async function orgSetDefaultCommand(orgId) {
4234
+ const config = loadConfig();
4235
+ const org2 = config.organizations.find((o) => o.id === orgId || o.name.toLowerCase() === orgId.toLowerCase());
4236
+ if (!org2) {
4237
+ console.error(`Organization not found: ${orgId}`);
4238
+ process.exit(1);
4239
+ }
4240
+ config.defaultOrganization = org2.id;
4241
+ saveConfig(config);
4242
+ console.log(`\u2705 Default organization set to: ${org2.name}`);
4243
+ }
4244
+
4245
+ // apps/cli/src/commands/context.ts
4246
+ var import_child_process = require("child_process");
4247
+ async function contextCommand() {
4248
+ console.log("\n\u{1F50D} Current Context\n");
4249
+ let repoInfo = {};
4250
+ try {
4251
+ const remoteUrl = (0, import_child_process.execSync)("git remote get-url origin", {
4252
+ encoding: "utf-8",
4253
+ stdio: ["pipe", "pipe", "pipe"]
4254
+ }).trim();
4255
+ let repoFullName = null;
4256
+ const sshMatch = remoteUrl.match(/git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
4257
+ if (sshMatch) {
4258
+ repoFullName = sshMatch[1];
4259
+ }
4260
+ const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
4261
+ if (httpsMatch) {
4262
+ repoFullName = httpsMatch[1];
4263
+ }
4264
+ if (repoFullName) {
4265
+ repoInfo.remote = repoFullName;
4266
+ }
4267
+ const branch = (0, import_child_process.execSync)("git rev-parse --abbrev-ref HEAD", {
4268
+ encoding: "utf-8",
4269
+ stdio: ["pipe", "pipe", "pipe"]
4270
+ }).trim();
4271
+ repoInfo.branch = branch;
4272
+ } catch {
4273
+ }
4274
+ if (!repoInfo.remote) {
4275
+ console.log("\u{1F4C1} Not in a git repository (or no remote configured)");
4276
+ console.log("");
4277
+ const config = loadConfig();
4278
+ if (config.organizations.length > 0) {
4279
+ console.log("Connected organizations:");
4280
+ for (const org3 of config.organizations) {
4281
+ const isDefault = org3.id === config.defaultOrganization;
4282
+ console.log(` - ${org3.name}${isDefault ? " (default)" : ""}`);
4283
+ }
4284
+ } else {
4285
+ console.log("No organizations configured. Run: flightdesk init");
4286
+ }
4287
+ return;
4288
+ }
4289
+ console.log(`\u{1F4C1} Repository: ${repoInfo.remote}`);
4290
+ console.log(`\u{1F33F} Branch: ${repoInfo.branch}`);
4291
+ console.log("");
4292
+ const org2 = getOrganizationByRepo(repoInfo.remote);
4293
+ if (org2) {
4294
+ console.log(`\u{1F3E2} Organization: ${org2.name}`);
4295
+ console.log(` API: ${org2.apiUrl}`);
4296
+ console.log("");
4297
+ console.log("This repository is mapped to the above organization.");
4298
+ console.log("Commands will use this organization automatically.");
4299
+ } else {
4300
+ console.log("\u26A0\uFE0F This repository is not mapped to any organization.");
4301
+ console.log("");
4302
+ const config = loadConfig();
4303
+ if (config.organizations.length > 0) {
4304
+ console.log("Connected organizations:");
4305
+ for (const org3 of config.organizations) {
4306
+ const isDefault = org3.id === config.defaultOrganization;
4307
+ console.log(` - ${org3.name}${isDefault ? " (default)" : ""}`);
4308
+ }
4309
+ console.log("");
4310
+ console.log("Run: flightdesk sync to refresh repository mappings");
4311
+ } else {
4312
+ console.log("No organizations configured. Run: flightdesk init");
4313
+ }
4314
+ }
4315
+ }
4316
+
4317
+ // apps/cli/src/commands/sync.ts
4318
+ async function syncCommand() {
4319
+ const config = loadConfig();
4320
+ if (config.organizations.length === 0) {
4321
+ console.error("No organizations configured. Run: flightdesk init");
4322
+ process.exit(1);
4323
+ }
4324
+ console.log("\u{1F504} Syncing repository mappings...\n");
4325
+ let totalProjects = 0;
4326
+ const newMappings = {};
4327
+ for (const org2 of config.organizations) {
4328
+ console.log(` ${org2.name}...`);
4329
+ try {
4330
+ const api = new FlightDeskAPI(org2);
4331
+ const projects = await api.listProjects();
4332
+ console.log(` Found ${projects.length} project(s)`);
4333
+ for (const project of projects) {
4334
+ if (project.githubRepo) {
4335
+ newMappings[project.githubRepo] = org2.id;
4336
+ totalProjects++;
4337
+ }
4338
+ }
4339
+ } catch (error) {
4340
+ console.log(` \u274C Error: ${error}`);
4341
+ }
4342
+ }
4343
+ config.repoMapping = newMappings;
4344
+ saveConfig(config);
4345
+ console.log("");
4346
+ console.log(`\u2705 Synced ${totalProjects} project(s)`);
4347
+ if (totalProjects > 0) {
4348
+ console.log("");
4349
+ console.log("Repository mappings:");
4350
+ for (const [repo, orgId] of Object.entries(newMappings)) {
4351
+ const org2 = config.organizations.find((o) => o.id === orgId);
4352
+ console.log(` ${repo} \u2192 ${org2?.name || orgId}`);
4353
+ }
4354
+ }
4355
+ }
4356
+
4357
+ // apps/cli/src/main.ts
4358
+ var program2 = new Command();
4359
+ program2.name("flightdesk").description("FlightDesk CLI - AI task management for Claude Code sessions").version("0.1.0");
4360
+ program2.command("init").description("Configure FlightDesk CLI with your API credentials").action(initCommand);
4361
+ program2.command("auth").description("Log in to Claude for session monitoring").action(authCommand);
4362
+ program2.command("register <project-id> [task-id]").description("Register a Claude Code session with a FlightDesk task").option("--view-url <url>", "Claude Code session view URL").option("--teleport-id <id>", "Claude Code teleport ID").option("--title <title>", "Task title (creates new task if task-id not provided)").option("--description <description>", "Task description").action(registerCommand);
4363
+ var task = program2.command("task").description("Task management commands");
4364
+ task.command("create").description("Create a new task").requiredOption("-p, --project <id>", "Project ID").requiredOption("-t, --title <title>", "Task title").option("-d, --description <description>", "Task description").action((options) => taskCommand("create", options));
4365
+ task.command("list").description("List tasks").option("-p, --project <id>", "Filter by project ID").option("--status <status>", "Filter by status").action((options) => taskCommand("list", options));
4366
+ task.command("status <task-id>").description("Get task status").action((taskId) => taskCommand("status", { taskId }));
4367
+ task.command("update <task-id>").description("Update task").option("-s, --status <status>", "New status").option("--branch <branch>", "Branch name").option("--pr-url <url>", "Pull request URL").action((taskId, options) => taskCommand("update", { taskId, ...options }));
4368
+ program2.command("watch").description("Start the Playwright daemon to monitor Claude Code sessions").option("--interval <minutes>", "Check interval in minutes", "5").option("--once", "Run once and exit").option("--auto-pr", 'Automatically click "Create PR" button when found').option("--no-headless", "Run browser in visible mode (for debugging)").action(watchCommand);
4369
+ program2.command("status").description("Show status of all active tasks").option("-p, --project <id>", "Filter by project").action(statusCommand);
4370
+ program2.command("prompt <task-id>").description("Get a prompt for a task (ready to paste into Claude)").option("--type <type>", "Prompt type: review, test_plan, summary, handoff", "review").action(promptCommand);
4371
+ var org = program2.command("org").description("Organization management");
4372
+ org.command("list").description("List connected organizations").action(orgListCommand);
4373
+ org.command("add").description("Connect to a new organization").action(orgAddCommand);
4374
+ org.command("remove <org-id>").description("Disconnect from an organization").action(orgRemoveCommand);
4375
+ org.command("default <org-id>").description("Set default organization").action(orgSetDefaultCommand);
4376
+ program2.command("context").description("Show current repository context and mapped organization").action(contextCommand);
4377
+ program2.command("sync").description("Refresh project-to-repository mappings from all organizations").action(syncCommand);
4378
+ program2.command("mount <task-id>").description("Mount preview environment filesystem via SSHFS").option("--vscode", "Open in VS Code after mounting").action((taskId) => {
4379
+ console.log("\u26A0\uFE0F Mount command requires preview environments (Phase 9)");
4380
+ console.log(` Task ID: ${taskId}`);
4381
+ console.log("");
4382
+ console.log("Preview environments are not yet implemented.");
4383
+ console.log("This feature will be available in a future release.");
4384
+ });
4385
+ program2.command("unmount <task-id>").description("Unmount a task filesystem").action((taskId) => {
4386
+ console.log("\u26A0\uFE0F Unmount command requires preview environments (Phase 9)");
4387
+ console.log(` Task ID: ${taskId}`);
4388
+ });
4389
+ program2.command("logs <task-id>").description("Stream logs from a preview environment").option("-f, --follow", "Follow log output").option("--process <name>", "Filter by process name").action((taskId) => {
4390
+ console.log("\u26A0\uFE0F Logs command requires preview environments (Phase 9)");
4391
+ console.log(` Task ID: ${taskId}`);
4392
+ });
4393
+ program2.parse();
4394
+ //# sourceMappingURL=main.js.map