primdy 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/index.js +23 -23
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{access as
|
|
4
|
-
`)}displayWidth(e){return
|
|
5
|
-
`+" ".repeat(t+
|
|
6
|
-
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach((s)=>{let o=s.match(n);if(o===null){r.push("");return}let
|
|
7
|
-
`)}}class S{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=
|
|
3
|
+
import{access as Ft,readdir as Vt}from"fs/promises";import{join as It,resolve as jt}from"path";class A extends Error{constructor(e,t,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class x extends A{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class H{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}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}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,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function F(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}import{EventEmitter as Le}from"events";import q from"child_process";import C from"path";import I from"fs";import d from"process";import{stripVTControlCharacters as Ue}from"util";import{stripVTControlCharacters as Be}from"util";class V{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((n)=>!n._hidden),i=e._getHelpCommand();if(i&&!i._hidden)t.push(i);if(this.sortSubcommands)t.sort((n,r)=>n.name().localeCompare(r.name()));return t}compareOptions(e,t){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);if(!n&&!r)t.push(i);else if(i.long&&!r)t.push(e.createOption(i.long,i.description));else if(i.short&&!n)t.push(e.createOption(i.short,i.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter((r)=>!r.hidden);t.push(...n)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((i)=>F(i)).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((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}formatItemList(e,t,i){if(t.length===0)return[];return[i.styleTitle(e),...t,""]}groupItems(e,t,i){let n=new Map;return e.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[])}),t.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[]);n.get(s).push(r)}),n}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function r(u,h){return t.formatItem(u,i,h,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),n),""]);let l=t.visibleArguments(e).map((u)=>r(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),(u)=>u.helpGroupHeading??"Options:").forEach((u,h)=>{let g=u.map((y)=>r(t.styleOptionTerm(t.optionTerm(y)),t.styleOptionDescription(t.optionDescription(y))));s=s.concat(this.formatItemList(h,g,t))}),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map((h)=>r(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));s=s.concat(this.formatItemList("Global Options:",u,t))}return this.groupItems(e.commands,t.visibleCommands(e),(u)=>u.helpGroup()||"Commands:").forEach((u,h)=>{let g=u.map((y)=>r(t.styleSubcommandTerm(t.subcommandTerm(y)),t.styleSubcommandDescription(t.subcommandDescription(y))));s=s.concat(this.formatItemList(h,g,t))}),s.join(`
|
|
4
|
+
`)}displayWidth(e){return Be(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,n){let s=" ".repeat(2);if(!i)return s+e;let o=e.padEnd(t+e.length-n.displayWidth(e)),l=2,a=(this.helpWidth??80)-t-l-2,u;if(a<this.minWidthToWrap||n.preformatted(i))u=i;else u=n.boxWrap(i,a).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(t+l));return s+o+" ".repeat(l)+u.replace(/\n/g,`
|
|
6
|
+
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach((s)=>{let o=s.match(n);if(o===null){r.push("");return}let l=[o.shift()],c=this.displayWidth(l[0]);o.forEach((a)=>{let u=this.displayWidth(a);if(c+u<=t){l.push(a),c+=u;return}r.push(l.join(""));let h=a.trimStart();l=[h],c=this.displayWidth(h)}),r.push(l.join(""))}),r.join(`
|
|
7
|
+
`)}}class S{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=Ge(e);if(this.short=i.shortFlag,this.long=i.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,this.helpGroupHeading=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;if(typeof e==="string")t={[e]:!0};return 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}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return ne(this.name().replace(/^no-/,""));return ne(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class L{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{if(this.positiveOptions.has(i))this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}}function ne(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function Ge(e){let t,i,n=/^-[^-]$/,r=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(n.test(s[0]))t=s.shift();if(r.test(s[0]))i=s.shift();if(!t&&n.test(s[0]))t=s.shift();if(!t&&r.test(s[0]))t=i,i=s.shift();if(s[0].startsWith("-")){let o=s[0],l=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${l}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${
|
|
11
|
-
- too many short flags`);if(r.test(o))throw Error(`${
|
|
12
|
-
- too many long flags`);throw Error(`${
|
|
13
|
-
- unrecognised flag format`)}if(t===void 0&&i===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}function
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${l}
|
|
11
|
+
- too many short flags`);if(r.test(o))throw Error(`${l}
|
|
12
|
+
- too many long flags`);throw Error(`${l}
|
|
13
|
+
- unrecognised flag format`)}if(t===void 0&&i===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}function We(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let n=0;n<=e.length;n++)i[n]=[n];for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=1;n<=t.length;n++)for(let r=1;r<=e.length;r++){let s;if(e[r-1]===t[n-1])s=0;else s=1;if(i[r][n]=Math.min(i[r-1][n]+1,i[r][n-1]+1,i[r-1][n-1]+s),r>1&&n>1&&e[r-1]===t[n-2]&&e[r-2]===t[n-1])i[r][n]=Math.min(i[r][n],i[r-2][n-2]+1)}return i[e.length][t.length]}function U(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");if(i)e=e.slice(2),t=t.map((o)=>o.slice(2));let n=[],r=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let l=We(e,o),c=Math.max(e.length,o.length);if((c-l)/c>s){if(l<r)r=l,n=[o];else if(l===r)n.push(o)}}),n.sort((o,l)=>o.localeCompare(l)),i)n=n.map((o)=>`--${o}`);if(n.length>1)return`
|
|
14
14
|
(Did you mean one of ${n.join(", ")}?)`;if(n.length===1)return`
|
|
15
|
-
(Did you mean ${n[0]}?)`;return""}class E extends
|
|
15
|
+
(Did you mean ${n[0]}?)`;return""}class E extends Le{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,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._savedState=null,this._outputConfiguration={writeOut:(t)=>d.stdout.write(t),writeErr:(t)=>d.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>se()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>se()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:(t)=>Ue(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,r=i;if(typeof n==="object"&&n!==null)r=n,n=null;r=r||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);if(n)l.description(n),l._executableHandler=!0;if(r.isDefault)this._defaultCommandName=l._name;if(l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,o)l.arguments(o);if(this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n)return this;return l}createCommand(e){return new E(e)}createHelp(){return Object.assign(new V,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
16
|
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new H(e,t)}argument(e,t,i,n){let r=this.createArgument(e,t);if(typeof i==="function")r.default(n).argParser(i);else r.default(i);return this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw 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"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let i=e??"help [command]",[,n,r]=i.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);if(o.helpOption(!1),r)o.arguments(r);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
-
Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,i){if(this._exitCallback)this._exitCallback(new
|
|
18
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(n)=>[n.name()].concat(n.aliases()),i=t(e).find((n)=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,o)=>{if(r==null&&e.presetArg!==void 0)r=e.presetArg;let
|
|
17
|
+
Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,i){if(this._exitCallback)this._exitCallback(new A(e,t,i));d.exit(e)}action(e){let t=(i)=>{let n=this.registeredArguments.length,r=i.slice(0,n);if(this._storeOptionsAsProperties)r[n]=this;else r[n]=this.opts();return r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new S(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(r){if(r.code==="commander.invalidArgument"){let s=`${n} ${r.message}`;this.error(s,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(n)=>[n.name()].concat(n.aliases()),i=t(e).find((n)=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,o)=>{if(r==null&&e.presetArg!==void 0)r=e.presetArg;let l=this.getOptionValue(i);if(r!==null&&e.parseArg)r=this._callParseArg(e,r,l,s);else if(r!==null&&e.variadic)r=e._collectValue(r,l);if(r==null)if(e.negate)r=!1;else if(e.isBoolean()||e.optional)r=!0;else r="";this.setOptionValueWithSource(i,r,o)};if(this.on("option:"+t,(r)=>{let s=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(r)=>{let s=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,s,"env")});return this}_optionEx(e,t,i,n,r){if(typeof t==="object"&&t instanceof S)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,i);if(s.makeOptionMandatory(!!e.mandatory),typeof n==="function")s.default(r).argParser(n);else if(n instanceof RegExp){let o=n;n=(l,c)=>{let a=o.exec(l);return a?a[0]:c},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}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 Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((i)=>{if(i.getOptionValueSource(e)!==void 0)t=i.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(d.versions?.electron)t.from="electron";let n=d.execArgv??[];if(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))t.from="eval"}if(e===void 0)e=d.argv;this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":if(d.defaultApp)this._scriptPath=e[1],i=e.slice(2);else i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
19
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,i){if(I.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
|
|
20
20
|
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${n}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(
|
|
22
|
+
- ${n}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(a,u){let h=C.resolve(a,u);if(I.existsSync(h))return h;if(i.includes(C.extname(u)))return;let g=i.find((y)=>I.existsSync(`${h}${y}`));if(g)return`${h}${g}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let a;try{a=I.realpathSync(this._scriptPath)}catch{a=this._scriptPath}s=C.resolve(C.dirname(a),s)}if(s){let a=n(s,r);if(!a&&!e._executableFile&&this._scriptPath){let u=C.basename(this._scriptPath,C.extname(this._scriptPath));if(u!==this._name)a=n(s,`${u}-${e._name}`)}r=a||r}let o=i.includes(C.extname(r)),l;if(d.platform!=="win32")if(o)t.unshift(r),t=re(d.execArgv).concat(t),l=q.spawn(d.argv[0],t,{stdio:"inherit"});else l=q.spawn(r,t,{stdio:"inherit"});else this._checkForMissingExecutable(r,s,e._name),t.unshift(r),t=re(d.execArgv).concat(t),l=q.spawn(d.execPath,t,{stdio:"inherit"});if(!l.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{d.on(u,()=>{if(l.killed===!1&&l.exitCode===null)l.kill(u)})});let c=this._exitCallback;l.on("close",(a)=>{if(a=a??1,!c)d.exit(a);else c(new A(a,"commander.executeSubCommandAsync","(close)"))}),l.on("error",(a)=>{if(a.code==="ENOENT")this._checkForMissingExecutable(r,s,e._name);else if(a.code==="EACCES")throw Error(`'${r}' not executable`);if(!c)d.exit(1);else{let u=new A(1,"commander.executeSubCommandAsync","(error)");u.nestedError=a,c(u)}}),this.runningCommand=l}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);if(!n)this.help({error:!0});n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),r}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;if(i.variadic){if(n<this.args.length){if(r=this.args.slice(n),i.parseArg)r=r.reduce((s,o)=>e(i,o,s),i.defaultValue)}else if(r===void 0)r=[]}else if(n<this.args.length){if(r=this.args[n],i.parseArg)r=e(i,r,i.defaultValue)}t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let i=e,n=[];if(this._getCommandAndAncestors().reverse().filter((r)=>r._lifeCycleHooks[t]!==void 0).forEach((r)=>{r._lifeCycleHooks[t].forEach((s)=>{n.push({hookedCommand:r,callback:s})})}),t==="postAction")n.reverse();return n.forEach((r)=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;if(this._lifeCycleHooks[i]!==void 0)this._lifeCycleHooks[i].forEach((r)=>{n=this._chainOrCall(n,()=>r(this,t))});return n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.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);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{if(i.unknown.length>0)this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(r,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else n(),this._processArguments()}else if(this.commands.length)n(),this.help({error:!0});else n(),this._processArguments()}_findCommand(e){if(!e)return;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)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((i)=>{let n=i.attributeName();if(this.getOptionValue(n)===void 0)return!1;return this.getOptionValueSource(n)!=="default"});e.filter((i)=>i.conflictsWith.length>0).forEach((i)=>{let n=e.find((r)=>i.conflictsWith.includes(r.attributeName()));if(n)this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t;function r(a){return a.length>1&&a[0]==="-"}let s=(a)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(a))return!1;return!this._getCommandAndAncestors().some((u)=>u.options.map((h)=>h.short).some((h)=>/^-\d$/.test(h)))},o=null,l=null,c=0;while(c<e.length||l){let a=l??e[c++];if(l=null,a==="--"){if(n===i)n.push(a);n.push(...e.slice(c));break}if(o&&(!r(a)||s(a))){this.emit(`option:${o.name()}`,a);continue}if(o=null,r(a)){let u=this._findOption(a);if(u){if(u.required){let h=e[c++];if(h===void 0)this.optionMissingArgument(u);this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;if(c<e.length&&(!r(e[c])||s(e[c])))h=e[c++];this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);o=u.variadic?u:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let u=this._findOption(`-${a[1]}`);if(u){if(u.required||u.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${u.name()}`,a.slice(2));else this.emit(`option:${u.name()}`),l=`-${a.slice(2)}`;continue}}if(/^--[^=]+=/.test(a)){let u=a.indexOf("="),h=this._findOption(a.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(u+1));continue}}if(n===t&&r(a)&&!(this.commands.length===0&&s(a)))n=i;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),i.push(...e.slice(c));break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a,...e.slice(c));break}else if(this._defaultCommandName){i.push(a,...e.slice(c));break}}if(this._passThroughOptions){n.push(a,...e.slice(c));break}n.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0});let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new L(this.options),t=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=(s)=>{let o=s.attributeName(),
|
|
26
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return 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];if(e===t._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((i)=>F(i));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){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=
|
|
25
|
+
`),this.outputHelp({error:!0});let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new L(this.options),t=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=(s)=>{let o=s.attributeName(),l=this.getOptionValue(o),c=this.options.find((u)=>u.negate&&o===u.attributeName()),a=this.options.find((u)=>!u.negate&&o===u.attributeName());if(c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg))return c;return a||s},n=(s)=>{let o=i(s),l=o.attributeName();if(this.getOptionValueSource(l)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter((o)=>o.long).map((o)=>o.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);t=U(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=e.length,r=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${r}. Expected ${t} argument${i} but got ${n}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((r)=>{if(n.push(r.name()),r.alias())n.push(r.alias())}),t=U(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return 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];if(e===t._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((i)=>F(i));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){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=C.basename(e,C.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=t.formatHelp(this,t);if(i.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,i,n,r;if(t)i=(o)=>this._outputConfiguration.writeErr(o),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth();else i=(o)=>this._outputConfiguration.writeOut(o),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!n)o=this._outputConfiguration.stripColor(o);return i(o)},hasColors:n,helpWidth:r}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(i.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{let s;if(typeof t==="function")s=t({error:r.error,command:r.command});else s=t;if(s)r.write(`${s}
|
|
28
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function re(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)i=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=s[1],/^\d+$/.test(s[3]))r=s[3];else n=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=s[1],n=s[3],r=s[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function se(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}var
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function re(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)i=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=s[1],/^\d+$/.test(s[3]))r=s[3];else n=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=s[1],n=s[3],r=s[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function se(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}var gi=new E;function oe(e,t,i){let n=e.indexOf(t);if(n===-1)return e;let r=t.length,s=0,o="";do o+=e.slice(s,n)+t+i,s=n+r,n=e.indexOf(t,s);while(n!==-1);return o+=e.slice(s),o}function ae(e,t,i,n){let r=0,s="";do{let o=e[n-1]==="\r";s+=e.slice(r,o?n-1:n)+t+(o?`\r
|
|
29
29
|
`:`
|
|
30
30
|
`)+i,r=n+1,n=e.indexOf(`
|
|
31
|
-
`,r)}while(n!==-1);return s+=e.slice(r),s}var le=(e=0)=>(t)=>`\x1B[${t+e}m`,Y=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,z=(e=0)=>(t,i,n)=>`\x1B[${38+e};2;${t};${i};${n}m`,
|
|
32
|
-
`);if(s!==-1)t=ae(t,r,n,s);return n+t+r};Object.defineProperties(N.prototype,{...P,level:
|
|
33
|
-
`;await
|
|
34
|
-
- Local: ${
|
|
35
|
-
- Local: http://${t.hostname}:${
|
|
36
|
-
Consider migrating your application: https://bun.sh/`)}),s}import{stat as
|
|
37
|
-
Cannot find ${e}`),!1}T.command("dev").argument("[directory]","Application directory",".").description("Starts the development server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,
|
|
31
|
+
`,r)}while(n!==-1);return s+=e.slice(r),s}var le=(e=0)=>(t)=>`\x1B[${t+e}m`,Y=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,z=(e=0)=>(t,i,n)=>`\x1B[${38+e};2;${t};${i};${n}m`,qe=(e)=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,p={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},bi=Object.keys(p.modifier),Ye=Object.keys(p.color),ze=Object.keys(p.bgColor),Oi=Object.keys(p.underlineColor),Ci=[...Ye,...ze];function Je(){let e=new Map;for(let[t,i]of Object.entries(p)){for(let[n,r]of Object.entries(i))p[n]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},i[n]=p[n],e.set(Number.parseInt(r[0],10),r[1]);Object.defineProperty(p,t,{value:i,enumerable:!1})}return Object.defineProperty(p,"codes",{value:e,enumerable:!1}),p.color.close="\x1B[39m",p.bgColor.close="\x1B[49m",p.underlineColor.close="\x1B[59m",p.color.ansi=le(),p.color.ansi256=Y(),p.color.ansi16m=z(),p.bgColor.ansi=le(10),p.bgColor.ansi256=Y(10),p.bgColor.ansi16m=z(10),p.underlineColor.ansi=qe,p.underlineColor.ansi256=Y(20),p.underlineColor.ansi16m=z(20),Object.defineProperties(p,{rgbToAnsi256:{value(t,i,n){if(t===i&&i===n){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(i/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let i=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!i)return[0,0,0];let[n]=i;if(n.length===3)n=[...n].map((s)=>s+s).join("");let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>p.rgbToAnsi256(...p.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let i,n,r;if(t>=232)i=((t-232)*10+8)/255,n=i,r=i;else{t-=16;let l=t%36;i=Math.floor(t/36)/5,n=Math.floor(l/6)/5,r=l%6/5}let s=Math.max(i,n,r)*2;if(s===0)return 30;let o=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(i));if(s===2)o+=60;return o},enumerable:!1},rgbToAnsi:{value:(t,i,n)=>p.ansi256ToAnsi(p.rgbToAnsi256(t,i,n)),enumerable:!1},hexToAnsi:{value:(t)=>p.ansi256ToAnsi(p.hexToAnsi256(t)),enumerable:!1}}),p}var Ke=Je(),O=Ke;import J from"process";import Qe from"os";import ue from"tty";function b(e,t=globalThis.Deno?globalThis.Deno.args:J.argv){let i=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(i+e),r=t.indexOf("--");return n!==-1&&(r===-1||n<r)}var{env:m}=J,j;if(b("no-color")||b("no-colors")||b("color=false")||b("color=never"))j=0;else if(b("color")||b("colors")||b("color=true")||b("color=always"))j=1;function he(){return/^\d+$/.test(m.FORCE_COLOR)}function Xe(){if(!("FORCE_COLOR"in m))return;if(m.FORCE_COLOR==="false")return 0;if(m.FORCE_COLOR==="true"||m.FORCE_COLOR.length===0)return 1;if(!he())return;return Math.min(Number.parseInt(m.FORCE_COLOR,10),3)}function Ze(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function et(e,{streamIsTTY:t,sniffFlags:i=!0}={}){let n=Xe();if(n!==void 0)j=n;let r=i?j:n;if(r===0)return 0;if(i){if(b("color=16m")||b("color=full")||b("color=truecolor"))return 3;if(b("color=256"))return 2}if(r!==void 0&&he())return r;if("TF_BUILD"in m&&"AGENT_NAME"in m)return 1;if(e&&!t&&r===void 0)return 0;let s=r||0;if(m.TERM==="dumb")return s;if(J.platform==="win32"){let o=Qe.release().split(".");if(Number(o[0])>=10&&Number(o[2])>=10586)return Number(o[2])>=14931?3:2;return 1}if("CI"in m){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((o)=>(o in m)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((o)=>(o in m))||m.CI_NAME==="codeship")return 1;return s}if("TEAMCITY_VERSION"in m)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(m.TEAMCITY_VERSION)?1:0;if(m.COLORTERM==="truecolor")return 3;if(m.TERM==="xterm-kitty")return 3;if(m.TERM==="xterm-ghostty")return 3;if(m.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m){let o=Number.parseInt((m.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(m.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(?:color)?$/i.test(m.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m.TERM))return 1;if("COLORTERM"in m)return 1;return s}function ce(e,t={}){let i=et(e,{streamIsTTY:e&&e.isTTY,...t});return Ze(i)}var tt={stdout:ce({isTTY:ue.isatty(1)}),stderr:ce({isTTY:ue.isatty(2)})},de=tt;var{stdout:pe,stderr:me}=de,R=Symbol("GENERATOR"),k=Symbol("STYLER"),B=Symbol("IS_EMPTY"),D=Symbol("LEVEL"),P=Object.create(null),fe=(e)=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},it={enumerable:!0,get(){return this[D]},set(e){fe(e),this[D]=e}},nt=(e,t={})=>{if(t.level!==void 0)fe(t.level);let i=pe?pe.level:0;e[D]=t.level===void 0?i:t.level};var rt=(e)=>{let t=(...i)=>i.join(" ");return nt(t,e),Object.setPrototypeOf(t,N.prototype),t};function N(e){return rt(e)}Object.setPrototypeOf(N.prototype,Function.prototype);for(let[e,t]of Object.entries(O))P[e]={get(){let i=Q(this,ge(t.open,t.close,this[k]),this[B]);return Object.defineProperty(this,e,{value:i}),i}};P.visible={get(){let e=Q(this,this[k],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var st=(e,t)=>{let i=O[t];if(e==="rgb"){let r=(o,l,c)=>i.ansi(O.rgbToAnsi(o,l,c));return[r,r,(o,l,c)=>i.ansi256(O.rgbToAnsi256(o,l,c)),i.ansi16m]}if(e==="hex"){let r=(o)=>i.ansi(O.hexToAnsi(o));return[r,r,(o)=>i.ansi256(O.hexToAnsi256(o)),(o)=>i.ansi16m(...O.hexToRgb(o))]}let n=(r)=>i.ansi(O.ansi256ToAnsi(r));return[n,n,i.ansi256,i.ansi256]},ot=["rgb","hex","ansi256"];for(let e of ot){let t=e[0].toUpperCase()+e.slice(1);for(let[i,n]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:r}=O[n],s=st(e,n);P[i]={get(){let o=function(l,c,a){let u=s[this.level](l,c,a);return Q(this,ge(u,r,this[k]),this[B])};return Object.defineProperty(this,i,{value:o}),o}}}}var at=Object.defineProperties(()=>{},{...P,level:{enumerable:!0,get(){return this[R].level},set(e){this[R].level=e}}}),ge=(e,t,i)=>{let n,r;if(i===void 0)n=e,r=t;else n=i.openAll+e,r=t+i.closeAll;return{open:e,close:t,openAll:n,closeAll:r,parent:i}},Q=(e,t,i)=>{let n=(...r)=>{if(r.length===1)return K(n,""+r[0]);if(r.length===2)return K(n,r[0]+" "+r[1]);return K(n,r.join(" "))};return Object.setPrototypeOf(n,at),n[R]=e[R]??e,n[k]=t,n[B]=i,n},K=(e,t)=>{if(e[R][D]<=0||!t)return e[B]?"":t;let i=e[k];if(i===void 0)return t;let{openAll:n,closeAll:r}=i;if(t.includes("\x1B"))while(i!==void 0)t=oe(t,i.close,i.open),i=i.parent;let s=t.indexOf(`
|
|
32
|
+
`);if(s!==-1)t=ae(t,r,n,s);return n+t+r};Object.defineProperties(N.prototype,{...P,level:it});var lt=N(),Ri=N({level:me?me.level:0});var f=lt;import{mkdir as bt,readFile as Ot,rm as Ct,writeFile as wt}from"fs/promises";import{basename as At,join as w}from"path";import{build as xt}from"esbuild";import{readdir as ut}from"fs/promises";import{dirname as ct,join as ht,relative as ye}from"path";function _e(e){let t=e.replaceAll("\\","/").split("/");if(t.at(-1)!=="route.ts"&&t.at(-1)!=="route.js")return null;t.pop();let i=t.join("/"),n=[];for(let r of t){if(!r||/^\(.+\)$/.test(r))continue;if(/^\[\[\.\.\..+\]\]$/.test(r)){n.push({type:"optionalCatchAll",name:r.slice(5,-2)});continue}if(/^\[\.\.\..+\]$/.test(r)){n.push({type:"catchAll",name:r.slice(4,-1)});continue}if(/^\[.+\]$/.test(r)){n.push({type:"dynamic",name:r.slice(1,-1)});continue}n.push({type:"static",value:r})}return{dir:i,segments:n,pathname:n.length?"/"+n.map((r)=>{if(r.type==="static")return r.value;if(r.type==="dynamic")return`[${r.name}]`;if(r.type==="catchAll")return`[...${r.name}]`;return`[[...${r.name}]]`}).join("/"):"/"}}var dt=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function be(e){return ut(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])}function Oe(e){return ht(e.parentPath??e.path,e.name)}async function M(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(i.name!=="route.ts"&&i.name!=="route.js")continue;let n=Oe(i),r=ye(e,n),s=_e(r);if(!s)continue;t.push({id:r.replaceAll("/",":").replace(/\.(ts|js)$/,""),file:n,dir:s.dir,pathname:s.pathname,segments:s.segments,methods:dt})}return t.sort(pt)}async function G(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(!/^(middleware|proxy)\.(ts|js)$/.test(i.name))continue;let n=Oe(i),r=ye(e,ct(n)).replaceAll("\\","/");t.push({file:n,dir:r==="."?"":r})}return t.sort((i,n)=>i.dir.length-n.dir.length)}function pt(e,t){let i=(n)=>n.segments.reduce((r,s)=>{if(s.type==="static")return r+1000;if(s.type==="dynamic")return r+100;if(s.type==="catchAll")return r+10;return r},n.segments.length);return i(t)-i(e)}import{mkdir as mt,readFile as ft,writeFile as gt}from"fs/promises";import{join as v,relative as Ce}from"path";async function we(e,t,i=[]){let n=v(e,".primdy");await mt(n,{recursive:!0});let r={version:1,routes:t.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")})),middleware:i.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")}))};await gt(v(n,"routes.json"),JSON.stringify(r))}async function Ae(e){let t=v(e,".primdy"),i=v(t,"routes.json"),n=JSON.parse(await ft(i,"utf8"));return{...n,routes:n.routes.map((r)=>({...r,file:v(t,r.file)})),middleware:(n.middleware??[]).map((r)=>({...r,file:v(t,r.file)}))}}import{mkdir as _t,writeFile as yt}from"fs/promises";import{join as xe}from"path";async function Ee(e,t){let i=xe(e,".primdy");await _t(i,{recursive:!0});let r=`export type PrimdyRoute = ${t.map((s)=>`"${s.pathname}"`).join(" | ")||"never"};
|
|
33
|
+
`;await yt(xe(i,"routes.d.ts"),r)}async function Te(e,t){let i=await M(w(e,t)),n=await G(w(e,t)),r=w(e,".primdy");await Ct(r,{recursive:!0,force:!0}),await bt(r,{recursive:!0});let s=w(r,"routes"),o=[];for(let[a,u]of i.entries())o.push({...u,file:await ve(u.file,w(s,String(a)))});let l=w(r,"middleware"),c=[];for(let[a,u]of n.entries())c.push({...u,file:await ve(u.file,w(l,String(a)))});return await we(e,o,c),await Ee(e,i),{routes:o,middleware:c}}async function ve(e,t){if((await xt({entryPoints:[e],outdir:t,bundle:!0,platform:"node",format:"esm",minifyWhitespace:!0,sourcemap:"external",logLevel:"silent"})).errors.length)throw Error(`Failed to build ${e}`);let n=w(t,At(e).replace(/\.(ts|js)$/,".js"));return await Et(`${n}.map`),n}async function Et(e){let t=await Ot(e,"utf8");await wt(e,JSON.stringify(JSON.parse(t)))}import{access as vt}from"fs/promises";import{join as Tt}from"path";async function $t(e){for(let t of["primdy.config.ts","primdy.config.js","primdy.config.mjs"]){let i=Tt(e,t);try{return await vt(i),i}catch{continue}}return null}async function X(e,t={}){let i=await $t(e),r=(i?await import(i).catch(()=>({default:{}})):{default:{}}).default??{};for(let[s,o]of Object.entries(t))if(o!==void 0)r[s]=o;return r}var _={success:(e)=>console.log(`${f.bold.green("\u2713")} ${e}`),info:(e)=>console.log(`${f.bold.cyan("\u2139")} ${e}`),warn:(e)=>console.log(`${f.bold.yellow("\u26A0")} ${e}`),err:(e)=>console.log(`${f.bold.red("\u2717")} ${e}`)},Z=(e)=>{_.success(`Ready in ${Math.round(performance.now()-e)}ms`)};import{createServer as St}from"http";import{Readable as Fe}from"stream";function Se(e,t){let i=t.split("/").filter(Boolean);for(let n of e){let r={},s=0,o=!0;for(let l of n.segments){if(l.type==="static"){if(i[s]!==l.value){o=!1;break}s++;continue}if(l.type==="dynamic"){let a=Re(i[s]);if(a===null){o=!1;break}r[l.name]=a,s++;continue}if(l.type==="catchAll"){if(s>=i.length){o=!1;break}let a=$e(i.slice(s));if(a===null){o=!1;break}r[l.name]=a,s=i.length;continue}let c=$e(i.slice(s));if(c===null){o=!1;break}r[l.name]=c,s=i.length}if(o&&s===i.length)return{route:n,params:r}}return null}function Re(e){try{return decodeURIComponent(e)}catch{return null}}function $e(e){let t=[];for(let i of e){let n=Re(i);if(n===null)return null;t.push(n)}return t}function ke(e,t){return e.filter((i)=>i.dir===""||t.dir===i.dir||t.dir.startsWith(`${i.dir}/`))}var Pe=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function Ne(e,t,i=[]){let n=new URL(e.url),r=Se(t,n.pathname);if(!r)return new Response("Not Found",{status:404});for(let c of ke(i,r.route)){let a=await import(c.file),u=a.default??a.middleware??a.proxy;if(typeof u!=="function")continue;let h=await u(e,{params:r.params});if(h)return h}let s=e.method;if(!Pe.includes(s))return new Response("Method Not Allowed",{status:405,headers:{Allow:r.route.methods.join(", ")}});let o=await import(r.route.file),l=o[s];if(typeof l!=="function"){let c=Pe.filter((a)=>typeof o[a]==="function");if(!c.length)return new Response("Method Not Allowed",{status:405});return new Response("Method Not Allowed",{status:405,headers:{Allow:c.join(", ")}})}return l(e,{params:r.params})}function ee(e,t,i,n){let r=performance.now()-n,s=f.dim(e.method),o=f.white(t),l=i>=500?f.red(i):i>=400?f.yellow(i):i>=300?f.cyan(i):f.green(i),c=r<1?f.dim(`${r.toFixed(2)}ms`):r>=100?f.yellow(`${Math.round(r)}ms`):f.dim(`${Math.round(r)}ms`);console.log(`${s} ${o} ${l} took ${c}`)}var Rt=typeof Bun<"u";function kt(e,t){let i=new Headers;for(let r in e.headers){let s=e.headers[r];if(s===void 0)continue;i.set(r,Array.isArray(s)?s.join(", "):s)}let n=e.method!=="GET"&&e.method!=="HEAD";return new Request(`http://${e.headers.host??t}${e.url??"/"}`,{method:e.method,headers:i,body:n?Fe.toWeb(e):void 0,duplex:n?"half":void 0})}function Me(e){return e?.code==="EADDRINUSE"}function He(e,t){let i=e?.code;if(i==="EADDRINUSE")return`Port ${t.port} is already in use`;if(i==="EACCES")return`Permission denied to listen on port ${t.port}`;return e instanceof Error?e.message:String(e)}function te(e,t,i=[]){let n=Rt&&!t.forceNode;async function r(a){let u=performance.now(),h=new URL(a.url);try{let g=await Ne(a,e,i);return ee(a,h.pathname,g.status,u),g}catch(g){console.error(g);let y=new Response("Internal Server Error",{status:500});return ee(a,h.pathname,y.status,u),y}}if(n){let a=t.port;for(let u=0;u<=5;u++)try{let h=Bun.serve({hostname:t.hostname,port:a,fetch:r});return console.log(`${f.bold.cyanBright("\u25C6 Primdy Server")}
|
|
34
|
+
- Local: ${h.url}`),h}catch(h){if(!Me(h)||u===5)_.err(He(h,{...t,port:a})),process.exit(1);let g=a+1;_.warn(`Port ${a} is in use, using ${g} instead`),a=g}}let s=St(async(a,u)=>{let h=await r(kt(a,t.hostname));u.statusCode=h.status;for(let[y,De]of h.headers)if(y.toLowerCase()!=="set-cookie")u.setHeader(y,De);let g=h.headers.getSetCookie?.();if(g?.length)u.setHeader("set-cookie",g);if(h.body)Fe.fromWeb(h.body).pipe(u);else u.end()}),o=t.port,l=0,c=()=>{s.once("error",(a)=>{if(Me(a)&&l<5){l++;let u=o+1;_.warn(`Port ${o} is in use, using ${u} instead`),o=u,c();return}_.err(He(a,{...t,port:o})),process.exit(1)}),s.listen(o,t.hostname,()=>{console.log(`${f.bold.yellowBright("\u25C6 Primdy Server")}
|
|
35
|
+
- Local: http://${t.hostname}:${o}/`),_.warn(`Primdy is optimized for Bun, and Node.js compatibility is slower
|
|
36
|
+
Consider migrating your application: https://bun.sh/`)})};return c(),s}import{stat as Pt}from"fs/promises";function Nt(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(1)} KB`}async function Mt(e){return(await Pt(e).catch(()=>({size:0}))).size}async function Ve(e){let t=e.filter((r)=>r.entries.length>0);if(!t.length)return;let i=await Promise.all(t.map((r)=>Promise.all(r.entries.slice().sort((s,o)=>s.label.localeCompare(o.label)).map(async(s)=>({label:s.label,size:await Mt(s.file)}))))),n=Math.max(...i.flat().map((r)=>r.label.length));t.forEach((r,s)=>{let o=i[s];console.log(f.bold(r.title)),o.forEach((l,c)=>{let a=c===o.length-1?"\u2514\u2500":"\u251C\u2500",u=f.dim(Nt(l.size).padStart(8));console.log(`${a} ${l.label.padEnd(n+2)}${u}`)})})}var Ie={name:"primdy",version:"0.1.1",description:"Blazingly fast, file-system routed API framework",license:"MIT",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:{primdy:"dist/server/index.js"},files:["dist"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun run build",test:"bun test"},dependencies:{chalk:"^6.0.0",commander:"^15.0.0",esbuild:"^0.28.2"},devDependencies:{"@types/bun":"^1.4.1",typescript:"^7.0.2"},engines:{bun:">=1.4.0"}};import{spawnSync as Dt}from"child_process";import{fileURLToPath as Bt}from"url";var Gt=typeof process<"u"&&!!process.versions?.bun;if(!Gt){if(!(process.argv.includes("--node")||process.argv.includes("-N")||await X(process.cwd()).then((i)=>i.node===!0).catch(()=>!1)))try{let i=Bt(import.meta.url),n=Dt("bun",[i,...process.argv.slice(2)],{stdio:"inherit",env:process.env});process.exit(n.status??0)}catch{}}process.on("uncaughtException",(e)=>{_.err(e instanceof Error?e.message:String(e)),process.exit(1)});process.on("unhandledRejection",(e)=>{_.err(e instanceof Error?e.message:String(e)),process.exit(1)});var T=new E;T.name("primdy").description("Blazingly fast, file-system routed API framework").version(Ie.version).helpOption("-h, --help","Display help").helpCommand("help","Displays this message.");async function W(e,t={}){let i=jt(process.cwd(),e),n=await X(i,{port:Number(process.env.PORT)||void 0,hostname:process.env.HOSTNAME,...t}),r=n.src??"src",s=It(i,r),o=n.port??3000,l=n.hostname??"localhost";return{cwd:i,config:n,src:r,appPath:s,port:o,hostname:l}}function je(e){let t={};if(e.port!==void 0)t.port=Number(e.port);if(e.hostname!==void 0)t.hostname=e.hostname;if(e.node!==void 0)t.node=e.node;return t}async function Wt(e){try{await Ft(e)}catch{return!1}return(await Vt(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])).some((i)=>i.isFile()&&(i.name==="route.ts"||i.name==="route.js"))}async function ie(e){if(await Wt(e))return!0;return _.err(`No application found
|
|
37
|
+
Cannot find ${e}`),!1}T.command("dev").argument("[directory]","Application directory",".").description("Starts the development server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,je(t));if(!await ie(n.appPath))process.exit(1);let r=await M(n.appPath),s=await G(n.appPath);te(r,{port:n.port,hostname:n.hostname,forceNode:n.config.node},s),Z(i)});T.command("build").argument("[directory]","Application directory",".").description("Creates a production build of your application.").action(async(e)=>{let t=performance.now(),i=await W(e);if(!await ie(i.appPath))process.exit(1);try{let{routes:n,middleware:r}=await Te(i.cwd,i.src);await Ve([{title:"Routes",entries:n.map((l)=>({label:l.pathname,file:l.file}))},{title:"Middleware",entries:r.map((l)=>({label:l.dir?`/${l.dir}`:"/",file:l.file}))}]);let s=performance.now()-t,o=s>=1000?`${(s/1000).toFixed(1)}s`:`${Math.round(s)}ms`;_.success(`Built ${n.length} routes in ${o}`)}catch(n){_.err(n instanceof Error?n.message:String(n)),process.exit(1)}});T.command("start").argument("[directory]","Application directory",".").description("Starts the production server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,je(t));try{let r=await Ae(n.cwd);te(r.routes,{port:n.port,hostname:n.hostname,forceNode:n.config.node},r.middleware),Z(i)}catch{_.err(`No production build found
|
|
38
38
|
Run ${f.bold("primdy build")} to build your application`),process.exit(1)}});T.command("analyze").argument("[directory]","Application directory",".").description("Analyzes application routes.").action(async(e)=>{let t=await W(e);if(!await ie(t.appPath))process.exit(1);let i=await M(t.appPath);for(let n of i)console.log(`${n.pathname} ${n.file}`)});await T.parseAsync();
|