flightdesk 0.4.0 → 0.4.1

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 +4523 -85
  2. package/main.js.map +2 -2
  3. package/package.json +1 -1
package/main.js CHANGED
@@ -1,28 +1,3200 @@
1
1
  #!/usr/bin/env node
2
- var Ke=Object.create;var he=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var P=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Xe=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Je(e))!Ze.call(i,s)&&s!==t&&he(i,s,{get:()=>e[s],enumerable:!(n=Ye(e,s))||n.enumerable});return i};var A=(i,e,t)=>(t=i!=null?Ke(Qe(i)):{},Xe(e||!i||!i.__esModule?he(t,"default",{value:i,enumerable:!0}):t,i));var N=P(G=>{var H=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},M=class extends H{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};G.CommanderError=H;G.InvalidArgumentError=M});var V=P(B=>{var{InvalidArgumentError:et}=N(),W=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new et(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function tt(i){let e=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+e+">":"["+e+"]"}B.Argument=W;B.humanReadableArgName=tt});var Y=P(pe=>{var{humanReadableArgName:nt}=V(),K=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>nt(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,o=2,r=2;function a(p,v){if(v){let L=`${p.padEnd(n+r)}${v}`;return t.wrap(L,s-o,n+r)}return p}function c(p){return p.join(`
3
- `).replace(/^/gm," ".repeat(o))}let l=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(l=l.concat([t.wrap(u,s,0),""]));let g=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));g.length>0&&(l=l.concat(["Arguments:",c(g),""]));let w=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(w.length>0&&(l=l.concat(["Options:",c(w),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(v=>a(t.optionTerm(v),t.optionDescription(v)));p.length>0&&(l=l.concat(["Global Options:",c(p),""]))}let $=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return $.length>0&&(l=l.concat(["Commands:",c($),""])),l.join(`
4
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",r=new RegExp(`[\\n][${o}]+`);if(e.match(r))return e;let a=t-n;if(a<s)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
5
- `,`
6
- `),u=" ".repeat(n),w="\\s\u200B",$=new RegExp(`
7
- |.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),p=l.match($)||[];return c+p.map((v,L)=>v===`
8
- `?"":(L>0?u:"")+v.trimEnd()).join(`
9
- `)}};pe.Help=K});var X=P(Z=>{var{InvalidArgumentError:st}=N(),J=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=ot(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new st(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return it(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Q=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function it(i){return i.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ot(i){let e,t,n=i.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Z.Option=J;Z.DualOptions=Q});var me=P(de=>{function rt(i,e){if(Math.abs(i.length-e.length)>3)return Math.max(i.length,e.length);let t=[];for(let n=0;n<=i.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=i.length;s++){let o=1;i[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&i[s-1]===e[n-2]&&i[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[i.length][e.length]}function at(i,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=i.startsWith("--");t&&(i=i.slice(2),e=e.map(r=>r.slice(2)));let n=[],s=3,o=.4;return e.forEach(r=>{if(r.length<=1)return;let a=rt(i,r),c=Math.max(i.length,r.length);(c-a)/c>o&&(a<s?(s=a,n=[r]):a===s&&n.push(r))}),n.sort((r,a)=>r.localeCompare(a)),t&&(n=n.map(r=>`--${r}`)),n.length>1?`
10
- (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
- (Did you mean ${n[0]}?)`:""}de.suggestSimilar=at});var _e=P(ye=>{var ct=require("node:events").EventEmitter,ee=require("node:child_process"),O=require("node:path"),te=require("node:fs"),h=require("node:process"),{Argument:lt,humanReadableArgName:ut}=V(),{CommanderError:ne}=N(),{Help:gt}=Y(),{Option:fe,DualOptions:ht}=X(),{suggestSimilar:we}=me(),se=class i extends ct{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>h.stdout.write(t),writeErr:t=>h.stderr.write(t),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,r,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(r);return s&&(c.description(s),c._executableHandler=!0),o.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(o.noHelp||o.hidden),c._executableFile=o.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new i(e)}createHelp(){return Object.assign(new gt,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new lt(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",r=this.createCommand(n);return r.helpOption(!1),s&&r.arguments(s),o&&r.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new ne(e,t,n)),h.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new fe(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let r=`${s} ${o.message}`;this.error(r,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,r,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let c=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,c,r):o!==null&&e.variadic&&(o=e._concatValue(o,c)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let r=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let r=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,r,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof fe)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,n);if(r.makeOptionMandatory(!!e.mandatory),typeof s=="function")r.default(o).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let u=a.exec(c);return u?u[0]:l},r.default(o).argParser(s)}else r.default(s);return this.addOption(r)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from="electron");let s=h.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(u,g){let w=O.resolve(u,g);if(te.existsSync(w))return w;if(s.includes(O.extname(g)))return;let $=s.find(p=>te.existsSync(`${w}${p}`));if($)return`${w}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=te.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=O.resolve(O.dirname(u),a)}if(a){let u=o(a,r);if(!u&&!e._executableFile&&this._scriptPath){let g=O.basename(this._scriptPath,O.extname(this._scriptPath));g!==this._name&&(u=o(a,`${g}-${e._name}`))}r=u||r}n=s.includes(O.extname(r));let c;h.platform!=="win32"?n?(t.unshift(r),t=ke(h.execArgv).concat(t),c=ee.spawn(h.argv[0],t,{stdio:"inherit"})):c=ee.spawn(r,t,{stdio:"inherit"}):(t.unshift(r),t=ke(h.execArgv).concat(t),c=ee.spawn(h.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(g=>{h.on(g,()=>{c.killed===!1&&c.exitCode===null&&c.kill(g)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new ne(u,"commander.executeSubCommandAsync","(close)")):h.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let g=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",w=`'${r}' does not exist
15
- - if '${e._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
16
1980
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${g}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!l)h.exit(1);else{let g=new ne(1,"commander.executeSubCommandAsync","(error)");g.nestedError=u,l(g)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,o)=>{let r=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;r=this._callParseArg(n,s,o,a)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((r,a)=>e(n,a,r),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(r=>{s.push({hookedCommand:o,callback:r})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),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,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function r(c){return c.length>1&&c[0]==="-"}let a=null;for(;o.length;){let c=o.shift();if(c==="--"){s===n&&s.push(c),s.push(...o);break}if(a&&!r(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,r(c)){let l=this._findOption(c);if(l){if(l.required){let u=o.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;o.length>0&&!r(o[0])&&(u=o.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(r(c)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(c),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(c),o.length>0&&s.push(...o);break}s.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
- `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ht(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=r=>{let a=r.attributeName(),c=this.getOptionValue(a),l=this.options.find(g=>g.negate&&a===g.attributeName()),u=this.options.find(g=>!g.negate&&a===g.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||r},s=r=>{let a=n(r),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let r=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(r),o=o.parent}while(o&&!o._enablePositionalOptions);t=we(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=we(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>ut(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=O.basename(e,O.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=h.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
- Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let r;typeof t=="function"?r=t({error:o.error,command:o.command}):r=t,r&&o.write(`${r}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ke(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}ye.Command=se});var Ae=P(k=>{var{Argument:Oe}=V(),{Command:ie}=_e(),{CommanderError:pt,InvalidArgumentError:Ie}=N(),{Help:dt}=Y(),{Option:ve}=X();k.program=new ie;k.createCommand=i=>new ie(i);k.createOption=(i,e)=>new ve(i,e);k.createArgument=(i,e)=>new Oe(i,e);k.Command=ie;k.Option=ve;k.Argument=Oe;k.Help=dt;k.CommanderError=pt;k.InvalidArgumentError=Ie;k.InvalidOptionArgumentError=Ie});var Ce=A(Ae(),1),{program:Kt,createCommand:Yt,createArgument:Jt,createOption:Qt,CommanderError:Zt,InvalidArgumentError:Xt,InvalidOptionArgumentError:en,Command:be,Argument:tn,Option:nn,Help:sn}=Ce.default;var T=A(require("fs")),$e=A(require("path")),Pe=A(require("os")),U=$e.join(Pe.homedir(),".flightdeskrc"),mt="https://api.flightdesk.dev",ft="http://localhost:3000",oe=null;function Ee(i){i&&(oe=ft)}function Se(i){oe=i}function C(){return oe??mt}function m(){try{if(T.existsSync(U)){let i=T.readFileSync(U,"utf-8"),e=JSON.parse(i);return{organizations:[],repoMapping:{},...e}}}catch(i){console.error("Warning: Failed to load config file:",i)}return{organizations:[],repoMapping:{}}}function x(i){T.writeFileSync(U,JSON.stringify(i,null,2))}function b(){let i=m();return i.activeOrganization?i.organizations.find(e=>e.id===i.activeOrganization)||null:i.organizations.length===1?i.organizations[0]:null}function Te(i){let e=m(),t=e.organizations.find(n=>n.id===i||n.name.toLowerCase()===i.toLowerCase());if(!t)throw new Error(`Organization not found: ${i}`);e.activeOrganization=t.id,x(e)}function xe(i){let e=m();e.organizations=i,e.activeOrganization&&!i.some(t=>t.id===e.activeOrganization)&&(e.activeOrganization=i[0]?.id),x(e)}function q(i){let e=m(),t=e.repoMapping[i];return t&&e.organizations.find(n=>n.id===t)||null}function R(){let i=m();return!!i.apiKey&&i.organizations.length>0}function re(){let i=m();return i.apiKey||(console.error("\u274C FlightDesk is not configured. Run: flightdesk init"),process.exit(1)),i.organizations.length===0&&(console.error("\u274C No organizations found. Run: flightdesk init"),process.exit(1)),i}function y(){let i=re(),e=b();return e||(console.error("\u274C No active organization. Run: flightdesk org switch <org-name>"),console.log(`
24
- Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}`)),process.exit(1)),{config:i,org:e}}var Re=A(require("readline"));var f=class i{constructor(e,t){if(!e.apiKey)throw new Error("API key is required. Run: flightdesk login");this.apiUrl=C(),this.apiKey=e.apiKey,this.organizationId=t.id}static fromConfig(e,t){return new i(e,t)}async graphql(e,t){let n=process.env.FLIGHTDESK_DEBUG==="1";n&&(console.log(`
25
- --- GraphQL Request ---`),console.log("URL:",`${this.apiUrl}/graphql`),console.log("Variables:",JSON.stringify(t,null,2)));let s=await fetch(`${this.apiUrl}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({query:e,variables:t})});if(!s.ok){let r=await s.text();throw n&&(console.log("--- Error Response ---"),console.log("Status:",s.status,s.statusText),console.log("Body:",r)),new Error(`API request failed: ${s.status} ${s.statusText}${n?"":" (set FLIGHTDESK_DEBUG=1 for details)"}`)}let o=await s.json();if(n&&(console.log("--- Response ---"),console.log(JSON.stringify(o,null,2))),o.errors&&o.errors.length>0)throw new Error(`GraphQL error: ${o.errors.map(r=>r.message).join(", ")}`);return o.data}async createTask(e){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/lib/config.ts
3039
+ var fs = __toESM(require("fs"));
3040
+ var path = __toESM(require("path"));
3041
+ var os = __toESM(require("os"));
3042
+ var CONFIG_FILE = path.join(os.homedir(), ".flightdeskrc");
3043
+ var DEFAULT_API_URL = "https://api.flightdesk.dev";
3044
+ var DEV_API_URL = "http://localhost:3000";
3045
+ var apiUrlOverride = null;
3046
+ function setDevMode(enabled) {
3047
+ if (enabled) {
3048
+ apiUrlOverride = DEV_API_URL;
3049
+ }
3050
+ }
3051
+ function setApiUrl(url) {
3052
+ apiUrlOverride = url;
3053
+ }
3054
+ function getApiUrl() {
3055
+ return apiUrlOverride ?? DEFAULT_API_URL;
3056
+ }
3057
+ function loadConfig() {
3058
+ try {
3059
+ if (fs.existsSync(CONFIG_FILE)) {
3060
+ const content = fs.readFileSync(CONFIG_FILE, "utf-8");
3061
+ const parsed = JSON.parse(content);
3062
+ return {
3063
+ organizations: [],
3064
+ repoMapping: {},
3065
+ ...parsed
3066
+ };
3067
+ }
3068
+ } catch (error) {
3069
+ console.error("Warning: Failed to load config file:", error);
3070
+ }
3071
+ return {
3072
+ organizations: [],
3073
+ repoMapping: {}
3074
+ };
3075
+ }
3076
+ function saveConfig(config) {
3077
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
3078
+ }
3079
+ function getActiveOrganization() {
3080
+ const config = loadConfig();
3081
+ if (!config.activeOrganization) {
3082
+ if (config.organizations.length === 1) {
3083
+ return config.organizations[0];
3084
+ }
3085
+ return null;
3086
+ }
3087
+ return config.organizations.find((o) => o.id === config.activeOrganization) || null;
3088
+ }
3089
+ function setActiveOrganization(orgId) {
3090
+ const config = loadConfig();
3091
+ const org2 = config.organizations.find((o) => o.id === orgId || o.name.toLowerCase() === orgId.toLowerCase());
3092
+ if (!org2) {
3093
+ throw new Error(`Organization not found: ${orgId}`);
3094
+ }
3095
+ config.activeOrganization = org2.id;
3096
+ saveConfig(config);
3097
+ }
3098
+ function updateOrganizations(orgs) {
3099
+ const config = loadConfig();
3100
+ config.organizations = orgs;
3101
+ if (config.activeOrganization && !orgs.some((o) => o.id === config.activeOrganization)) {
3102
+ config.activeOrganization = orgs[0]?.id;
3103
+ }
3104
+ saveConfig(config);
3105
+ }
3106
+ function getOrganizationByRepo(repoFullName) {
3107
+ const config = loadConfig();
3108
+ const orgId = config.repoMapping[repoFullName];
3109
+ if (!orgId) return null;
3110
+ return config.organizations.find((o) => o.id === orgId) || null;
3111
+ }
3112
+ function isConfigured() {
3113
+ const config = loadConfig();
3114
+ return !!config.apiKey && config.organizations.length > 0;
3115
+ }
3116
+ function requireConfig() {
3117
+ const config = loadConfig();
3118
+ if (!config.apiKey) {
3119
+ console.error("\u274C FlightDesk is not configured. Run: flightdesk init");
3120
+ process.exit(1);
3121
+ }
3122
+ if (config.organizations.length === 0) {
3123
+ console.error("\u274C No organizations found. Run: flightdesk init");
3124
+ process.exit(1);
3125
+ }
3126
+ return config;
3127
+ }
3128
+ function requireActiveOrg() {
3129
+ const config = requireConfig();
3130
+ const org2 = getActiveOrganization();
3131
+ if (!org2) {
3132
+ console.error("\u274C No active organization. Run: flightdesk org switch <org-name>");
3133
+ console.log("\nAvailable organizations:");
3134
+ config.organizations.forEach((o) => console.log(` - ${o.name}`));
3135
+ process.exit(1);
3136
+ }
3137
+ return { config, org: org2 };
3138
+ }
3139
+
3140
+ // apps/cli/src/commands/init.ts
3141
+ var readline = __toESM(require("readline"));
3142
+
3143
+ // apps/cli/src/lib/api.ts
3144
+ var FlightDeskAPI = class _FlightDeskAPI {
3145
+ constructor(config, org2) {
3146
+ if (!config.apiKey) {
3147
+ throw new Error("API key is required. Run: flightdesk login");
3148
+ }
3149
+ this.apiUrl = getApiUrl();
3150
+ this.apiKey = config.apiKey;
3151
+ this.organizationId = org2.id;
3152
+ }
3153
+ /**
3154
+ * Create an API client from config, using the active organization
3155
+ */
3156
+ static fromConfig(config, org2) {
3157
+ return new _FlightDeskAPI(config, org2);
3158
+ }
3159
+ async graphql(query, variables) {
3160
+ const verbose = process.env.FLIGHTDESK_DEBUG === "1";
3161
+ if (verbose) {
3162
+ console.log("\n--- GraphQL Request ---");
3163
+ console.log("URL:", `${this.apiUrl}/graphql`);
3164
+ console.log("Variables:", JSON.stringify(variables, null, 2));
3165
+ }
3166
+ const response = await fetch(`${this.apiUrl}/graphql`, {
3167
+ method: "POST",
3168
+ headers: {
3169
+ "Content-Type": "application/json",
3170
+ "Authorization": `Bearer ${this.apiKey}`
3171
+ },
3172
+ body: JSON.stringify({ query, variables })
3173
+ });
3174
+ if (!response.ok) {
3175
+ const body = await response.text();
3176
+ if (verbose) {
3177
+ console.log("--- Error Response ---");
3178
+ console.log("Status:", response.status, response.statusText);
3179
+ console.log("Body:", body);
3180
+ }
3181
+ throw new Error(`API request failed: ${response.status} ${response.statusText}${verbose ? "" : " (set FLIGHTDESK_DEBUG=1 for details)"}`);
3182
+ }
3183
+ const result = await response.json();
3184
+ if (verbose) {
3185
+ console.log("--- Response ---");
3186
+ console.log(JSON.stringify(result, null, 2));
3187
+ }
3188
+ if (result.errors && result.errors.length > 0) {
3189
+ throw new Error(`GraphQL error: ${result.errors.map((e) => e.message).join(", ")}`);
3190
+ }
3191
+ return result.data;
3192
+ }
3193
+ // ============================================================================
3194
+ // Task Operations
3195
+ // ============================================================================
3196
+ async createTask(input) {
3197
+ const query = `
26
3198
  mutation CreateTask($input: UserCreateTaskInput!) {
27
3199
  userCreateTask(input: $input) {
28
3200
  id
@@ -31,7 +3203,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
31
3203
  createdAt
32
3204
  }
33
3205
  }
34
- `,{input:e})).userCreateTask}async updateTask(e,t){return(await this.graphql(`
3206
+ `;
3207
+ const result = await this.graphql(query, { input });
3208
+ return result.userCreateTask;
3209
+ }
3210
+ async updateTask(taskId, input) {
3211
+ const query = `
35
3212
  mutation UpdateTask($taskId: String!, $input: UserUpdateTaskInput!) {
36
3213
  userUpdateTask(taskId: $taskId, input: $input) {
37
3214
  id
@@ -44,7 +3221,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
44
3221
  sessionTeleportId
45
3222
  }
46
3223
  }
47
- `,{taskId:e,input:t})).userUpdateTask}async registerSession(e,t){return(await this.graphql(`
3224
+ `;
3225
+ const result = await this.graphql(query, { taskId, input });
3226
+ return result.userUpdateTask;
3227
+ }
3228
+ async registerSession(taskId, input) {
3229
+ const query = `
48
3230
  mutation RegisterSession($taskId: String!, $input: RegisterSessionInput!) {
49
3231
  userRegisterSession(taskId: $taskId, input: $input) {
50
3232
  id
@@ -54,7 +3236,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
54
3236
  sessionTeleportId
55
3237
  }
56
3238
  }
57
- `,{taskId:e,input:t})).userRegisterSession}async getTask(e){return(await this.graphql(`
3239
+ `;
3240
+ const result = await this.graphql(query, { taskId, input });
3241
+ return result.userRegisterSession;
3242
+ }
3243
+ async getTask(taskId) {
3244
+ const query = `
58
3245
  query GetTask($taskId: String!) {
59
3246
  userTask(taskId: $taskId) {
60
3247
  id
@@ -75,7 +3262,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
75
3262
  }
76
3263
  }
77
3264
  }
78
- `,{taskId:e})).userTask}async listTasks(e){let t=`
3265
+ `;
3266
+ const result = await this.graphql(query, { taskId });
3267
+ return result.userTask;
3268
+ }
3269
+ async listTasks(options) {
3270
+ const query = `
79
3271
  query ListTasks($input: ListTasksInput!) {
80
3272
  userTasks(input: $input) {
81
3273
  id
@@ -91,7 +3283,22 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
91
3283
  }
92
3284
  }
93
3285
  }
94
- `,n={};return e?.projectId&&(n.projectId=e.projectId),e?.status&&(n.status=Array.isArray(e.status)?e.status:[e.status]),e?.limit&&(n.limit=e.limit),(await this.graphql(t,{input:n})).userTasks}async syncTaskChecks(e){return(await this.graphql(`
3286
+ `;
3287
+ const input = {};
3288
+ if (options?.projectId) {
3289
+ input.projectId = options.projectId;
3290
+ }
3291
+ if (options?.status) {
3292
+ input.status = Array.isArray(options.status) ? options.status : [options.status];
3293
+ }
3294
+ if (options?.limit) {
3295
+ input.limit = options.limit;
3296
+ }
3297
+ const result = await this.graphql(query, { input });
3298
+ return result.userTasks;
3299
+ }
3300
+ async syncTaskChecks(taskId) {
3301
+ const query = `
95
3302
  mutation SyncTaskChecks($taskId: String!) {
96
3303
  userSyncTaskChecks(taskId: $taskId) {
97
3304
  synced
@@ -102,7 +3309,15 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
102
3309
  }
103
3310
  }
104
3311
  }
105
- `,{taskId:e})).userSyncTaskChecks}async listProjects(){return(await this.graphql(`
3312
+ `;
3313
+ const result = await this.graphql(query, { taskId });
3314
+ return result.userSyncTaskChecks;
3315
+ }
3316
+ // ============================================================================
3317
+ // Project Operations
3318
+ // ============================================================================
3319
+ async listProjects() {
3320
+ const query = `
106
3321
  query ListProjects($organizationId: String!) {
107
3322
  userProjects(organizationId: $organizationId) {
108
3323
  id
@@ -110,7 +3325,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
110
3325
  githubRepo
111
3326
  }
112
3327
  }
113
- `,{organizationId:this.organizationId})).userProjects}async getProject(e){return(await this.graphql(`
3328
+ `;
3329
+ const result = await this.graphql(query, { organizationId: this.organizationId });
3330
+ return result.userProjects;
3331
+ }
3332
+ async getProject(projectId) {
3333
+ const query = `
114
3334
  query GetProject($projectId: String!) {
115
3335
  userProject(projectId: $projectId) {
116
3336
  id
@@ -119,7 +3339,12 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
119
3339
  tokenTtlHours
120
3340
  }
121
3341
  }
122
- `,{projectId:e})).userProject}async createProject(e){return(await this.graphql(`
3342
+ `;
3343
+ const result = await this.graphql(query, { projectId });
3344
+ return result.userProject;
3345
+ }
3346
+ async createProject(input) {
3347
+ const query = `
123
3348
  mutation CreateProject($input: UserCreateProjectInput!) {
124
3349
  userCreateProject(input: $input) {
125
3350
  id
@@ -129,14 +3354,30 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
129
3354
  createdAt
130
3355
  }
131
3356
  }
132
- `,{input:e})).userCreateProject}async createTaskToken(e){return(await this.graphql(`
3357
+ `;
3358
+ const result = await this.graphql(query, { input });
3359
+ return result.userCreateProject;
3360
+ }
3361
+ // ============================================================================
3362
+ // Task Token Operations (for agent authentication)
3363
+ // ============================================================================
3364
+ async createTaskToken(taskId) {
3365
+ const query = `
133
3366
  mutation CreateTaskToken($taskId: String!) {
134
3367
  userCreateTaskToken(taskId: $taskId) {
135
3368
  token
136
3369
  expiresAt
137
3370
  }
138
3371
  }
139
- `,{taskId:e})).userCreateTaskToken}async getTaskPrompts(e){return(await this.graphql(`
3372
+ `;
3373
+ const result = await this.graphql(query, { taskId });
3374
+ return result.userCreateTaskToken;
3375
+ }
3376
+ // ============================================================================
3377
+ // Prompt Operations
3378
+ // ============================================================================
3379
+ async getTaskPrompts(taskId) {
3380
+ const query = `
140
3381
  query GetTaskPrompts($taskId: String!) {
141
3382
  userTaskPrompts(taskId: $taskId) {
142
3383
  type
@@ -145,7 +3386,15 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
145
3386
  reason
146
3387
  }
147
3388
  }
148
- `,{taskId:e})).userTaskPrompts}async getTaskInstance(e){return(await this.graphql(`
3389
+ `;
3390
+ const result = await this.graphql(query, { taskId });
3391
+ return result.userTaskPrompts;
3392
+ }
3393
+ // ============================================================================
3394
+ // Preview Environment Operations
3395
+ // ============================================================================
3396
+ async getTaskInstance(taskId) {
3397
+ const query = `
149
3398
  query GetTaskInstance($taskId: String!) {
150
3399
  userTaskInstance(taskId: $taskId) {
151
3400
  id
@@ -169,25 +3418,58 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
169
3418
  }
170
3419
  }
171
3420
  }
172
- `,{taskId:e})).userTaskInstance}async getInstanceLogs(e,t=100){return(await this.graphql(`
3421
+ `;
3422
+ const result = await this.graphql(query, { taskId });
3423
+ return result.userTaskInstance;
3424
+ }
3425
+ async getInstanceLogs(taskId, lines = 100) {
3426
+ const query = `
173
3427
  query GetInstanceLogs($taskId: String!, $lines: Float) {
174
3428
  userInstanceLogs(taskId: $taskId, lines: $lines) {
175
3429
  logs
176
3430
  }
177
3431
  }
178
- `,{taskId:e,lines:t})).userInstanceLogs}async restartInstance(e){return(await this.graphql(`
3432
+ `;
3433
+ const result = await this.graphql(query, { taskId, lines });
3434
+ return result.userInstanceLogs;
3435
+ }
3436
+ async restartInstance(taskId) {
3437
+ const query = `
179
3438
  mutation RestartInstance($taskId: String!) {
180
3439
  userRestartInstance(taskId: $taskId)
181
3440
  }
182
- `,{taskId:e})).userRestartInstance}async resumeInstance(e){return(await this.graphql(`
3441
+ `;
3442
+ const result = await this.graphql(query, { taskId });
3443
+ return result.userRestartInstance;
3444
+ }
3445
+ async resumeInstance(taskId) {
3446
+ const query = `
183
3447
  mutation ResumeInstance($taskId: String!) {
184
3448
  userResumeInstance(taskId: $taskId)
185
3449
  }
186
- `,{taskId:e})).userResumeInstance}async tearDownInstance(e){return(await this.graphql(`
3450
+ `;
3451
+ const result = await this.graphql(query, { taskId });
3452
+ return result.userResumeInstance;
3453
+ }
3454
+ async tearDownInstance(taskId) {
3455
+ const query = `
187
3456
  mutation TearDownInstance($taskId: String!) {
188
3457
  userTearDownInstance(taskId: $taskId)
189
3458
  }
190
- `,{taskId:e})).userTearDownInstance}};async function F(i,e="https://api.flightdesk.dev"){let t=await fetch(`${e}/graphql`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:`{
3459
+ `;
3460
+ const result = await this.graphql(query, { taskId });
3461
+ return result.userTearDownInstance;
3462
+ }
3463
+ };
3464
+ async function fetchUserInfo(apiKey, apiUrl = "https://api.flightdesk.dev") {
3465
+ const response = await fetch(`${apiUrl}/graphql`, {
3466
+ method: "POST",
3467
+ headers: {
3468
+ "Content-Type": "application/json",
3469
+ "Authorization": `Bearer ${apiKey}`
3470
+ },
3471
+ body: JSON.stringify({
3472
+ query: `{
191
3473
  me {
192
3474
  id
193
3475
  emails {
@@ -201,50 +3483,1206 @@ Available organizations:`),i.organizations.forEach(t=>console.log(` - ${t.name}
201
3483
  }
202
3484
  }
203
3485
  }
204
- }`})});if(!t.ok)throw new Error(`API returned ${t.status}`);let n=await t.json();if(n.errors?.length)throw new Error(n.errors.map(s=>s.message).join(", "));if(!n.data?.me)throw new Error("Invalid API response");return n.data.me}function ae(i,e){return new Promise(t=>{i.question(e,n=>{t(n.trim())})})}async function De(){let i=Re.createInterface({input:process.stdin,output:process.stdout});console.log(`
205
- \u{1F6EB} FlightDesk CLI Setup
206
- `);try{if(R()){let n=m();if(console.log("FlightDesk is already configured."),console.log(` API Key: ${n.apiKey?.substring(0,20)}...`),console.log(` Organizations: ${n.organizations.map(o=>o.name).join(", ")}`),console.log(""),(await ae(i,"Reconfigure? (y/N): ")).toLowerCase()!=="y"){console.log(`
207
- Configuration unchanged.`),console.log('Use "flightdesk org refresh" to update organizations.'),console.log('Use "flightdesk org switch <name>" to change active organization.');return}}console.log("Enter your FlightDesk API key."),console.log(`You can find this at https://flightdesk.dev/settings/api-keys
208
- `);let e=await ae(i,"API Key: ");if(!e){console.error("API Key is required");return}let t=C();console.log(`
209
- Connecting to FlightDesk...`);try{let n=await F(e,t),s=n.organizations||[];if(s.length===0){console.error("\u274C No organizations found for this user"),console.log("Please make sure you are a member of at least one organization.");return}let o=n.emails?.find(l=>l.primary)?.email||n.emails?.[0]?.email||"unknown";console.log("\u2705 Connection successful!"),console.log(` Logged in as: ${o}`),console.log(` Organizations: ${s.length}`);let r=s.map(l=>({id:l.organization.id,name:l.organization.name})),a;if(r.length===1)a=r[0].id,console.log(`
210
- Active organization: ${r[0].name}`);else{console.log(`
211
- Your organizations:`),r.forEach((g,w)=>{console.log(` ${w+1}. ${g.name}`)});let l=await ae(i,`
212
- Select active organization (1-${r.length}): `),u=Number.parseInt(l,10)-1;u<0||u>=r.length?(console.error("Invalid selection, using first organization"),a=r[0].id):a=r[u].id}let c=m();c.apiKey=e,c.apiUrl=t,c.organizations=r,c.activeOrganization=a,x(c),console.log(`
213
- \u2705 Configuration saved to ${U}`),console.log(`
214
- You can now use:`),console.log(" flightdesk project list - List projects"),console.log(" flightdesk task create - Create a task"),console.log(" flightdesk org list - Show organizations"),console.log(" flightdesk org switch <name> - Switch active organization")}catch(n){console.error(`
215
- \u274C Connection failed: ${n}`),console.log(`
216
- Please check:`),console.log(" - Your API key is correct"),console.log(" - You have network connectivity"),console.log(" - The FlightDesk API is reachable")}}finally{i.close()}}var ce=require("node:child_process");function je(){try{let i=(0,ce.execSync)("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),e=wt(i);if(!e)return null;let t=(0,ce.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return{remote:e,branch:t,remoteUrl:i}}catch{return null}}function wt(i){let t=/git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/.exec(i);if(t)return t[1];let s=/https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/.exec(i);return s?s[1]:null}async function Ne(i,e){let{config:t,org:n}=y(),s=f.fromConfig(t,n);try{let o=e.project;o||(o=await _t(s,n));let r=e.viewUrl,a=e.teleportId;if(!process.stdin.isTTY){console.log("\u23F3 Waiting for Claude session output...");let l=await kt(),u=yt(l);r=r||u.viewUrl,a=a||u.teleportId}let c=i;if(!c){e.title||(console.error('Task title required when creating a new task. Use --title "..."'),process.exit(1)),console.log(`Creating task: ${e.title}`);let l=await s.createTask({projectId:o,title:e.title,description:e.description});c=l.id,console.log(`\u2705 Created task: ${l.id}`)}(r||a)&&(console.log("Registering session with task..."),await s.updateTask(c,{sessionViewUrl:r,sessionTeleportId:a,status:"DISPATCHED"}),console.log("\u2705 Session registered")),console.log(`
217
- Task ID: ${c}`),r&&console.log(`Session: ${r}`),a&&console.log(`Resume: claude --teleport ${a}`)}catch(o){console.error(`Error: ${o}`),process.exit(1)}}function kt(){return new Promise(i=>{let e="",t=!1;process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{e+=n}),process.stdin.on("end",()=>{t||(t=!0,i(e))}),process.stdin.on("close",()=>{t||(t=!0,i(e))}),setTimeout(()=>{t||(t=!0,i(e))},3e4)})}function yt(i){let e={},t=i.match(/View:\s+(https:\/\/claude\.ai\/code\/session_[^\s]+)/);t&&(e.viewUrl=t[1]);let n=i.match(/--teleport\s+(session_[^\s]+)/);return n&&(e.teleportId=n[1]),e}async function _t(i,e){let t=je();t||(console.error("\u274C Not in a git repository. Please provide a project ID."),console.error(" Usage: flightdesk register --project <project-id> [task-id]"),process.exit(1)),console.log(`\u{1F50D} Detecting project from repository: ${t.remote}`);let n=q(t.remote);n||(console.error(`\u274C Repository "${t.remote}" is not mapped to any organization.`),console.error(" Run: flightdesk sync"),console.error(" Or provide a project ID: flightdesk register --project <project-id> [task-id]"),process.exit(1)),n.id!==e.id&&(console.error(`\u274C Repository "${t.remote}" is mapped to organization "${n.name}",`),console.error(` but your active organization is "${e.name}".`),console.error(" Switch with: flightdesk org switch "+n.name),console.error(" Or provide a project ID: flightdesk register --project <project-id> [task-id]"),process.exit(1));let s=await i.listProjects(),o=s.filter(a=>a.githubRepo?.toLowerCase()===t.remote.toLowerCase());if(o.length===0){console.error(`\u274C No FlightDesk project found for repository "${t.remote}".`),console.error(" Available projects in this organization:");for(let a of s)console.error(` - ${a.name} (${a.githubRepo||"no repo"}) [${a.id}]`);console.error(`
218
- Create a project or provide a project ID explicitly.`),process.exit(1)}if(o.length>1){console.error(`\u274C Multiple projects found for repository "${t.remote}":`);for(let a of o)console.error(` - ${a.name} [${a.id}]`);console.error(`
219
- Please specify the project ID explicitly.`),process.exit(1)}let r=o[0];return console.log(`\u2705 Found project: ${r.name} (${r.id})`),r.id}async function Ue(i){let{config:e,org:t}=y(),n=f.fromConfig(e,t);try{let s=await n.listTasks({projectId:i.project});if(s.length===0){console.log("No tasks found.");return}let o={};for(let a of s)o[a.status]||(o[a.status]=[]),o[a.status].push(a);let r=["PENDING","DISPATCHED","IN_PROGRESS","BRANCH_CREATED","PR_OPEN","PREVIEW_STARTING","PREVIEW_READY","REVIEW_RUNNING","REVIEW_DONE","QA_READY","QA_APPROVED","MERGED","ARCHIVED"];console.log(`
220
- \u{1F4CB} FlightDesk Tasks
221
- `);for(let a of r){let c=o[a];if(!(!c||c.length===0)){console.log(`${Ot(a)} ${a} (${c.length})`);for(let l of c)console.log(` ${l.id.slice(0,8)} - ${l.title}`),l.branchName&&console.log(` Branch: ${l.branchName}`),l.prUrl&&console.log(` PR: ${l.prUrl}`);console.log("")}}}catch(s){console.error(`Error: ${s}`),process.exit(1)}}function Ot(i){switch(i){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 D(i,e){let{config:t,org:n}=y(),s=f.fromConfig(t,n);try{switch(i){case"create":await It(s,e);break;case"list":await vt(s,e);break;case"status":await At(s,e);break;case"update":await bt(s,e);break;case"sync":await $t(s,e);break}}catch(o){console.error(`Error: ${o}`),process.exit(1)}}async function It(i,e){console.log(`Creating task: ${e.title}`);let t=await i.createTask({projectId:e.project,title:e.title,description:e.description});console.log(`
222
- \u2705 Task created`),console.log(` ID: ${t.id}`),console.log(` Title: ${t.title}`),console.log(` Status: ${t.status}`)}async function vt(i,e){let t=await i.listTasks({projectId:e.project,status:e.status});if(t.length===0){console.log("No tasks found.");return}console.log(`
223
- Tasks:
224
- `);for(let n of t){let s=He(n.status);console.log(`${s} ${n.id.slice(0,8)} - ${n.title}`),n.project?.name&&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 At(i,e){let t=await i.getTask(e.taskId);t||(console.error("Task not found"),process.exit(1)),console.log(`
225
- \u{1F4CB} Task: ${t.title}
226
- `),console.log(`ID: ${t.id}`),console.log(`Status: ${He(t.status)} ${t.status}`),t.project&&console.log(`Project: ${t.project.name}${t.project.githubRepo?` (${t.project.githubRepo})`:""}`),t.description&&console.log(`
3486
+ }`
3487
+ })
3488
+ });
3489
+ if (!response.ok) {
3490
+ throw new Error(`API returned ${response.status}`);
3491
+ }
3492
+ const result = await response.json();
3493
+ if (result.errors?.length) {
3494
+ throw new Error(result.errors.map((e) => e.message).join(", "));
3495
+ }
3496
+ if (!result.data?.me) {
3497
+ throw new Error("Invalid API response");
3498
+ }
3499
+ return result.data.me;
3500
+ }
3501
+
3502
+ // apps/cli/src/commands/init.ts
3503
+ function question(rl, prompt) {
3504
+ return new Promise((resolve) => {
3505
+ rl.question(prompt, (answer) => {
3506
+ resolve(answer.trim());
3507
+ });
3508
+ });
3509
+ }
3510
+ async function initCommand() {
3511
+ const rl = readline.createInterface({
3512
+ input: process.stdin,
3513
+ output: process.stdout
3514
+ });
3515
+ console.log("\n\u{1F6EB} FlightDesk CLI Setup\n");
3516
+ try {
3517
+ if (isConfigured()) {
3518
+ const config = loadConfig();
3519
+ console.log("FlightDesk is already configured.");
3520
+ console.log(` API Key: ${config.apiKey?.substring(0, 20)}...`);
3521
+ console.log(` Organizations: ${config.organizations.map((o) => o.name).join(", ")}`);
3522
+ console.log("");
3523
+ const reconfigure = await question(rl, "Reconfigure? (y/N): ");
3524
+ if (reconfigure.toLowerCase() !== "y") {
3525
+ console.log("\nConfiguration unchanged.");
3526
+ console.log('Use "flightdesk org refresh" to update organizations.');
3527
+ console.log('Use "flightdesk org switch <name>" to change active organization.');
3528
+ return;
3529
+ }
3530
+ }
3531
+ console.log("Enter your FlightDesk API key.");
3532
+ console.log("You can find this at https://flightdesk.dev/settings/api-keys\n");
3533
+ const apiKey = await question(rl, "API Key: ");
3534
+ if (!apiKey) {
3535
+ console.error("API Key is required");
3536
+ return;
3537
+ }
3538
+ const apiUrl = getApiUrl();
3539
+ console.log("\nConnecting to FlightDesk...");
3540
+ try {
3541
+ const userInfo = await fetchUserInfo(apiKey, apiUrl);
3542
+ const orgs = userInfo.organizations || [];
3543
+ if (orgs.length === 0) {
3544
+ console.error("\u274C No organizations found for this user");
3545
+ console.log("Please make sure you are a member of at least one organization.");
3546
+ return;
3547
+ }
3548
+ const primaryEmail = userInfo.emails?.find((e) => e.primary)?.email || userInfo.emails?.[0]?.email || "unknown";
3549
+ console.log("\u2705 Connection successful!");
3550
+ console.log(` Logged in as: ${primaryEmail}`);
3551
+ console.log(` Organizations: ${orgs.length}`);
3552
+ const organizations = orgs.map((m) => ({
3553
+ id: m.organization.id,
3554
+ name: m.organization.name
3555
+ }));
3556
+ let activeOrganization;
3557
+ if (organizations.length === 1) {
3558
+ activeOrganization = organizations[0].id;
3559
+ console.log(`
3560
+ Active organization: ${organizations[0].name}`);
3561
+ } else {
3562
+ console.log("\nYour organizations:");
3563
+ organizations.forEach((org2, i) => {
3564
+ console.log(` ${i + 1}. ${org2.name}`);
3565
+ });
3566
+ const choice = await question(rl, `
3567
+ Select active organization (1-${organizations.length}): `);
3568
+ const choiceIndex = Number.parseInt(choice, 10) - 1;
3569
+ if (choiceIndex < 0 || choiceIndex >= organizations.length) {
3570
+ console.error("Invalid selection, using first organization");
3571
+ activeOrganization = organizations[0].id;
3572
+ } else {
3573
+ activeOrganization = organizations[choiceIndex].id;
3574
+ }
3575
+ }
3576
+ const config = loadConfig();
3577
+ config.apiKey = apiKey;
3578
+ config.apiUrl = apiUrl;
3579
+ config.organizations = organizations;
3580
+ config.activeOrganization = activeOrganization;
3581
+ saveConfig(config);
3582
+ console.log(`
3583
+ \u2705 Configuration saved to ${CONFIG_FILE}`);
3584
+ console.log("\nYou can now use:");
3585
+ console.log(" flightdesk project list - List projects");
3586
+ console.log(" flightdesk task create - Create a task");
3587
+ console.log(" flightdesk org list - Show organizations");
3588
+ console.log(" flightdesk org switch <name> - Switch active organization");
3589
+ } catch (error) {
3590
+ console.error(`
3591
+ \u274C Connection failed: ${error}`);
3592
+ console.log("\nPlease check:");
3593
+ console.log(" - Your API key is correct");
3594
+ console.log(" - You have network connectivity");
3595
+ console.log(" - The FlightDesk API is reachable");
3596
+ }
3597
+ } finally {
3598
+ rl.close();
3599
+ }
3600
+ }
3601
+
3602
+ // apps/cli/src/lib/git.ts
3603
+ var import_node_child_process = require("node:child_process");
3604
+ function detectGitRepo() {
3605
+ try {
3606
+ const remoteUrl = (0, import_node_child_process.execSync)("git remote get-url origin", {
3607
+ encoding: "utf-8",
3608
+ stdio: ["pipe", "pipe", "pipe"]
3609
+ }).trim();
3610
+ const repoFullName = parseGitRemoteUrl(remoteUrl);
3611
+ if (!repoFullName) {
3612
+ return null;
3613
+ }
3614
+ const branch = (0, import_node_child_process.execSync)("git rev-parse --abbrev-ref HEAD", {
3615
+ encoding: "utf-8",
3616
+ stdio: ["pipe", "pipe", "pipe"]
3617
+ }).trim();
3618
+ return {
3619
+ remote: repoFullName,
3620
+ branch,
3621
+ remoteUrl
3622
+ };
3623
+ } catch {
3624
+ return null;
3625
+ }
3626
+ }
3627
+ function parseGitRemoteUrl(remoteUrl) {
3628
+ const sshPattern = /git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/;
3629
+ const sshMatch = sshPattern.exec(remoteUrl);
3630
+ if (sshMatch) {
3631
+ return sshMatch[1];
3632
+ }
3633
+ const httpsPattern = /https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/;
3634
+ const httpsMatch = httpsPattern.exec(remoteUrl);
3635
+ if (httpsMatch) {
3636
+ return httpsMatch[1];
3637
+ }
3638
+ return null;
3639
+ }
3640
+
3641
+ // apps/cli/src/commands/register.ts
3642
+ async function registerCommand(taskId, options) {
3643
+ const { config, org: org2 } = requireActiveOrg();
3644
+ const api = FlightDeskAPI.fromConfig(config, org2);
3645
+ try {
3646
+ let projectId = options.project;
3647
+ if (!projectId) {
3648
+ projectId = await autoDetectProject(api, org2);
3649
+ }
3650
+ let viewUrl = options.viewUrl;
3651
+ let teleportId = options.teleportId;
3652
+ if (!process.stdin.isTTY) {
3653
+ console.log("\u23F3 Waiting for Claude session output...");
3654
+ const input = await readStdin();
3655
+ const parsed = parseClaudeOutput(input);
3656
+ viewUrl = viewUrl || parsed.viewUrl;
3657
+ teleportId = teleportId || parsed.teleportId;
3658
+ }
3659
+ let actualTaskId = taskId;
3660
+ if (!actualTaskId) {
3661
+ if (!options.title) {
3662
+ console.error('Task title required when creating a new task. Use --title "..."');
3663
+ process.exit(1);
3664
+ }
3665
+ console.log(`Creating task: ${options.title}`);
3666
+ const task2 = await api.createTask({
3667
+ projectId,
3668
+ title: options.title,
3669
+ description: options.description,
3670
+ subprojectId: options.subproject
3671
+ });
3672
+ actualTaskId = task2.id;
3673
+ console.log(`\u2705 Created task: ${task2.id}`);
3674
+ }
3675
+ if (viewUrl || teleportId) {
3676
+ console.log("Registering session with task...");
3677
+ await api.updateTask(actualTaskId, {
3678
+ sessionViewUrl: viewUrl,
3679
+ sessionTeleportId: teleportId,
3680
+ status: "DISPATCHED"
3681
+ });
3682
+ console.log("\u2705 Session registered");
3683
+ }
3684
+ console.log(`
3685
+ Task ID: ${actualTaskId}`);
3686
+ if (viewUrl) {
3687
+ console.log(`Session: ${viewUrl}`);
3688
+ }
3689
+ if (teleportId) {
3690
+ console.log(`Resume: claude --teleport ${teleportId}`);
3691
+ }
3692
+ } catch (error) {
3693
+ console.error(`Error: ${error}`);
3694
+ process.exit(1);
3695
+ }
3696
+ }
3697
+ function readStdin() {
3698
+ return new Promise((resolve) => {
3699
+ let data = "";
3700
+ let resolved = false;
3701
+ process.stdin.setEncoding("utf8");
3702
+ process.stdin.on("data", (chunk) => {
3703
+ data += chunk;
3704
+ });
3705
+ process.stdin.on("end", () => {
3706
+ if (!resolved) {
3707
+ resolved = true;
3708
+ resolve(data);
3709
+ }
3710
+ });
3711
+ process.stdin.on("close", () => {
3712
+ if (!resolved) {
3713
+ resolved = true;
3714
+ resolve(data);
3715
+ }
3716
+ });
3717
+ setTimeout(() => {
3718
+ if (!resolved) {
3719
+ resolved = true;
3720
+ resolve(data);
3721
+ }
3722
+ }, 3e4);
3723
+ });
3724
+ }
3725
+ function parseClaudeOutput(output) {
3726
+ const result = {};
3727
+ const viewMatch = output.match(/View:\s+(https:\/\/claude\.ai\/code\/session_[^\s]+)/);
3728
+ if (viewMatch) {
3729
+ result.viewUrl = viewMatch[1];
3730
+ }
3731
+ const teleportMatch = output.match(/--teleport\s+(session_[^\s]+)/);
3732
+ if (teleportMatch) {
3733
+ result.teleportId = teleportMatch[1];
3734
+ }
3735
+ return result;
3736
+ }
3737
+ async function autoDetectProject(api, activeOrg) {
3738
+ const repoInfo = detectGitRepo();
3739
+ if (!repoInfo) {
3740
+ console.error("\u274C Not in a git repository. Please provide a project ID.");
3741
+ console.error(" Usage: flightdesk register --project <project-id> [task-id]");
3742
+ process.exit(1);
3743
+ }
3744
+ console.log(`\u{1F50D} Detecting project from repository: ${repoInfo.remote}`);
3745
+ const mappedOrg = getOrganizationByRepo(repoInfo.remote);
3746
+ if (!mappedOrg) {
3747
+ console.error(`\u274C Repository "${repoInfo.remote}" is not mapped to any organization.`);
3748
+ console.error(" Run: flightdesk sync");
3749
+ console.error(" Or provide a project ID: flightdesk register --project <project-id> [task-id]");
3750
+ process.exit(1);
3751
+ }
3752
+ if (mappedOrg.id !== activeOrg.id) {
3753
+ console.error(`\u274C Repository "${repoInfo.remote}" is mapped to organization "${mappedOrg.name}",`);
3754
+ console.error(` but your active organization is "${activeOrg.name}".`);
3755
+ console.error(" Switch with: flightdesk org switch " + mappedOrg.name);
3756
+ console.error(" Or provide a project ID: flightdesk register --project <project-id> [task-id]");
3757
+ process.exit(1);
3758
+ }
3759
+ const projects = await api.listProjects();
3760
+ const matchingProjects = projects.filter(
3761
+ (p) => p.githubRepo?.toLowerCase() === repoInfo.remote.toLowerCase()
3762
+ );
3763
+ if (matchingProjects.length === 0) {
3764
+ console.error(`\u274C No FlightDesk project found for repository "${repoInfo.remote}".`);
3765
+ console.error(" Available projects in this organization:");
3766
+ for (const p of projects) {
3767
+ console.error(` - ${p.name} (${p.githubRepo || "no repo"}) [${p.id}]`);
3768
+ }
3769
+ console.error("\n Create a project or provide a project ID explicitly.");
3770
+ process.exit(1);
3771
+ }
3772
+ if (matchingProjects.length > 1) {
3773
+ console.error(`\u274C Multiple projects found for repository "${repoInfo.remote}":`);
3774
+ for (const p of matchingProjects) {
3775
+ console.error(` - ${p.name} [${p.id}]`);
3776
+ }
3777
+ console.error("\n Please specify the project ID explicitly.");
3778
+ process.exit(1);
3779
+ }
3780
+ const project2 = matchingProjects[0];
3781
+ console.log(`\u2705 Found project: ${project2.name} (${project2.id})`);
3782
+ return project2.id;
3783
+ }
3784
+
3785
+ // apps/cli/src/commands/status.ts
3786
+ async function statusCommand(options) {
3787
+ const { config, org: org2 } = requireActiveOrg();
3788
+ const api = FlightDeskAPI.fromConfig(config, org2);
3789
+ try {
3790
+ const tasks = await api.listTasks({ projectId: options.project });
3791
+ if (tasks.length === 0) {
3792
+ console.log("No tasks found.");
3793
+ return;
3794
+ }
3795
+ const byStatus = {};
3796
+ for (const task2 of tasks) {
3797
+ if (!byStatus[task2.status]) {
3798
+ byStatus[task2.status] = [];
3799
+ }
3800
+ byStatus[task2.status].push(task2);
3801
+ }
3802
+ const statusOrder = [
3803
+ "PENDING",
3804
+ "DISPATCHED",
3805
+ "IN_PROGRESS",
3806
+ "BRANCH_CREATED",
3807
+ "PR_OPEN",
3808
+ "PREVIEW_STARTING",
3809
+ "PREVIEW_READY",
3810
+ "REVIEW_RUNNING",
3811
+ "REVIEW_DONE",
3812
+ "QA_READY",
3813
+ "QA_APPROVED",
3814
+ "MERGED",
3815
+ "ARCHIVED"
3816
+ ];
3817
+ console.log("\n\u{1F4CB} FlightDesk Tasks\n");
3818
+ for (const status of statusOrder) {
3819
+ const statusTasks = byStatus[status];
3820
+ if (!statusTasks || statusTasks.length === 0) continue;
3821
+ console.log(`${getStatusEmoji(status)} ${status} (${statusTasks.length})`);
3822
+ for (const task2 of statusTasks) {
3823
+ console.log(` ${task2.id.slice(0, 8)} - ${task2.title}`);
3824
+ if (task2.branchName) {
3825
+ console.log(` Branch: ${task2.branchName}`);
3826
+ }
3827
+ if (task2.prUrl) {
3828
+ console.log(` PR: ${task2.prUrl}`);
3829
+ }
3830
+ }
3831
+ console.log("");
3832
+ }
3833
+ } catch (error) {
3834
+ console.error(`Error: ${error}`);
3835
+ process.exit(1);
3836
+ }
3837
+ }
3838
+ function getStatusEmoji(status) {
3839
+ switch (status) {
3840
+ case "PENDING":
3841
+ return "\u2B1C";
3842
+ case "DISPATCHED":
3843
+ return "\u{1F680}";
3844
+ case "IN_PROGRESS":
3845
+ return "\u{1F504}";
3846
+ case "BRANCH_CREATED":
3847
+ return "\u{1F33F}";
3848
+ case "PR_OPEN":
3849
+ return "\u{1F4DD}";
3850
+ case "PREVIEW_STARTING":
3851
+ return "\u23F3";
3852
+ case "PREVIEW_READY":
3853
+ return "\u{1F310}";
3854
+ case "REVIEW_RUNNING":
3855
+ return "\u{1F50D}";
3856
+ case "REVIEW_DONE":
3857
+ return "\u2705";
3858
+ case "QA_READY":
3859
+ return "\u{1F9EA}";
3860
+ case "QA_APPROVED":
3861
+ return "\u{1F44D}";
3862
+ case "MERGED":
3863
+ return "\u{1F389}";
3864
+ case "ARCHIVED":
3865
+ return "\u{1F4E6}";
3866
+ default:
3867
+ return "\u2753";
3868
+ }
3869
+ }
3870
+
3871
+ // apps/cli/src/commands/task.ts
3872
+ async function taskCommand(action, options) {
3873
+ const { config, org: org2 } = requireActiveOrg();
3874
+ const api = FlightDeskAPI.fromConfig(config, org2);
3875
+ try {
3876
+ switch (action) {
3877
+ case "create":
3878
+ await handleCreate(api, options);
3879
+ break;
3880
+ case "list":
3881
+ await handleList(api, options);
3882
+ break;
3883
+ case "status":
3884
+ await handleStatus(api, options);
3885
+ break;
3886
+ case "update":
3887
+ await handleUpdate(api, options);
3888
+ break;
3889
+ case "sync":
3890
+ await handleSync(api, options);
3891
+ break;
3892
+ }
3893
+ } catch (error) {
3894
+ console.error(`Error: ${error}`);
3895
+ process.exit(1);
3896
+ }
3897
+ }
3898
+ async function handleCreate(api, options) {
3899
+ console.log(`Creating task: ${options.title}`);
3900
+ const task2 = await api.createTask({
3901
+ projectId: options.project,
3902
+ title: options.title,
3903
+ description: options.description,
3904
+ subprojectId: options.subproject
3905
+ });
3906
+ console.log(`
3907
+ \u2705 Task created`);
3908
+ console.log(` ID: ${task2.id}`);
3909
+ console.log(` Title: ${task2.title}`);
3910
+ console.log(` Status: ${task2.status}`);
3911
+ }
3912
+ async function handleList(api, options) {
3913
+ const tasks = await api.listTasks({
3914
+ projectId: options.project,
3915
+ status: options.status
3916
+ });
3917
+ if (tasks.length === 0) {
3918
+ console.log("No tasks found.");
3919
+ return;
3920
+ }
3921
+ console.log("\nTasks:\n");
3922
+ for (const task2 of tasks) {
3923
+ const statusEmoji = getStatusEmoji2(task2.status);
3924
+ console.log(`${statusEmoji} ${task2.id.slice(0, 8)} - ${task2.title}`);
3925
+ if (task2.project?.name) console.log(` Project: ${task2.project.name}`);
3926
+ console.log(` Status: ${task2.status}`);
3927
+ if (task2.branchName) console.log(` Branch: ${task2.branchName}`);
3928
+ if (task2.prUrl) console.log(` PR: ${task2.prUrl}`);
3929
+ console.log("");
3930
+ }
3931
+ }
3932
+ async function handleStatus(api, options) {
3933
+ const task2 = await api.getTask(options.taskId);
3934
+ if (!task2) {
3935
+ console.error("Task not found");
3936
+ process.exit(1);
3937
+ }
3938
+ console.log(`
3939
+ \u{1F4CB} Task: ${task2.title}
3940
+ `);
3941
+ console.log(`ID: ${task2.id}`);
3942
+ console.log(`Status: ${getStatusEmoji2(task2.status)} ${task2.status}`);
3943
+ if (task2.project) {
3944
+ console.log(`Project: ${task2.project.name}${task2.project.githubRepo ? ` (${task2.project.githubRepo})` : ""}`);
3945
+ }
3946
+ if (task2.description) {
3947
+ console.log(`
227
3948
  Description:
228
- ${t.description}`),console.log(""),t.branchName&&console.log(`Branch: ${t.branchName}`),t.prUrl&&console.log(`PR: ${t.prUrl}`),t.prNumber&&console.log(`PR #: ${t.prNumber}`),t.sessionViewUrl&&console.log(`Session: ${t.sessionViewUrl}`),t.sessionTeleportId&&console.log(`Resume: claude --teleport ${t.sessionTeleportId}`),console.log(`
229
- Created: ${new Date(t.createdAt).toLocaleString()}`),console.log(`Updated: ${new Date(t.updatedAt).toLocaleString()}`)}function Ct(i){let e="https://claude.ai/code/";return i.startsWith(e)?i.slice(e.length):i}async function bt(i,e){let t={};if(e.status&&(t.status=e.status),e.branch&&(t.branchName=e.branch),e.prUrl){t.prUrl=e.prUrl;let s=e.prUrl.match(/\/pull\/(\d+)/);s&&(t.prNumber=parseInt(s[1],10))}if(e.prNumber&&(t.prNumber=parseInt(e.prNumber,10)),e.session){let s=Ct(e.session);t.sessionViewUrl=`https://claude.ai/code/${s}`,t.sessionTeleportId=s}Object.keys(t).length===0&&(console.error("No updates specified. Use --status, --branch, --pr-url, or --session"),process.exit(1)),e.branch&&!e.status&&(await i.getTask(e.taskId))?.status==="DISPATCHED"&&(t.status="IN_PROGRESS",console.log(" Auto-transitioning DISPATCHED \u2192 IN_PROGRESS")),console.log(`Updating task ${e.taskId}...`);let n=await i.updateTask(e.taskId,t);if(console.log(`
230
- \u2705 Task updated`),console.log(` Status: ${n.status}`),n.branchName&&console.log(` Branch: ${n.branchName}`),n.prUrl&&console.log(` PR: ${n.prUrl}`),n.prNumber&&console.log(` PR #: ${n.prNumber}`),n.sessionViewUrl&&console.log(` Session: ${n.sessionViewUrl}`),e.prUrl){console.log(`
231
- \u{1F504} Syncing PR review state...`);try{let s=await i.syncTaskChecks(e.taskId);ze(s)}catch(s){console.log(` \u26A0\uFE0F Sync failed (checks will update when webhooks arrive): ${s}`)}}}async function $t(i,e){console.log(`Syncing PR review state for task ${e.taskId}...`);let t=await i.syncTaskChecks(e.taskId);ze(t)}function ze(i){if(i.synced===0){console.log(" No review feedback found on the PR.");return}console.log(`
232
- Found ${i.synced} review check(s):`);for(let e of i.checks){let t=Pt(e.status);console.log(` ${t} ${e.integration} (${e.reviewer}): ${e.status}`)}}function Pt(i){switch(i){case"PASSED":return"\u2705";case"FAILED":return"\u274C";case"PENDING":return"\u23F3";case"SKIPPED":return"\u23ED\uFE0F";default:return"\u2753"}}function He(i){switch(i){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 Ve(i,e){let{config:t,org:n}=y(),s=f.fromConfig(t,n),o=["review","test_plan","summary","handoff"];o.includes(e.type)||(console.error(`Invalid prompt type: ${e.type}`),console.error(`Valid types: ${o.join(", ")}`),process.exit(1));try{let a=(await s.getTaskPrompts(i)).find(c=>c.type===e.type);a||(console.error(`Prompt type "${e.type}" not found for this task`),process.exit(1)),a.available||(console.error(`Prompt not available: ${a.reason||"Unknown reason"}`),process.exit(1)),console.log(a.content)}catch(r){console.error(`Error: ${r}`),process.exit(1)}}async function qe(){if(!R()){console.log("FlightDesk is not configured."),console.log("Run: flightdesk init");return}let i=m(),e=b();if(console.log(`
233
- \u{1F4CB} Organizations
234
- `),i.organizations.length===0){console.log("No organizations found."),console.log("Run: flightdesk org refresh");return}for(let t of i.organizations){let n=t.id===e?.id,s=n?" \u2190 active":"";console.log(` ${n?"\u25CF":"\u25CB"} ${t.name}${s}`)}console.log(""),console.log("Commands:"),console.log(" flightdesk org switch <name> Switch active organization"),console.log(" flightdesk org refresh Refresh organizations from API"),console.log("")}async function Fe(i){if(!R()){console.log("FlightDesk is not configured."),console.log("Run: flightdesk init");return}let e=m(),t=e.organizations.find(s=>s.id===i||s.name.toLowerCase()===i.toLowerCase());if(!t){console.error(`Organization not found: ${i}`),console.log(`
235
- Available organizations:`);for(let s of e.organizations)console.log(` - ${s.name}`);process.exit(1)}if(b()?.id===t.id){console.log(`Already using organization: ${t.name}`);return}Te(t.id),console.log(`\u2705 Switched to organization: ${t.name}`)}async function Le(){if(!R()){console.log("FlightDesk is not configured."),console.log("Run: flightdesk init");return}let i=m();if(!i.apiKey){console.error("No API key configured."),console.log("Run: flightdesk init");return}console.log("Refreshing organizations...");try{let e=C(),n=(await F(i.apiKey,e)).organizations||[];if(n.length===0){console.log("No organizations found for this user.");return}let s=n.map(u=>({id:u.organization.id,name:u.organization.name})),o=new Set(i.organizations.map(u=>u.id)),r=s.filter(u=>!o.has(u.id)),a=new Set(s.map(u=>u.id)),c=i.organizations.filter(u=>!a.has(u.id));if(xe(s),console.log(`\u2705 Found ${s.length} organization(s)`),r.length>0){console.log(`
236
- New organizations:`);for(let u of r)console.log(` + ${u.name}`)}if(c.length>0){console.log(`
237
- Removed organizations:`);for(let u of c)console.log(` - ${u.name}`)}let l=b();l&&console.log(`
238
- Active: ${l.name}`)}catch(e){console.error(`\u274C Failed to refresh: ${e}`)}}var le=require("child_process");async function Me(){console.log(`
239
- \u{1F50D} Current Context
240
- `);let i={};try{let n=(0,le.execSync)("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),s=null,o=n.match(/git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);o&&(s=o[1]);let r=n.match(/https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);r&&(s=r[1]),s&&(i.remote=s);let a=(0,le.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();i.branch=a}catch{}if(!i.remote){console.log("\u{1F4C1} Not in a git repository (or no remote configured)"),console.log("");let n=m(),s=b();if(n.organizations.length>0){console.log("Organizations:");for(let o of n.organizations){let r=o.id===s?.id;console.log(` ${r?"\u25CF":"\u25CB"} ${o.name}${r?" (active)":""}`)}}else console.log("No organizations configured. Run: flightdesk init");return}console.log(`\u{1F4C1} Repository: ${i.remote}`),console.log(`\u{1F33F} Branch: ${i.branch}`),console.log("");let e=q(i.remote),t=b();if(e)console.log(`\u{1F3E2} Organization: ${e.name}`),console.log(` API: ${C()}`),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 n=m();if(n.organizations.length>0){console.log("Organizations:");for(let s of n.organizations){let o=s.id===t?.id;console.log(` ${o?"\u25CF":"\u25CB"} ${s.name}${o?" (active)":""}`)}console.log(""),console.log("Run: flightdesk sync to refresh repository mappings")}else console.log("No organizations configured. Run: flightdesk init")}}async function Ge(){let i=re();i.organizations.length===0&&(console.error("No organizations configured. Run: flightdesk init"),process.exit(1)),console.log(`\u{1F504} Syncing repository mappings...
241
- `);let e=0,t={};for(let n of i.organizations){console.log(` ${n.name}...`);try{let o=await f.fromConfig(i,n).listProjects();console.log(` Found ${o.length} project(s)`);for(let r of o)r.githubRepo&&(t[r.githubRepo]=n.id,e++)}catch(s){console.log(` \u274C Error: ${s}`)}}if(i.repoMapping=t,x(i),console.log(""),console.log(`\u2705 Synced ${e} project(s)`),e>0){console.log(""),console.log("Repository mappings:");for(let[n,s]of Object.entries(t)){let o=i.organizations.find(r=>r.id===s);console.log(` ${n} \u2192 ${o?.name||s}`)}}}async function We(i,e){let{config:t,org:n}=y(),s=f.fromConfig(t,n);i==="list"?await Et(s):(console.error(`Unknown action: ${i}`),process.exit(1))}async function Et(i){let e=await i.listProjects();if(e.length===0){console.log("No projects found."),console.log(`
242
- Create a project at https://app.flightdesk.dev/app/projects/new`);return}console.log(`Projects:
243
- `);let t=Math.max(...e.map(n=>n.name.length),4);for(let n of e){let s=n.name.padEnd(t),o=n.githubRepo||"(no repo)";console.log(` ${n.id} ${s} ${o}`)}console.log(`
244
- ${e.length} project(s)`)}var I=require("node:child_process"),j=A(require("node:path")),ue=A(require("node:os")),E=A(require("node:fs"));function St(i){return/^[a-fA-F0-9]+$/.test(i)&&i.length>=12&&i.length<=64}function Be(i){if(i.containerId&&!St(i.containerId))throw new Error(`Invalid container ID format: ${i.containerId}`);if(!/^[a-zA-Z0-9_-]+$/.test(i.sshUser))throw new Error(`Invalid SSH user format: ${i.sshUser}`);if(!/^[a-zA-Z0-9.-]+$/.test(i.sshHost))throw new Error(`Invalid SSH host format: ${i.sshHost}`);if(!Number.isInteger(i.sshPort)||i.sshPort<1||i.sshPort>65535)throw new Error(`Invalid SSH port: ${i.sshPort}`)}async function _(i,e){let{config:t,org:n}=y(),s=f.fromConfig(t,n);try{switch(i){case"status":await xt(s,e);break;case"logs":await Rt(s,e);break;case"mount":await Dt(s,e);break;case"unmount":await jt(s,e);break;case"restart":await Nt(s,e);break;case"resume":await Ut(s,e);break;case"teardown":await zt(s,e);break}}catch(o){console.error(`Error: ${o}`),process.exit(1)}}function Tt(i){return{STARTING:"\u{1F504}",READY:"\u2705",SUSPENDED:"\u{1F4A4}",RESTARTING:"\u{1F504}",TEARDOWN:"\u{1F5D1}\uFE0F",ERROR:"\u274C"}[i]||"\u2753"}async function xt(i,e){let t=await i.getTaskInstance(e.taskId);if(!t){console.log(`
245
- \u26A0\uFE0F No preview environment found for this task`),console.log(" The preview environment may not have been created yet,"),console.log(" or the PR may be closed.");return}let n=Tt(t.status);if(console.log(`
246
- \u{1F4E6} Preview Environment`),console.log("\u2500".repeat(50)),console.log(`${n} Status: ${t.status}`),console.log(` ID: ${t.id.substring(0,8)}`),t.processUrls&&t.processUrls.length>0){console.log(" URLs:");for(let s of t.processUrls){let o=s.primary?`${s.name} (primary)`:s.name;console.log(` ${o}: ${s.url}`)}}else console.log(` Preview URL: ${t.previewUrl}`);if(console.log(` SSH: ${t.sshConnectionString}`),console.log(` Container: ${t.containerId.substring(0,12)}`),t.lastActivityAt){let s=new Date(t.lastActivityAt),o=Math.round((Date.now()-s.getTime())/6e4);console.log(` Last Activity: ${o} minutes ago`)}if(t.suspendedAt){let s=new Date(t.suspendedAt);console.log(` Suspended At: ${s.toLocaleString()}`)}console.log(` Created: ${new Date(t.createdAt).toLocaleString()}`),console.log("")}async function Rt(i,e){let t=e.lines||100;if(e.follow){let s=await i.getTaskInstance(e.taskId);s||(console.error("No preview environment found for this task"),process.exit(1)),console.log(`\u{1F4CB} Streaming logs from ${s.previewUrl}...
247
- `),console.log(`(Press Ctrl+C to stop)
248
- `),Be(s);let o=`docker logs -f ${s.containerId}`,r=(0,I.spawn)("ssh",["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-p",String(s.sshPort),`${s.sshUser}@${s.sshHost}`,o]);r.stdout.pipe(process.stdout),r.stderr.pipe(process.stderr),r.on("close",a=>{process.exit(a||0)}),process.on("SIGINT",()=>{r.kill(),process.exit(0)});return}let n=await i.getInstanceLogs(e.taskId,t);if(!n.logs){console.log("No logs available");return}console.log(n.logs)}async function Dt(i,e){let t=await i.getTaskInstance(e.taskId);t||(console.error("No preview environment found for this task"),process.exit(1)),t.status==="SUSPENDED"&&(console.log("\u23F8\uFE0F Instance is suspended. Resuming..."),await i.resumeInstance(e.taskId),await new Promise(a=>setTimeout(a,3e3)));try{(0,I.execSync)("which sshfs",{stdio:"ignore"})}catch{console.error("\u274C sshfs is not installed."),console.error(""),console.error("Install it with:"),process.platform==="darwin"?console.error(" brew install macfuse gromgit/fuse/sshfs-mac"):process.platform==="linux"?console.error(" sudo apt install sshfs"):console.error(" SSHFS is not supported on this platform"),process.exit(1)}let n=e.taskId.substring(0,8),s=j.basename(n).replaceAll(/[^a-zA-Z0-9_-]/g,"")||"task",o=e.directory||j.join(ue.homedir(),"flightdesk-mounts",s);E.existsSync(o)||E.mkdirSync(o,{recursive:!0});try{if((0,I.execSync)("mount",{encoding:"utf8"}).includes(o)){console.log(`\u{1F4C1} Already mounted at ${o}`);return}}catch{}console.log(`\u{1F4C1} Mounting preview environment to ${o}...`),Be(t);let r=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","reconnect","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=3","-p",String(t.sshPort),`${t.sshUser}@${t.sshHost}:/app`,o];try{let a=(0,I.spawnSync)("sshfs",r,{stdio:"inherit"});if(a.status!==0)throw new Error(`sshfs exited with code ${a.status}`);console.log(""),console.log("\u2705 Mounted successfully!"),console.log(` Location: ${o}`),console.log(""),console.log(" To unmount:"),console.log(` fd preview unmount ${e.taskId}`),console.log(""),console.log(" Or manually:"),process.platform==="darwin"?console.log(` umount ${o}`):console.log(` fusermount -u ${o}`)}catch(a){console.error(`\u274C Mount failed: ${a}`),process.exit(1)}}async function jt(i,e){let t=e.taskId.substring(0,8),n=j.basename(t).replaceAll(/[^a-zA-Z0-9_-]/g,"")||"task",s=j.join(ue.homedir(),"flightdesk-mounts",n);if(!E.existsSync(s)){console.log("Mount directory does not exist");return}console.log(`\u{1F4C1} Unmounting ${s}...`);try{let o;if(process.platform==="darwin"?o=(0,I.spawnSync)("umount",[s],{stdio:"inherit"}):o=(0,I.spawnSync)("fusermount",["-u",s],{stdio:"inherit"}),o.status!==0)throw new Error(`Unmount exited with code ${o.status}`);console.log("\u2705 Unmounted successfully");try{E.rmSync(s,{recursive:!0,force:!0})}catch{}}catch(o){console.error(`\u274C Unmount failed: ${o}`),console.error(""),console.error("Try force unmounting:"),process.platform==="darwin"?console.error(` diskutil unmount force ${s}`):console.error(` fusermount -uz ${s}`),process.exit(1)}}async function Nt(i,e){console.log("\u{1F504} Restarting preview environment..."),await i.restartInstance(e.taskId),console.log("\u2705 Restart initiated. The preview will be available shortly.")}async function Ut(i,e){console.log("\u25B6\uFE0F Resuming preview environment..."),await i.resumeInstance(e.taskId),console.log("\u2705 Resume initiated. The preview should be ready in about 30 seconds.")}async function zt(i,e){console.log("\u{1F5D1}\uFE0F Tearing down preview environment..."),await i.tearDownInstance(e.taskId),console.log("\u2705 Preview environment has been torn down.")}var d=new be;d.name("flightdesk").description("FlightDesk CLI - AI task management for Claude Code sessions").version("0.4.0").option("--dev","Use local development API (localhost:3000)").option("--api <url>","Use custom API URL");d.hook("preAction",()=>{let i=d.opts();i.api?(Se(i.api),console.log(`\u{1F527} Using custom API: ${i.api}
249
- `)):i.dev&&(Ee(!0),console.log(`\u{1F527} Development mode: using http://localhost:3000
250
- `))});d.command("init").description("Configure FlightDesk CLI with your API credentials").action(De);d.command("register [task-id]").description("Register a Claude Code session with a FlightDesk task (auto-detects project from git repo)").option("-p, --project <id>","Project ID (auto-detected from git repo if not provided)").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(Ne);var Ht=d.command("project").description("Project management commands");Ht.command("list").description("List projects in the active organization").action(()=>We("list",{}));var z=d.command("task").description("Task management commands");z.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(i=>D("create",i));z.command("list").description("List tasks").option("-p, --project <id>","Filter by project ID").option("--status <status>","Filter by status").action(i=>D("list",i));z.command("status <task-id>").description("Get task status").action(i=>D("status",{taskId:i}));z.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").option("--pr-number <number>","Pull request number (use if --pr-url is not enough)").option("--session <session>","Claude Code session (URL or session ID)").action((i,e)=>D("update",{taskId:i,...e}));z.command("sync <task-id>").description("Sync PR review state (Copilot feedback, Claude reviews, human reviews) from GitHub").action(i=>D("sync",{taskId:i}));d.command("status").description("Show status of all active tasks").option("-p, --project <id>","Filter by project").action(Ue);d.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(Ve);var ge=d.command("org").description("Organization management");ge.command("list").description("List your organizations").action(qe);ge.command("switch <name>").description("Switch active organization").action(Fe);ge.command("refresh").description("Refresh organizations from API").action(Le);d.command("context").description("Show current repository context and mapped organization").action(Me);d.command("sync").description("Refresh project-to-repository mappings from all organizations").action(Ge);var S=d.command("preview").description("Preview environment management");S.command("status <task-id>").description("Show preview environment status").action(i=>_("status",{taskId:i}));S.command("logs <task-id>").description("Get logs from preview environment").option("-n, --lines <lines>","Number of log lines (1-10000)","100").option("-f, --follow","Follow log output").action((i,e)=>{let t=Math.min(Math.max(Number.parseInt(e.lines||"100"),1),1e4);_("logs",{taskId:i,lines:t,follow:e.follow})});S.command("mount <task-id>").description("Mount preview environment filesystem via SSHFS").option("-d, --directory <path>","Custom mount directory").action((i,e)=>_("mount",{taskId:i,directory:e.directory}));S.command("unmount <task-id>").description("Unmount preview environment filesystem").action(i=>_("unmount",{taskId:i}));S.command("restart <task-id>").description("Restart preview environment processes").action(i=>_("restart",{taskId:i}));S.command("resume <task-id>").description("Resume a suspended preview environment").action(i=>_("resume",{taskId:i}));S.command("teardown <task-id>").description("Tear down preview environment").action(i=>_("teardown",{taskId:i}));d.command("mount <task-id>").description('Mount preview environment filesystem (shorthand for "preview mount")').option("-d, --directory <path>","Custom mount directory").action((i,e)=>_("mount",{taskId:i,directory:e.directory}));d.command("unmount <task-id>").description('Unmount preview environment filesystem (shorthand for "preview unmount")').action(i=>_("unmount",{taskId:i}));d.command("logs <task-id>").description('Get logs from preview environment (equivalent to "preview logs")').option("-n, --lines <lines>","Number of log lines (1-10000)","100").option("-f, --follow","Follow log output").action((i,e)=>{let t=Math.min(Math.max(Number.parseInt(e.lines||"100"),1),1e4);_("logs",{taskId:i,lines:t,follow:e.follow})});d.parse();
3949
+ ${task2.description}`);
3950
+ }
3951
+ console.log("");
3952
+ if (task2.branchName) console.log(`Branch: ${task2.branchName}`);
3953
+ if (task2.prUrl) console.log(`PR: ${task2.prUrl}`);
3954
+ if (task2.prNumber) console.log(`PR #: ${task2.prNumber}`);
3955
+ if (task2.sessionViewUrl) console.log(`Session: ${task2.sessionViewUrl}`);
3956
+ if (task2.sessionTeleportId) {
3957
+ console.log(`Resume: claude --teleport ${task2.sessionTeleportId}`);
3958
+ }
3959
+ console.log(`
3960
+ Created: ${new Date(task2.createdAt).toLocaleString()}`);
3961
+ console.log(`Updated: ${new Date(task2.updatedAt).toLocaleString()}`);
3962
+ }
3963
+ function parseSessionId(value) {
3964
+ const urlPrefix = "https://claude.ai/code/";
3965
+ if (value.startsWith(urlPrefix)) {
3966
+ return value.slice(urlPrefix.length);
3967
+ }
3968
+ return value;
3969
+ }
3970
+ async function handleUpdate(api, options) {
3971
+ const input = {};
3972
+ if (options.status) input.status = options.status;
3973
+ if (options.branch) input.branchName = options.branch;
3974
+ if (options.prUrl) {
3975
+ input.prUrl = options.prUrl;
3976
+ const prNumberMatch = options.prUrl.match(/\/pull\/(\d+)/);
3977
+ if (prNumberMatch) {
3978
+ input.prNumber = parseInt(prNumberMatch[1], 10);
3979
+ }
3980
+ }
3981
+ if (options.prNumber) {
3982
+ input.prNumber = parseInt(options.prNumber, 10);
3983
+ }
3984
+ if (options.session) {
3985
+ const sessionId = parseSessionId(options.session);
3986
+ input.sessionViewUrl = `https://claude.ai/code/${sessionId}`;
3987
+ input.sessionTeleportId = sessionId;
3988
+ }
3989
+ if (Object.keys(input).length === 0) {
3990
+ console.error("No updates specified. Use --status, --branch, --pr-url, or --session");
3991
+ process.exit(1);
3992
+ }
3993
+ if (options.branch && !options.status) {
3994
+ const current = await api.getTask(options.taskId);
3995
+ if (current?.status === "DISPATCHED") {
3996
+ input.status = "IN_PROGRESS";
3997
+ console.log(` Auto-transitioning DISPATCHED \u2192 IN_PROGRESS`);
3998
+ }
3999
+ }
4000
+ console.log(`Updating task ${options.taskId}...`);
4001
+ const task2 = await api.updateTask(options.taskId, input);
4002
+ console.log(`
4003
+ \u2705 Task updated`);
4004
+ console.log(` Status: ${task2.status}`);
4005
+ if (task2.branchName) console.log(` Branch: ${task2.branchName}`);
4006
+ if (task2.prUrl) console.log(` PR: ${task2.prUrl}`);
4007
+ if (task2.prNumber) console.log(` PR #: ${task2.prNumber}`);
4008
+ if (task2.sessionViewUrl) console.log(` Session: ${task2.sessionViewUrl}`);
4009
+ if (options.prUrl) {
4010
+ console.log(`
4011
+ \u{1F504} Syncing PR review state...`);
4012
+ try {
4013
+ const syncResult = await api.syncTaskChecks(options.taskId);
4014
+ printSyncResult(syncResult);
4015
+ } catch (err) {
4016
+ console.log(` \u26A0\uFE0F Sync failed (checks will update when webhooks arrive): ${err}`);
4017
+ }
4018
+ }
4019
+ }
4020
+ async function handleSync(api, options) {
4021
+ console.log(`Syncing PR review state for task ${options.taskId}...`);
4022
+ const syncResult = await api.syncTaskChecks(options.taskId);
4023
+ printSyncResult(syncResult);
4024
+ }
4025
+ function printSyncResult(result) {
4026
+ if (result.synced === 0) {
4027
+ console.log(` No review feedback found on the PR.`);
4028
+ return;
4029
+ }
4030
+ console.log(`
4031
+ Found ${result.synced} review check(s):`);
4032
+ for (const check of result.checks) {
4033
+ const icon = getCheckIcon(check.status);
4034
+ console.log(` ${icon} ${check.integration} (${check.reviewer}): ${check.status}`);
4035
+ }
4036
+ }
4037
+ function getCheckIcon(status) {
4038
+ switch (status) {
4039
+ case "PASSED":
4040
+ return "\u2705";
4041
+ case "FAILED":
4042
+ return "\u274C";
4043
+ case "PENDING":
4044
+ return "\u23F3";
4045
+ case "SKIPPED":
4046
+ return "\u23ED\uFE0F";
4047
+ default:
4048
+ return "\u2753";
4049
+ }
4050
+ }
4051
+ function getStatusEmoji2(status) {
4052
+ switch (status) {
4053
+ case "PENDING":
4054
+ return "\u2B1C";
4055
+ case "DISPATCHED":
4056
+ return "\u{1F680}";
4057
+ case "IN_PROGRESS":
4058
+ return "\u{1F504}";
4059
+ case "BRANCH_CREATED":
4060
+ return "\u{1F33F}";
4061
+ case "PR_OPEN":
4062
+ return "\u{1F4DD}";
4063
+ case "PREVIEW_STARTING":
4064
+ return "\u23F3";
4065
+ case "PREVIEW_READY":
4066
+ return "\u{1F310}";
4067
+ case "REVIEW_RUNNING":
4068
+ return "\u{1F50D}";
4069
+ case "REVIEW_DONE":
4070
+ return "\u2705";
4071
+ case "QA_READY":
4072
+ return "\u{1F9EA}";
4073
+ case "QA_APPROVED":
4074
+ return "\u{1F44D}";
4075
+ case "MERGED":
4076
+ return "\u{1F389}";
4077
+ case "ARCHIVED":
4078
+ return "\u{1F4E6}";
4079
+ default:
4080
+ return "\u2753";
4081
+ }
4082
+ }
4083
+
4084
+ // apps/cli/src/commands/prompt.ts
4085
+ async function promptCommand(taskId, options) {
4086
+ const { config, org: org2 } = requireActiveOrg();
4087
+ const api = FlightDeskAPI.fromConfig(config, org2);
4088
+ const validTypes = ["review", "test_plan", "summary", "handoff"];
4089
+ if (!validTypes.includes(options.type)) {
4090
+ console.error(`Invalid prompt type: ${options.type}`);
4091
+ console.error(`Valid types: ${validTypes.join(", ")}`);
4092
+ process.exit(1);
4093
+ }
4094
+ try {
4095
+ const prompts = await api.getTaskPrompts(taskId);
4096
+ const prompt = prompts.find((p) => p.type === options.type);
4097
+ if (!prompt) {
4098
+ console.error(`Prompt type "${options.type}" not found for this task`);
4099
+ process.exit(1);
4100
+ }
4101
+ if (!prompt.available) {
4102
+ console.error(`Prompt not available: ${prompt.reason || "Unknown reason"}`);
4103
+ process.exit(1);
4104
+ }
4105
+ console.log(prompt.content);
4106
+ } catch (error) {
4107
+ console.error(`Error: ${error}`);
4108
+ process.exit(1);
4109
+ }
4110
+ }
4111
+
4112
+ // apps/cli/src/commands/org.ts
4113
+ async function orgListCommand() {
4114
+ if (!isConfigured()) {
4115
+ console.log("FlightDesk is not configured.");
4116
+ console.log("Run: flightdesk init");
4117
+ return;
4118
+ }
4119
+ const config = loadConfig();
4120
+ const activeOrg = getActiveOrganization();
4121
+ console.log("\n\u{1F4CB} Organizations\n");
4122
+ if (config.organizations.length === 0) {
4123
+ console.log("No organizations found.");
4124
+ console.log("Run: flightdesk org refresh");
4125
+ return;
4126
+ }
4127
+ for (const org2 of config.organizations) {
4128
+ const isActive = org2.id === activeOrg?.id;
4129
+ const activeTag = isActive ? " \u2190 active" : "";
4130
+ console.log(` ${isActive ? "\u25CF" : "\u25CB"} ${org2.name}${activeTag}`);
4131
+ }
4132
+ console.log("");
4133
+ console.log("Commands:");
4134
+ console.log(" flightdesk org switch <name> Switch active organization");
4135
+ console.log(" flightdesk org refresh Refresh organizations from API");
4136
+ console.log("");
4137
+ }
4138
+ async function orgSwitchCommand(orgIdentifier) {
4139
+ if (!isConfigured()) {
4140
+ console.log("FlightDesk is not configured.");
4141
+ console.log("Run: flightdesk init");
4142
+ return;
4143
+ }
4144
+ const config = loadConfig();
4145
+ const org2 = config.organizations.find(
4146
+ (o) => o.id === orgIdentifier || o.name.toLowerCase() === orgIdentifier.toLowerCase()
4147
+ );
4148
+ if (!org2) {
4149
+ console.error(`Organization not found: ${orgIdentifier}`);
4150
+ console.log("\nAvailable organizations:");
4151
+ for (const o of config.organizations) {
4152
+ console.log(` - ${o.name}`);
4153
+ }
4154
+ process.exit(1);
4155
+ }
4156
+ const currentOrg = getActiveOrganization();
4157
+ if (currentOrg?.id === org2.id) {
4158
+ console.log(`Already using organization: ${org2.name}`);
4159
+ return;
4160
+ }
4161
+ setActiveOrganization(org2.id);
4162
+ console.log(`\u2705 Switched to organization: ${org2.name}`);
4163
+ }
4164
+ async function orgRefreshCommand() {
4165
+ if (!isConfigured()) {
4166
+ console.log("FlightDesk is not configured.");
4167
+ console.log("Run: flightdesk init");
4168
+ return;
4169
+ }
4170
+ const config = loadConfig();
4171
+ if (!config.apiKey) {
4172
+ console.error("No API key configured.");
4173
+ console.log("Run: flightdesk init");
4174
+ return;
4175
+ }
4176
+ console.log("Refreshing organizations...");
4177
+ try {
4178
+ const apiUrl = getApiUrl();
4179
+ const userInfo = await fetchUserInfo(config.apiKey, apiUrl);
4180
+ const orgs = userInfo.organizations || [];
4181
+ if (orgs.length === 0) {
4182
+ console.log("No organizations found for this user.");
4183
+ return;
4184
+ }
4185
+ const organizations = orgs.map((m) => ({
4186
+ id: m.organization.id,
4187
+ name: m.organization.name
4188
+ }));
4189
+ const currentIds = new Set(config.organizations.map((o) => o.id));
4190
+ const newOrgs = organizations.filter((o) => !currentIds.has(o.id));
4191
+ const newIds = new Set(organizations.map((o) => o.id));
4192
+ const removedOrgs = config.organizations.filter((o) => !newIds.has(o.id));
4193
+ updateOrganizations(organizations);
4194
+ console.log(`\u2705 Found ${organizations.length} organization(s)`);
4195
+ if (newOrgs.length > 0) {
4196
+ console.log("\n New organizations:");
4197
+ for (const org2 of newOrgs) {
4198
+ console.log(` + ${org2.name}`);
4199
+ }
4200
+ }
4201
+ if (removedOrgs.length > 0) {
4202
+ console.log("\n Removed organizations:");
4203
+ for (const org2 of removedOrgs) {
4204
+ console.log(` - ${org2.name}`);
4205
+ }
4206
+ }
4207
+ const activeOrg = getActiveOrganization();
4208
+ if (activeOrg) {
4209
+ console.log(`
4210
+ Active: ${activeOrg.name}`);
4211
+ }
4212
+ } catch (error) {
4213
+ console.error(`\u274C Failed to refresh: ${error}`);
4214
+ }
4215
+ }
4216
+
4217
+ // apps/cli/src/commands/context.ts
4218
+ var import_child_process = require("child_process");
4219
+ async function contextCommand() {
4220
+ console.log("\n\u{1F50D} Current Context\n");
4221
+ const repoInfo = {};
4222
+ try {
4223
+ const remoteUrl = (0, import_child_process.execSync)("git remote get-url origin", {
4224
+ encoding: "utf-8",
4225
+ stdio: ["pipe", "pipe", "pipe"]
4226
+ }).trim();
4227
+ let repoFullName = null;
4228
+ const sshMatch = remoteUrl.match(/git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
4229
+ if (sshMatch) {
4230
+ repoFullName = sshMatch[1];
4231
+ }
4232
+ const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
4233
+ if (httpsMatch) {
4234
+ repoFullName = httpsMatch[1];
4235
+ }
4236
+ if (repoFullName) {
4237
+ repoInfo.remote = repoFullName;
4238
+ }
4239
+ const branch = (0, import_child_process.execSync)("git rev-parse --abbrev-ref HEAD", {
4240
+ encoding: "utf-8",
4241
+ stdio: ["pipe", "pipe", "pipe"]
4242
+ }).trim();
4243
+ repoInfo.branch = branch;
4244
+ } catch {
4245
+ }
4246
+ if (!repoInfo.remote) {
4247
+ console.log("\u{1F4C1} Not in a git repository (or no remote configured)");
4248
+ console.log("");
4249
+ const config = loadConfig();
4250
+ const activeOrg2 = getActiveOrganization();
4251
+ if (config.organizations.length > 0) {
4252
+ console.log("Organizations:");
4253
+ for (const org2 of config.organizations) {
4254
+ const isActive = org2.id === activeOrg2?.id;
4255
+ console.log(` ${isActive ? "\u25CF" : "\u25CB"} ${org2.name}${isActive ? " (active)" : ""}`);
4256
+ }
4257
+ } else {
4258
+ console.log("No organizations configured. Run: flightdesk init");
4259
+ }
4260
+ return;
4261
+ }
4262
+ console.log(`\u{1F4C1} Repository: ${repoInfo.remote}`);
4263
+ console.log(`\u{1F33F} Branch: ${repoInfo.branch}`);
4264
+ console.log("");
4265
+ const mappedOrg = getOrganizationByRepo(repoInfo.remote);
4266
+ const activeOrg = getActiveOrganization();
4267
+ if (mappedOrg) {
4268
+ console.log(`\u{1F3E2} Organization: ${mappedOrg.name}`);
4269
+ console.log(` API: ${getApiUrl()}`);
4270
+ console.log("");
4271
+ console.log("This repository is mapped to the above organization.");
4272
+ console.log("Commands will use this organization automatically.");
4273
+ } else {
4274
+ console.log("\u26A0\uFE0F This repository is not mapped to any organization.");
4275
+ console.log("");
4276
+ const config = loadConfig();
4277
+ if (config.organizations.length > 0) {
4278
+ console.log("Organizations:");
4279
+ for (const org2 of config.organizations) {
4280
+ const isActive = org2.id === activeOrg?.id;
4281
+ console.log(` ${isActive ? "\u25CF" : "\u25CB"} ${org2.name}${isActive ? " (active)" : ""}`);
4282
+ }
4283
+ console.log("");
4284
+ console.log("Run: flightdesk sync to refresh repository mappings");
4285
+ } else {
4286
+ console.log("No organizations configured. Run: flightdesk init");
4287
+ }
4288
+ }
4289
+ }
4290
+
4291
+ // apps/cli/src/commands/sync.ts
4292
+ async function syncCommand() {
4293
+ const config = requireConfig();
4294
+ if (config.organizations.length === 0) {
4295
+ console.error("No organizations configured. Run: flightdesk init");
4296
+ process.exit(1);
4297
+ }
4298
+ console.log("\u{1F504} Syncing repository mappings...\n");
4299
+ let totalProjects = 0;
4300
+ const newMappings = {};
4301
+ for (const org2 of config.organizations) {
4302
+ console.log(` ${org2.name}...`);
4303
+ try {
4304
+ const api = FlightDeskAPI.fromConfig(config, org2);
4305
+ const projects = await api.listProjects();
4306
+ console.log(` Found ${projects.length} project(s)`);
4307
+ for (const project2 of projects) {
4308
+ if (project2.githubRepo) {
4309
+ newMappings[project2.githubRepo] = org2.id;
4310
+ totalProjects++;
4311
+ }
4312
+ }
4313
+ } catch (error) {
4314
+ console.log(` \u274C Error: ${error}`);
4315
+ }
4316
+ }
4317
+ config.repoMapping = newMappings;
4318
+ saveConfig(config);
4319
+ console.log("");
4320
+ console.log(`\u2705 Synced ${totalProjects} project(s)`);
4321
+ if (totalProjects > 0) {
4322
+ console.log("");
4323
+ console.log("Repository mappings:");
4324
+ for (const [repo, orgId] of Object.entries(newMappings)) {
4325
+ const org2 = config.organizations.find((o) => o.id === orgId);
4326
+ console.log(` ${repo} \u2192 ${org2?.name || orgId}`);
4327
+ }
4328
+ }
4329
+ }
4330
+
4331
+ // apps/cli/src/commands/project.ts
4332
+ async function projectCommand(action, _options) {
4333
+ const { config, org: org2 } = requireActiveOrg();
4334
+ const api = FlightDeskAPI.fromConfig(config, org2);
4335
+ switch (action) {
4336
+ case "list":
4337
+ await listProjects(api);
4338
+ break;
4339
+ default:
4340
+ console.error(`Unknown action: ${action}`);
4341
+ process.exit(1);
4342
+ }
4343
+ }
4344
+ async function listProjects(api) {
4345
+ const projects = await api.listProjects();
4346
+ if (projects.length === 0) {
4347
+ console.log("No projects found.");
4348
+ console.log("\nCreate a project at https://app.flightdesk.dev/app/projects/new");
4349
+ return;
4350
+ }
4351
+ console.log("Projects:\n");
4352
+ const maxNameLen = Math.max(...projects.map((p) => p.name.length), 4);
4353
+ for (const project2 of projects) {
4354
+ const name = project2.name.padEnd(maxNameLen);
4355
+ const repo = project2.githubRepo || "(no repo)";
4356
+ console.log(` ${project2.id} ${name} ${repo}`);
4357
+ }
4358
+ console.log(`
4359
+ ${projects.length} project(s)`);
4360
+ }
4361
+
4362
+ // apps/cli/src/commands/preview.ts
4363
+ var import_node_child_process2 = require("node:child_process");
4364
+ var path2 = __toESM(require("node:path"));
4365
+ var os2 = __toESM(require("node:os"));
4366
+ var fs2 = __toESM(require("node:fs"));
4367
+ function isValidContainerId(id) {
4368
+ return /^[a-fA-F0-9]+$/.test(id) && id.length >= 12 && id.length <= 64;
4369
+ }
4370
+ function validateSSHParams(instance) {
4371
+ if (instance.containerId && !isValidContainerId(instance.containerId)) {
4372
+ throw new Error(`Invalid container ID format: ${instance.containerId}`);
4373
+ }
4374
+ if (!/^[a-zA-Z0-9_-]+$/.test(instance.sshUser)) {
4375
+ throw new Error(`Invalid SSH user format: ${instance.sshUser}`);
4376
+ }
4377
+ if (!/^[a-zA-Z0-9.-]+$/.test(instance.sshHost)) {
4378
+ throw new Error(`Invalid SSH host format: ${instance.sshHost}`);
4379
+ }
4380
+ if (!Number.isInteger(instance.sshPort) || instance.sshPort < 1 || instance.sshPort > 65535) {
4381
+ throw new Error(`Invalid SSH port: ${instance.sshPort}`);
4382
+ }
4383
+ }
4384
+ async function previewCommand(action, options) {
4385
+ const { config, org: org2 } = requireActiveOrg();
4386
+ const api = FlightDeskAPI.fromConfig(config, org2);
4387
+ try {
4388
+ switch (action) {
4389
+ case "status":
4390
+ await handleStatus2(api, options);
4391
+ break;
4392
+ case "logs":
4393
+ await handleLogs(api, options);
4394
+ break;
4395
+ case "mount":
4396
+ await handleMount(api, options);
4397
+ break;
4398
+ case "unmount":
4399
+ await handleUnmount(api, options);
4400
+ break;
4401
+ case "restart":
4402
+ await handleRestart(api, options);
4403
+ break;
4404
+ case "resume":
4405
+ await handleResume(api, options);
4406
+ break;
4407
+ case "teardown":
4408
+ await handleTeardown(api, options);
4409
+ break;
4410
+ }
4411
+ } catch (error) {
4412
+ console.error(`Error: ${error}`);
4413
+ process.exit(1);
4414
+ }
4415
+ }
4416
+ function getStatusEmoji3(status) {
4417
+ const statusEmojis = {
4418
+ STARTING: "\u{1F504}",
4419
+ READY: "\u2705",
4420
+ SUSPENDED: "\u{1F4A4}",
4421
+ RESTARTING: "\u{1F504}",
4422
+ TEARDOWN: "\u{1F5D1}\uFE0F",
4423
+ ERROR: "\u274C"
4424
+ };
4425
+ return statusEmojis[status] || "\u2753";
4426
+ }
4427
+ async function handleStatus2(api, options) {
4428
+ const instance = await api.getTaskInstance(options.taskId);
4429
+ if (!instance) {
4430
+ console.log("\n\u26A0\uFE0F No preview environment found for this task");
4431
+ console.log(" The preview environment may not have been created yet,");
4432
+ console.log(" or the PR may be closed.");
4433
+ return;
4434
+ }
4435
+ const emoji = getStatusEmoji3(instance.status);
4436
+ console.log("\n\u{1F4E6} Preview Environment");
4437
+ console.log("\u2500".repeat(50));
4438
+ console.log(`${emoji} Status: ${instance.status}`);
4439
+ console.log(` ID: ${instance.id.substring(0, 8)}`);
4440
+ if (instance.processUrls && instance.processUrls.length > 0) {
4441
+ console.log(" URLs:");
4442
+ for (const pu of instance.processUrls) {
4443
+ const label = pu.primary ? `${pu.name} (primary)` : pu.name;
4444
+ console.log(` ${label}: ${pu.url}`);
4445
+ }
4446
+ } else {
4447
+ console.log(` Preview URL: ${instance.previewUrl}`);
4448
+ }
4449
+ console.log(` SSH: ${instance.sshConnectionString}`);
4450
+ console.log(` Container: ${instance.containerId.substring(0, 12)}`);
4451
+ if (instance.lastActivityAt) {
4452
+ const lastActivity = new Date(instance.lastActivityAt);
4453
+ const minutesAgo = Math.round((Date.now() - lastActivity.getTime()) / 6e4);
4454
+ console.log(` Last Activity: ${minutesAgo} minutes ago`);
4455
+ }
4456
+ if (instance.suspendedAt) {
4457
+ const suspended = new Date(instance.suspendedAt);
4458
+ console.log(` Suspended At: ${suspended.toLocaleString()}`);
4459
+ }
4460
+ console.log(` Created: ${new Date(instance.createdAt).toLocaleString()}`);
4461
+ console.log("");
4462
+ }
4463
+ async function handleLogs(api, options) {
4464
+ const lines = options.lines || 100;
4465
+ if (options.follow) {
4466
+ const instance = await api.getTaskInstance(options.taskId);
4467
+ if (!instance) {
4468
+ console.error("No preview environment found for this task");
4469
+ process.exit(1);
4470
+ }
4471
+ console.log(`\u{1F4CB} Streaming logs from ${instance.previewUrl}...
4472
+ `);
4473
+ console.log(`(Press Ctrl+C to stop)
4474
+ `);
4475
+ validateSSHParams(instance);
4476
+ const sshCommand = `docker logs -f ${instance.containerId}`;
4477
+ const ssh = (0, import_node_child_process2.spawn)("ssh", [
4478
+ "-o",
4479
+ "StrictHostKeyChecking=no",
4480
+ "-o",
4481
+ "UserKnownHostsFile=/dev/null",
4482
+ "-p",
4483
+ String(instance.sshPort),
4484
+ `${instance.sshUser}@${instance.sshHost}`,
4485
+ sshCommand
4486
+ ]);
4487
+ ssh.stdout.pipe(process.stdout);
4488
+ ssh.stderr.pipe(process.stderr);
4489
+ ssh.on("close", (code) => {
4490
+ process.exit(code || 0);
4491
+ });
4492
+ process.on("SIGINT", () => {
4493
+ ssh.kill();
4494
+ process.exit(0);
4495
+ });
4496
+ return;
4497
+ }
4498
+ const result = await api.getInstanceLogs(options.taskId, lines);
4499
+ if (!result.logs) {
4500
+ console.log("No logs available");
4501
+ return;
4502
+ }
4503
+ console.log(result.logs);
4504
+ }
4505
+ async function handleMount(api, options) {
4506
+ const instance = await api.getTaskInstance(options.taskId);
4507
+ if (!instance) {
4508
+ console.error("No preview environment found for this task");
4509
+ process.exit(1);
4510
+ }
4511
+ if (instance.status === "SUSPENDED") {
4512
+ console.log("\u23F8\uFE0F Instance is suspended. Resuming...");
4513
+ await api.resumeInstance(options.taskId);
4514
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
4515
+ }
4516
+ try {
4517
+ (0, import_node_child_process2.execSync)("which sshfs", { stdio: "ignore" });
4518
+ } catch {
4519
+ console.error("\u274C sshfs is not installed.");
4520
+ console.error("");
4521
+ console.error("Install it with:");
4522
+ if (process.platform === "darwin") {
4523
+ console.error(" brew install macfuse gromgit/fuse/sshfs-mac");
4524
+ } else if (process.platform === "linux") {
4525
+ console.error(" sudo apt install sshfs");
4526
+ } else {
4527
+ console.error(" SSHFS is not supported on this platform");
4528
+ }
4529
+ process.exit(1);
4530
+ }
4531
+ const rawTaskIdPrefix = options.taskId.substring(0, 8);
4532
+ const safeTaskId = path2.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, "") || "task";
4533
+ const mountDir = options.directory || path2.join(os2.homedir(), "flightdesk-mounts", safeTaskId);
4534
+ if (!fs2.existsSync(mountDir)) {
4535
+ fs2.mkdirSync(mountDir, { recursive: true });
4536
+ }
4537
+ try {
4538
+ const mounted = (0, import_node_child_process2.execSync)("mount", { encoding: "utf8" });
4539
+ if (mounted.includes(mountDir)) {
4540
+ console.log(`\u{1F4C1} Already mounted at ${mountDir}`);
4541
+ return;
4542
+ }
4543
+ } catch {
4544
+ }
4545
+ console.log(`\u{1F4C1} Mounting preview environment to ${mountDir}...`);
4546
+ validateSSHParams(instance);
4547
+ const sshfsArgs = [
4548
+ "-o",
4549
+ "StrictHostKeyChecking=no",
4550
+ "-o",
4551
+ "UserKnownHostsFile=/dev/null",
4552
+ "-o",
4553
+ "reconnect",
4554
+ "-o",
4555
+ "ServerAliveInterval=15",
4556
+ "-o",
4557
+ "ServerAliveCountMax=3",
4558
+ "-p",
4559
+ String(instance.sshPort),
4560
+ `${instance.sshUser}@${instance.sshHost}:/app`,
4561
+ mountDir
4562
+ ];
4563
+ try {
4564
+ const result = (0, import_node_child_process2.spawnSync)("sshfs", sshfsArgs, { stdio: "inherit" });
4565
+ if (result.status !== 0) {
4566
+ throw new Error(`sshfs exited with code ${result.status}`);
4567
+ }
4568
+ console.log("");
4569
+ console.log("\u2705 Mounted successfully!");
4570
+ console.log(` Location: ${mountDir}`);
4571
+ console.log("");
4572
+ console.log(" To unmount:");
4573
+ console.log(` fd preview unmount ${options.taskId}`);
4574
+ console.log("");
4575
+ console.log(" Or manually:");
4576
+ if (process.platform === "darwin") {
4577
+ console.log(` umount ${mountDir}`);
4578
+ } else {
4579
+ console.log(` fusermount -u ${mountDir}`);
4580
+ }
4581
+ } catch (error) {
4582
+ console.error(`\u274C Mount failed: ${error}`);
4583
+ process.exit(1);
4584
+ }
4585
+ }
4586
+ async function handleUnmount(_api, options) {
4587
+ const rawTaskIdPrefix = options.taskId.substring(0, 8);
4588
+ const safeTaskId = path2.basename(rawTaskIdPrefix).replaceAll(/[^a-zA-Z0-9_-]/g, "") || "task";
4589
+ const mountDir = path2.join(os2.homedir(), "flightdesk-mounts", safeTaskId);
4590
+ if (!fs2.existsSync(mountDir)) {
4591
+ console.log("Mount directory does not exist");
4592
+ return;
4593
+ }
4594
+ console.log(`\u{1F4C1} Unmounting ${mountDir}...`);
4595
+ try {
4596
+ let result;
4597
+ if (process.platform === "darwin") {
4598
+ result = (0, import_node_child_process2.spawnSync)("umount", [mountDir], { stdio: "inherit" });
4599
+ } else {
4600
+ result = (0, import_node_child_process2.spawnSync)("fusermount", ["-u", mountDir], { stdio: "inherit" });
4601
+ }
4602
+ if (result.status !== 0) {
4603
+ throw new Error(`Unmount exited with code ${result.status}`);
4604
+ }
4605
+ console.log("\u2705 Unmounted successfully");
4606
+ try {
4607
+ fs2.rmSync(mountDir, { recursive: true, force: true });
4608
+ } catch {
4609
+ }
4610
+ } catch (error) {
4611
+ console.error(`\u274C Unmount failed: ${error}`);
4612
+ console.error("");
4613
+ console.error("Try force unmounting:");
4614
+ if (process.platform === "darwin") {
4615
+ console.error(` diskutil unmount force ${mountDir}`);
4616
+ } else {
4617
+ console.error(` fusermount -uz ${mountDir}`);
4618
+ }
4619
+ process.exit(1);
4620
+ }
4621
+ }
4622
+ async function handleRestart(api, options) {
4623
+ console.log("\u{1F504} Restarting preview environment...");
4624
+ await api.restartInstance(options.taskId);
4625
+ console.log("\u2705 Restart initiated. The preview will be available shortly.");
4626
+ }
4627
+ async function handleResume(api, options) {
4628
+ console.log("\u25B6\uFE0F Resuming preview environment...");
4629
+ await api.resumeInstance(options.taskId);
4630
+ console.log("\u2705 Resume initiated. The preview should be ready in about 30 seconds.");
4631
+ }
4632
+ async function handleTeardown(api, options) {
4633
+ console.log("\u{1F5D1}\uFE0F Tearing down preview environment...");
4634
+ await api.tearDownInstance(options.taskId);
4635
+ console.log("\u2705 Preview environment has been torn down.");
4636
+ }
4637
+
4638
+ // apps/cli/src/main.ts
4639
+ var program2 = new Command();
4640
+ program2.name("flightdesk").description("FlightDesk CLI - AI task management for Claude Code sessions").version("0.4.1").option("--dev", "Use local development API (localhost:3000)").option("--api <url>", "Use custom API URL");
4641
+ program2.hook("preAction", () => {
4642
+ const opts = program2.opts();
4643
+ if (opts.api) {
4644
+ setApiUrl(opts.api);
4645
+ console.log(`\u{1F527} Using custom API: ${opts.api}
4646
+ `);
4647
+ } else if (opts.dev) {
4648
+ setDevMode(true);
4649
+ console.log("\u{1F527} Development mode: using http://localhost:3000\n");
4650
+ }
4651
+ });
4652
+ program2.command("init").description("Configure FlightDesk CLI with your API credentials").action(initCommand);
4653
+ program2.command("register [task-id]").description("Register a Claude Code session with a FlightDesk task (auto-detects project from git repo)").option("-p, --project <id>", "Project ID (auto-detected from git repo if not provided)").option("--subproject <id>", "Subproject ID (required if project has subprojects configured)").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);
4654
+ var project = program2.command("project").description("Project management commands");
4655
+ project.command("list").description("List projects in the active organization").action(() => projectCommand("list", {}));
4656
+ var task = program2.command("task").description("Task management commands");
4657
+ 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").option("--subproject <id>", "Subproject ID (required if project has subprojects configured)").action((options) => taskCommand("create", options));
4658
+ 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));
4659
+ task.command("status <task-id>").description("Get task status").action((taskId) => taskCommand("status", { taskId }));
4660
+ 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").option("--pr-number <number>", "Pull request number (use if --pr-url is not enough)").option("--session <session>", "Claude Code session (URL or session ID)").action((taskId, options) => taskCommand("update", { taskId, ...options }));
4661
+ task.command("sync <task-id>").description("Sync PR review state (Copilot feedback, Claude reviews, human reviews) from GitHub").action((taskId) => taskCommand("sync", { taskId }));
4662
+ program2.command("status").description("Show status of all active tasks").option("-p, --project <id>", "Filter by project").action(statusCommand);
4663
+ 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);
4664
+ var org = program2.command("org").description("Organization management");
4665
+ org.command("list").description("List your organizations").action(orgListCommand);
4666
+ org.command("switch <name>").description("Switch active organization").action(orgSwitchCommand);
4667
+ org.command("refresh").description("Refresh organizations from API").action(orgRefreshCommand);
4668
+ program2.command("context").description("Show current repository context and mapped organization").action(contextCommand);
4669
+ program2.command("sync").description("Refresh project-to-repository mappings from all organizations").action(syncCommand);
4670
+ var preview = program2.command("preview").description("Preview environment management");
4671
+ preview.command("status <task-id>").description("Show preview environment status").action((taskId) => previewCommand("status", { taskId }));
4672
+ preview.command("logs <task-id>").description("Get logs from preview environment").option("-n, --lines <lines>", "Number of log lines (1-10000)", "100").option("-f, --follow", "Follow log output").action((taskId, options) => {
4673
+ const lines = Math.min(Math.max(Number.parseInt(options.lines || "100"), 1), 1e4);
4674
+ previewCommand("logs", { taskId, lines, follow: options.follow });
4675
+ });
4676
+ preview.command("mount <task-id>").description("Mount preview environment filesystem via SSHFS").option("-d, --directory <path>", "Custom mount directory").action((taskId, options) => previewCommand("mount", { taskId, directory: options.directory }));
4677
+ preview.command("unmount <task-id>").description("Unmount preview environment filesystem").action((taskId) => previewCommand("unmount", { taskId }));
4678
+ preview.command("restart <task-id>").description("Restart preview environment processes").action((taskId) => previewCommand("restart", { taskId }));
4679
+ preview.command("resume <task-id>").description("Resume a suspended preview environment").action((taskId) => previewCommand("resume", { taskId }));
4680
+ preview.command("teardown <task-id>").description("Tear down preview environment").action((taskId) => previewCommand("teardown", { taskId }));
4681
+ program2.command("mount <task-id>").description('Mount preview environment filesystem (shorthand for "preview mount")').option("-d, --directory <path>", "Custom mount directory").action((taskId, options) => previewCommand("mount", { taskId, directory: options.directory }));
4682
+ program2.command("unmount <task-id>").description('Unmount preview environment filesystem (shorthand for "preview unmount")').action((taskId) => previewCommand("unmount", { taskId }));
4683
+ program2.command("logs <task-id>").description('Get logs from preview environment (equivalent to "preview logs")').option("-n, --lines <lines>", "Number of log lines (1-10000)", "100").option("-f, --follow", "Follow log output").action((taskId, options) => {
4684
+ const lines = Math.min(Math.max(Number.parseInt(options.lines || "100"), 1), 1e4);
4685
+ previewCommand("logs", { taskId, lines, follow: options.follow });
4686
+ });
4687
+ program2.parse();
4688
+ //# sourceMappingURL=main.js.map