UNPKG

memdisk

Version:

A library and a CLI to create RAM disk on macOS and Linux.

17 lines (16 loc) 37.5 kB
#!/usr/bin/env node let t;var e,i,r=require("node:events"),n=require("node:child_process"),s=require("node:path"),o=require("node:fs"),a=require("node:process"),l=require("which"),h=require("gensync"),u=require("./index.cjs");function p(t){return t&&t.__esModule?t:{default:t}}var m=/*#__PURE__*/p(r),d=/*#__PURE__*/p(n),c=/*#__PURE__*/p(s),g=/*#__PURE__*/p(o),f=/*#__PURE__*/p(a),_=/*#__PURE__*/p(l),O=/*#__PURE__*/p(h),A={exports:{}},v={},b={},C={};let w=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},E=class extends w{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};C.CommanderError=w,C.InvalidArgumentError=E;const{InvalidArgumentError:$}=C;let y=class{name(){return this._name}_concatValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?e.concat(t):[t]}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,e)=>{if(!this.argChoices.includes(t))throw new $(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,e):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t}this._name.length>3&&"..."===this._name.slice(-3)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}};b.Argument=y,b.humanReadableArgName=function(t){let e=t.name()+(!0===t.variadic?"...":"");return t.required?"<"+e+">":"["+e+"]"};var x={},k={};const{humanReadableArgName:H}=b;let V=class{visibleCommands(t){let e=t.commands.filter(t=>!t._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((t,e)=>t.name().localeCompare(e.name())),e}compareOptions(t,e){let i=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(t=>!t.hidden),i=t._getHelpOption();if(i&&!i.hidden){let r=i.short&&t._findOption(i.short),n=i.long&&t._findOption(i.long);r||n?i.long&&!n?e.push(t.createOption(i.long,i.description)):i.short&&!r&&e.push(t.createOption(i.short,i.description)):e.push(i)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let t=i.options.filter(t=>!t.hidden);e.push(...t)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return(t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(t=>t.description))?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(t=>H(t)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((t,i)=>Math.max(t,e.subcommandTerm(i).length),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((t,i)=>Math.max(t,e.optionTerm(i).length),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((t,i)=>Math.max(t,e.optionTerm(i).length),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((t,i)=>Math.max(t,e.argumentTerm(i).length),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let e=t.parent;e;e=e.parent)i=e.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];return(t.argChoices&&e.push(`choices: ${t.argChoices.map(t=>JSON.stringify(t)).join(", ")}`),void 0!==t.defaultValue&&(t.required||t.optional||t.isBoolean()&&"boolean"==typeof t.defaultValue)&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),void 0!==t.presetArg&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),void 0!==t.envVar&&e.push(`env: ${t.envVar}`),e.length>0)?`${t.description} (${e.join(", ")})`:t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(t=>JSON.stringify(t)).join(", ")}`),void 0!==t.defaultValue&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatHelp(t,e){let i=e.padWidth(t,e),r=e.helpWidth||80;function n(t,n){if(n){let s=`${t.padEnd(i+2)}${n}`;return e.wrap(s,r-2,i+2)}return t}function s(t){return t.join("\n").replace(/^/gm," ".repeat(2))}let o=[`Usage: ${e.commandUsage(t)}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.wrap(a,r,0),""]));let l=e.visibleArguments(t).map(t=>n(e.argumentTerm(t),e.argumentDescription(t)));l.length>0&&(o=o.concat(["Arguments:",s(l),""]));let h=e.visibleOptions(t).map(t=>n(e.optionTerm(t),e.optionDescription(t)));if(h.length>0&&(o=o.concat(["Options:",s(h),""])),this.showGlobalOptions){let i=e.visibleGlobalOptions(t).map(t=>n(e.optionTerm(t),e.optionDescription(t)));i.length>0&&(o=o.concat(["Global Options:",s(i),""]))}let u=e.visibleCommands(t).map(t=>n(e.subcommandTerm(t),e.subcommandDescription(t)));return u.length>0&&(o=o.concat(["Commands:",s(u),""])),o.join("\n")}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}wrap(t,e,i,r=40){let n=RegExp(`[\\n][ \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]+`);if(t.match(n))return t;let s=e-i;if(s<r)return t;let o=t.slice(0,i),a=t.slice(i).replace("\r\n","\n"),l=" ".repeat(i),h=`\\s\u200B`,u=RegExp(` |.{1,${s-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g");return o+(a.match(u)||[]).map((t,e)=>"\n"===t?"":(e>0?l:"")+t.trimEnd()).join("\n")}constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}};k.Help=V;var S={};const{InvalidArgumentError:P}=C;let N=class{default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return"string"==typeof t&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?e.concat(t):[t]}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,e)=>{if(!this.argChoices.includes(t))throw new P(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,e):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.name().replace(/^no-/,"").split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=function(t){let e,i;let r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),i=r.shift(),!e&&/^-[^-]$/.test(i)&&(e=i,i=void 0),{shortFlag:e,longFlag:i}}(t);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}},T=class{valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg;return e.negate===((void 0!==r&&r)===t)}constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,e)=>{this.positiveOptions.has(e)&&this.dualOptions.add(e)})}};S.Option=N,S.DualOptions=T;var M={};M.suggestSimilar=function(t,e){if(!e||0===e.length)return"";e=Array.from(new Set(e));let i=t.startsWith("--");i&&(t=t.slice(2),e=e.map(t=>t.slice(2)));let r=[],n=3;return(e.forEach(e=>{if(e.length<=1)return;let i=function(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let i=[];for(let e=0;e<=t.length;e++)i[e]=[e];for(let t=0;t<=e.length;t++)i[0][t]=t;for(let r=1;r<=e.length;r++)for(let n=1;n<=t.length;n++){let s=1;s=t[n-1]===e[r-1]?0:1,i[n][r]=Math.min(i[n-1][r]+1,i[n][r-1]+1,i[n-1][r-1]+s),n>1&&r>1&&t[n-1]===e[r-2]&&t[n-2]===e[r-1]&&(i[n][r]=Math.min(i[n][r],i[n-2][r-2]+1))}return i[t.length][e.length]}(t,e),s=Math.max(t.length,e.length);(s-i)/s>.4&&(i<n?(n=i,r=[e]):i===n&&r.push(e))}),r.sort((t,e)=>t.localeCompare(e)),i&&(r=r.map(t=>`--${t}`)),r.length>1)?` (Did you mean one of ${r.join(", ")}?)`:1===r.length?` (Did you mean ${r[0]}?)`:""};const I=m.default.EventEmitter,D=d.default,F=c.default,q=g.default,j=f.default,{Argument:W,humanReadableArgName:R}=b,{CommanderError:U}=C,{Help:G}=k,{Option:L,DualOptions:B}=S,{suggestSimilar:z}=M;let J=class t extends I{copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let r=e,n=i;"object"==typeof r&&null!==r&&(n=r,r=null),n=n||{};let[,s,o]=t.match(/([^ ]+) *(.*)/),a=this.createCommand(s);return(r&&(a.description(r),a._executableHandler=!0),n.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,o&&a.arguments(o),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r)?this:a}createCommand(e){return new t(e)}createHelp(){return Object.assign(new G,this.configureHelp())}configureHelp(t){return void 0===t?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return void 0===t?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return"string"!=typeof t&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`);return(e=e||{}).isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new W(t,e)}argument(t,e,i,r){let n=this.createArgument(t,e);return"function"==typeof i?n.default(r).argParser(i):n.default(i),this.addArgument(n),this}arguments(t){return t.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic)throw Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&void 0!==t.defaultValue&&void 0===t.parseArg)throw Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if("boolean"==typeof t)return this._addImplicitHelpCommand=t,this;let[,i,r]=(t=t??"help [command]").match(/([^ ]+) *(.*)/),n=e??"display help for command",s=this.createCommand(i);return s.helpOption(!1),r&&s.arguments(r),n&&s.description(n),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(t,e){return"object"!=typeof t?this.helpCommand(t,e):(this._addImplicitHelpCommand=!0,this._helpCommand=t),this}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw Error(`Unexpected value for event passed to hook : '${t}'. Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=t=>{if("commander.executeSubCommandAsync"!==t.code)throw t},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new U(t,e,i)),j.exit(t)}action(t){return this._actionHandler=e=>{let i=this.registeredArguments.length,r=e.slice(0,i);return this._storeOptionsAsProperties?r[i]=this:r[i]=this.opts(),r.push(this),t.apply(this,r)},this}createOption(t,e){return new L(t,e)}_callParseArg(t,e,i,r){try{return t.parseArg(e,i)}catch(t){if("commander.invalidArgument"===t.code){let e=`${r} ${t.message}`;this.error(e,{exitCode:t.exitCode,code:t.code})}throw t}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}' - already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){let e=t=>[t.name()].concat(t.aliases()),i=e(t).find(t=>this._findCommand(t));if(i){let r=e(this._findCommand(i)).join("|"),n=e(t).join("|");throw Error(`cannot add command '${n}' as already have command '${r}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();if(t.negate){let e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(i,void 0===t.defaultValue||t.defaultValue,"default")}else void 0!==t.defaultValue&&this.setOptionValueWithSource(i,t.defaultValue,"default");let r=(e,r,n)=>{null==e&&void 0!==t.presetArg&&(e=t.presetArg);let s=this.getOptionValue(i);null!==e&&t.parseArg?e=this._callParseArg(t,e,s,r):null!==e&&t.variadic&&(e=t._concatValue(e,s)),null==e&&(e=!t.negate&&(!!t.isBoolean()||!!t.optional||"")),this.setOptionValueWithSource(i,e,n)};return this.on("option:"+e,e=>{let i=`error: option '${t.flags}' argument '${e}' is invalid.`;r(e,i,"cli")}),t.envVar&&this.on("optionEnv:"+e,e=>{let i=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;r(e,i,"env")}),this}_optionEx(t,e,i,r,n){if("object"==typeof e&&e instanceof L)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(e,i);if(s.makeOptionMandatory(!!t.mandatory),"function"==typeof r)s.default(n).argParser(r);else if(r instanceof RegExp){let t=r;r=(e,i)=>{let r=t.exec(e);return r?r[0]:i},s.default(n).argParser(r)}else s.default(r);return this.addOption(s)}option(t,e,i,r){return this._optionEx({},t,e,i,r)}requiredOption(t,e,i,r){return this._optionEx({mandatory:!0},t,e,i,r)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,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(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{void 0!==i.getOptionValueSource(t)&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){let i;if(void 0!==t&&!Array.isArray(t))throw Error("first parameter to parse must be array or undefined");if(e=e||{},void 0===t&&void 0===e.from){j.versions?.electron&&(e.from="electron");let t=j.execArgv??[];(t.includes("-e")||t.includes("--eval")||t.includes("-p")||t.includes("--print"))&&(e.from="eval")}switch(void 0===t&&(t=j.argv),this.rawArgs=t.slice(),e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":j.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_executeSubCommand(t,e){let i;e=e.slice();let r=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(t,e){let i=F.resolve(t,e);if(q.existsSync(i))return i;if(n.includes(F.extname(e)))return;let r=n.find(t=>q.existsSync(`${i}${t}`));if(r)return`${i}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let t;try{t=q.realpathSync(this._scriptPath)}catch(e){t=this._scriptPath}a=F.resolve(F.dirname(t),a)}if(a){let e=s(a,o);if(!e&&!t._executableFile&&this._scriptPath){let i=F.basename(this._scriptPath,F.extname(this._scriptPath));i!==this._name&&(e=s(a,`${i}-${t._name}`))}o=e||o}r=n.includes(F.extname(o)),"win32"!==j.platform?r?(e.unshift(o),e=Y(j.execArgv).concat(e),i=D.spawn(j.argv[0],e,{stdio:"inherit"})):i=D.spawn(o,e,{stdio:"inherit"}):(e.unshift(o),e=Y(j.execArgv).concat(e),i=D.spawn(j.execPath,e,{stdio:"inherit"})),i.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(t=>{j.on(t,()=>{!1===i.killed&&null===i.exitCode&&i.kill(t)})});let l=this._exitCallback;i.on("close",t=>{t=t??1,l?l(new U(t,"commander.executeSubCommandAsync","(close)")):j.exit(t)}),i.on("error",e=>{if("ENOENT"===e.code){let e=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";throw Error(`'${o}' does not exist - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - ${e}`)}if("EACCES"===e.code)throw Error(`'${o}' not executable`);if(l){let t=new U(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e,l(t)}else j.exit(1)}),this.runningCommand=i}_dispatchSubcommand(t,e,i){let r;let n=this._findCommand(t);return n||this.help({error:!0}),r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(!n._executableHandler)return n._parseCommand(e,i);this._executeSubCommand(n,e.concat(i))})}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&null==this.args[e]&&this.missingArgument(t.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||!(this.args.length>this.registeredArguments.length)||this._excessArguments(this.args)}_processArguments(){let t=(t,e,i)=>{let r=e;if(null!==e&&t.parseArg){let n=`error: command-argument value '${e}' is invalid for argument '${t.name()}'.`;r=this._callParseArg(t,e,i,n)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,r)=>{let n=i.defaultValue;i.variadic?r<this.args.length?(n=this.args.slice(r),i.parseArg&&(n=n.reduce((e,r)=>t(i,r,e),i.defaultValue))):void 0===n&&(n=[]):r<this.args.length&&(n=this.args[r],i.parseArg&&(n=t(i,n,i.defaultValue))),e[r]=n}),this.processedArgs=e}_chainOrCall(t,e){return t&&t.then&&"function"==typeof t.then?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,r=[];return this._getCommandAndAncestors().reverse().filter(t=>void 0!==t._lifeCycleHooks[e]).forEach(t=>{t._lifeCycleHooks[e].forEach(e=>{r.push({hookedCommand:t,callback:e})})}),"postAction"===e&&r.reverse(),r.forEach(t=>{i=this._chainOrCall(i,()=>t.callback(t.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let r=t;return void 0!==this._lifeCycleHooks[i]&&this._lifeCycleHooks[i].forEach(t=>{r=this._chainOrCall(r,()=>t(this,e))}),r}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){let i;return r(),this._processArguments(),i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(n,t,e)})),i=this._chainOrCallHooks(i,"postAction")}if(this.parent&&this.parent.listenerCount(n))r(),this._processArguments(),this.parent.emit(n,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&void 0===t.getOptionValue(e.attributeName())&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(t=>{let e=t.attributeName();return void 0!==this.getOptionValue(e)&&"default"!==this.getOptionValueSource(e)});t.filter(t=>t.conflictsWith.length>0).forEach(e=>{let i=t.find(t=>e.conflictsWith.includes(t.attributeName()));i&&this._conflictingOption(e,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],r=e,n=t.slice();function s(t){return t.length>1&&"-"===t[0]}let o=null;for(;n.length;){let t=n.shift();if("--"===t){r===i&&r.push(t),r.push(...n);break}if(o&&!s(t)){this.emit(`option:${o.name()}`,t);continue}if(o=null,s(t)){let e=this._findOption(t);if(e){if(e.required){let t=n.shift();void 0===t&&this.optionMissingArgument(e),this.emit(`option:${e.name()}`,t)}else if(e.optional){let t=null;n.length>0&&!s(n[0])&&(t=n.shift()),this.emit(`option:${e.name()}`,t)}else this.emit(`option:${e.name()}`);o=e.variadic?e:null;continue}}if(t.length>2&&"-"===t[0]&&"-"!==t[1]){let e=this._findOption(`-${t[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,t.slice(2)):(this.emit(`option:${e.name()}`),n.unshift(`-${t.slice(2)}`));continue}}if(/^--[^=]+=/.test(t)){let e=t.indexOf("="),i=this._findOption(t.slice(0,e));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(e+1));continue}}if(s(t)&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&0===e.length&&0===i.length){if(this._findCommand(t)){e.push(t),n.length>0&&i.push(...n);break}if(this._getHelpCommand()&&t===this._getHelpCommand().name()){e.push(t),n.length>0&&e.push(...n);break}if(this._defaultCommandName){i.push(t),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){r.push(t),n.length>0&&r.push(...n);break}r.push(t)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let e=this.options[i].attributeName();t[e]=e===this._versionOptionName?this._version:this[e]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t} `,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError} `):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));let i=e||{},r=i.exitCode||1,n=i.code||"commander.error";this._exit(r,n,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in j.env){let e=t.attributeName();(void 0===this.getOptionValue(e)||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,j.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new B(this.options),e=t=>void 0!==this.getOptionValue(t)&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter(i=>void 0!==i.implied&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(t=>{Object.keys(t.implied).filter(t=>!e(t)).forEach(e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=t=>{let e=t.attributeName(),i=this.getOptionValue(e),r=this.options.find(t=>t.negate&&e===t.attributeName()),n=this.options.find(t=>!t.negate&&e===t.attributeName());return r&&(void 0===r.presetArg&&!1===i||void 0!==r.presetArg&&i===r.presetArg)?r:n||t},r=t=>{let e=i(t),r=e.attributeName();return"env"===this.getOptionValueSource(r)?`environment variable '${e.envVar}'`:`option '${e.flags}'`},n=`error: ${r(t)} cannot be used with ${r(e)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[],r=this;do{let t=r.createHelp().visibleOptions(r).filter(t=>t.long).map(t=>t.long);i=i.concat(t),r=r.parent}while(r&&!r._enablePositionalOptions);e=z(t,i)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=this.parent?` for '${this.name()}'`:"",r=`error: too many arguments${i}. Expected ${e} argument${1===e?"":"s"} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(t=>{i.push(t.name()),t.alias()&&i.push(t.alias())}),e=z(t,i)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(void 0===t)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let r=this.createOption(e,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${t} `),this._exit(0,"commander.version",t)}),this}description(t,e){return void 0===t&&void 0===e?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return void 0===t?this._summary:(this._summary=t,this)}alias(t){if(void 0===t)return this._aliases[0];let e=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let e=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${e}'`)}return e._aliases.push(t),this}aliases(t){return void 0===t?this._aliases:(t.forEach(t=>this.alias(t)),this)}usage(t){if(void 0===t){if(this._usage)return this._usage;let t=this.registeredArguments.map(t=>R(t));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=t,this}name(t){return void 0===t?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=F.basename(t,F.extname(t)),this}executableDir(t){return void 0===t?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp();return void 0===e.helpWidth&&(e.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),e.formatHelp(this,e)}_getHelpContext(t){let e;let i={error:!!(t=t||{}).error};return e=i.error?t=>this._outputConfiguration.writeErr(t):t=>this._outputConfiguration.writeOut(t),i.write=t.write||e,i.command=this,i}outputHelp(t){let e;"function"==typeof t&&(e=t,t=void 0);let i=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach(t=>t.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let r=this.helpInformation(i);if(e&&"string"!=typeof(r=e(r))&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(t=>t.emit("afterAllHelp",i))}helpOption(t,e){return"boolean"==typeof t?t?this._helpOption=this._helpOption??void 0:this._helpOption=null:(t=t??"-h, --help",e=e??"display help for command",this._helpOption=this.createOption(t,e)),this}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let e=j.exitCode||0;0===e&&t&&"function"!=typeof t&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw Error(`Unexpected value for position to addHelpText. Expecting one of '${i.join("', '")}'`);let r=`${t}Help`;return this.on(r,t=>{let i;(i="function"==typeof e?e({error:t.error,command:t.command}):e)&&t.write(`${i} `)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(t=>e.is(t))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}constructor(t){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=t||"",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:t=>j.stdout.write(t),writeErr:t=>j.stderr.write(t),getOutHelpWidth:()=>j.stdout.isTTY?j.stdout.columns:void 0,getErrHelpWidth:()=>j.stderr.isTTY?j.stderr.columns:void 0,outputError:(t,e)=>e(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}};function Y(t){return t.map(t=>{let e,i;if(!t.startsWith("--inspect"))return t;let r="127.0.0.1",n="9229";return(null!==(i=t.match(/^(--inspect(-brk)?)$/))?e=i[1]:null!==(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(e=i[1],/^\d+$/.test(i[3])?n=i[3]:r=i[3]):null!==(i=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(e=i[1],r=i[3],n=i[4]),e&&"0"!==n)?`${e}=${r}:${parseInt(n)+1}`:t})}x.Command=J;const{Argument:K}=b,{Command:Q}=x,{CommanderError:X,InvalidArgumentError:Z}=C,{Help:tt}=k,{Option:te}=S;v.program=new Q,v.createCommand=t=>new Q(t),v.createOption=(t,e)=>new te(t,e),v.createArgument=(t,e)=>new K(t,e),v.Command=Q,v.Option=te,v.Argument=K,v.Help=tt,v.CommanderError=X,v.InvalidArgumentError=Z,v.InvalidOptionArgumentError=Z,e=A.exports,(e=A.exports={}).program=new v.Command,e.Argument=v.Argument,e.Command=v.Command,e.CommanderError=v.CommanderError,e.Help=v.Help,e.InvalidArgumentError=v.InvalidArgumentError,e.InvalidOptionArgumentError=v.InvalidArgumentError,e.Option=v.Option,e.createCommand=t=>new v.Command(t),e.createOption=(t,e)=>new v.Option(t,e),e.createArgument=(t,e)=>new v.Argument(t,e);const{program:ti,createCommand:tr,createArgument:tn,createOption:ts,CommanderError:to,InvalidArgumentError:ta,InvalidOptionArgumentError:tl,Command:th,Argument:tu,Option:tp,Help:tm}=(i=A.exports)&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i,td=_.default.sync,tc=O.default({sync:td,async:_.default});O.default(function*(e){return(void 0===t&&(t=yield*tc("sudo",{nothrow:!0})),null===t)?e:t+" "+e});const tg=t=>"darwin"===a.platform?`/Volumes/${t}`:`/mnt/${t}`,tf=/^\d+$/,t_=/(\d+)\s*([a-z]+)/i,tO=t=>{if(tf.test(t))return Number.parseInt(t,10);let e=t_.exec(t);if(!e||e.length<2)throw TypeError("Invalid size: "+t);let i=Number.parseInt(e[1],10);if(Number.isNaN(i))throw TypeError("Invalid size: "+t);let r=e[2].toLowerCase();switch(r.endsWith("s")&&(r=r.slice(0,-1)),r){case"b":case"byte":return i;case"k":case"kib":return 1024*i;case"kb":return 1e3*i;case"m":case"mib":return 1048576*i;case"mb":return 1e6*i;case"g":case"gib":return 1073741824*i;case"gb":return 1e9*i;case"t":case"tib":return 1099511627776*i;case"tb":return 1e12*i;default:throw TypeError("Not supported unit: "+r)}},tA=(t,e)=>{let i=s.relative(t,e);return i.length>0&&!i.startsWith("..")&&!s.isAbsolute(i)};(()=>{let t=new th("memdisk").version("1.2.1").description("CLI to create and destroy RAM disks").option("--silent, --quiet","Disable messages",!1).option("--no-throw-on-not-supported-platform","Do not throw an error if the current platform doesn't support RAM disks",!1).option("--throw-on-not-supported-platform","Throw an error if the current platform doesn't support RAM disks",!0);t.command("create").description("Create a RAM disk with size and disk name").argument("<size>","Size of the RAM disk, accepts number or string with unit (e.g. 16mb, 32mib, 128m, 1G, 4g, 8gib, etc.)").argument("[name]",'Name of the RAM disk, default is "ramdisk"',"ramdisk").option("--darwin-use-hfs-plus","Use HFS+ instead of APFS on macOS",!1).action((e,i,{darwinUseHfsPlus:r})=>{let n=tO(e);if(s.isAbsolute(i))throw TypeError("[name] must not be a path");let{quiet:o,throwOnNotSupportedPlatform:a}=t.opts();u.create.sync(i,n,{quiet:o,throwOnNotSupportedPlatform:a,darwinUseHFSPlus:r})}),t.command("destroy").description("Destroy a RAM disk with name or path").argument("[nameOrPath]",'Name or path of the RAM disk (if argument is not an absolute path, it will be treated as a name), default is "ramdisk"',"ramdisk").option("--force","Force unmouting and removing the RAM disk",!1).action((e,{force:i})=>{let r=s.isAbsolute(e)?e:tg(e);if(tA(r,a.cwd()))throw Error("Cannot perform destroy as the current working directory is in the RAM disk to be destroyed");let{quiet:n,throwOnNotSupportedPlatform:o}=t.opts();u.destroy.sync(r,{quiet:n,throwOnNotSupportedPlatform:o,force:i})}),t.showHelpAfterError().showSuggestionAfterError(),t.parse()})();