@frontstackdev/cli 0.0.0-canary-20250206213255 → 0.0.0-canary-20250207182729
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 +23 -23
- package/dist/version +1 -1
- package/package.json +1 -1
package/dist/frontstack.mjs
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Te=Object.defineProperty;var f=(n,
|
|
3
|
-
`).replace(/^/gm," ".repeat(d))}f(g,"formatList");let b=[`Usage: ${i.commandUsage(r)}`,""];const $=i.commandDescription(r);$.length>0&&(b=b.concat([i.wrap($,p,0),""]));const T=i.visibleArguments(r).map(t=>u(i.argumentTerm(t),i.argumentDescription(t)));T.length>0&&(b=b.concat(["Arguments:",g(T),""]));const j=i.visibleOptions(r).map(t=>u(i.optionTerm(t),i.optionDescription(t)));if(j.length>0&&(b=b.concat(["Options:",g(j),""])),this.showGlobalOptions){const t=i.visibleGlobalOptions(r).map(
|
|
2
|
+
var Te=Object.defineProperty;var f=(n,s)=>Te(n,"name",{value:s,configurable:!0});import ke from"node:events";import je from"node:child_process";import Pe from"node:path";import Re from"node:fs";import xe from"node:process";import C from"chalk";import S,{readFileSync as He}from"fs";import v from"path";import ie from"js-yaml";import Ne from"http";import Ve from"open";import R from"handlebars";import Ie from"openapi-typescript";import oe from"prompts";function Fe(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}f(Fe,"getDefaultExportFromCjs");var P={},F={},D={},se;function q(){if(se)return D;se=1;const h=class h extends Error{constructor(i,l,p){super(p),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=l,this.exitCode=i,this.nestedError=void 0}};f(h,"CommanderError");let n=h;const m=class m extends n{constructor(i){super(1,"commander.invalidArgument",i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};f(m,"InvalidArgumentError");let s=m;return D.CommanderError=n,D.InvalidArgumentError=s,D}f(q,"requireError");var ae;function G(){if(ae)return F;ae=1;const{InvalidArgumentError:n}=q(),m=class m{constructor(i,l){switch(this.description=l||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(i,l){return l===this.defaultValue||!Array.isArray(l)?[i]:l.concat(i)}default(i,l){return this.defaultValue=i,this.defaultValueDescription=l,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(l,p)=>{if(!this.argChoices.includes(l))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(l,p):l},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};f(m,"Argument");let s=m;function h(r){const i=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+i+">":"["+i+"]"}return f(h,"humanReadableArgName"),F.Argument=s,F.humanReadableArgName=h,F}f(G,"requireArgument");var J={},B={},ce;function le(){if(ce)return B;ce=1;const{humanReadableArgName:n}=G(),h=class h{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(r){const i=r.commands.filter(p=>!p._hidden),l=r._getHelpCommand();return l&&!l._hidden&&i.push(l),this.sortSubcommands&&i.sort((p,d)=>p.name().localeCompare(d.name())),i}compareOptions(r,i){const l=f(p=>p.short?p.short.replace(/^-/,""):p.long.replace(/^--/,""),"getSortKey");return l(r).localeCompare(l(i))}visibleOptions(r){const i=r.options.filter(p=>!p.hidden),l=r._getHelpOption();if(l&&!l.hidden){const p=l.short&&r._findOption(l.short),d=l.long&&r._findOption(l.long);!p&&!d?i.push(l):l.long&&!d?i.push(r.createOption(l.long,l.description)):l.short&&!p&&i.push(r.createOption(l.short,l.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(r){if(!this.showGlobalOptions)return[];const i=[];for(let l=r.parent;l;l=l.parent){const p=l.options.filter(d=>!d.hidden);i.push(...p)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(r){return r._argsDescription&&r.registeredArguments.forEach(i=>{i.description=i.description||r._argsDescription[i.name()]||""}),r.registeredArguments.find(i=>i.description)?r.registeredArguments:[]}subcommandTerm(r){const i=r.registeredArguments.map(l=>n(l)).join(" ");return r._name+(r._aliases[0]?"|"+r._aliases[0]:"")+(r.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(r){return r.flags}argumentTerm(r){return r.name()}longestSubcommandTermLength(r,i){return i.visibleCommands(r).reduce((l,p)=>Math.max(l,i.subcommandTerm(p).length),0)}longestOptionTermLength(r,i){return i.visibleOptions(r).reduce((l,p)=>Math.max(l,i.optionTerm(p).length),0)}longestGlobalOptionTermLength(r,i){return i.visibleGlobalOptions(r).reduce((l,p)=>Math.max(l,i.optionTerm(p).length),0)}longestArgumentTermLength(r,i){return i.visibleArguments(r).reduce((l,p)=>Math.max(l,i.argumentTerm(p).length),0)}commandUsage(r){let i=r._name;r._aliases[0]&&(i=i+"|"+r._aliases[0]);let l="";for(let p=r.parent;p;p=p.parent)l=p.name()+" "+l;return l+i+" "+r.usage()}commandDescription(r){return r.description()}subcommandDescription(r){return r.summary()||r.description()}optionDescription(r){const i=[];return r.argChoices&&i.push(`choices: ${r.argChoices.map(l=>JSON.stringify(l)).join(", ")}`),r.defaultValue!==void 0&&(r.required||r.optional||r.isBoolean()&&typeof r.defaultValue=="boolean")&&i.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),r.presetArg!==void 0&&r.optional&&i.push(`preset: ${JSON.stringify(r.presetArg)}`),r.envVar!==void 0&&i.push(`env: ${r.envVar}`),i.length>0?`${r.description} (${i.join(", ")})`:r.description}argumentDescription(r){const i=[];if(r.argChoices&&i.push(`choices: ${r.argChoices.map(l=>JSON.stringify(l)).join(", ")}`),r.defaultValue!==void 0&&i.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),i.length>0){const l=`(${i.join(", ")})`;return r.description?`${r.description} ${l}`:l}return r.description}formatHelp(r,i){const l=i.padWidth(r,i),p=i.helpWidth||80,d=2,_=2;function u(t,o){if(o){const a=`${t.padEnd(l+_)}${o}`;return i.wrap(a,p-d,l+_)}return t}f(u,"formatItem");function g(t){return t.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(d))}f(g,"formatList");let b=[`Usage: ${i.commandUsage(r)}`,""];const $=i.commandDescription(r);$.length>0&&(b=b.concat([i.wrap($,p,0),""]));const T=i.visibleArguments(r).map(t=>u(i.argumentTerm(t),i.argumentDescription(t)));T.length>0&&(b=b.concat(["Arguments:",g(T),""]));const j=i.visibleOptions(r).map(t=>u(i.optionTerm(t),i.optionDescription(t)));if(j.length>0&&(b=b.concat(["Options:",g(j),""])),this.showGlobalOptions){const t=i.visibleGlobalOptions(r).map(o=>u(i.optionTerm(o),i.optionDescription(o)));t.length>0&&(b=b.concat(["Global Options:",g(t),""]))}const e=i.visibleCommands(r).map(t=>u(i.subcommandTerm(t),i.subcommandDescription(t)));return e.length>0&&(b=b.concat(["Commands:",g(e),""])),b.join(`
|
|
4
4
|
`)}padWidth(r,i){return Math.max(i.longestOptionTermLength(r,i),i.longestGlobalOptionTermLength(r,i),i.longestSubcommandTermLength(r,i),i.longestArgumentTermLength(r,i))}wrap(r,i,l,p=40){const d=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",_=new RegExp(`[\\n][${d}]+`);if(r.match(_))return r;const u=i-l;if(u<p)return r;const g=r.slice(0,l),b=r.slice(l).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),$=" ".repeat(l),j="\\s\u200B",e=new RegExp(`
|
|
7
|
-
|.{1,${u-1}}([${j}]|$)|[^${j}]+?([${j}]|$)`,"g"),t=b.match(e)||[];return g+t.map((
|
|
8
|
-
`?"":(a>0?$:"")+
|
|
9
|
-
`)}};f(h,"Help");let
|
|
7
|
+
|.{1,${u-1}}([${j}]|$)|[^${j}]+?([${j}]|$)`,"g"),t=b.match(e)||[];return g+t.map((o,a)=>o===`
|
|
8
|
+
`?"":(a>0?$:"")+o.trimEnd()).join(`
|
|
9
|
+
`)}};f(h,"Help");let s=h;return B.Help=s,B}f(le,"requireHelp");var L={},ue;function he(){if(ue)return L;ue=1;const{InvalidArgumentError:n}=q(),i=class i{constructor(d,_){this.flags=d,this.description=_||"",this.required=d.includes("<"),this.optional=d.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(d),this.mandatory=!1;const u=r(d);this.short=u.shortFlag,this.long=u.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(d,_){return this.defaultValue=d,this.defaultValueDescription=_,this}preset(d){return this.presetArg=d,this}conflicts(d){return this.conflictsWith=this.conflictsWith.concat(d),this}implies(d){let _=d;return typeof d=="string"&&(_={[d]:!0}),this.implied=Object.assign(this.implied||{},_),this}env(d){return this.envVar=d,this}argParser(d){return this.parseArg=d,this}makeOptionMandatory(d=!0){return this.mandatory=!!d,this}hideHelp(d=!0){return this.hidden=!!d,this}_concatValue(d,_){return _===this.defaultValue||!Array.isArray(_)?[d]:_.concat(d)}choices(d){return this.argChoices=d.slice(),this.parseArg=(_,u)=>{if(!this.argChoices.includes(_))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(_,u):_},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return m(this.name().replace(/^no-/,""))}is(d){return this.short===d||this.long===d}isBoolean(){return!this.required&&!this.optional&&!this.negate}};f(i,"Option");let s=i;const l=class l{constructor(d){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,d.forEach(_=>{_.negate?this.negativeOptions.set(_.attributeName(),_):this.positiveOptions.set(_.attributeName(),_)}),this.negativeOptions.forEach((_,u)=>{this.positiveOptions.has(u)&&this.dualOptions.add(u)})}valueFromOption(d,_){const u=_.attributeName();if(!this.dualOptions.has(u))return!0;const g=this.negativeOptions.get(u).presetArg,b=g!==void 0?g:!1;return _.negate===(b===d)}};f(l,"DualOptions");let h=l;function m(p){return p.split("-").reduce((d,_)=>d+_[0].toUpperCase()+_.slice(1))}f(m,"camelcase");function r(p){let d,_;const u=p.split(/[ |,]+/);return u.length>1&&!/^[[<]/.test(u[1])&&(d=u.shift()),_=u.shift(),!d&&/^-[^-]$/.test(_)&&(d=_,_=void 0),{shortFlag:d,longFlag:_}}return f(r,"splitOptionFlags"),L.Option=s,L.DualOptions=h,L}f(he,"requireOption");var K={},pe;function De(){if(pe)return K;pe=1;const n=3;function s(m,r){if(Math.abs(m.length-r.length)>n)return Math.max(m.length,r.length);const i=[];for(let l=0;l<=m.length;l++)i[l]=[l];for(let l=0;l<=r.length;l++)i[0][l]=l;for(let l=1;l<=r.length;l++)for(let p=1;p<=m.length;p++){let d=1;m[p-1]===r[l-1]?d=0:d=1,i[p][l]=Math.min(i[p-1][l]+1,i[p][l-1]+1,i[p-1][l-1]+d),p>1&&l>1&&m[p-1]===r[l-2]&&m[p-2]===r[l-1]&&(i[p][l]=Math.min(i[p][l],i[p-2][l-2]+1))}return i[m.length][r.length]}f(s,"editDistance");function h(m,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));const i=m.startsWith("--");i&&(m=m.slice(2),r=r.map(_=>_.slice(2)));let l=[],p=n;const d=.4;return r.forEach(_=>{if(_.length<=1)return;const u=s(m,_),g=Math.max(m.length,_.length);(g-u)/g>d&&(u<p?(p=u,l=[_]):u===p&&l.push(_))}),l.sort((_,u)=>_.localeCompare(u)),i&&(l=l.map(_=>`--${_}`)),l.length>1?`
|
|
10
10
|
(Did you mean one of ${l.join(", ")}?)`:l.length===1?`
|
|
11
|
-
(Did you mean ${l[0]}?)`:""}return f(h,"suggestSimilar$1"),K.suggestSimilar=h,K}f(De,"requireSuggestSimilar");var fe;function qe(){if(fe)return J;fe=1;const n=ke.EventEmitter,
|
|
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 i(e,t)}argument(e,t,
|
|
13
|
-
Expecting one of '${
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=f(a=>[a.name()].concat(a.aliases()),"knownBy"),
|
|
11
|
+
(Did you mean ${l[0]}?)`:""}return f(h,"suggestSimilar$1"),K.suggestSimilar=h,K}f(De,"requireSuggestSimilar");var fe;function qe(){if(fe)return J;fe=1;const n=ke.EventEmitter,s=je,h=Pe,m=Re,r=xe,{Argument:i,humanReadableArgName:l}=G(),{CommanderError:p}=q(),{Help:d}=le(),{Option:_,DualOptions:u}=he(),{suggestSimilar:g}=De(),T=class T extends n{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:f(t=>r.stdout.write(t),"writeOut"),writeErr:f(t=>r.stderr.write(t),"writeErr"),getOutHelpWidth:f(()=>r.stdout.isTTY?r.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:f(()=>r.stderr.isTTY?r.stderr.columns:void 0,"getErrHelpWidth"),outputError:f((t,o)=>o(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,o){let a=t,c=o;typeof a=="object"&&a!==null&&(c=a,a=null),c=c||{};const[,y,w]=e.match(/([^ ]+) *(.*)/),O=this.createCommand(y);return a&&(O.description(a),O._executableHandler=!0),c.isDefault&&(this._defaultCommandName=O._name),O._hidden=!!(c.noHelp||c.hidden),O._executableFile=c.executableFile||null,w&&O.arguments(w),this._registerCommand(O),O.parent=this,O.copyInheritedSettings(this),a?this:O}createCommand(e){return new T(e)}createHelp(){return Object.assign(new d,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 i(e,t)}argument(e,t,o,a){const c=this.createArgument(e,t);return typeof o=="function"?c.default(a).argParser(o):c.default(o),this.addArgument(c),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[,o,a]=e.match(/([^ ]+) *(.*)/),c=t??"display help for command",y=this.createCommand(o);return y.helpOption(!1),a&&y.arguments(a),c&&y.description(c),this._addImplicitHelpCommand=!0,this._helpCommand=y,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 o=["preSubcommand","preAction","postAction"];if(!o.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${o.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,o){this._exitCallback&&this._exitCallback(new p(e,t,o)),r.exit(e)}action(e){const t=f(o=>{const a=this.registeredArguments.length,c=o.slice(0,a);return this._storeOptionsAsProperties?c[a]=this:c[a]=this.opts(),c.push(this),e.apply(this,c)},"listener");return this._actionHandler=t,this}createOption(e,t){return new _(e,t)}_callParseArg(e,t,o,a){try{return e.parseArg(t,o)}catch(c){if(c.code==="commander.invalidArgument"){const y=`${a} ${c.message}`;this.error(y,{exitCode:c.exitCode,code:c.code})}throw c}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const o=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 '${o}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=f(a=>[a.name()].concat(a.aliases()),"knownBy"),o=t(e).find(a=>this._findCommand(a));if(o){const a=t(this._findCommand(o)).join("|"),c=t(e).join("|");throw new Error(`cannot add command '${c}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),o=e.attributeName();if(e.negate){const c=e.long.replace(/^--no-/,"--");this._findOption(c)||this.setOptionValueWithSource(o,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(o,e.defaultValue,"default");const a=f((c,y,w)=>{c==null&&e.presetArg!==void 0&&(c=e.presetArg);const O=this.getOptionValue(o);c!==null&&e.parseArg?c=this._callParseArg(e,c,O,y):c!==null&&e.variadic&&(c=e._concatValue(c,O)),c==null&&(e.negate?c=!1:e.isBoolean()||e.optional?c=!0:c=""),this.setOptionValueWithSource(o,c,w)},"handleOptionValue");return this.on("option:"+t,c=>{const y=`error: option '${e.flags}' argument '${c}' is invalid.`;a(c,y,"cli")}),e.envVar&&this.on("optionEnv:"+t,c=>{const y=`error: option '${e.flags}' value '${c}' from env '${e.envVar}' is invalid.`;a(c,y,"env")}),this}_optionEx(e,t,o,a,c){if(typeof t=="object"&&t instanceof _)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const y=this.createOption(t,o);if(y.makeOptionMandatory(!!e.mandatory),typeof a=="function")y.default(c).argParser(a);else if(a instanceof RegExp){const w=a;a=f((O,E)=>{const A=w.exec(O);return A?A[0]:E},"fn"),y.default(c).argParser(a)}else y.default(a);return this.addOption(y)}option(e,t,o,a){return this._optionEx({},e,t,o,a)}requiredOption(e,t,o,a){return this._optionEx({mandatory:!0},e,t,o,a)}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,o){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=o,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(o=>{o.getOptionValueSource(e)!==void 0&&(t=o.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){r.versions?.electron&&(t.from="electron");const a=r.execArgv??[];(a.includes("-e")||a.includes("--eval")||a.includes("-p")||a.includes("--print"))&&(t.from="eval")}e===void 0&&(e=r.argv),this.rawArgs=e.slice();let o;switch(t.from){case void 0:case"node":this._scriptPath=e[1],o=e.slice(2);break;case"electron":r.defaultApp?(this._scriptPath=e[1],o=e.slice(2)):o=e.slice(1);break;case"user":o=e.slice(0);break;case"eval":o=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",o}parse(e,t){const o=this._prepareUserArgs(e,t);return this._parseCommand([],o),this}async parseAsync(e,t){const o=this._prepareUserArgs(e,t);return await this._parseCommand([],o),this}_executeSubCommand(e,t){t=t.slice();let o=!1;const a=[".js",".ts",".tsx",".mjs",".cjs"];function c(A,k){const N=h.resolve(A,k);if(m.existsSync(N))return N;if(a.includes(h.extname(k)))return;const re=a.find(Se=>m.existsSync(`${N}${Se}`));if(re)return`${N}${re}`}f(c,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let y=e._executableFile||`${this._name}-${e._name}`,w=this._executableDir||"";if(this._scriptPath){let A;try{A=m.realpathSync(this._scriptPath)}catch{A=this._scriptPath}w=h.resolve(h.dirname(A),w)}if(w){let A=c(w,y);if(!A&&!e._executableFile&&this._scriptPath){const k=h.basename(this._scriptPath,h.extname(this._scriptPath));k!==this._name&&(A=c(w,`${k}-${e._name}`))}y=A||y}o=a.includes(h.extname(y));let O;r.platform!=="win32"?o?(t.unshift(y),t=$(r.execArgv).concat(t),O=s.spawn(r.argv[0],t,{stdio:"inherit"})):O=s.spawn(y,t,{stdio:"inherit"}):(t.unshift(y),t=$(r.execArgv).concat(t),O=s.spawn(r.execPath,t,{stdio:"inherit"})),O.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(k=>{r.on(k,()=>{O.killed===!1&&O.exitCode===null&&O.kill(k)})});const E=this._exitCallback;O.on("close",A=>{A=A??1,E?E(new p(A,"commander.executeSubCommandAsync","(close)")):r.exit(A)}),O.on("error",A=>{if(A.code==="ENOENT"){const k=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",N=`'${y}' 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
|
-
- ${k}`;throw new Error(N)}else if(A.code==="EACCES")throw new Error(`'${y}' not executable`);if(!E)r.exit(1);else{const k=new p(1,"commander.executeSubCommandAsync","(error)");k.nestedError=A,E(k)}}),this.runningCommand=O}_dispatchSubcommand(e,t,
|
|
17
|
+
- ${k}`;throw new Error(N)}else if(A.code==="EACCES")throw new Error(`'${y}' not executable`);if(!E)r.exit(1);else{const k=new p(1,"commander.executeSubCommandAsync","(error)");k.nestedError=A,E(k)}}),this.runningCommand=O}_dispatchSubcommand(e,t,o){const a=this._findCommand(e);a||this.help({error:!0});let c;return c=this._chainOrCallSubCommandHook(c,a,"preSubcommand"),c=this._chainOrCall(c,()=>{if(a._executableHandler)this._executeSubCommand(a,t.concat(o));else return a._parseCommand(t,o)}),c}_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=f((o,a,c)=>{let y=a;if(a!==null&&o.parseArg){const w=`error: command-argument value '${a}' is invalid for argument '${o.name()}'.`;y=this._callParseArg(o,a,c,w)}return y},"myParseArg");this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((o,a)=>{let c=o.defaultValue;o.variadic?a<this.args.length?(c=this.args.slice(a),o.parseArg&&(c=c.reduce((y,w)=>e(o,w,y),o.defaultValue))):c===void 0&&(c=[]):a<this.args.length&&(c=this.args[a],o.parseArg&&(c=e(o,c,o.defaultValue))),t[a]=c}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let o=e;const a=[];return this._getCommandAndAncestors().reverse().filter(c=>c._lifeCycleHooks[t]!==void 0).forEach(c=>{c._lifeCycleHooks[t].forEach(y=>{a.push({hookedCommand:c,callback:y})})}),t==="postAction"&&a.reverse(),a.forEach(c=>{o=this._chainOrCall(o,()=>c.callback(c.hookedCommand,this))}),o}_chainOrCallSubCommandHook(e,t,o){let a=e;return this._lifeCycleHooks[o]!==void 0&&this._lifeCycleHooks[o].forEach(c=>{a=this._chainOrCall(a,()=>c(this,t))}),a}_parseCommand(e,t){const o=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(o.operands),t=o.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(o.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const a=f(()=>{o.unknown.length>0&&this.unknownOption(o.unknown[0])},"checkForUnknownOptions"),c=`command:${this.name()}`;if(this._actionHandler){a(),this._processArguments();let y;return y=this._chainOrCallHooks(y,"preAction"),y=this._chainOrCall(y,()=>this._actionHandler(this.processedArgs)),this.parent&&(y=this._chainOrCall(y,()=>{this.parent.emit(c,e,t)})),y=this._chainOrCallHooks(y,"postAction"),y}if(this.parent&&this.parent.listenerCount(c))a(),this._processArguments(),this.parent.emit(c,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():(a(),this._processArguments())}else this.commands.length?(a(),this.help({error:!0})):(a(),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(o=>{const a=o.attributeName();return this.getOptionValue(a)===void 0?!1:this.getOptionValueSource(a)!=="default"});e.filter(o=>o.conflictsWith.length>0).forEach(o=>{const a=e.find(c=>o.conflictsWith.includes(c.attributeName()));a&&this._conflictingOption(o,a)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],o=[];let a=t;const c=e.slice();function y(O){return O.length>1&&O[0]==="-"}f(y,"maybeOption");let w=null;for(;c.length;){const O=c.shift();if(O==="--"){a===o&&a.push(O),a.push(...c);break}if(w&&!y(O)){this.emit(`option:${w.name()}`,O);continue}if(w=null,y(O)){const E=this._findOption(O);if(E){if(E.required){const A=c.shift();A===void 0&&this.optionMissingArgument(E),this.emit(`option:${E.name()}`,A)}else if(E.optional){let A=null;c.length>0&&!y(c[0])&&(A=c.shift()),this.emit(`option:${E.name()}`,A)}else this.emit(`option:${E.name()}`);w=E.variadic?E:null;continue}}if(O.length>2&&O[0]==="-"&&O[1]!=="-"){const E=this._findOption(`-${O[1]}`);if(E){E.required||E.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${E.name()}`,O.slice(2)):(this.emit(`option:${E.name()}`),c.unshift(`-${O.slice(2)}`));continue}}if(/^--[^=]+=/.test(O)){const E=O.indexOf("="),A=this._findOption(O.slice(0,E));if(A&&(A.required||A.optional)){this.emit(`option:${A.name()}`,O.slice(E+1));continue}}if(y(O)&&(a=o),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&o.length===0){if(this._findCommand(O)){t.push(O),c.length>0&&o.push(...c);break}else if(this._getHelpCommand()&&O===this._getHelpCommand().name()){t.push(O),c.length>0&&t.push(...c);break}else if(this._defaultCommandName){o.push(O),c.length>0&&o.push(...c);break}}if(this._passThroughOptions){a.push(O),c.length>0&&a.push(...c);break}a.push(O)}return{operands:t,unknown:o}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let o=0;o<t;o++){const a=this.options[o].attributeName();e[a]=a===this._versionOptionName?this._version:this[a]}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
|
|
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
|
|
22
|
-
Expecting one of '${
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};f(T,"Command");let b=T;function $(j){return j.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",a="9229",c;return(c=e.match(/^(--inspect(-brk)?)$/))!==null?t=c[1]:(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=c[1],/^\d+$/.test(c[3])?a=c[3]:s=c[3]):(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=c[1],s=c[3],a=c[4]),t&&a!=="0"?`${t}=${s}:${parseInt(a)+1}`:e})}return f($,"incrementNodeInspectorPort"),J.Command=b,J}f(qe,"requireCommand");var de;function Le(){if(de)return P;de=1;const{Argument:n}=G(),{Command:o}=qe(),{CommanderError:h,InvalidArgumentError:m}=q(),{Help:r}=le(),{Option:i}=he();return P.program=new o,P.createCommand=l=>new o(l),P.createOption=(l,p)=>new i(l,p),P.createArgument=(l,p)=>new n(l,p),P.Command=o,P.Option=i,P.Argument=n,P.Help=r,P.CommanderError=h,P.InvalidArgumentError=m,P.InvalidOptionArgumentError=m,P}f(Le,"requireCommander");var Ue=Le(),Me=Fe(Ue);const{program:wn,createCommand:An,createArgument:Cn,createOption:En,CommanderError:$n,InvalidArgumentError:Sn,InvalidOptionArgumentError:vn,Command:We,Argument:Tn,Option:kn,Help:jn}=Me,Ge=/"(?:_|\\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*:/,Je=/"(?: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*:/,Be=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ke(n,o){if(n==="__proto__"||n==="constructor"&&o&&typeof o=="object"&&"prototype"in o){ze(n);return}return o}f(Ke,"jsonParseTransform");function ze(n){console.warn(`[destr] Dropping "${n}" key to prevent prototype pollution.`)}f(ze,"warnKeyDropped");function Qe(n,o={}){if(typeof n!="string")return n;const h=n.trim();if(n[0]==='"'&&n.endsWith('"')&&!n.includes("\\"))return h.slice(1,-1);if(h.length<=9){const m=h.toLowerCase();if(m==="true")return!0;if(m==="false")return!1;if(m==="undefined")return;if(m==="null")return null;if(m==="nan")return Number.NaN;if(m==="infinity")return Number.POSITIVE_INFINITY;if(m==="-infinity")return Number.NEGATIVE_INFINITY}if(!Be.test(n)){if(o.strict)throw new SyntaxError("[destr] Invalid JSON");return n}try{if(Ge.test(n)||Je.test(n)){if(o.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(n,Ke)}return JSON.parse(n)}catch(m){if(o.strict)throw m;return n}}f(Qe,"destr");const Ye=/#/g,Ze=/&/g,Xe=/\//g,et=/=/g,z=/\+/g,tt=/%5e/gi,nt=/%60/gi,rt=/%7c/gi,it=/%20/gi;function st(n){return encodeURI(""+n).replace(rt,"|")}f(st,"encode");function Q(n){return st(typeof n=="string"?n:JSON.stringify(n)).replace(z,"%2B").replace(it,"+").replace(Ye,"%23").replace(Ze,"%26").replace(nt,"`").replace(tt,"^").replace(Xe,"%2F")}f(Q,"encodeQueryValue");function Y(n){return Q(n).replace(et,"%3D")}f(Y,"encodeQueryKey");function me(n=""){try{return decodeURIComponent(""+n)}catch{return""+n}}f(me,"decode");function ot(n){return me(n.replace(z," "))}f(ot,"decodeQueryKey");function at(n){return me(n.replace(z," "))}f(at,"decodeQueryValue");function ct(n=""){const o={};n[0]==="?"&&(n=n.slice(1));for(const h of n.split("&")){const m=h.match(/([^=]+)=?(.*)/)||[];if(m.length<2)continue;const r=ot(m[1]);if(r==="__proto__"||r==="constructor")continue;const i=at(m[2]||"");o[r]===void 0?o[r]=i:Array.isArray(o[r])?o[r].push(i):o[r]=[o[r],i]}return o}f(ct,"parseQuery");function lt(n,o){return(typeof o=="number"||typeof o=="boolean")&&(o=String(o)),o?Array.isArray(o)?o.map(h=>`${Y(n)}=${Q(h)}`).join("&"):`${Y(n)}=${Q(o)}`:Y(n)}f(lt,"encodeQueryItem");function ut(n){return Object.keys(n).filter(o=>n[o]!==void 0).map(o=>lt(o,n[o])).filter(Boolean).join("&")}f(ut,"stringifyQuery");const ht=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,pt=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,ft=/^([/\\]\s*){2,}[^/\\]/,dt=/^\.?\//;function ge(n,o={}){return typeof o=="boolean"&&(o={acceptRelative:o}),o.strict?ht.test(n):pt.test(n)||(o.acceptRelative?ft.test(n):!1)}f(ge,"hasProtocol");function mt(n="",o){return n.endsWith("/")}f(mt,"hasTrailingSlash");function gt(n="",o){return(mt(n)?n.slice(0,-1):n)||"/"}f(gt,"withoutTrailingSlash");function _t(n="",o){return n.endsWith("/")?n:n+"/"}f(_t,"withTrailingSlash");function yt(n,o){if(bt(o)||ge(n))return n;const h=gt(o);return n.startsWith(h)?n:At(h,n)}f(yt,"withBase");function Ot(n,o){const h=Ct(n),m={...ct(h.search),...o};return h.search=ut(m),Et(h)}f(Ot,"withQuery");function bt(n){return!n||n==="/"}f(bt,"isEmptyURL");function wt(n){return n&&n!=="/"}f(wt,"isNonEmptyURL");function At(n,...o){let h=n||"";for(const m of o.filter(r=>wt(r)))if(h){const r=m.replace(dt,"");h=_t(h)+r}else h=m;return h}f(At,"joinURL");const _e=Symbol.for("ufo:protocolRelative");function Ct(n="",o){const h=n.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(h){const[,g,b=""]=h;return{protocol:g.toLowerCase(),pathname:b,href:g+b,auth:"",host:"",search:"",hash:""}}if(!ge(n,{acceptRelative:!0}))return ye(n);const[,m="",r,i=""]=n.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,l="",p=""]=i.match(/([^#/?]*)(.*)?/)||[];m==="file:"&&(p=p.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:d,search:_,hash:u}=ye(p);return{protocol:m.toLowerCase(),auth:r?r.slice(0,Math.max(0,r.length-1)):"",host:l,pathname:d,search:_,hash:u,[_e]:!m}}f(Ct,"parseURL");function ye(n=""){const[o="",h="",m=""]=(n.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:o,search:h,hash:m}}f(ye,"parsePath");function Et(n){const o=n.pathname||"",h=n.search?(n.search.startsWith("?")?"":"?")+n.search:"",m=n.hash||"",r=n.auth?n.auth+"@":"",i=n.host||"";return(n.protocol||n[_e]?(n.protocol||"")+"//":"")+r+i+o+h+m}f(Et,"stringifyParsedURL");const ne=class ne extends Error{constructor(o,h){super(o,h),this.name="FetchError",h?.cause&&!this.cause&&(this.cause=h.cause)}};f(ne,"FetchError");let Z=ne;function $t(n){const o=n.error?.message||n.error?.toString()||"",h=n.request?.method||n.options?.method||"GET",m=n.request?.url||String(n.request)||"/",r=`[${h}] ${JSON.stringify(m)}`,i=n.response?`${n.response.status} ${n.response.statusText}`:"<no response>",l=`${r}: ${i}${o?` ${o}`:""}`,p=new Z(l,n.error?{cause:n.error}:void 0);for(const d of["request","options","response"])Object.defineProperty(p,d,{get(){return n[d]}});for(const[d,_]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(p,d,{get(){return n.response&&n.response[_]}});return p}f($t,"createFetchError");const St=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function Oe(n="GET"){return St.has(n.toUpperCase())}f(Oe,"isPayloadMethod");function vt(n){if(n===void 0)return!1;const o=typeof n;return o==="string"||o==="number"||o==="boolean"||o===null?!0:o!=="object"?!1:Array.isArray(n)?!0:n.buffer?!1:n.constructor&&n.constructor.name==="Object"||typeof n.toJSON=="function"}f(vt,"isJSONSerializable");const Tt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),kt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function jt(n=""){if(!n)return"json";const o=n.split(";").shift()||"";return kt.test(o)?"json":Tt.has(o)||o.startsWith("text/")?"text":"blob"}f(jt,"detectResponseType");function Pt(n,o,h,m){const r=Rt(o?.headers??n?.headers,h?.headers,m);let i;return(h?.query||h?.params||o?.params||o?.query)&&(i={...h?.params,...h?.query,...o?.params,...o?.query}),{...h,...o,query:i,params:i,headers:r}}f(Pt,"resolveFetchOptions");function Rt(n,o,h){if(!o)return new h(n);const m=new h(o);if(n)for(const[r,i]of Symbol.iterator in n||Array.isArray(n)?n:new h(n))m.set(r,i);return m}f(Rt,"mergeHeaders");async function U(n,o){if(o)if(Array.isArray(o))for(const h of o)await h(n);else await o(n)}f(U,"callHooks");const xt=new Set([408,409,425,429,500,502,503,504]),Ht=new Set([101,204,205,304]);function be(n={}){const{fetch:o=globalThis.fetch,Headers:h=globalThis.Headers,AbortController:m=globalThis.AbortController}=n;async function r(p){const d=p.error&&p.error.name==="AbortError"&&!p.options.timeout||!1;if(p.options.retry!==!1&&!d){let u;typeof p.options.retry=="number"?u=p.options.retry:u=Oe(p.options.method)?0:1;const g=p.response&&p.response.status||500;if(u>0&&(Array.isArray(p.options.retryStatusCodes)?p.options.retryStatusCodes.includes(g):xt.has(g))){const b=typeof p.options.retryDelay=="function"?p.options.retryDelay(p):p.options.retryDelay||0;return b>0&&await new Promise($=>setTimeout($,b)),i(p.request,{...p.options,retry:u-1})}}const _=$t(p);throw Error.captureStackTrace&&Error.captureStackTrace(_,i),_}f(r,"onError");const i=f(async function(d,_={}){const u={request:d,options:Pt(d,_,n.defaults,h),response:void 0,error:void 0};u.options.method&&(u.options.method=u.options.method.toUpperCase()),u.options.onRequest&&await U(u,u.options.onRequest),typeof u.request=="string"&&(u.options.baseURL&&(u.request=yt(u.request,u.options.baseURL)),u.options.query&&(u.request=Ot(u.request,u.options.query),delete u.options.query),"query"in u.options&&delete u.options.query,"params"in u.options&&delete u.options.params),u.options.body&&Oe(u.options.method)&&(vt(u.options.body)?(u.options.body=typeof u.options.body=="string"?u.options.body:JSON.stringify(u.options.body),u.options.headers=new h(u.options.headers||{}),u.options.headers.has("content-type")||u.options.headers.set("content-type","application/json"),u.options.headers.has("accept")||u.options.headers.set("accept","application/json")):("pipeTo"in u.options.body&&typeof u.options.body.pipeTo=="function"||typeof u.options.body.pipe=="function")&&("duplex"in u.options||(u.options.duplex="half")));let g;if(!u.options.signal&&u.options.timeout){const $=new m;g=setTimeout(()=>{const T=new Error("[TimeoutError]: The operation was aborted due to timeout");T.name="TimeoutError",T.code=23,$.abort(T)},u.options.timeout),u.options.signal=$.signal}try{u.response=await o(u.request,u.options)}catch($){return u.error=$,u.options.onRequestError&&await U(u,u.options.onRequestError),await r(u)}finally{g&&clearTimeout(g)}if((u.response.body||u.response._bodyInit)&&!Ht.has(u.response.status)&&u.options.method!=="HEAD"){const $=(u.options.parseResponse?"json":u.options.responseType)||jt(u.response.headers.get("content-type")||"");switch($){case"json":{const T=await u.response.text(),j=u.options.parseResponse||Qe;u.response._data=j(T);break}case"stream":{u.response._data=u.response.body||u.response._bodyInit;break}default:u.response._data=await u.response[$]()}}return u.options.onResponse&&await U(u,u.options.onResponse),!u.options.ignoreResponseError&&u.response.status>=400&&u.response.status<600?(u.options.onResponseError&&await U(u,u.options.onResponseError),await r(u)):u.response},"$fetchRaw2"),l=f(async function(d,_){return(await i(d,_))._data},"$fetch2");return l.raw=i,l.native=(...p)=>o(...p),l.create=(p={},d={})=>be({...n,...d,defaults:{...n.defaults,...d.defaults,...p}}),l}f(be,"createFetch");const M=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")}(),Nt=M.fetch?(...n)=>M.fetch(...n):()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!")),Vt=M.Headers,It=M.AbortController,W=be({fetch:Nt,Headers:Vt,AbortController:It}),Ft={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.test/":"https://backend.frontstack.dev/")},I=Ft.apiRoot,Dt=`${I}login`,qt=`${I}api/fetch-api/spec.yaml`,we=3008,Ae=`http://localhost:${we}`,Ce=`${Dt}?redirectUrl=${Ae}/callback`,Lt=".frontstack-local/",x=S.join(process.cwd(),Lt),X="api_session.jwt",Ee="project.json",V=f(()=>{const n=f(()=>{console.info("Not auth.login implemented yet")},"login"),o=f(async()=>{try{return l(),0}catch(g){console.log(g)}},"logout"),h=f(async(g=void 0)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await W(`${I}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g||r()}`}})}catch(b){return console.log(b),1}},"getProfile"),m=f(async g=>{try{if(g==null)throw new Error(`You have no project selected
|
|
24
|
-
Run ${C.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 W(qt,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`,"FS-Project":g},parseResponse:f($=>{try{return ie.load($)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(b){throw"data"in b&&"message"in b.data?new Error(`Server error: ${b.data.message}`):b}},"getFetchApiSpec"),r=f(()=>{const g=
|
|
25
|
-
`+g.error);let b="";try{b=await Ie(g)}catch(j){throw new Error(`Invalid API Specification: ${j.message}`)}const $=i({paths:g.paths,components:g.components}),T=d({components:g.components,paths:g.paths,servers:g.servers});return{_schemaTypes:b,_types:$,_client:T,_query:u,_specFile:g}},"generate");const zt=f(async n=>{const
|
|
26
|
-
Schema types path: ${C.dim(b)}`),console.log(`Types path: ${C.dim($)}`),console.log(`Client path: ${C.dim(T)}`),console.log(`Target directory: ${C.dim(g)}`)),
|
|
27
|
-
Persisting OpenAPI Specification file in ${t}`),
|
|
20
|
+
`),this.outputHelp({error:!0}));const o=t||{},a=o.exitCode||1,c=o.code||"commander.error";this._exit(a,c,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in r.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()}`,r.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new u(this.options),t=f(o=>this.getOptionValue(o)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(o)),"hasCustomOptionValue");this.options.filter(o=>o.implied!==void 0&&t(o.attributeName())&&e.valueFromOption(this.getOptionValue(o.attributeName()),o)).forEach(o=>{Object.keys(o.implied).filter(a=>!t(a)).forEach(a=>{this.setOptionValueWithSource(a,o.implied[a],"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 o=f(y=>{const w=y.attributeName(),O=this.getOptionValue(w),E=this.options.find(k=>k.negate&&w===k.attributeName()),A=this.options.find(k=>!k.negate&&w===k.attributeName());return E&&(E.presetArg===void 0&&O===!1||E.presetArg!==void 0&&O===E.presetArg)?E:A||y},"findBestOptionFromValue"),a=f(y=>{const w=o(y),O=w.attributeName();return this.getOptionValueSource(O)==="env"?`environment variable '${w.envVar}'`:`option '${w.flags}'`},"getErrorMessage"),c=`error: ${a(e)} cannot be used with ${a(t)}`;this.error(c,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let a=[],c=this;do{const y=c.createHelp().visibleOptions(c).filter(w=>w.long).map(w=>w.long);a=a.concat(y),c=c.parent}while(c&&!c._enablePositionalOptions);t=g(e,a)}const o=`error: unknown option '${e}'${t}`;this.error(o,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,o=t===1?"":"s",c=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${o} but got ${e.length}.`;this.error(c,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const a=[];this.createHelp().visibleCommands(this).forEach(c=>{a.push(c.name()),c.alias()&&a.push(c.alias())}),t=g(e,a)}const o=`error: unknown command '${e}'${t}`;this.error(o,{code:"commander.unknownCommand"})}version(e,t,o){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",o=o||"output the version number";const a=this.createOption(t,o);return this._versionOptionName=a.attributeName(),this._registerOption(a),this.on("option:"+a.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 o=this.parent?._findCommand(e);if(o){const a=[o.name()].concat(o.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${a}'`)}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(o=>l(o));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=h.basename(e,h.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 o;return t.error?o=f(a=>this._outputConfiguration.writeErr(a),"write"):o=f(a=>this._outputConfiguration.writeOut(a),"write"),t.write=e.write||o,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);const o=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(c=>c.emit("beforeAllHelp",o)),this.emit("beforeHelp",o);let a=this.helpInformation(o);if(t&&(a=t(a),typeof a!="string"&&!Buffer.isBuffer(a)))throw new Error("outputHelp callback must return a string or a Buffer");o.write(a),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",o),this._getCommandAndAncestors().forEach(c=>c.emit("afterAllHelp",o))}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=r.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const o=["beforeAll","before","after","afterAll"];if(!o.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${o.join("', '")}'`);const a=`${e}Help`;return this.on(a,c=>{let y;typeof t=="function"?y=t({error:c.error,command:c.command}):y=t,y&&c.write(`${y}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};f(T,"Command");let b=T;function $(j){return j.map(e=>{if(!e.startsWith("--inspect"))return e;let t,o="127.0.0.1",a="9229",c;return(c=e.match(/^(--inspect(-brk)?)$/))!==null?t=c[1]:(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=c[1],/^\d+$/.test(c[3])?a=c[3]:o=c[3]):(c=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=c[1],o=c[3],a=c[4]),t&&a!=="0"?`${t}=${o}:${parseInt(a)+1}`:e})}return f($,"incrementNodeInspectorPort"),J.Command=b,J}f(qe,"requireCommand");var de;function Le(){if(de)return P;de=1;const{Argument:n}=G(),{Command:s}=qe(),{CommanderError:h,InvalidArgumentError:m}=q(),{Help:r}=le(),{Option:i}=he();return P.program=new s,P.createCommand=l=>new s(l),P.createOption=(l,p)=>new i(l,p),P.createArgument=(l,p)=>new n(l,p),P.Command=s,P.Option=i,P.Argument=n,P.Help=r,P.CommanderError=h,P.InvalidArgumentError=m,P.InvalidOptionArgumentError=m,P}f(Le,"requireCommander");var Ue=Le(),Me=Fe(Ue);const{program:wn,createCommand:An,createArgument:Cn,createOption:En,CommanderError:$n,InvalidArgumentError:vn,InvalidOptionArgumentError:Sn,Command:We,Argument:Tn,Option:kn,Help:jn}=Me,Ge=/"(?:_|\\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*:/,Je=/"(?: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*:/,Be=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ke(n,s){if(n==="__proto__"||n==="constructor"&&s&&typeof s=="object"&&"prototype"in s){ze(n);return}return s}f(Ke,"jsonParseTransform");function ze(n){console.warn(`[destr] Dropping "${n}" key to prevent prototype pollution.`)}f(ze,"warnKeyDropped");function Qe(n,s={}){if(typeof n!="string")return n;const h=n.trim();if(n[0]==='"'&&n.endsWith('"')&&!n.includes("\\"))return h.slice(1,-1);if(h.length<=9){const m=h.toLowerCase();if(m==="true")return!0;if(m==="false")return!1;if(m==="undefined")return;if(m==="null")return null;if(m==="nan")return Number.NaN;if(m==="infinity")return Number.POSITIVE_INFINITY;if(m==="-infinity")return Number.NEGATIVE_INFINITY}if(!Be.test(n)){if(s.strict)throw new SyntaxError("[destr] Invalid JSON");return n}try{if(Ge.test(n)||Je.test(n)){if(s.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(n,Ke)}return JSON.parse(n)}catch(m){if(s.strict)throw m;return n}}f(Qe,"destr");const Ye=/#/g,Ze=/&/g,Xe=/\//g,et=/=/g,z=/\+/g,tt=/%5e/gi,nt=/%60/gi,rt=/%7c/gi,it=/%20/gi;function ot(n){return encodeURI(""+n).replace(rt,"|")}f(ot,"encode");function Q(n){return ot(typeof n=="string"?n:JSON.stringify(n)).replace(z,"%2B").replace(it,"+").replace(Ye,"%23").replace(Ze,"%26").replace(nt,"`").replace(tt,"^").replace(Xe,"%2F")}f(Q,"encodeQueryValue");function Y(n){return Q(n).replace(et,"%3D")}f(Y,"encodeQueryKey");function me(n=""){try{return decodeURIComponent(""+n)}catch{return""+n}}f(me,"decode");function st(n){return me(n.replace(z," "))}f(st,"decodeQueryKey");function at(n){return me(n.replace(z," "))}f(at,"decodeQueryValue");function ct(n=""){const s={};n[0]==="?"&&(n=n.slice(1));for(const h of n.split("&")){const m=h.match(/([^=]+)=?(.*)/)||[];if(m.length<2)continue;const r=st(m[1]);if(r==="__proto__"||r==="constructor")continue;const i=at(m[2]||"");s[r]===void 0?s[r]=i:Array.isArray(s[r])?s[r].push(i):s[r]=[s[r],i]}return s}f(ct,"parseQuery");function lt(n,s){return(typeof s=="number"||typeof s=="boolean")&&(s=String(s)),s?Array.isArray(s)?s.map(h=>`${Y(n)}=${Q(h)}`).join("&"):`${Y(n)}=${Q(s)}`:Y(n)}f(lt,"encodeQueryItem");function ut(n){return Object.keys(n).filter(s=>n[s]!==void 0).map(s=>lt(s,n[s])).filter(Boolean).join("&")}f(ut,"stringifyQuery");const ht=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,pt=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,ft=/^([/\\]\s*){2,}[^/\\]/,dt=/^\.?\//;function ge(n,s={}){return typeof s=="boolean"&&(s={acceptRelative:s}),s.strict?ht.test(n):pt.test(n)||(s.acceptRelative?ft.test(n):!1)}f(ge,"hasProtocol");function mt(n="",s){return n.endsWith("/")}f(mt,"hasTrailingSlash");function gt(n="",s){return(mt(n)?n.slice(0,-1):n)||"/"}f(gt,"withoutTrailingSlash");function _t(n="",s){return n.endsWith("/")?n:n+"/"}f(_t,"withTrailingSlash");function yt(n,s){if(bt(s)||ge(n))return n;const h=gt(s);return n.startsWith(h)?n:At(h,n)}f(yt,"withBase");function Ot(n,s){const h=Ct(n),m={...ct(h.search),...s};return h.search=ut(m),Et(h)}f(Ot,"withQuery");function bt(n){return!n||n==="/"}f(bt,"isEmptyURL");function wt(n){return n&&n!=="/"}f(wt,"isNonEmptyURL");function At(n,...s){let h=n||"";for(const m of s.filter(r=>wt(r)))if(h){const r=m.replace(dt,"");h=_t(h)+r}else h=m;return h}f(At,"joinURL");const _e=Symbol.for("ufo:protocolRelative");function Ct(n="",s){const h=n.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(h){const[,g,b=""]=h;return{protocol:g.toLowerCase(),pathname:b,href:g+b,auth:"",host:"",search:"",hash:""}}if(!ge(n,{acceptRelative:!0}))return ye(n);const[,m="",r,i=""]=n.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[];let[,l="",p=""]=i.match(/([^#/?]*)(.*)?/)||[];m==="file:"&&(p=p.replace(/\/(?=[A-Za-z]:)/,""));const{pathname:d,search:_,hash:u}=ye(p);return{protocol:m.toLowerCase(),auth:r?r.slice(0,Math.max(0,r.length-1)):"",host:l,pathname:d,search:_,hash:u,[_e]:!m}}f(Ct,"parseURL");function ye(n=""){const[s="",h="",m=""]=(n.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname:s,search:h,hash:m}}f(ye,"parsePath");function Et(n){const s=n.pathname||"",h=n.search?(n.search.startsWith("?")?"":"?")+n.search:"",m=n.hash||"",r=n.auth?n.auth+"@":"",i=n.host||"";return(n.protocol||n[_e]?(n.protocol||"")+"//":"")+r+i+s+h+m}f(Et,"stringifyParsedURL");const ne=class ne extends Error{constructor(s,h){super(s,h),this.name="FetchError",h?.cause&&!this.cause&&(this.cause=h.cause)}};f(ne,"FetchError");let Z=ne;function $t(n){const s=n.error?.message||n.error?.toString()||"",h=n.request?.method||n.options?.method||"GET",m=n.request?.url||String(n.request)||"/",r=`[${h}] ${JSON.stringify(m)}`,i=n.response?`${n.response.status} ${n.response.statusText}`:"<no response>",l=`${r}: ${i}${s?` ${s}`:""}`,p=new Z(l,n.error?{cause:n.error}:void 0);for(const d of["request","options","response"])Object.defineProperty(p,d,{get(){return n[d]}});for(const[d,_]of[["data","_data"],["status","status"],["statusCode","status"],["statusText","statusText"],["statusMessage","statusText"]])Object.defineProperty(p,d,{get(){return n.response&&n.response[_]}});return p}f($t,"createFetchError");const vt=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function Oe(n="GET"){return vt.has(n.toUpperCase())}f(Oe,"isPayloadMethod");function St(n){if(n===void 0)return!1;const s=typeof n;return s==="string"||s==="number"||s==="boolean"||s===null?!0:s!=="object"?!1:Array.isArray(n)?!0:n.buffer?!1:n.constructor&&n.constructor.name==="Object"||typeof n.toJSON=="function"}f(St,"isJSONSerializable");const Tt=new Set(["image/svg","application/xml","application/xhtml","application/html"]),kt=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function jt(n=""){if(!n)return"json";const s=n.split(";").shift()||"";return kt.test(s)?"json":Tt.has(s)||s.startsWith("text/")?"text":"blob"}f(jt,"detectResponseType");function Pt(n,s,h,m){const r=Rt(s?.headers??n?.headers,h?.headers,m);let i;return(h?.query||h?.params||s?.params||s?.query)&&(i={...h?.params,...h?.query,...s?.params,...s?.query}),{...h,...s,query:i,params:i,headers:r}}f(Pt,"resolveFetchOptions");function Rt(n,s,h){if(!s)return new h(n);const m=new h(s);if(n)for(const[r,i]of Symbol.iterator in n||Array.isArray(n)?n:new h(n))m.set(r,i);return m}f(Rt,"mergeHeaders");async function U(n,s){if(s)if(Array.isArray(s))for(const h of s)await h(n);else await s(n)}f(U,"callHooks");const xt=new Set([408,409,425,429,500,502,503,504]),Ht=new Set([101,204,205,304]);function be(n={}){const{fetch:s=globalThis.fetch,Headers:h=globalThis.Headers,AbortController:m=globalThis.AbortController}=n;async function r(p){const d=p.error&&p.error.name==="AbortError"&&!p.options.timeout||!1;if(p.options.retry!==!1&&!d){let u;typeof p.options.retry=="number"?u=p.options.retry:u=Oe(p.options.method)?0:1;const g=p.response&&p.response.status||500;if(u>0&&(Array.isArray(p.options.retryStatusCodes)?p.options.retryStatusCodes.includes(g):xt.has(g))){const b=typeof p.options.retryDelay=="function"?p.options.retryDelay(p):p.options.retryDelay||0;return b>0&&await new Promise($=>setTimeout($,b)),i(p.request,{...p.options,retry:u-1})}}const _=$t(p);throw Error.captureStackTrace&&Error.captureStackTrace(_,i),_}f(r,"onError");const i=f(async function(d,_={}){const u={request:d,options:Pt(d,_,n.defaults,h),response:void 0,error:void 0};u.options.method&&(u.options.method=u.options.method.toUpperCase()),u.options.onRequest&&await U(u,u.options.onRequest),typeof u.request=="string"&&(u.options.baseURL&&(u.request=yt(u.request,u.options.baseURL)),u.options.query&&(u.request=Ot(u.request,u.options.query),delete u.options.query),"query"in u.options&&delete u.options.query,"params"in u.options&&delete u.options.params),u.options.body&&Oe(u.options.method)&&(St(u.options.body)?(u.options.body=typeof u.options.body=="string"?u.options.body:JSON.stringify(u.options.body),u.options.headers=new h(u.options.headers||{}),u.options.headers.has("content-type")||u.options.headers.set("content-type","application/json"),u.options.headers.has("accept")||u.options.headers.set("accept","application/json")):("pipeTo"in u.options.body&&typeof u.options.body.pipeTo=="function"||typeof u.options.body.pipe=="function")&&("duplex"in u.options||(u.options.duplex="half")));let g;if(!u.options.signal&&u.options.timeout){const $=new m;g=setTimeout(()=>{const T=new Error("[TimeoutError]: The operation was aborted due to timeout");T.name="TimeoutError",T.code=23,$.abort(T)},u.options.timeout),u.options.signal=$.signal}try{u.response=await s(u.request,u.options)}catch($){return u.error=$,u.options.onRequestError&&await U(u,u.options.onRequestError),await r(u)}finally{g&&clearTimeout(g)}if((u.response.body||u.response._bodyInit)&&!Ht.has(u.response.status)&&u.options.method!=="HEAD"){const $=(u.options.parseResponse?"json":u.options.responseType)||jt(u.response.headers.get("content-type")||"");switch($){case"json":{const T=await u.response.text(),j=u.options.parseResponse||Qe;u.response._data=j(T);break}case"stream":{u.response._data=u.response.body||u.response._bodyInit;break}default:u.response._data=await u.response[$]()}}return u.options.onResponse&&await U(u,u.options.onResponse),!u.options.ignoreResponseError&&u.response.status>=400&&u.response.status<600?(u.options.onResponseError&&await U(u,u.options.onResponseError),await r(u)):u.response},"$fetchRaw2"),l=f(async function(d,_){return(await i(d,_))._data},"$fetch2");return l.raw=i,l.native=(...p)=>s(...p),l.create=(p={},d={})=>be({...n,...d,defaults:{...n.defaults,...d.defaults,...p}}),l}f(be,"createFetch");const M=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")}(),Nt=M.fetch?(...n)=>M.fetch(...n):()=>Promise.reject(new Error("[ofetch] global.fetch is not supported!")),Vt=M.Headers,It=M.AbortController,W=be({fetch:Nt,Headers:Vt,AbortController:It}),Ft={apiRoot:process.env.FRONTSTACK_CLI_API_ROOT||(process.env.FRONTSTACK_CLI_DEV_MODE=="1"?"https://backend.frontstack.test/":"https://backend.frontstack.dev/")},I=Ft.apiRoot,Dt=`${I}login`,qt=`${I}api/fetch-api/spec.yaml`,we=3008,Ae=`http://localhost:${we}`,Ce=`${Dt}?redirectUrl=${Ae}/callback`,Lt=".frontstack-local/",x=v.join(process.cwd(),Lt),X="api_session.jwt",Ee="project.json",V=f(()=>{const n=f(()=>{console.info("Not auth.login implemented yet")},"login"),s=f(async()=>{try{return l(),0}catch(g){console.log(g)}},"logout"),h=f(async(g=void 0)=>{try{return process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await W(`${I}profile`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g||r()}`}})}catch(b){return console.log(b),1}},"getProfile"),m=f(async g=>{try{if(g==null)throw new Error(`You have no project selected
|
|
24
|
+
Run ${C.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 W(qt,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`,"FS-Project":g},parseResponse:f($=>{try{return ie.load($)}catch{throw new Error("Invalid API specification. The API specification must be a valid YAML file.")}},"parseResponse")})}catch(b){throw"data"in b&&"message"in b.data?new Error(`Server error: ${b.data.message}`):b}},"getFetchApiSpec"),r=f(()=>{const g=v.join(x,X);return S.existsSync(g)?S.readFileSync(g,"utf8"):null},"getToken"),i=f(g=>(S.existsSync(x)||S.mkdirSync(x),S.writeFileSync(v.join(x,X),g),0),"writeToken"),l=f(()=>{const g=v.join(x,X);S.existsSync(g)&&S.unlinkSync(g)},"deleteToken"),p=f(async()=>(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await W(`${I}api/project`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:f(g=>JSON.parse(g),"parseResponse")})),"getProjects"),d=f(()=>{const g=v.join(x,Ee);if(!S.existsSync(g))return null;try{return JSON.parse(S.readFileSync(g,"utf8")).projectId}catch{console.error("[Error] Corrupt project file - please run 'frontstack project'")}},"getProjectId");return{login:n,logout:s,getProfile:h,getFetchApiSpec:m,getToken:r,writeToken:i,deleteToken:l,getProjects:p,getProject:f(async(g=void 0)=>{try{return g===void 0&&(g=d()),g===void 0?void 0:(process.env.NODE_TLS_REJECT_UNAUTHORIZED=process.env.FRONTSTACK_CLI_DEV_MODE?"0":"1",await W(`${I}api/project/${g}`,{method:"GET",headers:{"Content-Type":"application/yaml",Authorization:`Bearer ${r()}`},parseResponse:f(b=>JSON.parse(b),"parseResponse")}))}catch(b){return{error:b.message}}},"getProject"),getProjectId:d,writeProject:f(g=>(S.existsSync(x)||S.mkdirSync(x),S.writeFileSync(v.join(x,Ee),JSON.stringify({projectId:g})),0),"writeProject")}},"auth"),{writeToken:Ut}=V(),Mt=f(async(n,s)=>{const h=new Set,m=Ne.createServer((r,i)=>{const l=Ae;if(r.url===void 0)return;const d=new URL(r.url,l).searchParams.get("token");d&&(i.writeHead(200,{"Content-Type":"text/html"}),i.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>'),i.on("finish",async()=>{for(const _ of h)_.destroy();Ut(d),console.log(`${C.hex("#008000")("[SUCCESS]")} Login successful`),m.close(),process.exit(0)}))}).listen(n,()=>{console.log(`Please continue login in your browser at ${C.hex("#7c3bed")(s)}`)});m.on("connection",r=>{h.add(r),r.on("close",()=>h.delete(r))}),setTimeout(()=>{m.close()},6e4)},"login$1"),Wt=f(async()=>{await Ve(Ce),await Mt(we,Ce)},"login"),Gt=V(),Jt=f(async n=>{await Gt.logout()!==0&&(console.error("Logout failed."),process.exit(1)),console.log("Logout successful."),process.exit(0)},"logout"),{getFetchApiSpec:Bt}=V();R.registerHelper("eq",function(n,s,h){return n===s}),R.registerHelper("uc",function(n){return n.toUpperCase()}),R.registerHelper("contains",function(n,s,h){return n===void 0?!1:n.includes(s)}),R.registerHelper("endsWith",function(n,s,h){return n===void 0?!1:n.endsWith(s)}),R.registerHelper("blockNameFromOperationId",function(n){return n.replace("get","").replace("Block","")});const ee=f((n,s=!1)=>n.$ref?`components['schemas']['${n.$ref.split("/").pop()}']`:n.type==="array"?`Array<${ee(n.items,!0)}>`:n.type==="object"?`{ ${Object.keys(n.properties).map(m=>`${m}: ${ee(n.properties[m])}`).join("; ")} }`:n.type,"getSchemaType");R.registerHelper("getSchemaType",n=>ee(n)),R.registerHelper("stringInArray",function(n,s,h){return s==null||s.length===0?!1:h.fn?s.indexOf(n)>-1?h.fn(this):h.inverse(this):s.indexOf(n)>-1});var Kt=f(async n=>{const s=v.dirname(new URL(import.meta.url).pathname),h=v.join(s,"src/commands/generate/templates"),m=v.join(h,"types.js.hbs"),r=S.readFileSync(m,"utf8"),i=R.compile(r),l=v.join(h,"client.js.hbs"),p=S.readFileSync(l,"utf8"),d=R.compile(p),_=v.join(h,"query.js.hbs"),u=S.readFileSync(_,"utf8");let g;if(g=await Bt(n),g.error)throw new Error(`Issue fetching API specification. Check more information below.
|
|
25
|
+
`+g.error);let b="";try{b=await Ie(g)}catch(j){throw new Error(`Invalid API Specification: ${j.message}`)}const $=i({paths:g.paths,components:g.components}),T=d({components:g.components,paths:g.paths,servers:g.servers});return{_schemaTypes:b,_types:$,_client:T,_query:u,_specFile:g}},"generate");const zt=f(async n=>{const s=n.verbose||!1,h=n.persistOas||!1,{getProject:m}=V(),r=await m();if(!r||"error"in r){console.info(`${C.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${C.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),console.info(" * Are you connected to the internet?"),console.info(` * Are you logged in using the ${C.hex("#7c3bed")("frontstack login")} command?`),console.info(` * Have you selected a project using the ${C.hex("#7c3bed")("frontstack project")} command?`),console.info(`Alternatively, run ${C.hex("#7c3bed")("frontstack generate -v")} for additional output.`);return}let i=r;if(n.env){let e;if(n.env!=="develop"){if(e=r.environments.find(t=>t.environment===n.env),!e){console.info(`${C.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${C.hex("#b90404")("[ERROR]")} Environment ${n.env} not found`);return}i=e}}if(!n.env&&r.environments.length>0){const e={type:"select",name:"projectId",message:"Pick an environment (use arrow keys and enter)",choices:[{title:`${r.name} (${r.environment})`,value:r.id},...r.environments.map(o=>({title:(o.id===i?.id?"(\u2714) ":"")+`${o.name} (${o.environment})`,value:o.id}))]},t=await oe(e);i=r.environments.find(o=>o.id===t.projectId)??r}let l,p,d,_,u;try{s&&console.log("Generating Javascript client"),{_schemaTypes:l,_types:p,_client:d,_query:_,_specFile:u}=await Kt(i.id)}catch(e){console.info(`${C.hex("#b90404")("[ERROR]")} frontstack generate`),console.info(`${C.hex("#b90404")("[ERROR]")} Failed to generate Javascript client`),s?console.info(`${C.hex("#b90404")("[ERROR]")} ${e.message}`):(console.info("Are you..."),console.info(` * logged in using the ${C.hex("#7c3bed")("frontstack login")} command?`),console.info(" * connected to the internet?"),console.info(`Alternatively, run ${C.hex("#7c3bed")("frontstack generate -v")} for additional output.`));return}let g=n.output||".frontstack";process.stdout.write("Generating Javascript client"),g.startsWith("/")||(g=v.join(process.cwd(),g)),g.endsWith("/")||(g+="/");const b=v.join(g,"fetch-api.d.ts"),$=v.join(g,"generated-types.d.ts"),T=v.join(g,"generated-client.ts"),j=v.join(g,"query-types.ts");if(s&&(console.log(`
|
|
26
|
+
Schema types path: ${C.dim(b)}`),console.log(`Types path: ${C.dim($)}`),console.log(`Client path: ${C.dim(T)}`),console.log(`Target directory: ${C.dim(g)}`)),S.mkdirSync(g,{recursive:!0}),h){const e=ie.dump(u,{indent:2}),t=v.join(g,"fetch-api.spec.yaml");console.log(`
|
|
27
|
+
Persisting OpenAPI Specification file in ${t}`),S.writeFileSync(v.join(t),e)}S.writeFileSync(v.join(b),l),S.writeFileSync(v.join($),p),S.writeFileSync(v.join(T),d),S.writeFileSync(v.join(j),_),s?console.log(`Javascript client generated for ${C.hex("#7c3bed")(`${i.name} (${i.environment})`)}`):(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(C.green(`Javascript client generated for ${C.hex("#7c3bed")(`${i.name} (${i.environment})`)}
|
|
28
28
|
`))),console.log(`
|
|
29
29
|
Use the following imports in your project:
|
|
30
30
|
`),console.log(" "+C.hex("#7c3bed")("import client from '@frontstack/client';")),console.log(`
|
|
31
31
|
and use the client like this:
|
|
32
32
|
`),console.log(" "+C.hex("#7c3bed")("const productDetail = await client.block('DetailPage', { key: 'my-product-id' });")),console.log(`
|
|
33
33
|
If you make changes to your schema, run ${C.hex("#7c3bed")("frontstack generate")} again to update the client.`)},"generateCommand"),{getToken:Qt,getProfile:Yt,getProject:Zt}=V(),Xt=f(async()=>{if(Qt()===null){console.log(`Status: Not logged in.
|
|
34
|
-
`),console.log("Run "+C.hex("#7c3bed")("frontstack login")+" to login.");return}try{const
|
|
35
|
-
`),console.log("Run "+C.hex("#7c3bed")("frontstack project")+" to select a frontstack project");return}if(
|
|
36
|
-
`),console.log("Run "+C.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+C.hex("#7c3bed")(
|
|
37
|
-
`),console.log(`Organization: ${
|
|
34
|
+
`),console.log("Run "+C.hex("#7c3bed")("frontstack login")+" to login.");return}try{const s=await Yt(),h=await Zt();if(h===void 0||"error"in h){console.log(`Status: No project selected.
|
|
35
|
+
`),console.log("Run "+C.hex("#7c3bed")("frontstack project")+" to select a frontstack project");return}if(s===1){console.log(`Not logged in.
|
|
36
|
+
`),console.log("Run "+C.hex("#7c3bed")("frontstack login")+" to login.");return}console.log("Logged in as "+C.hex("#7c3bed")(s.email)+`
|
|
37
|
+
`),console.log(`Organization: ${s.organization.name}`),console.log(`Current Project: ${h.name??"[No active project selected]"}`)}catch(s){console.log(s)}},"info"),{getProjects:en,writeProject:$e}=V(),tn=f(async n=>{let s=n.project??void 0,h=[];try{h=await en()}catch{console.log(`You are not logged in. Please run ${C.hex("#7c3bed")("frontstack login")} to login`);return}if(h.length<1){console.log("No projects found. Please create a new project in your Admin dashboard");return}if(s!==void 0){const r=h.find(i=>i.id===s);if(r){console.log(`Project ${C.hex("#7c3bed")(r.name)} selected`),$e(r.id);return}else{console.log(`Project with ID "${s}" not found. Please select a valid project ID`);return}}const m={type:"select",name:"projectId",message:"Pick a project (Use arrow keys and Enter)",choices:h.map(r=>({title:(r.id===s?"(\u2714) ":"")+`${r.name}`,value:r.id}))};(async()=>{const r=await oe(m),i=h.find(l=>l.id===r.projectId);if(i===void 0){console.log(`Project with ID "${r.projectId}" not found. Please select a valid project ID`);return}console.log(`Project ${C.hex("#7c3bed")(i.name)} selected`),$e(r.projectId)})()},"project"),nn=v.dirname(new URL(import.meta.url).pathname),ve=He(v.join(nn,"version"),"utf8");let te="0.0.1-dev";ve&&(te=ve.trim());const H=new We;H.name("frontstack").alias("fst").description(`${C.bgHex("#7c3bed").bold("frontstack CLI")}
|
|
38
38
|
Manage frontstack projects from the command line.
|
|
39
|
-
${C.dim(`Version: ${te}`)}`).version(te),H.command("login").description("Login to frontstack account").action(()=>{Wt()}),H.command("logout").description("Logout from frontstack account").action(async n=>{await Jt()}),H.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 n=>{await zt(n)}),H.command("info").description("Display information about the current organization, project, and user").action(async()=>{await Xt()}),H.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 n=>{await tn(n)});const rn=f(()=>{try{H.parse(process.argv)}catch(n){console.log(n)}},"run");var
|
|
39
|
+
${C.dim(`Version: ${te}`)}`).version(te),H.command("login").description("Login to frontstack account").action(()=>{Wt()}),H.command("logout").description("Logout from frontstack account").action(async n=>{await Jt()}),H.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 n=>{await zt(n)}),H.command("info").description("Display information about the current organization, project, and user").action(async()=>{await Xt()}),H.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 n=>{await tn(n)});const rn=f(()=>{try{H.parse(process.argv)}catch(n){console.log(n)}},"run");var on=rn();export{on as default};
|
package/dist/version
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.0.0-canary-
|
|
1
|
+
0.0.0-canary-20250207182729
|