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