@frontstackdev/cli 0.0.0-canary-20251111091309 → 0.0.0-canary-20251116182422
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/frontstack.mjs +18 -18
- package/dist/version +1 -1
- package/package.json +3 -2
package/dist/frontstack.mjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ge=Object.defineProperty;var l=(
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}l(c,"formatList");let h=[`Usage: ${t.commandUsage(e)}`,""];const s=t.commandDescription(e);s.length>0&&(h=h.concat([t.wrap(s,
|
|
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,
|
|
2
|
+
var Ge=Object.defineProperty;var l=(r,e)=>Ge(r,"name",{value:e,configurable:!0});var R,H,N,I,F,V,T;import Je from"events";import Be from"child_process";import Ke from"path";import _,{existsSync as fe,readFileSync as de,mkdirSync as ze,writeFileSync as Qe}from"fs";import Ye from"process";import f from"chalk";import g,{join as Ze,dirname as Xe}from"pathe";import me from"js-yaml";import{defu as et}from"defu";import tt from"http";import nt from"open";import E from"handlebars";import rt from"openapi-typescript";import U from"prompts";import K from"semver";import{fileURLToPath as ot}from"url";var A={},D={},k={};let ge=(R=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}},l(R,"CommanderError"),R),it=(H=class extends ge{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},l(H,"InvalidArgumentError"),H);k.CommanderError=ge,k.InvalidArgumentError=it;const{InvalidArgumentError:st}=k;let at=(N=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 st(`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}},l(N,"Argument"),N);function ct(r){const e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}l(ct,"humanReadableArgName$2"),D.Argument=at,D.humanReadableArgName=ct;var _e={},z={};const{humanReadableArgName:lt}=D;let ut=(I=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){const t=e.commands.filter(o=>!o._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((o,i)=>o.name().localeCompare(i.name())),t}compareOptions(e,t){const n=l(o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,""),"getSortKey");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(o=>!o.hidden),n=e._getHelpOption();if(n&&!n.hidden){const o=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!o&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!o&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const o=n.options.filter(i=>!i.hidden);t.push(...o)}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){const t=e.registeredArguments.map(n=>lt(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,o)=>Math.max(n,t.subcommandTerm(o).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,o)=>Math.max(n,t.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,t.optionTerm(o).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,o)=>Math.max(n,t.argumentTerm(o).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const 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){const 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){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),o=t.helpWidth||80,i=2,a=2;function u(m,b){if(b){const x=`${m.padEnd(n+a)}${b}`;return t.wrap(x,o-i,n+a)}return m}l(u,"formatItem");function c(m){return m.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}l(c,"formatList");let h=[`Usage: ${t.commandUsage(e)}`,""];const s=t.commandDescription(e);s.length>0&&(h=h.concat([t.wrap(s,o,0),""]));const p=t.visibleArguments(e).map(m=>u(t.argumentTerm(m),t.argumentDescription(m)));p.length>0&&(h=h.concat(["Arguments:",c(p),""]));const d=t.visibleOptions(e).map(m=>u(t.optionTerm(m),t.optionDescription(m)));if(d.length>0&&(h=h.concat(["Options:",c(d),""])),this.showGlobalOptions){const m=t.visibleGlobalOptions(e).map(b=>u(t.optionTerm(b),t.optionDescription(b)));m.length>0&&(h=h.concat(["Global Options:",c(m),""]))}const y=t.visibleCommands(e).map(m=>u(t.subcommandTerm(m),t.subcommandDescription(m)));return y.length>0&&(h=h.concat(["Commands:",c(y),""])),h.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,o=40){const i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${i}]+`);if(e.match(a))return e;const u=t-n;if(u<o)return e;const c=e.slice(0,n),h=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),s=" ".repeat(n),d="\\s\u200B",y=new RegExp(`
|
|
7
7
|
|.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),m=h.match(y)||[];return c+m.map((b,x)=>b===`
|
|
8
8
|
`?"":(x>0?s:"")+b.trimEnd()).join(`
|
|
9
|
-
`)}},l(I,"Help"),I);z.Help=
|
|
9
|
+
`)}},l(I,"Help"),I);z.Help=ut;var W={};const{InvalidArgumentError:ht}=k;let pt=(F=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;const n=mt(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 ht(`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 dt(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},l(F,"Option"),F),ft=(V=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){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const o=this.negativeOptions.get(n).presetArg,i=o!==void 0?o:!1;return t.negate===(i===e)}},l(V,"DualOptions"),V);function dt(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(dt,"camelcase");function mt(r){let e,t;const n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}l(mt,"splitOptionFlags"),W.Option=pt,W.DualOptions=ft;var ye={};const Oe=3;function gt(r,e){if(Math.abs(r.length-e.length)>Oe)return Math.max(r.length,e.length);const t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=r.length;o++){let i=1;r[o-1]===e[n-1]?i=0:i=1,t[o][n]=Math.min(t[o-1][n]+1,t[o][n-1]+1,t[o-1][n-1]+i),o>1&&n>1&&r[o-1]===e[n-2]&&r[o-2]===e[n-1]&&(t[o][n]=Math.min(t[o][n],t[o-2][n-2]+1))}return t[r.length][e.length]}l(gt,"editDistance");function _t(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(a=>a.slice(2)));let n=[],o=Oe;const i=.4;return e.forEach(a=>{if(a.length<=1)return;const u=gt(r,a),c=Math.max(r.length,a.length);(c-u)/c>i&&(u<o?(o=u,n=[a]):u===o&&n.push(a))}),n.sort((a,u)=>a.localeCompare(u)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}l(
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Z(e,t,n)),O.exit(e)}action(e){const t=l(n=>{const
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=l(
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}l(_t,"suggestSimilar$1"),ye.suggestSimilar=_t;const yt=Je.EventEmitter,Q=Be,v=Ke,Y=_,O=Ye,{Argument:Ot,humanReadableArgName:bt}=D,{CommanderError:Z}=k,{Help:wt}=z,{Option:be,DualOptions:At}=W,{suggestSimilar:we}=ye;let Ct=(T=class extends yt{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:l(t=>O.stdout.write(t),"writeOut"),writeErr:l(t=>O.stderr.write(t),"writeErr"),getOutHelpWidth:l(()=>O.stdout.isTTY?O.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>O.stderr.isTTY?O.stderr.columns:void 0,"getErrHelpWidth"),outputError:l((t,n)=>n(t),"outputError")},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(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let o=t,i=n;typeof o=="object"&&o!==null&&(i=o,o=null),i=i||{};const[,a,u]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(a);return o&&(c.description(o),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,u&&c.arguments(u),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new T(e)}createHelp(){return Object.assign(new wt,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 Ot(e,t)}argument(e,t,n,o){const i=this.createArgument(e,t);return typeof n=="function"?i.default(o).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){const 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]";const[,n,o]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),o&&a.arguments(o),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,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){const 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 Z(e,t,n)),O.exit(e)}action(e){const t=l(n=>{const o=this.registeredArguments.length,i=n.slice(0,o);return this._storeOptionsAsProperties?i[o]=this:i[o]=this.opts(),i.push(this),e.apply(this,i)},"listener");return this._actionHandler=t,this}createOption(e,t){return new be(e,t)}_callParseArg(e,t,n,o){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){const a=`${o} ${i.message}`;this.error(a,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const 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){const t=l(o=>[o.name()].concat(o.aliases()),"knownBy"),n=t(e).find(o=>this._findCommand(o));if(n){const o=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");const o=l((i,a,u)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);const c=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,a):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,u)},"handleOptionValue");return this.on("option:"+t,i=>{const a=`error: option '${e.flags}' argument '${i}' is invalid.`;o(i,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{const a=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;o(i,a,"env")}),this}_optionEx(e,t,n,o,i){if(typeof t=="object"&&t instanceof be)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof o=="function")a.default(i).argParser(o);else if(o instanceof RegExp){const u=o;o=l((c,h)=>{const s=u.exec(c);return s?s[0]:h},"fn"),a.default(i).argParser(o)}else a.default(o);return this.addOption(a)}option(e,t,n,o){return this._optionEx({},e,t,n,o)}requiredOption(e,t,n,o){return this._optionEx({mandatory:!0},e,t,n,o)}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");t=t||{},e===void 0&&(e=O.argv,O.versions&&O.versions.electron&&(t.from="electron")),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":O.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);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){const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1;const o=[".js",".ts",".tsx",".mjs",".cjs"];function i(s,p){const d=v.resolve(s,p);if(Y.existsSync(d))return d;if(o.includes(v.extname(p)))return;const y=o.find(m=>Y.existsSync(`${d}${m}`));if(y)return`${d}${y}`}l(i,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let s;try{s=Y.realpathSync(this._scriptPath)}catch{s=this._scriptPath}u=v.resolve(v.dirname(s),u)}if(u){let s=i(u,a);if(!s&&!e._executableFile&&this._scriptPath){const p=v.basename(this._scriptPath,v.extname(this._scriptPath));p!==this._name&&(s=i(u,`${p}-${e._name}`))}a=s||a}n=o.includes(v.extname(a));let c;O.platform!=="win32"?n?(t.unshift(a),t=Ae(O.execArgv).concat(t),c=Q.spawn(O.argv[0],t,{stdio:"inherit"})):c=Q.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=Ae(O.execArgv).concat(t),c=Q.spawn(O.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{O.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});const h=this._exitCallback;c.on("close",(s,p)=>{s=s??1,h?h(new Z(s,"commander.executeSubCommandAsync","(close)")):O.exit(s)}),c.on("error",s=>{if(s.code==="ENOENT"){const p=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${a}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${p}`;throw new Error(d)}else if(s.code==="EACCES")throw new Error(`'${a}' not executable`);if(!h)O.exit(1);else{const p=new Z(1,"commander.executeSubCommandAsync","(error)");p.nestedError=s,h(p)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){const
|
|
17
|
+
- ${p}`;throw new Error(d)}else if(s.code==="EACCES")throw new Error(`'${a}' not executable`);if(!h)O.exit(1);else{const p=new Z(1,"commander.executeSubCommandAsync","(error)");p.nestedError=s,h(p)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){const o=this._findCommand(e);o||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,o,"preSubcommand"),i=this._chainOrCall(i,()=>{if(o._executableHandler)this._executeSubCommand(o,t.concat(n));else return o._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();const 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(){const e=l((n,o,i)=>{let a=o;if(o!==null&&n.parseArg){const u=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,o,i,u)}return a},"myParseArg");this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,o)=>{let i=n.defaultValue;n.variadic?o<this.args.length?(i=this.args.slice(o),n.parseArg&&(i=i.reduce((a,u)=>e(n,u,a),n.defaultValue))):i===void 0&&(i=[]):o<this.args.length&&(i=this.args[o],n.parseArg&&(i=e(n,i,n.defaultValue))),t[o]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const o=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(a=>{o.push({hookedCommand:i,callback:a})})}),t==="postAction"&&o.reverse(),o.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{o=this._chainOrCall(o,()=>i(this,t))}),o}_parseCommand(e,t){const 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();const o=l(()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},"checkForUnknownOptions"),i=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(i,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(i))o(),this._processArguments(),this.parent.emit(i,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():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),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(){const e=this.options.filter(n=>{const o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{const o=e.find(i=>n.conflictsWith.includes(i.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let o=t;const i=e.slice();function a(c){return c.length>1&&c[0]==="-"}l(a,"maybeOption");let u=null;for(;i.length;){const c=i.shift();if(c==="--"){o===n&&o.push(c),o.push(...i);break}if(u&&!a(c)){this.emit(`option:${u.name()}`,c);continue}if(u=null,a(c)){const h=this._findOption(c);if(h){if(h.required){const s=i.shift();s===void 0&&this.optionMissingArgument(h),this.emit(`option:${h.name()}`,s)}else if(h.optional){let s=null;i.length>0&&!a(i[0])&&(s=i.shift()),this.emit(`option:${h.name()}`,s)}else this.emit(`option:${h.name()}`);u=h.variadic?h:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){const h=this._findOption(`-${c[1]}`);if(h){h.required||h.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${h.name()}`,c.slice(2)):(this.emit(`option:${h.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){const h=c.indexOf("="),s=this._findOption(c.slice(0,h));if(s&&(s.required||s.optional)){this.emit(`option:${s.name()}`,c.slice(h+1));continue}}if(a(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(c)){t.push(c),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(c),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){o.push(c),i.length>0&&o.push(...i);break}o.push(c)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));const n=t||{},
|
|
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");const n=this.parent?._findCommand(e);if(n){const
|
|
22
|
-
Expecting one of '${n.join("', '")}'`);const
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}},l(T,"Command"),T);function Ae(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}l(Ae,"incrementNodeInspectorPort"),_e.Command=At;const{Argument:Ce}=D,{Command:X}=_e,{CommanderError:Ct,InvalidArgumentError:Ee}=k,{Help:Et}=z,{Option:$e}=W;A.program=new X,A.createCommand=o=>new X(o),A.createOption=(o,e)=>new $e(o,e),A.createArgument=(o,e)=>new Ce(o,e),A.Command=X,A.Option=$e,A.Argument=Ce,A.Help=Et,A.CommanderError=Ct,A.InvalidArgumentError=Ee,A.InvalidOptionArgumentError=Ee;const{program:lo,createCommand:uo,createArgument:ho,createOption:po,CommanderError:fo,InvalidArgumentError:mo,InvalidOptionArgumentError:go,Command:$t,Argument:_o,Option:yo,Help:Oo}=A,vt=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,St=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,jt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Tt(o,e){if(o==="__proto__"||o==="constructor"&&e&&typeof e=="object"&&"prototype"in e){xt(o);return}return e}l(Tt,"jsonParseTransform");function xt(o){console.warn(`[destr] Dropping "${o}" key to prevent prototype pollution.`)}l(xt,"warnKeyDropped");function kt(o,e={}){if(typeof o!="string")return o;const t=o.trim();if(o[0]==='"'&&o.endsWith('"')&&!o.includes("\\"))return t.slice(1,-1);if(t.length<=9){const n=t.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!jt.test(o)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return o}try{if(vt.test(o)||St.test(o)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(o,Tt)}return JSON.parse(o)}catch(n){if(e.strict)throw n;return o}}l(kt,"destr");const Pt=/#/g,Rt=/&/g,Ht=/\//g,Nt=/=/g,ee=/\+/g,It=/%5e/gi,Ft=/%60/gi,Vt=/%7c/gi,Dt=/%20/gi;function Lt(o){return encodeURI(""+o).replace(Vt,"|")}l(Lt,"encode");function te(o){return Lt(typeof o=="string"?o:JSON.stringify(o)).replace(ee,"%2B").replace(Dt,"+").replace(Pt,"%23").replace(Rt,"%26").replace(Ft,"`").replace(It,"^").replace(Ht,"%2F")}l(te,"encodeQueryValue");function ne(o){return te(o).replace(Nt,"%3D")}l(ne,"encodeQueryKey");function ve(o=""){try{return decodeURIComponent(""+o)}catch{return""+o}}l(ve,"decode");function qt(o){return ve(o.replace(ee," "))}l(qt,"decodeQueryKey");function Mt(o){return ve(o.replace(ee," "))}l(Mt,"decodeQueryValue");function Ut(o=""){const e={};o[0]==="?"&&(o=o.slice(1));for(const t of o.split("&")){const n=t.match(/([^=]+)=?(.*)/)||[];if(n.length<2)continue;const r=qt(n[1]);if(r==="__proto__"||r==="constructor")continue;const i=Mt(n[2]||"");e[r]===void 0?e[r]=i:Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]}return e}l(Ut,"parseQuery");function Wt(o,e){return(typeof e=="number"||typeof e=="boolean")&&(e=String(e)),e?Array.isArray(e)?e.map(t=>`${ne(o)}=${te(t)}`).join("&"):`${ne(o)}=${te(e)}`:ne(o)}l(Wt,"encodeQueryItem");function Gt(o){return Object.keys(o).filter(e=>o[e]!==void 0).map(e=>Wt(e,o[e])).filter(Boolean).join("&")}l(Gt,"stringifyQuery");const Jt=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,Bt=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,Kt=/^([/\\]\s*){2,}[^/\\]/,zt=/^\.?\//;function Se(o,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?Jt.test(o):Bt.test(o)||(e.acceptRelative?Kt.test(o):!1)}l(Se,"hasProtocol");function Qt(o="",e){return o.endsWith("/")}l(Qt,"hasTrailingSlash");function Yt(o="",e){return(Qt(o)?o.slice(0,-1):o)||"/"}l(Yt,"withoutTrailingSlash");function Zt(o="",e){return o.endsWith("/")?o:o+"/"}l(Zt,"withTrailingSlash");function Xt(o,e){if(tn(e)||Se(o))return o;const t=Yt(e);return o.startsWith(t)?o:on(t,o)}l(Xt,"withBase");function en(o,e){const t=rn(o),n={...Ut(t.search),...e};return t.search=Gt(n),sn(t)}l(en,"withQuery");function tn(o){return!o||o==="/"}l(tn,"isEmptyURL");function nn(o){return o&&o!=="/"}l(nn,"isNonEmptyURL");function on(o,...e){let t=o||"";for(const n of e.filter(r=>nn(r)))if(t){const r=n.replace(zt,"");t=Zt(t)+r}else t=n;return t}l(on,"joinURL");const je=Symbol.for("ufo:protocolRelative");function rn(o="",e){const t=o.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){const[,p,d=""]=t;return{protocol:p.toLowerCase(),pathname:d,href:p+d,auth:"",host:"",search:"",hash:""}}if(!Se(o,{acceptRelative:!0}))return Te(o);const[,n="",r,i=""]=o.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,a="",u=""]=i.match(/([^#/?]*)(.*)?/)||[];n==="file:"&&(u=u.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:c,search:h,hash:s}=Te(u);return{protocol:n.toLowerCase(),auth:r?r.slice(0,Math.max(0,r.length-1)):"",host:a,pathname:c,search:h,hash:s,[je]:!n}}l(rn,"parseURL");function Te(o=""){const[e="",t="",n=""]=(o.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:e,search:t,hash:n}}l(Te,"parsePath");function sn(o){const e=o.pathname||"",t=o.search?(o.search.startsWith("?")?"":"?")+o.search:"",n=o.hash||"",r=o.auth?o.auth+"@":"",i=o.host||"";return(o.protocol||o[je]?(o.protocol||"")+"//":"")+r+i+e+t+n}l(sn,"stringifyParsedURL");const ae=class ae extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}};l(ae,"FetchError");let oe=ae;function an(o){const e=o.error?.message||o.error?.toString()||"",t=o.request?.method||o.options?.method||"GET",n=o.request?.url||String(o.request)||"/",r=`[${t}] ${JSON.stringify(n)}`,i=o.response?`${o.response.status} ${o.response.statusText}`:"<no response>",a=`${r}: ${i}${e?` ${e}`:""}`,u=new oe(a,o.error?{cause:o.error}:void 0);for(const c of["request","options","response"])Object.defineProperty(u,c,{get(){return o[c]}});for(const[c,h]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(u,c,{get(){return o.response&&o.response[h]}});return u}l(an,"createFetchError");const cn=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function xe(o="GET"){return cn.has(o.toUpperCase())}l(xe,"isPayloadMethod");function ln(o){if(o===void 0)return!1;const e=typeof o;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(o)?!0:o.buffer?!1:o.constructor&&o.constructor.name==="Object"||typeof o.toJSON=="function"}l(ln,"isJSONSerializable");const un=new Set(["image/svg","application/xml","application/xhtml","application/html"]),hn=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function pn(o=""){if(!o)return"json";const e=o.split(";").shift()||"";return hn.test(e)?"json":un.has(e)||e.startsWith("text/")?"text":"blob"}l(pn,"detectResponseType");function fn(o,e,t=globalThis.Headers){const n={...e,...o};if(e?.params&&o?.params&&(n.params={...e?.params,...o?.params}),e?.query&&o?.query&&(n.query={...e?.query,...o?.query}),e?.headers&&o?.headers){n.headers=new t(e?.headers||{});for(const[r,i]of new t(o?.headers||{}))n.headers.set(r,i)}return n}l(fn,"mergeFetchOptions");const dn=new Set([408,409,425,429,500,502,503,504]),mn=new Set([101,204,205,304]);function ke(o={}){const{fetch:e=globalThis.fetch,Headers:t=globalThis.Headers,AbortController:n=globalThis.AbortController}=o;async function r(u){const c=u.error&&u.error.name==="AbortError"&&!u.options.timeout||!1;if(u.options.retry!==!1&&!c){let s;typeof u.options.retry=="number"?s=u.options.retry:s=xe(u.options.method)?0:1;const p=u.response&&u.response.status||500;if(s>0&&(Array.isArray(u.options.retryStatusCodes)?u.options.retryStatusCodes.includes(p):dn.has(p))){const d=u.options.retryDelay||0;return d>0&&await new Promise(y=>setTimeout(y,d)),i(u.request,{...u.options,retry:s-1})}}const h=an(u);throw Error.captureStackTrace&&Error.captureStackTrace(h,i),h}l(r,"onError");const i=l(async function(c,h={}){const s={request:c,options:fn(h,o.defaults,t),response:void 0,error:void 0};s.options.method=s.options.method?.toUpperCase(),s.options.onRequest&&await s.options.onRequest(s),typeof s.request=="string"&&(s.options.baseURL&&(s.request=Xt(s.request,s.options.baseURL)),(s.options.query||s.options.params)&&(s.request=en(s.request,{...s.options.params,...s.options.query}))),s.options.body&&xe(s.options.method)&&(ln(s.options.body)?(s.options.body=typeof s.options.body=="string"?s.options.body:JSON.stringify(s.options.body),s.options.headers=new t(s.options.headers||{}),s.options.headers.has("content-type")||s.options.headers.set("content-type","application/json"),s.options.headers.has("accept")||s.options.headers.set("accept","application/json")):("pipeTo"in s.options.body&&typeof s.options.body.pipeTo=="function"||typeof s.options.body.pipe=="function")&&("duplex"in s.options||(s.options.duplex="half")));let p;if(!s.options.signal&&s.options.timeout){const y=new n;p=setTimeout(()=>y.abort(),s.options.timeout),s.options.signal=y.signal}try{s.response=await e(s.request,s.options)}catch(y){return s.error=y,s.options.onRequestError&&await s.options.onRequestError(s),await r(s)}finally{p&&clearTimeout(p)}if(s.response.body&&!mn.has(s.response.status)&&s.options.method!=="HEAD"){const y=(s.options.parseResponse?"json":s.options.responseType)||pn(s.response.headers.get("content-type")||"");switch(y){case"json":{const m=await s.response.text(),b=s.options.parseResponse||kt;s.response._data=b(m);break}case"stream":{s.response._data=s.response.body;break}default:s.response._data=await s.response[y]()}}return s.options.onResponse&&await s.options.onResponse(s),!s.options.ignoreResponseError&&s.response.status>=400&&s.response.status<600?(s.options.onResponseError&&await s.options.onResponseError(s),await r(s)):s.response},"$fetchRaw2"),a=l(async function(c,h){return(await i(c,h))._data},"$fetch2");return a.raw=i,a.native=(...u)=>e(...u),a.create=(u={})=>ke({...o,defaults:{...o.defaults,...u}}),a}l(ke,"createFetch");const re=function(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}(),gn=re.fetch||(()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!"))),_n=re.Headers,yn=re.AbortController,L=ke({fetch:gn,Headers:_n,AbortController:yn}),On={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.test/":"https://backend.frontstack.dev/")},q=On.apiRoot,bn=`${q}login`,wn=`${q}api/fetch-api/spec.yaml`,Pe=3008,Re=`http://localhost:${Pe}`,He=`${bn}?redirectUrl=${Re}/callback`,An=".frontstack-local/",S=g.join(process.cwd(),An),ie="api_session.jwt",Ne="project.json",P=l(()=>{const o=l(()=>{console.info("Not auth.login implemented yet")},"login"),e=l(async()=>{try{return a(),0}catch(p){console.log(p)}},"logout"),t=l(async(p=!1)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(`${q}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r()}`}})}catch(d){return p&&console.log(d),1}},"getProfile"),n=l(async p=>{try{if(p==null)throw new Error(`You have no project selected
|
|
24
|
-
Run ${f.hex("#7c3bed")("frontstack project")} to select a frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(
|
|
25
|
-
`+p.error);let d="";try{d=await
|
|
26
|
-
`);const Ue={type:"select",name:"action",message:"How would you like to proceed?",choices
|
|
20
|
+
`),this.outputHelp({error:!0}));const n=t||{},o=n.exitCode||1,i=n.code||"commander.error";this._exit(o,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in O.env){const t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,O.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new At(this.options),t=l(n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n)),"hasCustomOptionValue");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(o=>!t(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=l(a=>{const u=a.attributeName(),c=this.getOptionValue(u),h=this.options.find(p=>p.negate&&u===p.attributeName()),s=this.options.find(p=>!p.negate&&u===p.attributeName());return h&&(h.presetArg===void 0&&c===!1||h.presetArg!==void 0&&c===h.presetArg)?h:s||a},"findBestOptionFromValue"),o=l(a=>{const u=n(a),c=u.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},"getErrorMessage"),i=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],i=this;do{const a=i.createHelp().visibleOptions(i).filter(u=>u.long).map(u=>u.long);o=o.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=we(e,o)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const o=[];this.createHelp().visibleCommands(this).forEach(i=>{o.push(i.name()),i.alias()&&o.push(i.alias())}),t=we(e,o)}const 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";const o=this.createOption(t,n);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.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");const n=this.parent?._findCommand(e);if(n){const o=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}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;const t=this.registeredArguments.map(n=>bt(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=v.basename(e,v.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const 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||{};const t={error:!!e.error};let n;return t.error?n=l(o=>this._outputConfiguration.writeErr(o),"write"):n=l(o=>this._outputConfiguration.writeOut(o),"write"),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.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=O.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${n.join("', '")}'`);const o=`${e}Help`;return this.on(o,i=>{let a;typeof t=="function"?a=t({error:i.error,command:i.command}):a=t,a&&i.write(`${a}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(o=>t.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}},l(T,"Command"),T);function Ae(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",o="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?o=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],o=i[4]),t&&o!=="0"?`${t}=${n}:${parseInt(o)+1}`:e})}l(Ae,"incrementNodeInspectorPort"),_e.Command=Ct;const{Argument:Ce}=D,{Command:X}=_e,{CommanderError:$t,InvalidArgumentError:$e}=k,{Help:Et}=z,{Option:Ee}=W;A.program=new X,A.createCommand=r=>new X(r),A.createOption=(r,e)=>new Ee(r,e),A.createArgument=(r,e)=>new Ce(r,e),A.Command=X,A.Option=Ee,A.Argument=Ce,A.Help=Et,A.CommanderError=$t,A.InvalidArgumentError=$e,A.InvalidOptionArgumentError=$e;const{program:hr,createCommand:pr,createArgument:fr,createOption:dr,CommanderError:mr,InvalidArgumentError:gr,InvalidOptionArgumentError:_r,Command:vt,Argument:yr,Option:Or,Help:br}=A,St=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,jt=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Tt=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function xt(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){kt(r);return}return e}l(xt,"jsonParseTransform");function kt(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}l(kt,"warnKeyDropped");function Pt(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const n=t.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!Tt.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(St.test(r)||jt.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,xt)}return JSON.parse(r)}catch(n){if(e.strict)throw n;return r}}l(Pt,"destr");const Rt=/#/g,Ht=/&/g,Nt=/\//g,It=/=/g,ee=/\+/g,Ft=/%5e/gi,Vt=/%60/gi,Dt=/%7c/gi,Lt=/%20/gi;function qt(r){return encodeURI(""+r).replace(Dt,"|")}l(qt,"encode");function te(r){return qt(typeof r=="string"?r:JSON.stringify(r)).replace(ee,"%2B").replace(Lt,"+").replace(Rt,"%23").replace(Ht,"%26").replace(Vt,"`").replace(Ft,"^").replace(Nt,"%2F")}l(te,"encodeQueryValue");function ne(r){return te(r).replace(It,"%3D")}l(ne,"encodeQueryKey");function ve(r=""){try{return decodeURIComponent(""+r)}catch{return""+r}}l(ve,"decode");function Mt(r){return ve(r.replace(ee," "))}l(Mt,"decodeQueryKey");function Ut(r){return ve(r.replace(ee," "))}l(Ut,"decodeQueryValue");function Wt(r=""){const e={};r[0]==="?"&&(r=r.slice(1));for(const t of r.split("&")){const n=t.match(/([^=]+)=?(.*)/)||[];if(n.length<2)continue;const o=Mt(n[1]);if(o==="__proto__"||o==="constructor")continue;const i=Ut(n[2]||"");e[o]===void 0?e[o]=i:Array.isArray(e[o])?e[o].push(i):e[o]=[e[o],i]}return e}l(Wt,"parseQuery");function Gt(r,e){return(typeof e=="number"||typeof e=="boolean")&&(e=String(e)),e?Array.isArray(e)?e.map(t=>`${ne(r)}=${te(t)}`).join("&"):`${ne(r)}=${te(e)}`:ne(r)}l(Gt,"encodeQueryItem");function Jt(r){return Object.keys(r).filter(e=>r[e]!==void 0).map(e=>Gt(e,r[e])).filter(Boolean).join("&")}l(Jt,"stringifyQuery");const Bt=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,Kt=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,zt=/^([/\\]\s*){2,}[^/\\]/,Qt=/^\.?\//;function Se(r,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?Bt.test(r):Kt.test(r)||(e.acceptRelative?zt.test(r):!1)}l(Se,"hasProtocol");function Yt(r="",e){return r.endsWith("/")}l(Yt,"hasTrailingSlash");function Zt(r="",e){return(Yt(r)?r.slice(0,-1):r)||"/"}l(Zt,"withoutTrailingSlash");function Xt(r="",e){return r.endsWith("/")?r:r+"/"}l(Xt,"withTrailingSlash");function en(r,e){if(nn(e)||Se(r))return r;const t=Zt(e);return r.startsWith(t)?r:on(t,r)}l(en,"withBase");function tn(r,e){const t=sn(r),n={...Wt(t.search),...e};return t.search=Jt(n),an(t)}l(tn,"withQuery");function nn(r){return!r||r==="/"}l(nn,"isEmptyURL");function rn(r){return r&&r!=="/"}l(rn,"isNonEmptyURL");function on(r,...e){let t=r||"";for(const n of e.filter(o=>rn(o)))if(t){const o=n.replace(Qt,"");t=Xt(t)+o}else t=n;return t}l(on,"joinURL");const je=Symbol.for("ufo:protocolRelative");function sn(r="",e){const t=r.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){const[,p,d=""]=t;return{protocol:p.toLowerCase(),pathname:d,href:p+d,auth:"",host:"",search:"",hash:""}}if(!Se(r,{acceptRelative:!0}))return Te(r);const[,n="",o,i=""]=r.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,a="",u=""]=i.match(/([^#/?]*)(.*)?/)||[];n==="file:"&&(u=u.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:c,search:h,hash:s}=Te(u);return{protocol:n.toLowerCase(),auth:o?o.slice(0,Math.max(0,o.length-1)):"",host:a,pathname:c,search:h,hash:s,[je]:!n}}l(sn,"parseURL");function Te(r=""){const[e="",t="",n=""]=(r.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:e,search:t,hash:n}}l(Te,"parsePath");function an(r){const e=r.pathname||"",t=r.search?(r.search.startsWith("?")?"":"?")+r.search:"",n=r.hash||"",o=r.auth?r.auth+"@":"",i=r.host||"";return(r.protocol||r[je]?(r.protocol||"")+"//":"")+o+i+e+t+n}l(an,"stringifyParsedURL");const ae=class ae extends Error{constructor(e,t){super(e,t),this.name="FetchError",t?.cause&&!this.cause&&(this.cause=t.cause)}};l(ae,"FetchError");let re=ae;function cn(r){const e=r.error?.message||r.error?.toString()||"",t=r.request?.method||r.options?.method||"GET",n=r.request?.url||String(r.request)||"/",o=`[${t}] ${JSON.stringify(n)}`,i=r.response?`${r.response.status} ${r.response.statusText}`:"<no response>",a=`${o}: ${i}${e?` ${e}`:""}`,u=new re(a,r.error?{cause:r.error}:void 0);for(const c of["request","options","response"])Object.defineProperty(u,c,{get(){return r[c]}});for(const[c,h]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(u,c,{get(){return r.response&&r.response[h]}});return u}l(cn,"createFetchError");const ln=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function xe(r="GET"){return ln.has(r.toUpperCase())}l(xe,"isPayloadMethod");function un(r){if(r===void 0)return!1;const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(r)?!0:r.buffer?!1:r.constructor&&r.constructor.name==="Object"||typeof r.toJSON=="function"}l(un,"isJSONSerializable");const hn=new Set(["image/svg","application/xml","application/xhtml","application/html"]),pn=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function fn(r=""){if(!r)return"json";const e=r.split(";").shift()||"";return pn.test(e)?"json":hn.has(e)||e.startsWith("text/")?"text":"blob"}l(fn,"detectResponseType");function dn(r,e,t=globalThis.Headers){const n={...e,...r};if(e?.params&&r?.params&&(n.params={...e?.params,...r?.params}),e?.query&&r?.query&&(n.query={...e?.query,...r?.query}),e?.headers&&r?.headers){n.headers=new t(e?.headers||{});for(const[o,i]of new t(r?.headers||{}))n.headers.set(o,i)}return n}l(dn,"mergeFetchOptions");const mn=new Set([408,409,425,429,500,502,503,504]),gn=new Set([101,204,205,304]);function ke(r={}){const{fetch:e=globalThis.fetch,Headers:t=globalThis.Headers,AbortController:n=globalThis.AbortController}=r;async function o(u){const c=u.error&&u.error.name==="AbortError"&&!u.options.timeout||!1;if(u.options.retry!==!1&&!c){let s;typeof u.options.retry=="number"?s=u.options.retry:s=xe(u.options.method)?0:1;const p=u.response&&u.response.status||500;if(s>0&&(Array.isArray(u.options.retryStatusCodes)?u.options.retryStatusCodes.includes(p):mn.has(p))){const d=u.options.retryDelay||0;return d>0&&await new Promise(y=>setTimeout(y,d)),i(u.request,{...u.options,retry:s-1})}}const h=cn(u);throw Error.captureStackTrace&&Error.captureStackTrace(h,i),h}l(o,"onError");const i=l(async function(c,h={}){const s={request:c,options:dn(h,r.defaults,t),response:void 0,error:void 0};s.options.method=s.options.method?.toUpperCase(),s.options.onRequest&&await s.options.onRequest(s),typeof s.request=="string"&&(s.options.baseURL&&(s.request=en(s.request,s.options.baseURL)),(s.options.query||s.options.params)&&(s.request=tn(s.request,{...s.options.params,...s.options.query}))),s.options.body&&xe(s.options.method)&&(un(s.options.body)?(s.options.body=typeof s.options.body=="string"?s.options.body:JSON.stringify(s.options.body),s.options.headers=new t(s.options.headers||{}),s.options.headers.has("content-type")||s.options.headers.set("content-type","application/json"),s.options.headers.has("accept")||s.options.headers.set("accept","application/json")):("pipeTo"in s.options.body&&typeof s.options.body.pipeTo=="function"||typeof s.options.body.pipe=="function")&&("duplex"in s.options||(s.options.duplex="half")));let p;if(!s.options.signal&&s.options.timeout){const y=new n;p=setTimeout(()=>y.abort(),s.options.timeout),s.options.signal=y.signal}try{s.response=await e(s.request,s.options)}catch(y){return s.error=y,s.options.onRequestError&&await s.options.onRequestError(s),await o(s)}finally{p&&clearTimeout(p)}if(s.response.body&&!gn.has(s.response.status)&&s.options.method!=="HEAD"){const y=(s.options.parseResponse?"json":s.options.responseType)||fn(s.response.headers.get("content-type")||"");switch(y){case"json":{const m=await s.response.text(),b=s.options.parseResponse||Pt;s.response._data=b(m);break}case"stream":{s.response._data=s.response.body;break}default:s.response._data=await s.response[y]()}}return s.options.onResponse&&await s.options.onResponse(s),!s.options.ignoreResponseError&&s.response.status>=400&&s.response.status<600?(s.options.onResponseError&&await s.options.onResponseError(s),await o(s)):s.response},"$fetchRaw2"),a=l(async function(c,h){return(await i(c,h))._data},"$fetch2");return a.raw=i,a.native=(...u)=>e(...u),a.create=(u={})=>ke({...r,defaults:{...r.defaults,...u}}),a}l(ke,"createFetch");const oe=function(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}(),_n=oe.fetch||(()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!"))),yn=oe.Headers,On=oe.AbortController,L=ke({fetch:_n,Headers:yn,AbortController:On}),bn={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.test/":"https://backend.frontstack.dev/")},q=bn.apiRoot,wn=`${q}login`,An=`${q}api/fetch-api/spec.yaml`,Pe=3008,Re=`http://localhost:${Pe}`,He=`${wn}?redirectUrl=${Re}/callback`,Cn=".frontstack-local/",S=g.join(process.cwd(),Cn),ie="api_session.jwt",Ne="project.json",P=l(()=>{const r=l(()=>{console.info("Not auth.login implemented yet")},"login"),e=l(async()=>{try{return a(),0}catch(p){console.log(p)}},"logout"),t=l(async(p=!1)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(`${q}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o()}`}})}catch(d){return p&&console.log(d),1}},"getProfile"),n=l(async p=>{try{if(p==null)throw new Error(`You have no project selected
|
|
24
|
+
Run ${f.hex("#7c3bed")("frontstack project")} to select a frontstack project`);return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(An,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${o()}`,"FS-Project":p},parseResponse:l(y=>{try{return me.load(y)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(d){throw"data"in d&&"message"in d.data?new Error(`Server error: ${d.data.message}`):d}},"getFetchApiSpec"),o=l(()=>{const p=g.join(S,ie);return _.existsSync(p)?_.readFileSync(p,"utf8"):null},"getToken"),i=l(p=>(_.existsSync(S)||_.mkdirSync(S),_.writeFileSync(g.join(S,ie),p),0),"writeToken"),a=l(()=>{const p=g.join(S,ie);_.existsSync(p)&&_.unlinkSync(p)},"deleteToken"),u=l(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(`${q}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${o()}`},parseResponse:l(p=>JSON.parse(p),"parseResponse")})),"getProjects"),c=l(()=>{const p=g.join(S,Ne);if(!_.existsSync(p))return null;try{return JSON.parse(_.readFileSync(p,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:r,logout:e,getProfile:t,getFetchApiSpec:n,getToken:o,writeToken:i,deleteToken:a,getProjects:u,getProject:l(async(p=void 0)=>{try{return p===void 0&&(p=c()),p===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await L(`${q}api/project/${p}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${o()}`},parseResponse:l(d=>JSON.parse(d),"parseResponse")}))}catch(d){return{error:d.message}}},"getProject"),getProjectId:c,writeProject:l(p=>(_.existsSync(S)||_.mkdirSync(S),_.writeFileSync(g.join(S,Ne),JSON.stringify({projectId:p})),0),"writeProject")}},"auth"),Ie=l(()=>{const r=l(t=>{const n=g.join(t,"metadata.json");if(_.existsSync(n)){const o=_.readFileSync(n,"utf8");return JSON.parse(o)}return null},"getMetadata");return{getMetadata:r,projectGuard:l(t=>{r(t)||(console.log(`${f.hex("#FFA500")("[WARNING]")} No \`${t}/metadata.json\` found, run ${f.hex("#7c3bed")("frontstack generate")} to create a metadata file.`),console.log(`${f.hex("#FFA500")("[WARNING]")} Metadata files have been introduced to keep track of your generated code across multiple projects and organizations.`),console.log(`${f.hex("#FFA500")("[WARNING]")} If you only have a single project, you can ignore this message.`))},"projectGuard")}},"useMetadata"),{writeToken:$n}=P(),En=l(async(r,e,t=!1)=>new Promise(n=>{const o=new Set,i=tt.createServer((a,u)=>{const c=Re;if(a.url===void 0)return;const s=new URL(a.url,c).searchParams.get("token");s&&(u.writeHead(200,{"Content-Type":"text/html"}),u.end('<html><head><script>// window.close()<\/script></head><body style="font-family: sans-serif;"><div style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"><div style="text-align: center"><h1 style="color: #7c3bed;">Login Successful</h1><p>You can <a href="#" onClick="window.close()">close</a> this browser window and return to the terminal.<p style="font-size: .8rem; color: #666; text-align: left; margin-top: 20px;">© 2024 frontstack</p></div></div></html>'),u.on("finish",async()=>{for(const d of o)d.destroy();$n(s)!==0?(console.error("Login failed."),i.close(),n(!1)):(console.log(`${f.hex("#008000")("[SUCCESS]")} Login successful`),i.close(),n(!0)),t&&process.exit(0)}))}).listen(r,()=>{console.log(`Please continue login in your browser at ${f.hex("#7c3bed")(e)}`)});i.on("connection",a=>{o.add(a),a.on("close",()=>o.delete(a))}),setTimeout(()=>{i.close(),n(!1)},6e4)}),"login$1"),vn={processExit:!0,skipProjectGuard:!1},Fe=l(async r=>{const e=et(r,vn);await nt(He),await En(Pe,He,!1);let t=".frontstack";if(e.skipProjectGuard){const{projectGuard:n}=Ie();n(t)}e?.processExit&&process.exit(0)},"login"),Sn=P(),jn=l(async r=>{await Sn.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:Tn}=P();E.registerHelper("eq",function(r,e){return r===e}),E.registerHelper("uc",function(r){return r.toUpperCase()}),E.registerHelper("and",function(r,e){return r&&e}),E.registerHelper("contains",function(r,e){return r===void 0?!1:r.includes(e)}),E.registerHelper("endsWith",function(r,e){return r===void 0?!1:r.endsWith(e)}),E.registerHelper("blockNameFromOperationId",function(r){return r.replace("get","").replace("Block","")});const se=l(r=>r.$ref?`components['schemas']['${r.$ref.split("/").pop()}']`:r.type==="array"?`Array<${se(r.items)}>`:r.type==="object"?`{ ${Object.keys(r.properties).map(t=>`${t}: ${se(r.properties[t])}`).join("; ")} }`:r.type,"getSchemaType");E.registerHelper("getSchemaType",r=>se(r)),E.registerHelper("stringInArray",function(r,e,t){return e==null||e.length===0?!1:t.fn?e.indexOf(r)>-1?t.fn(this):t.inverse(this):e.indexOf(r)>-1}),E.registerHelper("log",function(r){console.log(r)});var xn=l(async r=>{const e=g.dirname(new URL(import.meta.url).pathname),t=g.join(e,"src/commands/generate/templates"),n=g.join(t,"types.js.hbs"),o=_.readFileSync(n,"utf8"),i=E.compile(o),a=g.join(t,"client.js.hbs"),u=_.readFileSync(a,"utf8"),c=E.compile(u),h=g.join(t,"query.js.hbs"),s=_.readFileSync(h,"utf8");let p;if(p=await Tn(r),p.error)throw new Error(`Issue fetching API specification. Check more information below.
|
|
25
|
+
`+p.error);let d="";try{d=await rt(p)}catch(b){throw new Error(`Invalid API Specification: ${b.message}`)}const y=i({paths:p.paths,components:p.components}),m=c({components:p.components,paths:p.paths,servers:p.servers});return{_schemaTypes:d,_types:y,_client:m,_query:s,_specFile:p}},"generate");const{getProjects:kn,writeProject:Ve}=P(),De=l(async r=>{let e=r.project??void 0,t=[];try{t=await kn()}catch{console.log(`You are not logged in. Please run ${f.hex("#7c3bed")("frontstack login")} to login`);return}if(t.length<1){console.log("No projects found. Please create a new project in your Admin dashboard");return}if(e!==void 0){const i=t.find(a=>a.id===e);if(i){console.log(`Project ${f.hex("#7c3bed")(i.name)} selected`),Ve(i.id);return}else{console.log(`Project with ID "${e}" not found. Please select a valid project ID`);return}}const n={type:"select",name:"projectId",message:"Pick a project (Use arrow keys and Enter)",choices:t.map(i=>({title:(i.id===e?"(\u2714) ":"")+`${i.name}`,value:i.id}))};async function o(){const i=await U(n),a=t.find(u=>u.id===i.projectId);if(a===void 0){console.log(`Project with ID "${i.projectId}" not found. Please select a valid project ID`);return}console.log(`Project ${f.hex("#7c3bed")(a.name)} selected`),Ve(i.projectId)}l(o,"getProject"),await o()},"project"),Pn=l(async r=>{const e=r.verbose||!1,t=r.persistOas||!1,{getProject:n,getProfile:o,getProjects:i,writeProject:a}=P(),u=await o(e);if(!u||u===1){console.info("User not logged in"),await Fe({processExit:!1,skipProjectGuard:!0});const w=await o();(!w||w===1)&&(console.info(`${f.hex("#b90404")("[ERROR]")} Login failed`),process.exit(1))}let c=r.output||".frontstack",h=await n();(!h||"error"in h)&&(console.info("No project selected"),console.info("Running project selection..."),await De({}));const{getMetadata:s}=Ie(),p=s(c);if(h=await n(),!h||"error"in h){console.info(`${f.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${f.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}if(p&&p.project.id!==h.id&&!h.environments.some(w=>w.id===p.project.id)){const C=(await i()).find(B=>B.id===p.project.id),$=[];C&&$.push({title:`Switch to project ${f.hex("#7c3bed")(p.project.name)} and generate client`,value:"switch"}),$.push({title:`Overwrite client with project ${f.hex("#7c3bed")(h.name)} (${f.hex("#7c3bed")(h.environment)})`,value:"overwrite"}),$.push({title:"Cancel",value:"cancel"}),console.log(`${f.hex("#FFA500")("[WARNING]")} Client mismatch detected`),console.log(`${f.hex("#FFA500")("[WARNING]")} The client in ${f.hex("#7c3bed")(c)} was generated for project ${f.hex("#7c3bed")(p.project.name)}.`),console.log(`${f.hex("#FFA500")("[WARNING]")} The selected project is ${f.hex("#7c3bed")(h.name)} (${f.hex("#7c3bed")(h.environment)}).
|
|
26
|
+
`);const Ue={type:"select",name:"action",message:"How would you like to proceed?",choices:$},{action:M}=await U(Ue);if(M==="cancel"){console.info("Generation cancelled.");return}if(M==="switch"&&C&&(a(C.id),h=C,console.info(`Switched to project ${f.hex("#7c3bed")(h.name)}.`)),M==="overwrite"){const B={type:"text",name:"confirmation",message:'This is a destructive action and will overwrite the existing client. Type "confirm" to proceed.'},{confirmation:We}=await U(B);if(We!=="confirm"){console.info("Generation cancelled.");return}console.info(`Proceeding to generate client for project ${f.hex("#7c3bed")(h.name)}.`)}if(!M){console.info("Generation cancelled.");return}}let d=h;if(!h||"error"in h){console.info(`${f.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${f.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`);return}if(r.env&&h.environments.length>0){let w;if(r.env!=="develop"){if(w=h.environments.find(C=>C.environment===r.env),!w){console.info(`${f.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${f.hex("#b90404")("[ERROR]")} Environment ${r.env} not found`);return}d=w}}if(!r.env&&h.environments.length>0){const w={type:"select",name:"projectId",message:"Pick an environment (use arrow keys and enter)",choices:[{title:`${h.name} (${h.environment})`,value:h.id},...h.environments.map($=>({title:($.id===d?.id?"(\u2714) ":"")+`${$.name} (${$.environment})`,value:$.id}))]},C=await U(w);d=h.environments.find($=>$.id===C.projectId)??h}let y,m,b,x,ce;try{e&&console.log("Generating Javascript client"),{_schemaTypes:y,_types:m,_client:b,_query:x,_specFile:ce}=await xn(d.id)}catch(w){console.info(`${f.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${f.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),e?console.info(`${f.hex("#b90404")("[ERROR]")} ${w.message}`):(console.info("Are you..."),console.info(` * logged in using the ${f.hex("#7c3bed")("frontstack login")} command?`),console.info(" * connected to the internet?"),console.info(`Alternatively, run ${f.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}process.stdout.write("Generating Javascript client"),c.startsWith("/")||(c=g.join(process.cwd(),c)),c.endsWith("/")||(c+="/");const le=g.join(c,"fetch-api.d.ts"),ue=g.join(c,"generated-types.d.ts"),he=g.join(c,"generated-client.ts"),qe=g.join(c,"query-types.ts"),pe=g.join(c,"metadata.json"),Me={project:{id:d.id,name:d.name}};if(e&&(console.log(`
|
|
27
27
|
Schema types path: ${f.dim(le)}`),console.log(`Types path: ${f.dim(ue)}`),console.log(`Client path: ${f.dim(he)}`),console.log(`Target directory: ${f.dim(c)}`),console.log(`Metadata path: ${f.dim(pe)}`)),_.mkdirSync(c,{recursive:!0}),t){const w=me.dump(ce,{indent:2}),C=g.join(c,"fetch-api.spec.yaml");console.log(`
|
|
28
28
|
Persisting OpenAPI Specification file in ${C}`),_.writeFileSync(g.join(C),w)}_.writeFileSync(g.join(le),y),_.writeFileSync(g.join(ue),m),_.writeFileSync(g.join(he),b),_.writeFileSync(g.join(qe),x),_.writeFileSync(g.join(pe),JSON.stringify(Me,null,2)),e?console.log(`Javascript client generated for ${f.hex("#7c3bed")(`${d.name} (${d.environment})`)}`):(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(f.green(`Javascript client generated for ${f.hex("#7c3bed")(`${d.name} (${d.environment})`)}
|
|
29
29
|
`))),console.log(`
|
|
@@ -31,6 +31,6 @@ Use the following import in your project:
|
|
|
31
31
|
`),console.log(" "+f.hex("#7c3bed")("import client from '.frontstack/generated-client';")),console.log(`
|
|
32
32
|
and use the client like this:
|
|
33
33
|
`),console.log(" "+f.hex("#7c3bed")("const productDetail = await client.block('DetailPage', { key: 'my-product-id' });")),console.log(`
|
|
34
|
-
If you make changes to your schema, run ${f.hex("#7c3bed")("frontstack generate")} again to update the client.`),process.exit(0)},"generateCommand"),{getToken:
|
|
34
|
+
If you make changes to your schema, run ${f.hex("#7c3bed")("frontstack generate")} again to update the client.`),process.exit(0)},"generateCommand"),{getToken:Rn,getProfile:Hn,getProject:Nn}=P(),In=l(async()=>{if(Rn()===null){console.log("Status: Not logged in."),console.log("Run "+f.hex("#7c3bed")("frontstack login")+" to login.");return}try{const e=await Hn();if(e===void 0||e===1){console.log("Status: Not logged in."),console.log("Run "+f.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+f.hex("#7c3bed")(e.email)),console.log(`Organization: ${e.organization.name}`);const t=await Nn();if(t===void 0||"error"in t){console.log("Status: No project selected."),console.log("Run "+f.hex("#7c3bed")("frontstack project")+" to select a frontstack project");return}console.log(`Current Project: ${t.name??"[No active project selected]"}`)}catch(e){console.log(e)}},"info"),G=Ze(".frontstack","version-check-cache.json"),Fn=24*60*60*1e3,Vn="https://registry.npmjs.org/@frontstackdev/cli/latest";function Dn(r,e){const t=K.clean(r),n=K.clean(e);return!t||!n?!1:K.gt(n,t)}l(Dn,"isOutdated");function Ln(){try{if(!fe(G))return null;const r=de(G,"utf8"),e=JSON.parse(r);return Date.now()-e.lastChecked<Fn?e:null}catch{return null}}l(Ln,"readCache");function qn(r){try{const e=Xe(G);fe(e)||ze(e,{recursive:!0});const t={latestVersion:r,lastChecked:Date.now()};Qe(G,JSON.stringify(t,null,2))}catch{}}l(qn,"writeCache");async function Mn(){try{return(await L(Vn,{timeout:3e3})).version}catch{return null}}l(Mn,"fetchLatestVersion");async function Un(r){if(!r.includes("dev"))try{let e=Ln(),t;e?t=e.latestVersion:(t=await Mn(),t&&qn(t)),t&&Dn(r,t)&&(console.log(),console.log(f.bgHex("#7c3bed").bold("Update available!")),console.log(`Current version: ${f.red(r)}`),console.log(`Latest version: ${f.green(t)}`),console.log())}catch{}}l(Un,"checkVersion");const Wn=ot(import.meta.url),Gn=g.dirname(Wn),Le=de(g.join(Gn,"version"),"utf8");let J="0.0.1-dev";Le&&(J=Le.trim());const j=new vt;j.name("frontstack").alias("fst").description(`${f.bgHex("#7c3bed").bold("frontstack CLI")}
|
|
35
35
|
Manage frontstack projects from the command line.
|
|
36
|
-
${f.dim(`Version: ${J}`)}`).version(J),j.command("login").description("Login to frontstack account").action(()=>{Fe()}),j.command("logout").description("Logout from frontstack account").action(async
|
|
36
|
+
${f.dim(`Version: ${J}`)}`).version(J),j.command("login").description("Login to frontstack account").action(()=>{Fe()}),j.command("logout").description("Logout from frontstack account").action(async r=>{await jn()}),j.command("generate").description("Generate a JavaScript client for the current project").option("-o, --output <path>","Output path",".frontstack").option("-v, --verbose","Enable verbose logging").option("-e --env <alias>",'Pass an environment alias like "develop" or "preview"').option("-s --persist-oas","Persist OpenAPI specification file").action(async r=>{await Pn(r)}),j.command("info").description("Display information about the current organization, project, and user").action(async()=>{await In()}),j.command("project").description("Select current working project which will be used for schema and client updates").option("-p --project <project-id>","Set current project ID").action(async r=>{await De(r)});const Jn=l(async()=>{try{await Un(J),j.parse(process.argv)}catch(r){console.log(r)}},"run");var Bn=Jn();export{Bn as default};
|
package/dist/version
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.0.0-canary-
|
|
1
|
+
0.0.0-canary-20251116182422
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontstackdev/cli",
|
|
3
|
-
"version": "0.0.0-canary-
|
|
3
|
+
"version": "0.0.0-canary-20251116182422",
|
|
4
4
|
"description": "frontstack CLI for managing projects",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "dist/frontstack.mjs",
|
|
@@ -47,8 +47,9 @@
|
|
|
47
47
|
"js-yaml": "^4.1.0",
|
|
48
48
|
"open": "^10.1.0",
|
|
49
49
|
"openapi-typescript": "^6.7.5",
|
|
50
|
+
"pathe": "^2.0.3",
|
|
50
51
|
"prompts": "^2.4.2",
|
|
51
52
|
"semver": "^7.7.3"
|
|
52
53
|
},
|
|
53
|
-
"packageManager": "pnpm@
|
|
54
|
+
"packageManager": "pnpm@10.20.0"
|
|
54
55
|
}
|