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