domani 0.4.12 → 0.4.14

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.
Files changed (2) hide show
  1. package/dist/domani.cjs +183 -172
  2. package/package.json +1 -1
package/dist/domani.cjs CHANGED
@@ -1,266 +1,266 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var _o=Object.create;var Fs=Object.defineProperty;var So=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var ko=Object.getPrototypeOf,jo=Object.prototype.hasOwnProperty;var xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var nt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Nt=(t,e)=>{for(var s in e)Fs(t,s,{get:e[s],enumerable:!0})},Co=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xo(e))!jo.call(t,n)&&n!==s&&Fs(t,n,{get:()=>e[n],enumerable:!(i=So(e,n))||i.enumerable});return t};var F=(t,e,s)=>(s=t!=null?_o(ko(t)):{},Co(e||!t||!t.__esModule?Fs(s,"default",{value:t,enumerable:!0}):s,t));var Ht=nt(Us=>{var rs=class extends Error{constructor(e,s,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=s,this.exitCode=e,this.nestedError=void 0}},Ls=class extends rs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Us.CommanderError=rs;Us.InvalidArgumentError=Ls});var os=nt(Vs=>{var{InvalidArgumentError:Oo}=Ht(),Ms=class{constructor(e,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,s){return s===this.defaultValue||!Array.isArray(s)?[e]:s.concat(e)}default(e,s){return this.defaultValue=e,this.defaultValueDescription=s,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(s,i)=>{if(!this.argChoices.includes(s))throw new Oo(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(s,i):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ro(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Vs.Argument=Ms;Vs.humanReadableArgName=Ro});var Hs=nt(Ws=>{var{humanReadableArgName:Io}=os(),qs=class{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 s=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&s.push(i),this.sortSubcommands&&s.sort((n,r)=>n.name().localeCompare(r.name())),s}compareOptions(e,s){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(s))}visibleOptions(e){let s=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);!n&&!r?s.push(i):i.long&&!r?s.push(e.createOption(i.long,i.description)):i.short&&!n&&s.push(e.createOption(i.short,i.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let s=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);s.push(...n)}return this.sortOptions&&s.sort(this.compareOptions),s}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(s=>{s.description=s.description||e._argsDescription[s.name()]||""}),e.registeredArguments.find(s=>s.description)?e.registeredArguments:[]}subcommandTerm(e){let s=e.registeredArguments.map(i=>Io(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(s?" "+s:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,s){return s.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(n)))),0)}longestOptionTermLength(e,s){return s.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleOptionTerm(s.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,s){return s.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleOptionTerm(s.optionTerm(n)))),0)}longestArgumentTermLength(e,s){return s.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(n)))),0)}commandUsage(e){let s=e._name;e._aliases[0]&&(s=s+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+s+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let s=[];return e.argChoices&&s.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&s.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&s.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&s.push(`env: ${e.envVar}`),s.length>0?`${e.description} (${s.join(", ")})`:e.description}argumentDescription(e){let s=[];if(e.argChoices&&s.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&s.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),s.length>0){let i=`(${s.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,s){let i=s.padWidth(e,s),n=s.helpWidth??80;function r(f,p){return s.formatItem(f,i,p,s)}let o=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(e))}`,""],a=s.commandDescription(e);a.length>0&&(o=o.concat([s.boxWrap(s.styleCommandDescription(a),n),""]));let l=s.visibleArguments(e).map(f=>r(s.styleArgumentTerm(s.argumentTerm(f)),s.styleArgumentDescription(s.argumentDescription(f))));l.length>0&&(o=o.concat([s.styleTitle("Arguments:"),...l,""]));let c=s.visibleOptions(e).map(f=>r(s.styleOptionTerm(s.optionTerm(f)),s.styleOptionDescription(s.optionDescription(f))));if(c.length>0&&(o=o.concat([s.styleTitle("Options:"),...c,""])),s.showGlobalOptions){let f=s.visibleGlobalOptions(e).map(p=>r(s.styleOptionTerm(s.optionTerm(p)),s.styleOptionDescription(s.optionDescription(p))));f.length>0&&(o=o.concat([s.styleTitle("Global Options:"),...f,""]))}let d=s.visibleCommands(e).map(f=>r(s.styleSubcommandTerm(s.subcommandTerm(f)),s.styleSubcommandDescription(s.subcommandDescription(f))));return d.length>0&&(o=o.concat([s.styleTitle("Commands:"),...d,""])),o.join(`
3
- `)}displayWidth(e){return en(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s==="[command]"?this.styleSubcommandText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleCommandText(s)).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(s=>s==="[options]"?this.styleOptionText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleSubcommandText(s)).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,s){return Math.max(s.longestOptionTermLength(e,s),s.longestGlobalOptionTermLength(e,s),s.longestSubcommandTermLength(e,s),s.longestArgumentTermLength(e,s))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,s,i,n){let o=" ".repeat(2);if(!i)return o+e;let a=e.padEnd(s+e.length-n.displayWidth(e)),l=2,d=(this.helpWidth??80)-s-l-2,f;return d<this.minWidthToWrap||n.preformatted(i)?f=i:f=n.boxWrap(i,d).replace(/\n/g,`
2
+ "use strict";var Ro=Object.create;var Ms=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Ao=Object.getOwnPropertyNames;var To=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var rt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ft=(t,e)=>{for(var s in e)Ms(t,s,{get:e[s],enumerable:!0})},Do=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ao(e))!Eo.call(t,n)&&n!==s&&Ms(t,n,{get:()=>e[n],enumerable:!(i=Io(e,n))||i.enumerable});return t};var F=(t,e,s)=>(s=t!=null?Ro(To(t)):{},Do(e||!t||!t.__esModule?Ms(s,"default",{value:t,enumerable:!0}):s,t));var Jt=rt(qs=>{var os=class extends Error{constructor(e,s,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=s,this.exitCode=e,this.nestedError=void 0}},Vs=class extends os{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};qs.CommanderError=os;qs.InvalidArgumentError=Vs});var as=rt(Hs=>{var{InvalidArgumentError:Po}=Jt(),Ws=class{constructor(e,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,s){return s===this.defaultValue||!Array.isArray(s)?[e]:s.concat(e)}default(e,s){return this.defaultValue=e,this.defaultValueDescription=s,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(s,i)=>{if(!this.argChoices.includes(s))throw new Po(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(s,i):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function No(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Hs.Argument=Ws;Hs.humanReadableArgName=No});var Gs=rt(Bs=>{var{humanReadableArgName:Fo}=as(),Js=class{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 s=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&s.push(i),this.sortSubcommands&&s.sort((n,r)=>n.name().localeCompare(r.name())),s}compareOptions(e,s){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(s))}visibleOptions(e){let s=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);!n&&!r?s.push(i):i.long&&!r?s.push(e.createOption(i.long,i.description)):i.short&&!n&&s.push(e.createOption(i.short,i.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let s=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(r=>!r.hidden);s.push(...n)}return this.sortOptions&&s.sort(this.compareOptions),s}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(s=>{s.description=s.description||e._argsDescription[s.name()]||""}),e.registeredArguments.find(s=>s.description)?e.registeredArguments:[]}subcommandTerm(e){let s=e.registeredArguments.map(i=>Fo(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(s?" "+s:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,s){return s.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(n)))),0)}longestOptionTermLength(e,s){return s.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleOptionTerm(s.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,s){return s.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleOptionTerm(s.optionTerm(n)))),0)}longestArgumentTermLength(e,s){return s.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(n)))),0)}commandUsage(e){let s=e._name;e._aliases[0]&&(s=s+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+s+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let s=[];return e.argChoices&&s.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&s.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&s.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&s.push(`env: ${e.envVar}`),s.length>0?`${e.description} (${s.join(", ")})`:e.description}argumentDescription(e){let s=[];if(e.argChoices&&s.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&s.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),s.length>0){let i=`(${s.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,s){let i=s.padWidth(e,s),n=s.helpWidth??80;function r(f,p){return s.formatItem(f,i,p,s)}let o=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(e))}`,""],a=s.commandDescription(e);a.length>0&&(o=o.concat([s.boxWrap(s.styleCommandDescription(a),n),""]));let l=s.visibleArguments(e).map(f=>r(s.styleArgumentTerm(s.argumentTerm(f)),s.styleArgumentDescription(s.argumentDescription(f))));l.length>0&&(o=o.concat([s.styleTitle("Arguments:"),...l,""]));let c=s.visibleOptions(e).map(f=>r(s.styleOptionTerm(s.optionTerm(f)),s.styleOptionDescription(s.optionDescription(f))));if(c.length>0&&(o=o.concat([s.styleTitle("Options:"),...c,""])),s.showGlobalOptions){let f=s.visibleGlobalOptions(e).map(p=>r(s.styleOptionTerm(s.optionTerm(p)),s.styleOptionDescription(s.optionDescription(p))));f.length>0&&(o=o.concat([s.styleTitle("Global Options:"),...f,""]))}let u=s.visibleCommands(e).map(f=>r(s.styleSubcommandTerm(s.subcommandTerm(f)),s.styleSubcommandDescription(s.subcommandDescription(f))));return u.length>0&&(o=o.concat([s.styleTitle("Commands:"),...u,""])),o.join(`
3
+ `)}displayWidth(e){return rn(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s==="[command]"?this.styleSubcommandText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleCommandText(s)).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(s=>s==="[options]"?this.styleOptionText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleSubcommandText(s)).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,s){return Math.max(s.longestOptionTermLength(e,s),s.longestGlobalOptionTermLength(e,s),s.longestSubcommandTermLength(e,s),s.longestArgumentTermLength(e,s))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,s,i,n){let o=" ".repeat(2);if(!i)return o+e;let a=e.padEnd(s+e.length-n.displayWidth(e)),l=2,u=(this.helpWidth??80)-s-l-2,f;return u<this.minWidthToWrap||n.preformatted(i)?f=i:f=n.boxWrap(i,u).replace(/\n/g,`
4
4
  `+" ".repeat(s+l)),o+a+" ".repeat(l)+f.replace(/\n/g,`
5
- ${o}`)}boxWrap(e,s){if(s<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach(d=>{let f=this.displayWidth(d);if(c+f<=s){l.push(d),c+=f;return}r.push(l.join(""));let p=d.trimStart();l=[p],c=this.displayWidth(p)}),r.push(l.join(""))}),r.join(`
6
- `)}};function en(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}Ws.Help=qs;Ws.stripColor=en});var Ys=nt(Gs=>{var{InvalidArgumentError:Ao}=Ht(),Js=class{constructor(e,s){this.flags=e,this.description=s||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=To(e);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}default(e,s){return this.defaultValue=e,this.defaultValueDescription=s,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let s=e;return typeof e=="string"&&(s={[e]:!0}),this.implied=Object.assign(this.implied||{},s),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,s){return s===this.defaultValue||!Array.isArray(s)?[e]:s.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(s,i)=>{if(!this.argChoices.includes(s))throw new Ao(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(s,i):s},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?tn(this.name().replace(/^no-/,"")):tn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Bs=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(s=>{s.negate?this.negativeOptions.set(s.attributeName(),s):this.positiveOptions.set(s.attributeName(),s)}),this.negativeOptions.forEach((s,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,s){let i=s.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return s.negate===(r===e)}};function tn(t){return t.split("-").reduce((e,s)=>e+s[0].toUpperCase()+s.slice(1))}function To(t){let e,s,i=/^-[^-]$/,n=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(e=r.shift()),n.test(r[0])&&(s=r.shift()),!e&&i.test(r[0])&&(e=r.shift()),!e&&n.test(r[0])&&(e=s,s=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
5
+ ${o}`)}boxWrap(e,s){if(s<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach(u=>{let f=this.displayWidth(u);if(c+f<=s){l.push(u),c+=f;return}r.push(l.join(""));let p=u.trimStart();l=[p],c=this.displayWidth(p)}),r.push(l.join(""))}),r.join(`
6
+ `)}};function rn(t){let e=/\x1b\[\d*(;\d*)*m/g;return t.replace(e,"")}Bs.Help=Js;Bs.stripColor=rn});var Xs=rt(zs=>{var{InvalidArgumentError:Lo}=Jt(),Ys=class{constructor(e,s){this.flags=e,this.description=s||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=Uo(e);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}default(e,s){return this.defaultValue=e,this.defaultValueDescription=s,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let s=e;return typeof e=="string"&&(s={[e]:!0}),this.implied=Object.assign(this.implied||{},s),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,s){return s===this.defaultValue||!Array.isArray(s)?[e]:s.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(s,i)=>{if(!this.argChoices.includes(s))throw new Lo(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(s,i):s},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?on(this.name().replace(/^no-/,"")):on(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ks=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(s=>{s.negate?this.negativeOptions.set(s.attributeName(),s):this.positiveOptions.set(s.attributeName(),s)}),this.negativeOptions.forEach((s,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,s){let i=s.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return s.negate===(r===e)}};function on(t){return t.split("-").reduce((e,s)=>e+s[0].toUpperCase()+s.slice(1))}function Uo(t){let e,s,i=/^-[^-]$/,n=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(e=r.shift()),n.test(r[0])&&(s=r.shift()),!e&&i.test(r[0])&&(e=r.shift()),!e&&n.test(r[0])&&(e=s,s=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
9
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${a}
10
10
  - too many short flags`):n.test(o)?new Error(`${a}
11
11
  - too many long flags`):new Error(`${a}
12
- - unrecognised flag format`)}if(e===void 0&&s===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:s}}Gs.Option=Js;Gs.DualOptions=Bs});var nn=nt(sn=>{function Eo(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let s=[];for(let i=0;i<=t.length;i++)s[i]=[i];for(let i=0;i<=e.length;i++)s[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=t.length;n++){let r=1;t[n-1]===e[i-1]?r=0:r=1,s[n][i]=Math.min(s[n-1][i]+1,s[n][i-1]+1,s[n-1][i-1]+r),n>1&&i>1&&t[n-1]===e[i-2]&&t[n-2]===e[i-1]&&(s[n][i]=Math.min(s[n][i],s[n-2][i-2]+1))}return s[t.length][e.length]}function Do(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let s=t.startsWith("--");s&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let i=[],n=3,r=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Eo(t,o),l=Math.max(t.length,o.length);(l-a)/l>r&&(a<n?(n=a,i=[o]):a===n&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),s&&(i=i.map(o=>`--${o}`)),i.length>1?`
12
+ - unrecognised flag format`)}if(e===void 0&&s===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:s}}zs.Option=Ys;zs.DualOptions=Ks});var ln=rt(an=>{function Mo(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let s=[];for(let i=0;i<=t.length;i++)s[i]=[i];for(let i=0;i<=e.length;i++)s[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=t.length;n++){let r=1;t[n-1]===e[i-1]?r=0:r=1,s[n][i]=Math.min(s[n-1][i]+1,s[n][i-1]+1,s[n-1][i-1]+r),n>1&&i>1&&t[n-1]===e[i-2]&&t[n-2]===e[i-1]&&(s[n][i]=Math.min(s[n][i],s[n-2][i-2]+1))}return s[t.length][e.length]}function Vo(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let s=t.startsWith("--");s&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let i=[],n=3,r=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Mo(t,o),l=Math.max(t.length,o.length);(l-a)/l>r&&(a<n?(n=a,i=[o]):a===n&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),s&&(i=i.map(o=>`--${o}`)),i.length>1?`
13
13
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
14
- (Did you mean ${i[0]}?)`:""}sn.suggestSimilar=Do});var ln=nt(Qs=>{var Po=require("node:events").EventEmitter,Ks=require("node:child_process"),rt=require("node:path"),as=require("node:fs"),se=require("node:process"),{Argument:No,humanReadableArgName:Fo}=os(),{CommanderError:zs}=Ht(),{Help:Lo,stripColor:Uo}=Hs(),{Option:rn,DualOptions:Mo}=Ys(),{suggestSimilar:on}=nn(),Xs=class t extends Po{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:s=>se.stdout.write(s),writeErr:s=>se.stderr.write(s),outputError:(s,i)=>i(s),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,getOutHasColors:()=>Zs()??(se.stdout.isTTY&&se.stdout.hasColors?.()),getErrHasColors:()=>Zs()??(se.stderr.isTTY&&se.stderr.hasColors?.()),stripColor:s=>Uo(s)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let s=this;s;s=s.parent)e.push(s);return e}command(e,s,i){let n=s,r=i;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),r.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Lo,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,s){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);return s=s||{},s.isDefault&&(this._defaultCommandName=e._name),(s.noHelp||s.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,s){return new No(e,s)}argument(e,s,i,n){let r=this.createArgument(e,s);return typeof i=="function"?r.default(n).argParser(i):r.default(i),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(s=>{this.argument(s)}),this}addArgument(e){let s=this.registeredArguments.slice(-1)[0];if(s&&s.variadic)throw new Error(`only the last argument can be variadic '${s.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,s){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),r=s??"display help for command",o=this.createCommand(i);return o.helpOption(!1),n&&o.arguments(n),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,s){return typeof e!="object"?(this.helpCommand(e,s),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,s){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
- Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(s):this._lifeCycleHooks[e]=[s],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=s=>{if(s.code!=="commander.executeSubCommandAsync")throw s},this}_exit(e,s,i){this._exitCallback&&this._exitCallback(new zs(e,s,i)),se.exit(e)}action(e){let s=i=>{let n=this.registeredArguments.length,r=i.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=s,this}createOption(e,s){return new rn(e,s)}_callParseArg(e,s,i,n){try{return e.parseArg(s,i)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${n} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let s=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(s){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
17
- - already used by option '${s.flags}'`)}this.options.push(e)}_registerCommand(e){let s=n=>[n.name()].concat(n.aliases()),i=s(e).find(n=>this._findCommand(n));if(i){let n=s(this._findCommand(i)).join("|"),r=s(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let s=e.name(),i=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,o,a)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let l=this.getOptionValue(i);r!==null&&e.parseArg?r=this._callParseArg(e,r,l,o):r!==null&&e.variadic&&(r=e._concatValue(r,l)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,a)};return this.on("option:"+s,r=>{let o=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),e.envVar&&this.on("optionEnv:"+s,r=>{let o=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(e,s,i,n,r){if(typeof s=="object"&&s instanceof rn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(s,i);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,c)=>{let d=a.exec(l);return d?d[0]:c},o.default(r).argParser(n)}else o.default(n);return this.addOption(o)}option(e,s,i,n){return this._optionEx({},e,s,i,n)}requiredOption(e,s,i,n){return this._optionEx({mandatory:!0},e,s,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 new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,s){return this.setOptionValueWithSource(e,s,void 0)}setOptionValueWithSource(e,s,i){return this._storeOptionsAsProperties?this[e]=s:this._optionValues[e]=s,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let s;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(s=i.getOptionValueSource(e))}),s}_prepareUserArgs(e,s){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(s=s||{},e===void 0&&s.from===void 0){se.versions?.electron&&(s.from="electron");let n=se.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(s.from="eval")}e===void 0&&(e=se.argv),this.rawArgs=e.slice();let i;switch(s.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${s.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,s){this._prepareForParse();let i=this._prepareUserArgs(e,s);return this._parseCommand([],i),this}async parseAsync(e,s){this._prepareForParse();let i=this._prepareUserArgs(e,s);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
18
- - 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,s,i){if(as.existsSync(e))return;let n=s?`searched for local subcommand relative to directory '${s}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
14
+ (Did you mean ${i[0]}?)`:""}an.suggestSimilar=Vo});var mn=rt(si=>{var qo=require("node:events").EventEmitter,Zs=require("node:child_process"),ot=require("node:path"),ls=require("node:fs"),se=require("node:process"),{Argument:Wo,humanReadableArgName:Ho}=as(),{CommanderError:Qs}=Jt(),{Help:Jo,stripColor:Bo}=Gs(),{Option:cn,DualOptions:Go}=Xs(),{suggestSimilar:dn}=ln(),ei=class t extends qo{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:s=>se.stdout.write(s),writeErr:s=>se.stderr.write(s),outputError:(s,i)=>i(s),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,getOutHasColors:()=>ti()??(se.stdout.isTTY&&se.stdout.hasColors?.()),getErrHasColors:()=>ti()??(se.stderr.isTTY&&se.stderr.hasColors?.()),stripColor:s=>Bo(s)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let s=this;s;s=s.parent)e.push(s);return e}command(e,s,i){let n=s,r=i;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),r.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Jo,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,s){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);return s=s||{},s.isDefault&&(this._defaultCommandName=e._name),(s.noHelp||s.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,s){return new Wo(e,s)}argument(e,s,i,n){let r=this.createArgument(e,s);return typeof i=="function"?r.default(n).argParser(i):r.default(i),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(s=>{this.argument(s)}),this}addArgument(e){let s=this.registeredArguments.slice(-1)[0];if(s&&s.variadic)throw new Error(`only the last argument can be variadic '${s.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,s){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),r=s??"display help for command",o=this.createCommand(i);return o.helpOption(!1),n&&o.arguments(n),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,s){return typeof e!="object"?(this.helpCommand(e,s),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,s){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
+ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(s):this._lifeCycleHooks[e]=[s],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=s=>{if(s.code!=="commander.executeSubCommandAsync")throw s},this}_exit(e,s,i){this._exitCallback&&this._exitCallback(new Qs(e,s,i)),se.exit(e)}action(e){let s=i=>{let n=this.registeredArguments.length,r=i.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=s,this}createOption(e,s){return new cn(e,s)}_callParseArg(e,s,i,n){try{return e.parseArg(s,i)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${n} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let s=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(s){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
17
+ - already used by option '${s.flags}'`)}this.options.push(e)}_registerCommand(e){let s=n=>[n.name()].concat(n.aliases()),i=s(e).find(n=>this._findCommand(n));if(i){let n=s(this._findCommand(i)).join("|"),r=s(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let s=e.name(),i=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,o,a)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let l=this.getOptionValue(i);r!==null&&e.parseArg?r=this._callParseArg(e,r,l,o):r!==null&&e.variadic&&(r=e._concatValue(r,l)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,a)};return this.on("option:"+s,r=>{let o=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),e.envVar&&this.on("optionEnv:"+s,r=>{let o=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(e,s,i,n,r){if(typeof s=="object"&&s instanceof cn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(s,i);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(r).argParser(n)}else o.default(n);return this.addOption(o)}option(e,s,i,n){return this._optionEx({},e,s,i,n)}requiredOption(e,s,i,n){return this._optionEx({mandatory:!0},e,s,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 new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,s){return this.setOptionValueWithSource(e,s,void 0)}setOptionValueWithSource(e,s,i){return this._storeOptionsAsProperties?this[e]=s:this._optionValues[e]=s,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let s;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(s=i.getOptionValueSource(e))}),s}_prepareUserArgs(e,s){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(s=s||{},e===void 0&&s.from===void 0){se.versions?.electron&&(s.from="electron");let n=se.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(s.from="eval")}e===void 0&&(e=se.argv),this.rawArgs=e.slice();let i;switch(s.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${s.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,s){this._prepareForParse();let i=this._prepareUserArgs(e,s);return this._parseCommand([],i),this}async parseAsync(e,s){this._prepareForParse();let i=this._prepareUserArgs(e,s);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - 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,s,i){if(ls.existsSync(e))return;let n=s?`searched for local subcommand relative to directory '${s}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
19
19
  - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${n}`;throw new Error(r)}_executeSubCommand(e,s){s=s.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(d,f){let p=rt.resolve(d,f);if(as.existsSync(p))return p;if(n.includes(rt.extname(f)))return;let $=n.find(w=>as.existsSync(`${p}${w}`));if($)return`${p}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=as.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=rt.resolve(rt.dirname(d),a)}if(a){let d=r(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=rt.basename(this._scriptPath,rt.extname(this._scriptPath));f!==this._name&&(d=r(a,`${f}-${e._name}`))}o=d||o}i=n.includes(rt.extname(o));let l;se.platform!=="win32"?i?(s.unshift(o),s=an(se.execArgv).concat(s),l=Ks.spawn(se.argv[0],s,{stdio:"inherit"})):l=Ks.spawn(o,s,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),s.unshift(o),s=an(se.execArgv).concat(s),l=Ks.spawn(se.execPath,s,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{se.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",d=>{d=d??1,c?c(new zs(d,"commander.executeSubCommandAsync","(close)")):se.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)se.exit(1);else{let f=new zs(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,c(f)}}),this.runningCommand=l}_dispatchSubcommand(e,s,i){let n=this._findCommand(e);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,s.concat(i));else return n._parseCommand(s,i)}),r}_dispatchHelpCommand(e){e||this.help();let s=this._findCommand(e);return s&&!s._executableHandler&&s.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,s)=>{e.required&&this.args[s]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let o=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,n,r,a)}return o};this._checkNumberOfArguments();let s=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;i.variadic?n<this.args.length?(r=this.args.slice(n),i.parseArg&&(r=r.reduce((o,a)=>e(i,a,o),i.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],i.parseArg&&(r=e(i,r,i.defaultValue))),s[n]=r}),this.processedArgs=s}_chainOrCall(e,s){return e&&e.then&&typeof e.then=="function"?e.then(()=>s()):s()}_chainOrCallHooks(e,s){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[s]!==void 0).forEach(r=>{r._lifeCycleHooks[s].forEach(o=>{n.push({hookedCommand:r,callback:o})})}),s==="postAction"&&n.reverse(),n.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,s,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{n=this._chainOrCall(n,()=>r(this,s))}),n}_parseCommand(e,s){let i=this.parseOptions(s);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),s=i.unknown,this.args=e.concat(s),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),s);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(s),this._dispatchSubcommand(this._defaultCommandName,e,s);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=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,e,s)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,s);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,s);this.listenerCount("command:*")?this.emit("command:*",e,s):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(s=>s._name===e||s._aliases.includes(e))}_findOption(e){return this.options.find(s=>s.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(s=>{s.mandatory&&e.getOptionValue(s.attributeName())===void 0&&e.missingMandatoryOptionValue(s)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(r=>i.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let s=[],i=[],n=s,r=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;r.length;){let l=r.shift();if(l==="--"){n===i&&n.push(l),n.push(...r);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let d=r.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;r.length>0&&!o(r[0])&&(d=r.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),d=this._findOption(l.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(c+1));continue}}if(o(l)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&s.length===0&&i.length===0){if(this._findCommand(l)){s.push(l),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){s.push(l),r.length>0&&s.push(...r);break}else if(this._defaultCommandName){i.push(l),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){n.push(l),r.length>0&&n.push(...r);break}n.push(l)}return{operands:s,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},s=this.options.length;for(let i=0;i<s;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,s)=>Object.assign(e,s.opts()),{})}error(e,s){this._outputConfiguration.outputError(`${e}
21
+ - ${n}`;throw new Error(r)}_executeSubCommand(e,s){s=s.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(u,f){let p=ot.resolve(u,f);if(ls.existsSync(p))return p;if(n.includes(ot.extname(f)))return;let y=n.find(w=>ls.existsSync(`${p}${w}`));if(y)return`${p}${y}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=ls.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ot.resolve(ot.dirname(u),a)}if(a){let u=r(a,o);if(!u&&!e._executableFile&&this._scriptPath){let f=ot.basename(this._scriptPath,ot.extname(this._scriptPath));f!==this._name&&(u=r(a,`${f}-${e._name}`))}o=u||o}i=n.includes(ot.extname(o));let l;se.platform!=="win32"?i?(s.unshift(o),s=un(se.execArgv).concat(s),l=Zs.spawn(se.argv[0],s,{stdio:"inherit"})):l=Zs.spawn(o,s,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),s.unshift(o),s=un(se.execArgv).concat(s),l=Zs.spawn(se.execPath,s,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{se.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new Qs(u,"commander.executeSubCommandAsync","(close)")):se.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)se.exit(1);else{let f=new Qs(1,"commander.executeSubCommandAsync","(error)");f.nestedError=u,c(f)}}),this.runningCommand=l}_dispatchSubcommand(e,s,i){let n=this._findCommand(e);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,s.concat(i));else return n._parseCommand(s,i)}),r}_dispatchHelpCommand(e){e||this.help();let s=this._findCommand(e);return s&&!s._executableHandler&&s.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,s)=>{e.required&&this.args[s]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let o=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,n,r,a)}return o};this._checkNumberOfArguments();let s=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;i.variadic?n<this.args.length?(r=this.args.slice(n),i.parseArg&&(r=r.reduce((o,a)=>e(i,a,o),i.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],i.parseArg&&(r=e(i,r,i.defaultValue))),s[n]=r}),this.processedArgs=s}_chainOrCall(e,s){return e&&e.then&&typeof e.then=="function"?e.then(()=>s()):s()}_chainOrCallHooks(e,s){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[s]!==void 0).forEach(r=>{r._lifeCycleHooks[s].forEach(o=>{n.push({hookedCommand:r,callback:o})})}),s==="postAction"&&n.reverse(),n.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,s,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{n=this._chainOrCall(n,()=>r(this,s))}),n}_parseCommand(e,s){let i=this.parseOptions(s);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),s=i.unknown,this.args=e.concat(s),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),s);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(s),this._dispatchSubcommand(this._defaultCommandName,e,s);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=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,e,s)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,s);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,s);this.listenerCount("command:*")?this.emit("command:*",e,s):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(s=>s._name===e||s._aliases.includes(e))}_findOption(e){return this.options.find(s=>s.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(s=>{s.mandatory&&e.getOptionValue(s.attributeName())===void 0&&e.missingMandatoryOptionValue(s)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(r=>i.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let s=[],i=[],n=s,r=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;r.length;){let l=r.shift();if(l==="--"){n===i&&n.push(l),n.push(...r);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let u=r.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;r.length>0&&!o(r[0])&&(u=r.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&s.length===0&&i.length===0){if(this._findCommand(l)){s.push(l),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){s.push(l),r.length>0&&s.push(...r);break}else if(this._defaultCommandName){i.push(l),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){n.push(l),r.length>0&&n.push(...r);break}n.push(l)}return{operands:s,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},s=this.options.length;for(let i=0;i<s;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,s)=>Object.assign(e,s.opts()),{})}error(e,s){this._outputConfiguration.outputError(`${e}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0}));let i=s||{},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 se.env){let s=e.attributeName();(this.getOptionValue(s)===void 0||["default","config","env"].includes(this.getOptionValueSource(s)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Mo(this.options),s=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&s(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!s(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let s=`error: missing required argument '${e}'`;this.error(s,{code:"commander.missingArgument"})}optionMissingArgument(e){let s=`error: option '${e.flags}' argument missing`;this.error(s,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let s=`error: required option '${e.flags}' not specified`;this.error(s,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,s){let i=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:d||o},n=o=>{let a=i(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${n(e)} cannot be used with ${n(s)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let s="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);n=n.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);s=on(e,n)}let i=`error: unknown option '${e}'${s}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let s=this.registeredArguments.length,i=s===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${s} argument${i} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],s="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),s=on(e,n)}let i=`error: unknown command '${e}'${s}`;this.error(i,{code:"commander.unknownCommand"})}version(e,s,i){if(e===void 0)return this._version;this._version=e,s=s||"-V, --version",i=i||"output the version number";let n=this.createOption(s,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
- `),this._exit(0,"commander.version",e)}),this}description(e,s){return e===void 0&&s===void 0?this._description:(this._description=e,s&&(this._argsDescription=s),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let s=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(s=this.commands[this.commands.length-1]),e===s._name)throw new 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 new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return s._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(s=>this.alias(s)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let s=this.registeredArguments.map(i=>Fo(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?s:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=rt.basename(e,rt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let s=this.createHelp(),i=this._getOutputContext(e);s.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=s.formatHelp(this,s);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let s=!!e.error,i,n,r;return s?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:s,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:r}}outputHelp(e){let s;typeof e=="function"&&(s=e,e=void 0);let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(s&&(r=s(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,s){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",s=s??"display help for command",this._helpOption=this.createOption(e,s),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let s=Number(se.exitCode??0);s===0&&e&&typeof e!="function"&&e.error&&(s=1),this._exit(s,"commander.help","(outputHelp)")}addHelpText(e,s){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
24
+ `),this.outputHelp({error:!0}));let i=s||{},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 se.env){let s=e.attributeName();(this.getOptionValue(s)===void 0||["default","config","env"].includes(this.getOptionValueSource(s)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Go(this.options),s=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&s(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!s(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let s=`error: missing required argument '${e}'`;this.error(s,{code:"commander.missingArgument"})}optionMissingArgument(e){let s=`error: option '${e.flags}' argument missing`;this.error(s,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let s=`error: required option '${e.flags}' not specified`;this.error(s,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,s){let i=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(f=>f.negate&&a===f.attributeName()),u=this.options.find(f=>!f.negate&&a===f.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},n=o=>{let a=i(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${n(e)} cannot be used with ${n(s)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let s="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);n=n.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);s=dn(e,n)}let i=`error: unknown option '${e}'${s}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let s=this.registeredArguments.length,i=s===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${s} argument${i} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],s="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),s=dn(e,n)}let i=`error: unknown command '${e}'${s}`;this.error(i,{code:"commander.unknownCommand"})}version(e,s,i){if(e===void 0)return this._version;this._version=e,s=s||"-V, --version",i=i||"output the version number";let n=this.createOption(s,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
+ `),this._exit(0,"commander.version",e)}),this}description(e,s){return e===void 0&&s===void 0?this._description:(this._description=e,s&&(this._argsDescription=s),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let s=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(s=this.commands[this.commands.length-1]),e===s._name)throw new 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 new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return s._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(s=>this.alias(s)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let s=this.registeredArguments.map(i=>Ho(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?s:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ot.basename(e,ot.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let s=this.createHelp(),i=this._getOutputContext(e);s.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=s.formatHelp(this,s);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let s=!!e.error,i,n,r;return s?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:s,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:r}}outputHelp(e){let s;typeof e=="function"&&(s=e,e=void 0);let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(s&&(r=s(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,s){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",s=s??"display help for command",this._helpOption=this.createOption(e,s),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let s=Number(se.exitCode??0);s===0&&e&&typeof e!="function"&&e.error&&(s=1),this._exit(s,"commander.help","(outputHelp)")}addHelpText(e,s){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
26
  Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let o;typeof s=="function"?o=s({error:r.error,command:r.command}):o=s,o&&r.write(`${o}
27
- `)}),this}_outputHelpIfRequested(e){let s=this._getHelpOption();s&&e.find(n=>s.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function an(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let s,i="127.0.0.1",n="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?s=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(s=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(s=r[1],i=r[3],n=r[4]),s&&n!=="0"?`${s}=${i}:${parseInt(n)+1}`:e})}function Zs(){if(se.env.NO_COLOR||se.env.FORCE_COLOR==="0"||se.env.FORCE_COLOR==="false")return!1;if(se.env.FORCE_COLOR||se.env.CLICOLOR_FORCE!==void 0)return!0}Qs.Command=Xs;Qs.useColor=Zs});var mn=nt(He=>{var{Argument:cn}=os(),{Command:ei}=ln(),{CommanderError:Vo,InvalidArgumentError:dn}=Ht(),{Help:qo}=Hs(),{Option:un}=Ys();He.program=new ei;He.createCommand=t=>new ei(t);He.createOption=(t,e)=>new un(t,e);He.createArgument=(t,e)=>new cn(t,e);He.Command=ei;He.Option=un;He.Argument=cn;He.Help=qo;He.CommanderError=Vo;He.InvalidArgumentError=dn;He.InvalidOptionArgumentError=dn});var W=nt((Rc,ti)=>{var cs=process||{},pn=cs.argv||[],ls=cs.env||{},Wo=!(ls.NO_COLOR||pn.includes("--no-color"))&&(!!ls.FORCE_COLOR||pn.includes("--color")||cs.platform==="win32"||(cs.stdout||{}).isTTY&&ls.TERM!=="dumb"||!!ls.CI),Ho=(t,e,s=t)=>i=>{let n=""+i,r=n.indexOf(e,t.length);return~r?t+Jo(n,e,s,r)+e:t+n+e},Jo=(t,e,s,i)=>{let n="",r=0;do n+=t.substring(r,i)+s,r=i+e.length,i=t.indexOf(e,r);while(~i);return n+t.substring(r)},gn=(t=Wo)=>{let e=t?Ho:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};ti.exports=gn();ti.exports.createColors=gn});var Ft,Jt,Bt=xe(()=>{"use strict";Ft="domani.run",Jt=`https://${Ft}`});function bn(t){yn=t}function ot(){try{let t=pt.default.readFileSync(si,"utf-8");return JSON.parse(t)}catch{return{}}}function Lt(t){pt.default.mkdirSync(ms,{recursive:!0,mode:448}),pt.default.writeFileSync(si,JSON.stringify(t,null,2),{mode:384})}function wn(){try{pt.default.unlinkSync(si)}catch{}}function Ye(){return yn||ot().api_url||Jt}function gt(){return process.env.DOMANI_API_KEY||ot().token}function Go(){try{let t=pt.default.readFileSync(vn,"utf-8");return JSON.parse(t)}catch{return null}}function Yo(t){try{pt.default.mkdirSync(ms,{recursive:!0,mode:448}),pt.default.writeFileSync(vn,JSON.stringify(t),{mode:384})}catch{}}function ds(t,e){let s=t.split(".").map(Number),i=e.split(".").map(Number);for(let n=0;n<3;n++){if((s[n]||0)>(i[n]||0))return 1;if((s[n]||0)<(i[n]||0))return-1}return 0}async function _n(){let t=Go();if(t&&Date.now()-t.checkedAt<Bo)return ds(t.version,ke)>0?{update:t.version,forced:ds(ke,t.min)<0}:null;try{let e=Ye(),s=await fetch(`${e}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!s.ok)return null;let i=await s.json();if(Yo({version:i.version,min:i.min,checkedAt:Date.now()}),ds(i.version,ke)>0)return{update:i.version,forced:ds(ke,i.min)<0}}catch{}return null}var pt,us,$n,ms,si,yn,vn,Bo,ii,ke,$t=xe(()=>{"use strict";pt=F(require("fs"),1),us=F(require("path"),1),$n=F(require("os"),1);Bt();ms=process.env.DOMANI_CONFIG_DIR||us.default.join($n.default.homedir(),".domani"),si=us.default.join(ms,"config.json");vn=us.default.join(ms,"version-check.json"),Bo=1440*60*1e3;ii=process.stdout.isTTY??!1,ke="0.4.12"});var Sn,xn,kn,jn=xe(()=>{Sn=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let s=0;for(t.lastIndex=0;t.test(e);)s+=1;return e.length-s}})(),xn=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,kn=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141});var Ko,zo,Cn,Xo,On,Zo,Qo,ea,Rn,In,An=xe(()=>{jn();Ko=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,zo=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Cn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Xo=/\t{1,1000}/y,On=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Zo=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Qo=new RegExp("\\p{M}+","gu"),ea={limit:1/0,ellipsis:""},Rn=(t,e={},s={})=>{let i=e.limit??1/0,n=e.ellipsis??"",r=e?.ellipsisWidth??(n?Rn(n,ea,s).width:0),o=0,a=s.controlWidth??0,l=s.tabWidth??8,c=s.emojiWidth??2,d=2,f=s.regularWidth??1,p=s.wideWidth??d,$=[[Zo,f],[Ko,o],[zo,a],[Xo,l],[On,c],[Cn,p]],w=0,g=0,_=t.length,S=0,R=!1,N=_,V=Math.max(0,i-r),U=0,le=0,Q=0,J=0;e:for(;;){if(le>U||g>=_&&g>w){let A=t.slice(U,le)||t.slice(w,g);S=0;for(let te of A.replaceAll(Qo,"")){let B=te.codePointAt(0)||0;if(xn(B)?J=d:kn(B)?J=p:J=f,Q+J>V&&(N=Math.min(N,Math.max(U,w)+S)),Q+J>i){R=!0;break e}S+=te.length,Q+=J}U=le=0}if(g>=_)break e;for(let A=0,te=$.length;A<te;A++){let[B,E]=$[A];if(B.lastIndex=g,B.test(t)){if(S=B===Cn?Sn(t.slice(g,B.lastIndex)):B===On?1:B.lastIndex-g,J=S*E,Q+J>V&&(N=Math.min(N,g+Math.floor((V-Q)/E))),Q+J>i){R=!0;break e}Q+=J,U=w,le=g,g=w=B.lastIndex;continue e}}g+=1}return{width:R?V:Q,index:R?N:_,truncated:R,ellipsed:R&&i>=r}},In=Rn});var ta,sa,$e,ni=xe(()=>{An();ta={limit:1/0,ellipsis:"",ellipsisWidth:0},sa=(t,e={})=>In(t,ta,e).width,$e=sa});function Ke(t,e,s){return String(t).normalize().split(aa).map(i=>oa(i,e,s)).join(`
28
- `)}var fs,Nn,ia,oi,Fn,na,Ln,ai,Tn,En,Dn,Pn,ri,ra,oa,aa,li=xe(()=>{ni();fs="\x1B",Nn="\x9B",ia=39,oi="\x07",Fn="[",na="]",Ln="m",ai=`${na}8;;`,Tn=new RegExp(`(?:\\${Fn}(?<code>\\d+)m|\\${ai}(?<uri>.*)${oi})`,"y"),En=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Dn=t=>`${fs}${Fn}${t}${Ln}`,Pn=t=>`${fs}${ai}${t}${oi}`,ri=(t,e,s)=>{let i=e[Symbol.iterator](),n=!1,r=!1,o=t.at(-1),a=o===void 0?0:$e(o),l=i.next(),c=i.next(),d=0;for(;!l.done;){let f=l.value,p=$e(f);a+p<=s?t[t.length-1]+=f:(t.push(f),a=0),(f===fs||f===Nn)&&(n=!0,r=e.startsWith(ai,d+1)),n?r?f===oi&&(n=!1,r=!1):f===Ln&&(n=!1):(a+=p,a===s&&!c.done&&(t.push(""),a=0)),l=c,c=i.next(),d+=f.length}o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},ra=t=>{let e=t.split(" "),s=e.length;for(;s&&!$e(e[s-1]);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},oa=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let i="",n,r,o=t.split(" "),a=[""],l=0;for(let f=0;f<o.length;f++){let p=o[f];if(s.trim!==!1){let w=a.at(-1)??"",g=w.trimStart();w.length!==g.length&&(a[a.length-1]=g,l=$e(g))}f!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(a.push(""),l=0),(l||s.trim===!1)&&(a[a.length-1]+=" ",l++));let $=$e(p);if(s.hard&&$>e){let w=e-l,g=1+Math.floor(($-w-1)/e);Math.floor(($-1)/e)<g&&a.push(""),ri(a,p,e),l=$e(a.at(-1)??"");continue}if(l+$>e&&l&&$){if(s.wordWrap===!1&&l<e){ri(a,p,e),l=$e(a.at(-1)??"");continue}a.push(""),l=0}if(l+$>e&&s.wordWrap===!1){ri(a,p,e),l=$e(a.at(-1)??"");continue}a[a.length-1]+=p,l+=$}s.trim!==!1&&(a=a.map(f=>ra(f)));let c=a.join(`
29
- `),d=!1;for(let f=0;f<c.length;f++){let p=c[f];if(i+=p,d)d=!1;else if(d=p>="\uD800"&&p<="\uDBFF",d)continue;if(p===fs||p===Nn){Tn.lastIndex=f+1;let w=Tn.exec(c)?.groups;if(w?.code!==void 0){let g=Number.parseFloat(w.code);n=g===ia?void 0:g}else w?.uri!==void 0&&(r=w.uri.length===0?void 0:w.uri)}if(c[f+1]===`
30
- `){r&&(i+=Pn(""));let $=n?En(n):void 0;n&&$&&(i+=Dn($))}else p===`
31
- `&&(n&&En(n)&&(i+=Dn(n)),r&&(i+=Pn(r)))}return i},aa=/\r?\n/});var di=nt((Mc,Un)=>{"use strict";var ci={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let s="";return t<0?s+=`\x1B[${-t}D`:t>0&&(s+=`\x1B[${t}C`),e<0?s+=`\x1B[${-e}A`:e>0&&(s+=`\x1B[${e}B`),s},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},la={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ca={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let s=0;s<t;s++)e+=this.line+(s<t-1?ci.up():"");return t&&(e+=ci.left),e}};Un.exports={cursor:ci,scroll:la,erase:ca,beep:"\x07"}});function at(t,e,s){if(!s.some(o=>!o.disabled))return t;let i=t+e,n=Math.max(s.length-1,0),r=i<0?n:i>n?0:i;return s[r]?.disabled?at(r,e<0?-1:1,s):r}function hs(t,e,s,i){let n=i.split(`
32
- `),r=0,o=t;for(let l of n){if(o<=l.length)break;o-=l.length+1,r++}for(r=Math.max(0,Math.min(n.length-1,r+s)),o=Math.min(o,n[r].length)+e;o<0&&r>0;)r--,o+=n[r].length+1;for(;o>n[r].length&&r<n.length-1;)o-=n[r].length+1,r++;o=Math.max(0,Math.min(n[r].length,o));let a=0;for(let l=0;l<r;l++)a+=n[l].length+1;return a+o}function Wn(t){if(t.aliases!==void 0){let e=t.aliases;for(let s in e){if(!Object.hasOwn(e,s))continue;let i=e[s];i===void 0||!M.actions.has(i)||M.aliases.has(s)||M.aliases.set(s,i)}}if(t.messages!==void 0){let e=t.messages;e.cancel!==void 0&&(M.messages.cancel=e.cancel),e.error!==void 0&&(M.messages.error=e.error)}if(t.withGuide!==void 0&&(M.withGuide=t.withGuide!==!1),t.date!==void 0){let e=t.date;e.monthNames!==void 0&&(M.date.monthNames=[...e.monthNames]),e.messages!==void 0&&(e.messages.required!==void 0&&(M.date.messages.required=e.messages.required),e.messages.invalidMonth!==void 0&&(M.date.messages.invalidMonth=e.messages.invalidMonth),e.messages.invalidDay!==void 0&&(M.date.messages.invalidDay=e.messages.invalidDay),e.messages.afterMin!==void 0&&(M.date.messages.afterMin=e.messages.afterMin),e.messages.beforeMax!==void 0&&(M.date.messages.beforeMax=e.messages.beforeMax))}}function pi(t,e){if(typeof t=="string")return M.aliases.get(t)===e;for(let s of t)if(s!==void 0&&pi(s,e))return!0;return!1}function ma(t,e){if(t===e)return;let s=t.split(`
27
+ `)}),this}_outputHelpIfRequested(e){let s=this._getHelpOption();s&&e.find(n=>s.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function un(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let s,i="127.0.0.1",n="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?s=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(s=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(s=r[1],i=r[3],n=r[4]),s&&n!=="0"?`${s}=${i}:${parseInt(n)+1}`:e})}function ti(){if(se.env.NO_COLOR||se.env.FORCE_COLOR==="0"||se.env.FORCE_COLOR==="false")return!1;if(se.env.FORCE_COLOR||se.env.CLICOLOR_FORCE!==void 0)return!0}si.Command=ei;si.useColor=ti});var gn=rt(Je=>{var{Argument:fn}=as(),{Command:ii}=mn(),{CommanderError:Yo,InvalidArgumentError:hn}=Jt(),{Help:Ko}=Gs(),{Option:pn}=Xs();Je.program=new ii;Je.createCommand=t=>new ii(t);Je.createOption=(t,e)=>new pn(t,e);Je.createArgument=(t,e)=>new fn(t,e);Je.Command=ii;Je.Option=pn;Je.Argument=fn;Je.Help=Ko;Je.CommanderError=Yo;Je.InvalidArgumentError=hn;Je.InvalidOptionArgumentError=hn});var W=rt((Lc,ni)=>{var ds=process||{},bn=ds.argv||[],cs=ds.env||{},zo=!(cs.NO_COLOR||bn.includes("--no-color"))&&(!!cs.FORCE_COLOR||bn.includes("--color")||ds.platform==="win32"||(ds.stdout||{}).isTTY&&cs.TERM!=="dumb"||!!cs.CI),Xo=(t,e,s=t)=>i=>{let n=""+i,r=n.indexOf(e,t.length);return~r?t+Zo(n,e,s,r)+e:t+n+e},Zo=(t,e,s,i)=>{let n="",r=0;do n+=t.substring(r,i)+s,r=i+e.length,i=t.indexOf(e,r);while(~i);return n+t.substring(r)},vn=(t=zo)=>{let e=t?Xo:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};ni.exports=vn();ni.exports.createColors=vn});var Lt,Bt,Gt=xe(()=>{"use strict";Lt="domani.run",Bt=`https://${Lt}`});function Sn(t){_n=t}function at(){try{let t=gt.default.readFileSync(ri,"utf-8");return JSON.parse(t)}catch{return{}}}function Ut(t){gt.default.mkdirSync(fs,{recursive:!0,mode:448}),gt.default.writeFileSync(ri,JSON.stringify(t,null,2),{mode:384})}function kn(){try{gt.default.unlinkSync(ri)}catch{}}function Ke(){return _n||at().api_url||Bt}function $t(){return process.env.DOMANI_API_KEY||at().token}function ea(){try{let t=gt.default.readFileSync(xn,"utf-8");return JSON.parse(t)}catch{return null}}function ta(t){try{gt.default.mkdirSync(fs,{recursive:!0,mode:448}),gt.default.writeFileSync(xn,JSON.stringify(t),{mode:384})}catch{}}function us(t,e){let s=t.split(".").map(Number),i=e.split(".").map(Number);for(let n=0;n<3;n++){if((s[n]||0)>(i[n]||0))return 1;if((s[n]||0)<(i[n]||0))return-1}return 0}async function jn(){let t=ea();if(t&&Date.now()-t.checkedAt<Qo)return us(t.version,ke)>0?{update:t.version,forced:us(ke,t.min)<0}:null;try{let e=Ke(),s=await fetch(`${e}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!s.ok)return null;let i=await s.json();if(ta({version:i.version,min:i.min,checkedAt:Date.now()}),us(i.version,ke)>0)return{update:i.version,forced:us(ke,i.min)<0}}catch{}return null}var gt,ms,wn,fs,ri,_n,xn,Qo,oi,ke,yt=xe(()=>{"use strict";gt=F(require("fs"),1),ms=F(require("path"),1),wn=F(require("os"),1);Gt();fs=process.env.DOMANI_CONFIG_DIR||ms.default.join(wn.default.homedir(),".domani"),ri=ms.default.join(fs,"config.json");xn=ms.default.join(fs,"version-check.json"),Qo=1440*60*1e3;oi=process.stdout.isTTY??!1,ke="0.4.14"});var Cn,On,Rn,In=xe(()=>{Cn=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let s=0;for(t.lastIndex=0;t.test(e);)s+=1;return e.length-s}})(),On=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Rn=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141});var sa,ia,An,na,Tn,ra,oa,aa,En,Dn,Pn=xe(()=>{In();sa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ia=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,An=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,na=/\t{1,1000}/y,Tn=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),ra=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,oa=new RegExp("\\p{M}+","gu"),aa={limit:1/0,ellipsis:""},En=(t,e={},s={})=>{let i=e.limit??1/0,n=e.ellipsis??"",r=e?.ellipsisWidth??(n?En(n,aa,s).width:0),o=0,a=s.controlWidth??0,l=s.tabWidth??8,c=s.emojiWidth??2,u=2,f=s.regularWidth??1,p=s.wideWidth??u,y=[[ra,f],[sa,o],[ia,a],[na,l],[Tn,c],[An,p]],w=0,$=0,_=t.length,S=0,I=!1,N=_,q=Math.max(0,i-r),U=0,le=0,Q=0,J=0;e:for(;;){if(le>U||$>=_&&$>w){let A=t.slice(U,le)||t.slice(w,$);S=0;for(let te of A.replaceAll(oa,"")){let B=te.codePointAt(0)||0;if(On(B)?J=u:Rn(B)?J=p:J=f,Q+J>q&&(N=Math.min(N,Math.max(U,w)+S)),Q+J>i){I=!0;break e}S+=te.length,Q+=J}U=le=0}if($>=_)break e;for(let A=0,te=y.length;A<te;A++){let[B,E]=y[A];if(B.lastIndex=$,B.test(t)){if(S=B===An?Cn(t.slice($,B.lastIndex)):B===Tn?1:B.lastIndex-$,J=S*E,Q+J>q&&(N=Math.min(N,$+Math.floor((q-Q)/E))),Q+J>i){I=!0;break e}Q+=J,U=w,le=$,$=w=B.lastIndex;continue e}}$+=1}return{width:I?q:Q,index:I?N:_,truncated:I,ellipsed:I&&i>=r}},Dn=En});var la,ca,ye,ai=xe(()=>{Pn();la={limit:1/0,ellipsis:"",ellipsisWidth:0},ca=(t,e={})=>Dn(t,la,e).width,ye=ca});function ze(t,e,s){return String(t).normalize().split(ha).map(i=>fa(i,e,s)).join(`
28
+ `)}var hs,Mn,da,ci,Vn,ua,qn,di,Nn,Fn,Ln,Un,li,ma,fa,ha,ui=xe(()=>{ai();hs="\x1B",Mn="\x9B",da=39,ci="\x07",Vn="[",ua="]",qn="m",di=`${ua}8;;`,Nn=new RegExp(`(?:\\${Vn}(?<code>\\d+)m|\\${di}(?<uri>.*)${ci})`,"y"),Fn=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Ln=t=>`${hs}${Vn}${t}${qn}`,Un=t=>`${hs}${di}${t}${ci}`,li=(t,e,s)=>{let i=e[Symbol.iterator](),n=!1,r=!1,o=t.at(-1),a=o===void 0?0:ye(o),l=i.next(),c=i.next(),u=0;for(;!l.done;){let f=l.value,p=ye(f);a+p<=s?t[t.length-1]+=f:(t.push(f),a=0),(f===hs||f===Mn)&&(n=!0,r=e.startsWith(di,u+1)),n?r?f===ci&&(n=!1,r=!1):f===qn&&(n=!1):(a+=p,a===s&&!c.done&&(t.push(""),a=0)),l=c,c=i.next(),u+=f.length}o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},ma=t=>{let e=t.split(" "),s=e.length;for(;s&&!ye(e[s-1]);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},fa=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let i="",n,r,o=t.split(" "),a=[""],l=0;for(let f=0;f<o.length;f++){let p=o[f];if(s.trim!==!1){let w=a.at(-1)??"",$=w.trimStart();w.length!==$.length&&(a[a.length-1]=$,l=ye($))}f!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(a.push(""),l=0),(l||s.trim===!1)&&(a[a.length-1]+=" ",l++));let y=ye(p);if(s.hard&&y>e){let w=e-l,$=1+Math.floor((y-w-1)/e);Math.floor((y-1)/e)<$&&a.push(""),li(a,p,e),l=ye(a.at(-1)??"");continue}if(l+y>e&&l&&y){if(s.wordWrap===!1&&l<e){li(a,p,e),l=ye(a.at(-1)??"");continue}a.push(""),l=0}if(l+y>e&&s.wordWrap===!1){li(a,p,e),l=ye(a.at(-1)??"");continue}a[a.length-1]+=p,l+=y}s.trim!==!1&&(a=a.map(f=>ma(f)));let c=a.join(`
29
+ `),u=!1;for(let f=0;f<c.length;f++){let p=c[f];if(i+=p,u)u=!1;else if(u=p>="\uD800"&&p<="\uDBFF",u)continue;if(p===hs||p===Mn){Nn.lastIndex=f+1;let w=Nn.exec(c)?.groups;if(w?.code!==void 0){let $=Number.parseFloat(w.code);n=$===da?void 0:$}else w?.uri!==void 0&&(r=w.uri.length===0?void 0:w.uri)}if(c[f+1]===`
30
+ `){r&&(i+=Un(""));let y=n?Fn(n):void 0;n&&y&&(i+=Ln(y))}else p===`
31
+ `&&(n&&Fn(n)&&(i+=Ln(n)),r&&(i+=Un(r)))}return i},ha=/\r?\n/});var fi=rt((Kc,Wn)=>{"use strict";var mi={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let s="";return t<0?s+=`\x1B[${-t}D`:t>0&&(s+=`\x1B[${t}C`),e<0?s+=`\x1B[${-e}A`:e>0&&(s+=`\x1B[${e}B`),s},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},pa={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ga={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let s=0;s<t;s++)e+=this.line+(s<t-1?mi.up():"");return t&&(e+=mi.left),e}};Wn.exports={cursor:mi,scroll:pa,erase:ga,beep:"\x07"}});function lt(t,e,s){if(!s.some(o=>!o.disabled))return t;let i=t+e,n=Math.max(s.length-1,0),r=i<0?n:i>n?0:i;return s[r]?.disabled?lt(r,e<0?-1:1,s):r}function ps(t,e,s,i){let n=i.split(`
32
+ `),r=0,o=t;for(let l of n){if(o<=l.length)break;o-=l.length+1,r++}for(r=Math.max(0,Math.min(n.length-1,r+s)),o=Math.min(o,n[r].length)+e;o<0&&r>0;)r--,o+=n[r].length+1;for(;o>n[r].length&&r<n.length-1;)o-=n[r].length+1,r++;o=Math.max(0,Math.min(n[r].length,o));let a=0;for(let l=0;l<r;l++)a+=n[l].length+1;return a+o}function Gn(t){if(t.aliases!==void 0){let e=t.aliases;for(let s in e){if(!Object.hasOwn(e,s))continue;let i=e[s];i===void 0||!M.actions.has(i)||M.aliases.has(s)||M.aliases.set(s,i)}}if(t.messages!==void 0){let e=t.messages;e.cancel!==void 0&&(M.messages.cancel=e.cancel),e.error!==void 0&&(M.messages.error=e.error)}if(t.withGuide!==void 0&&(M.withGuide=t.withGuide!==!1),t.date!==void 0){let e=t.date;e.monthNames!==void 0&&(M.date.monthNames=[...e.monthNames]),e.messages!==void 0&&(e.messages.required!==void 0&&(M.date.messages.required=e.messages.required),e.messages.invalidMonth!==void 0&&(M.date.messages.invalidMonth=e.messages.invalidMonth),e.messages.invalidDay!==void 0&&(M.date.messages.invalidDay=e.messages.invalidDay),e.messages.afterMin!==void 0&&(M.date.messages.afterMin=e.messages.afterMin),e.messages.beforeMax!==void 0&&(M.date.messages.beforeMax=e.messages.beforeMax))}}function yi(t,e){if(typeof t=="string")return M.aliases.get(t)===e;for(let s of t)if(s!==void 0&&yi(s,e))return!0;return!1}function ba(t,e){if(t===e)return;let s=t.split(`
33
33
  `),i=e.split(`
34
- `),n=Math.max(s.length,i.length),r=[];for(let o=0;o<n;o++)s[o]!==i[o]&&r.push(o);return{lines:r,numLinesBefore:s.length,numLinesAfter:i.length,numLines:n}}function ae(t){return t===fi}function ps(t,e){let s=t;s.isTTY&&s.setRawMode(e)}function Hn({input:t=xt.stdin,output:e=xt.stdout,overwrite:s=!0,hideCursor:i=!0}={}){let n=yt.createInterface({input:t,output:e,prompt:"",tabSize:1});yt.emitKeypressEvents(t,n),t instanceof mi.ReadStream&&t.isTTY&&t.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let c=String(o);if(pi([c,a,l],"cancel")){i&&e.write(Ae.cursor.show),process.exit(0);return}if(!s)return;yt.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{yt.clearLine(e,1,()=>{t.once("keypress",r)})})};return i&&e.write(Ae.cursor.hide),t.once("keypress",r),()=>{t.off("keypress",r),i&&e.write(Ae.cursor.show),t instanceof mi.ReadStream&&t.isTTY&&!fa&&t.setRawMode(!1),n.terminal=!1,n.close()}}function pe(t,e,s,i=s,n=s,r){let o=kt(t??xt.stdout);return Ke(e,o-s.length,{hard:!0,trim:!1}).split(`
35
- `).map((a,l,c)=>{let d=r?r(a,l):a;return l===0?`${i}${d}`:l===c.length-1?`${n}${d}`:`${s}${d}`}).join(`
36
- `)}function Gt(t,e){if("~standard"in t){let s=t["~standard"].validate(e);if(s instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return s.issues?.at(0)?.message}return t(e)}function ha(t,e){if(t===void 0||e.length===0)return 0;let s=e.findIndex(i=>i.value===t);return s!==-1?s:0}function pa(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function ga(t,e){if(e)return t?e:e[0]}function Mn(t){return[...t].map(e=>$a[e])}function ya(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2e3,0,15)),s=[],i="/";for(let n of e)n.type==="literal"?i=n.value.trim()||n.value:(n.type==="year"||n.type==="month"||n.type==="day")&&s.push({type:n.type,len:n.type==="year"?4:2});return{segments:s,separator:i}}function ui(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function gs(t){return{year:ui(t.year),month:ui(t.month),day:ui(t.day)}}function hi(t,e){return new Date(t||2001,e||1,0).getDate()}function Jn(t){let{year:e,month:s,day:i}=gs(t);if(!e||e<0||e>9999||!s||s<1||s>12||!i||i<1)return;let n=new Date(Date.UTC(e,s-1,i));if(!(n.getUTCFullYear()!==e||n.getUTCMonth()!==s-1||n.getUTCDate()!==i))return{year:e,month:s,day:i}}function Vn(t){let e=Jn(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function ba(t,e,s,i){let n=s?{year:s.getUTCFullYear(),month:s.getUTCMonth()+1,day:s.getUTCDate()}:null,r=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return t==="year"?{min:n?.year??1,max:r?.year??9999}:t==="month"?{min:n&&e.year===n.year?n.month:1,max:r&&e.year===r.year?r.month:12}:{min:n&&e.year===n.year&&e.month===n.month?n.day:1,max:r&&e.year===r.year&&e.month===r.month?r.day:hi(e.year,e.month)}}var St,xt,yt,qn,Ae,mi,da,ua,M,fa,fi,kt,gi,Je,$i,$s,$a,ys,Bn,va,bs,vs,Gn,Yn,ws,_s,yi=xe(()=>{St=require("node:util"),xt=require("node:process"),yt=F(require("node:readline"),1),qn=F(require("node:readline"),1);li();Ae=F(di(),1),mi=require("node:tty");da=["up","down","left","right","space","enter","cancel"],ua=["January","February","March","April","May","June","July","August","September","October","November","December"],M={actions:new Set(da),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...ua],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};fa=globalThis.process.platform.startsWith("win"),fi=Symbol("clack:cancel");kt=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,gi=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;Je=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,s=!0){let{input:i=xt.stdin,output:n=xt.stdout,render:r,signal:o,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=s,this._abortSignal=o,this.input=i,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,s){let i=this._subscribers.get(e)??[];i.push(s),this._subscribers.set(e,i)}on(e,s){this.setSubscriber(e,{cb:s})}once(e,s){this.setSubscriber(e,{cb:s,once:!0})}emit(e,...s){let i=this._subscribers.get(e)??[],n=[];for(let r of i)r.cb(...s),r.once&&n.push(()=>i.splice(i.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(fi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=qn.default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),ps(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ae.cursor.show),this.output.off("resize",this.render),ps(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Ae.cursor.show),this.output.off("resize",this.render),ps(this.input,!1),e(fi)})})}_isActionKey(e,s){return e===" "}_shouldSubmit(e,s){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,s){this.userInput=e??"",this.emit("userInput",this.userInput),s&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,s){if(this._track&&s.name!=="return"&&(s.name&&this._isActionKey(e,s)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),s?.name&&(!this._track&&M.aliases.has(s.name)&&this.emit("cursor",M.aliases.get(s.name)),M.actions.has(s.name)&&this.emit("cursor",s.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,s),s?.name==="return"&&this._shouldSubmit(e,s)){if(this.opts.validate){let i=Gt(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}pi([e,s?.name,s?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
37
- `),ps(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Ke(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
38
- `).length-1;this.output.write(Ae.cursor.move(-999,e*-1))}render(){let e=Ke(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Ae.cursor.hide);else{let s=ma(this._prevFrame,e),i=gi(this.output);if(this.restoreCursor(),s){let n=Math.max(0,s.numLinesAfter-i),r=Math.max(0,s.numLinesBefore-i),o=s.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=e;return}if(s.lines.length===1){this.output.write(Ae.cursor.move(0,o-r)),this.output.write(Ae.erase.lines(1));let a=e.split(`
34
+ `),n=Math.max(s.length,i.length),r=[];for(let o=0;o<n;o++)s[o]!==i[o]&&r.push(o);return{lines:r,numLinesBefore:s.length,numLinesAfter:i.length,numLines:n}}function ae(t){return t===gi}function gs(t,e){let s=t;s.isTTY&&s.setRawMode(e)}function Yn({input:t=kt.stdin,output:e=kt.stdout,overwrite:s=!0,hideCursor:i=!0}={}){let n=bt.createInterface({input:t,output:e,prompt:"",tabSize:1});bt.emitKeypressEvents(t,n),t instanceof pi.ReadStream&&t.isTTY&&t.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let c=String(o);if(yi([c,a,l],"cancel")){i&&e.write(Ae.cursor.show),process.exit(0);return}if(!s)return;bt.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{bt.clearLine(e,1,()=>{t.once("keypress",r)})})};return i&&e.write(Ae.cursor.hide),t.once("keypress",r),()=>{t.off("keypress",r),i&&e.write(Ae.cursor.show),t instanceof pi.ReadStream&&t.isTTY&&!va&&t.setRawMode(!1),n.terminal=!1,n.close()}}function pe(t,e,s,i=s,n=s,r){let o=jt(t??kt.stdout);return ze(e,o-s.length,{hard:!0,trim:!1}).split(`
35
+ `).map((a,l,c)=>{let u=r?r(a,l):a;return l===0?`${i}${u}`:l===c.length-1?`${n}${u}`:`${s}${u}`}).join(`
36
+ `)}function Yt(t,e){if("~standard"in t){let s=t["~standard"].validate(e);if(s instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return s.issues?.at(0)?.message}return t(e)}function wa(t,e){if(t===void 0||e.length===0)return 0;let s=e.findIndex(i=>i.value===t);return s!==-1?s:0}function _a(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function Sa(t,e){if(e)return t?e:e[0]}function Hn(t){return[...t].map(e=>xa[e])}function ka(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2e3,0,15)),s=[],i="/";for(let n of e)n.type==="literal"?i=n.value.trim()||n.value:(n.type==="year"||n.type==="month"||n.type==="day")&&s.push({type:n.type,len:n.type==="year"?4:2});return{segments:s,separator:i}}function hi(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function $s(t){return{year:hi(t.year),month:hi(t.month),day:hi(t.day)}}function $i(t,e){return new Date(t||2001,e||1,0).getDate()}function Kn(t){let{year:e,month:s,day:i}=$s(t);if(!e||e<0||e>9999||!s||s<1||s>12||!i||i<1)return;let n=new Date(Date.UTC(e,s-1,i));if(!(n.getUTCFullYear()!==e||n.getUTCMonth()!==s-1||n.getUTCDate()!==i))return{year:e,month:s,day:i}}function Jn(t){let e=Kn(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function ja(t,e,s,i){let n=s?{year:s.getUTCFullYear(),month:s.getUTCMonth()+1,day:s.getUTCDate()}:null,r=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return t==="year"?{min:n?.year??1,max:r?.year??9999}:t==="month"?{min:n&&e.year===n.year?n.month:1,max:r&&e.year===r.year?r.month:12}:{min:n&&e.year===n.year&&e.month===n.month?n.day:1,max:r&&e.year===r.year&&e.month===r.month?r.day:$i(e.year,e.month)}}var xt,kt,bt,Bn,Ae,pi,$a,ya,M,va,gi,jt,bi,Be,vi,ys,xa,bs,zn,Ca,vs,ws,Xn,Zn,_s,Ss,wi=xe(()=>{xt=require("node:util"),kt=require("node:process"),bt=F(require("node:readline"),1),Bn=F(require("node:readline"),1);ui();Ae=F(fi(),1),pi=require("node:tty");$a=["up","down","left","right","space","enter","cancel"],ya=["January","February","March","April","May","June","July","August","September","October","November","December"],M={actions:new Set($a),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...ya],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};va=globalThis.process.platform.startsWith("win"),gi=Symbol("clack:cancel");jt=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,bi=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;Be=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,s=!0){let{input:i=kt.stdin,output:n=kt.stdout,render:r,signal:o,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=s,this._abortSignal=o,this.input=i,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,s){let i=this._subscribers.get(e)??[];i.push(s),this._subscribers.set(e,i)}on(e,s){this.setSubscriber(e,{cb:s})}once(e,s){this.setSubscriber(e,{cb:s,once:!0})}emit(e,...s){let i=this._subscribers.get(e)??[],n=[];for(let r of i)r.cb(...s),r.once&&n.push(()=>i.splice(i.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(gi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Bn.default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),gs(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ae.cursor.show),this.output.off("resize",this.render),gs(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Ae.cursor.show),this.output.off("resize",this.render),gs(this.input,!1),e(gi)})})}_isActionKey(e,s){return e===" "}_shouldSubmit(e,s){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,s){this.userInput=e??"",this.emit("userInput",this.userInput),s&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,s){if(this._track&&s.name!=="return"&&(s.name&&this._isActionKey(e,s)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),s?.name&&(!this._track&&M.aliases.has(s.name)&&this.emit("cursor",M.aliases.get(s.name)),M.actions.has(s.name)&&this.emit("cursor",s.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,s),s?.name==="return"&&this._shouldSubmit(e,s)){if(this.opts.validate){let i=Yt(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}yi([e,s?.name,s?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
37
+ `),gs(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=ze(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
38
+ `).length-1;this.output.write(Ae.cursor.move(-999,e*-1))}render(){let e=ze(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Ae.cursor.hide);else{let s=ba(this._prevFrame,e),i=bi(this.output);if(this.restoreCursor(),s){let n=Math.max(0,s.numLinesAfter-i),r=Math.max(0,s.numLinesBefore-i),o=s.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=e;return}if(s.lines.length===1){this.output.write(Ae.cursor.move(0,o-r)),this.output.write(Ae.erase.lines(1));let a=e.split(`
39
39
  `);this.output.write(a[o]),this._prevFrame=e,this.output.write(Ae.cursor.move(0,a.length-o-1));return}else if(s.lines.length>1){if(n<r)o=n;else{let l=o-r;l>0&&this.output.write(Ae.cursor.move(0,l))}this.output.write(Ae.erase.down());let a=e.split(`
40
40
  `).slice(o);this.output.write(a.join(`
41
- `)),this._prevFrame=e;return}}this.output.write(Ae.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};$i=class extends Je{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#r;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return(0,St.styleText)(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let e=this.userInput.slice(0,this.cursor),s=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${e}${(0,St.styleText)("inverse",s)}${i}`}get options(){return typeof this.#r=="function"?this.#r():this.#r}constructor(e){super(e),this.#r=e.options,this.#a=e.placeholder;let s=this.options;this.filteredOptions=[...s],this.multiple=e.multiple===!0,this.#e=typeof e.options=="function"?e.filter:e.filter??pa;let i;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?i=e.initialValue:i=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let n of i){let r=s.findIndex(o=>o.value===n);r!==-1&&(this.toggleSelected(n),this.#t=r)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(n,r)=>this.#s(n,r)),this.on("userInput",n=>this.#i(n))}_isActionKey(e,s){return e===" "||this.multiple&&this.isNavigating&&s.name==="space"&&e!==void 0&&e!==""}#s(e,s){let i=s.name==="up",n=s.name==="down",r=s.name==="return",o=this.userInput===""||this.userInput===" ",a=this.#a,l=this.options,c=a!==void 0&&a!==""&&l.some(d=>!d.disabled&&(this.#e?this.#e(a,d):!0));if(s.name==="tab"&&o&&c){this.userInput===" "&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}i||n?(this.#t=at(this.#t,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=ga(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(s.name==="tab"||this.isNavigating&&s.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter(s=>s!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#i(e){if(e!==this.#n){this.#n=e;let s=this.options;e&&this.#e?this.filteredOptions=s.filter(r=>this.#e?.(e,r)):this.filteredOptions=[...s];let i=ha(this.focusedValue,this.filteredOptions);this.#t=at(i,0,this.filteredOptions);let n=this.filteredOptions[this.#t];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},$s=class extends Je{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",s=>{this.output.write(Ae.cursor.move(0,-1)),this.value=s,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},$a={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};ys=class extends Je{#t;#n;#e;#r;#a;#s={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#s}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#u(this.#e)}#u(e){return this.#t.map(s=>e[s.type]).join(this.#n)}#l(){this._setUserInput(this.#u(this.#e)),this._setValue(Vn(this.#e)??void 0)}constructor(e){let s=e.format?{segments:Mn(e.format),separator:e.separator??"/"}:ya(e.locale),i=e.separator??s.separator,n=e.format?Mn(e.format):s.segments,r=e.initialValue??e.defaultValue,o=r?{year:String(r.getUTCFullYear()).padStart(4,"0"),month:String(r.getUTCMonth()+1).padStart(2,"0"),day:String(r.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=n.map(l=>o[l.type]).join(i);super({...e,initialUserInput:a},!1),this.#t=n,this.#n=i,this.#e=o,this.#r=e.minDate,this.#a=e.maxDate,this.#l(),this.on("cursor",l=>this.#h(l)),this.on("key",(l,c)=>this.#p(l,c)),this.on("finalize",()=>this.#g(e))}#c(){let e=Math.max(0,Math.min(this.#s.segmentIndex,this.#t.length-1)),s=this.#t[e];if(s)return this.#s.positionInSegment=Math.max(0,Math.min(this.#s.positionInSegment,s.len-1)),{segment:s,index:e}}#d(e){this.inlineError="",this.#o=null;let s=this.#c();s&&(this.#s.segmentIndex=Math.max(0,Math.min(this.#t.length-1,s.index+e)),this.#s.positionInSegment=0,this.#i=!0)}#m(e){let s=this.#c();if(!s)return;let{segment:i}=s,n=this.#e[i.type],r=!n||n.replace(/_/g,"")==="",o=Number.parseInt((n||"0").replace(/_/g,"0"),10)||0,a=ba(i.type,gs(this.#e),this.#r,this.#a),l;r?l=e===1?a.min:a.max:l=Math.max(Math.min(a.max,o+e),a.min),this.#e={...this.#e,[i.type]:l.toString().padStart(i.len,"0")},this.#i=!0,this.#o=null,this.#l()}#h(e){if(e)switch(e){case"right":return this.#d(1);case"left":return this.#d(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#p(e,s){if(s?.name==="backspace"||s?.sequence==="\x7F"||s?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let i=this.#c();if(!i)return;if(!this.#e[i.segment.type].replace(/_/g,"")){this.#d(-1);return}this.#e[i.segment.type]="_".repeat(i.segment.len),this.#i=!0,this.#s.positionInSegment=0,this.#l();return}if(s?.name==="tab"){this.inlineError="";let i=this.#c();if(!i)return;let n=s.shift?-1:1,r=i.index+n;r>=0&&r<this.#t.length&&(this.#s.segmentIndex=r,this.#s.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let i=this.#c();if(!i)return;let{segment:n}=i,r=!this.#e[n.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!r){let $=this.#o+e,w={...this.#e,[n.type]:$},g=this.#f(w,n);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[n.type]=$,this.#o=null,this.#i=!1,this.#l(),i.index<this.#t.length-1&&(this.#s.segmentIndex=i.index+1,this.#s.positionInSegment=0,this.#i=!0);return}this.#i&&!r&&(this.#e[n.type]="_".repeat(n.len),this.#s.positionInSegment=0),this.#i=!1,this.#o=null;let o=this.#e[n.type],a=o.indexOf("_"),l=a>=0?a:Math.min(this.#s.positionInSegment,n.len-1);if(l<0||l>=n.len)return;let c=o.slice(0,l)+e+o.slice(l+1),d=!1;if(l===0&&o==="__"&&(n.type==="month"||n.type==="day")){let $=Number.parseInt(e,10);c=`0${e}`,d=$<=(n.type==="month"?1:2)}if(n.type==="year"&&(c=(o.replace(/_/g,"")+e).padStart(n.len,"_")),!c.includes("_")){let $={...this.#e,[n.type]:c},w=this.#f($,n);if(w){this.inlineError=w;return}}this.inlineError="",this.#e[n.type]=c;let f=c.includes("_")?void 0:Jn(this.#e);if(f){let{year:$,month:w}=f,g=hi($,w);this.#e={year:String(Math.max(0,Math.min(9999,$))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,w))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,f.day))).padStart(2,"0")}}this.#l();let p=c.indexOf("_");d?(this.#i=!0,this.#o=e):p>=0?this.#s.positionInSegment=p:a>=0&&i.index<this.#t.length-1?(this.#s.segmentIndex=i.index+1,this.#s.positionInSegment=0,this.#i=!0):this.#s.positionInSegment=Math.min(l+1,n.len-1)}}#f(e,s){let{month:i,day:n}=gs(e);if(s.type==="month"&&(i<0||i>12))return M.date.messages.invalidMonth;if(s.type==="day"&&(n<0||n>31))return M.date.messages.invalidDay(31,"any month")}#g(e){let{year:s,month:i,day:n}=gs(this.#e);if(s&&i&&n){let r=hi(s,i);this.#e={...this.#e,day:String(Math.min(n,r)).padStart(2,"0")}}this.value=Vn(this.#e)??e.defaultValue??void 0}},Bn=class extends Je{options;cursor=0;#t;getGroupItems(e){return this.options.filter(s=>s.group===e)}isGroupSelected(e){let s=this.getGroupItems(e),i=this.value;return i===void 0?!1:s.every(n=>i.includes(n.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let s=e.value,i=this.getGroupItems(s);this.isGroupSelected(s)?this.value=this.value.filter(n=>i.findIndex(r=>r.value===n)===-1):this.value=[...this.value,...i.map(n=>n.value)],this.value=Array.from(new Set(this.value))}else{let s=this.value.includes(e.value);this.value=s?this.value.filter(i=>i!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:s}=e;this.#t=e.selectableGroups!==!1,this.options=Object.entries(s).flatMap(([i,n])=>[{value:i,group:!0,label:i},...n.map(r=>({...r,group:i}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),this.#t?0:1),this.on("cursor",i=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let n=this.options[this.cursor]?.group===!0;!this.#t&&n&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let n=this.options[this.cursor]?.group===!0;!this.#t&&n&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},va=new Set(["up","down","left","right"]),bs=class extends Je{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return i===`
41
+ `)),this._prevFrame=e;return}}this.output.write(Ae.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};vi=class extends Be{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#r;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return(0,xt.styleText)(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let e=this.userInput.slice(0,this.cursor),s=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${e}${(0,xt.styleText)("inverse",s)}${i}`}get options(){return typeof this.#r=="function"?this.#r():this.#r}constructor(e){super(e),this.#r=e.options,this.#a=e.placeholder;let s=this.options;this.filteredOptions=[...s],this.multiple=e.multiple===!0,this.#e=typeof e.options=="function"?e.filter:e.filter??_a;let i;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?i=e.initialValue:i=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let n of i){let r=s.findIndex(o=>o.value===n);r!==-1&&(this.toggleSelected(n),this.#t=r)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(n,r)=>this.#s(n,r)),this.on("userInput",n=>this.#i(n))}_isActionKey(e,s){return e===" "||this.multiple&&this.isNavigating&&s.name==="space"&&e!==void 0&&e!==""}#s(e,s){let i=s.name==="up",n=s.name==="down",r=s.name==="return",o=this.userInput===""||this.userInput===" ",a=this.#a,l=this.options,c=a!==void 0&&a!==""&&l.some(u=>!u.disabled&&(this.#e?this.#e(a,u):!0));if(s.name==="tab"&&o&&c){this.userInput===" "&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}i||n?(this.#t=lt(this.#t,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=Sa(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(s.name==="tab"||this.isNavigating&&s.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter(s=>s!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#i(e){if(e!==this.#n){this.#n=e;let s=this.options;e&&this.#e?this.filteredOptions=s.filter(r=>this.#e?.(e,r)):this.filteredOptions=[...s];let i=wa(this.focusedValue,this.filteredOptions);this.#t=lt(i,0,this.filteredOptions);let n=this.filteredOptions[this.#t];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},ys=class extends Be{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",s=>{this.output.write(Ae.cursor.move(0,-1)),this.value=s,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},xa={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};bs=class extends Be{#t;#n;#e;#r;#a;#s={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#s}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#u(this.#e)}#u(e){return this.#t.map(s=>e[s.type]).join(this.#n)}#l(){this._setUserInput(this.#u(this.#e)),this._setValue(Jn(this.#e)??void 0)}constructor(e){let s=e.format?{segments:Hn(e.format),separator:e.separator??"/"}:ka(e.locale),i=e.separator??s.separator,n=e.format?Hn(e.format):s.segments,r=e.initialValue??e.defaultValue,o=r?{year:String(r.getUTCFullYear()).padStart(4,"0"),month:String(r.getUTCMonth()+1).padStart(2,"0"),day:String(r.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=n.map(l=>o[l.type]).join(i);super({...e,initialUserInput:a},!1),this.#t=n,this.#n=i,this.#e=o,this.#r=e.minDate,this.#a=e.maxDate,this.#l(),this.on("cursor",l=>this.#h(l)),this.on("key",(l,c)=>this.#p(l,c)),this.on("finalize",()=>this.#g(e))}#c(){let e=Math.max(0,Math.min(this.#s.segmentIndex,this.#t.length-1)),s=this.#t[e];if(s)return this.#s.positionInSegment=Math.max(0,Math.min(this.#s.positionInSegment,s.len-1)),{segment:s,index:e}}#d(e){this.inlineError="",this.#o=null;let s=this.#c();s&&(this.#s.segmentIndex=Math.max(0,Math.min(this.#t.length-1,s.index+e)),this.#s.positionInSegment=0,this.#i=!0)}#m(e){let s=this.#c();if(!s)return;let{segment:i}=s,n=this.#e[i.type],r=!n||n.replace(/_/g,"")==="",o=Number.parseInt((n||"0").replace(/_/g,"0"),10)||0,a=ja(i.type,$s(this.#e),this.#r,this.#a),l;r?l=e===1?a.min:a.max:l=Math.max(Math.min(a.max,o+e),a.min),this.#e={...this.#e,[i.type]:l.toString().padStart(i.len,"0")},this.#i=!0,this.#o=null,this.#l()}#h(e){if(e)switch(e){case"right":return this.#d(1);case"left":return this.#d(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#p(e,s){if(s?.name==="backspace"||s?.sequence==="\x7F"||s?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let i=this.#c();if(!i)return;if(!this.#e[i.segment.type].replace(/_/g,"")){this.#d(-1);return}this.#e[i.segment.type]="_".repeat(i.segment.len),this.#i=!0,this.#s.positionInSegment=0,this.#l();return}if(s?.name==="tab"){this.inlineError="";let i=this.#c();if(!i)return;let n=s.shift?-1:1,r=i.index+n;r>=0&&r<this.#t.length&&(this.#s.segmentIndex=r,this.#s.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let i=this.#c();if(!i)return;let{segment:n}=i,r=!this.#e[n.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!r){let y=this.#o+e,w={...this.#e,[n.type]:y},$=this.#f(w,n);if($){this.inlineError=$,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[n.type]=y,this.#o=null,this.#i=!1,this.#l(),i.index<this.#t.length-1&&(this.#s.segmentIndex=i.index+1,this.#s.positionInSegment=0,this.#i=!0);return}this.#i&&!r&&(this.#e[n.type]="_".repeat(n.len),this.#s.positionInSegment=0),this.#i=!1,this.#o=null;let o=this.#e[n.type],a=o.indexOf("_"),l=a>=0?a:Math.min(this.#s.positionInSegment,n.len-1);if(l<0||l>=n.len)return;let c=o.slice(0,l)+e+o.slice(l+1),u=!1;if(l===0&&o==="__"&&(n.type==="month"||n.type==="day")){let y=Number.parseInt(e,10);c=`0${e}`,u=y<=(n.type==="month"?1:2)}if(n.type==="year"&&(c=(o.replace(/_/g,"")+e).padStart(n.len,"_")),!c.includes("_")){let y={...this.#e,[n.type]:c},w=this.#f(y,n);if(w){this.inlineError=w;return}}this.inlineError="",this.#e[n.type]=c;let f=c.includes("_")?void 0:Kn(this.#e);if(f){let{year:y,month:w}=f,$=$i(y,w);this.#e={year:String(Math.max(0,Math.min(9999,y))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,w))).padStart(2,"0"),day:String(Math.max(1,Math.min($,f.day))).padStart(2,"0")}}this.#l();let p=c.indexOf("_");u?(this.#i=!0,this.#o=e):p>=0?this.#s.positionInSegment=p:a>=0&&i.index<this.#t.length-1?(this.#s.segmentIndex=i.index+1,this.#s.positionInSegment=0,this.#i=!0):this.#s.positionInSegment=Math.min(l+1,n.len-1)}}#f(e,s){let{month:i,day:n}=$s(e);if(s.type==="month"&&(i<0||i>12))return M.date.messages.invalidMonth;if(s.type==="day"&&(n<0||n>31))return M.date.messages.invalidDay(31,"any month")}#g(e){let{year:s,month:i,day:n}=$s(this.#e);if(s&&i&&n){let r=$i(s,i);this.#e={...this.#e,day:String(Math.min(n,r)).padStart(2,"0")}}this.value=Jn(this.#e)??e.defaultValue??void 0}},zn=class extends Be{options;cursor=0;#t;getGroupItems(e){return this.options.filter(s=>s.group===e)}isGroupSelected(e){let s=this.getGroupItems(e),i=this.value;return i===void 0?!1:s.every(n=>i.includes(n.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let s=e.value,i=this.getGroupItems(s);this.isGroupSelected(s)?this.value=this.value.filter(n=>i.findIndex(r=>r.value===n)===-1):this.value=[...this.value,...i.map(n=>n.value)],this.value=Array.from(new Set(this.value))}else{let s=this.value.includes(e.value);this.value=s?this.value.filter(i=>i!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:s}=e;this.#t=e.selectableGroups!==!1,this.options=Object.entries(s).flatMap(([i,n])=>[{value:i,group:!0,label:i},...n.map(r=>({...r,group:i}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),this.#t?0:1),this.on("cursor",i=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let n=this.options[this.cursor]?.group===!0;!this.#t&&n&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let n=this.options[this.cursor]?.group===!0;!this.#t&&n&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ca=new Set(["up","down","left","right"]),vs=class extends Be{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return i===`
42
42
  `?`${s}\u2588
43
- ${n}`:`${s}${(0,St.styleText)("inverse",i)}${n}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#r(e){let s=this.value??"";switch(e){case"up":this._cursor=hs(this._cursor,0,-1,s);return;case"down":this._cursor=hs(this._cursor,0,1,s);return;case"left":this._cursor=hs(this._cursor,-1,0,s);return;case"right":this._cursor=hs(this._cursor,1,0,s);return}}_shouldSubmit(e,s){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
43
+ ${n}`:`${s}${(0,xt.styleText)("inverse",i)}${n}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#r(e){let s=this.value??"";switch(e){case"up":this._cursor=ps(this._cursor,0,-1,s);return;case"down":this._cursor=ps(this._cursor,0,1,s);return;case"left":this._cursor=ps(this._cursor,-1,0,s);return;case"right":this._cursor=ps(this._cursor,1,0,s);return}}_shouldSubmit(e,s){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
44
44
  `),this._cursor++,!1);let i=this.#t;return this.#t=!0,i&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
45
45
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
46
- `),this._cursor++,!1)}constructor(e){let s=e.initialUserInput??e.initialValue;super({...e,initialUserInput:s},!1),s!==void 0&&(this._cursor=s.length),this.#n=e.showSubmit??!1,this.on("key",(i,n)=>{if(n?.name&&va.has(n.name)){this.#t=!1,this.#r(n.name);return}if(i===" "&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(n?.name!=="return"){if(this.#t=!1,n?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(n?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}i&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(i??""),this._cursor++)}}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}},vs=class extends Je{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,s=this.value!==void 0&&this.value.length===e.length;this.value=s?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let s=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=s.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(s=>s!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let s=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[s]?.disabled?at(s,1,this.options):s,this.on("key",(i,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=at(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=at(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Gn=class extends Je{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${(0,St.styleText)(["inverse","hidden"],"_")}`;let s=this.masked,i=s.slice(0,this.cursor),n=s.slice(this.cursor,this.cursor+1),r=s.slice(this.cursor+1);return`${i}${(0,St.styleText)("inverse",n)}${r}`}clear(){this._clearUserInput()}constructor({mask:e,...s}){super(s),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value===void 0&&(this.value="")})}},Yn=class extends Je{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let s=this.options.findIndex(({value:n})=>n===e.initialValue),i=s===-1?0:s;this.cursor=this.options[i]?.disabled?at(i,1,this.options):i,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=at(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=at(this.cursor,1,this.options);break}this.changeValue()})}},ws=class extends Je{options;cursor=0;constructor(e){super(e,!1),this.options=e.options;let s=e.caseSensitive===!0,i=this.options.map(({value:[n]})=>s?n:n?.toLowerCase());this.cursor=Math.max(i.indexOf(e.initialValue),0),this.on("key",n=>{if(!n)return;let r=s?n:n.toLowerCase();if(!i.includes(r))return;let o=this.options.find(({value:[a]})=>s?a===r:a?.toLowerCase()===r);o&&(this.value=o.value,this.state="submit",this.emit("submit"))})}},_s=class extends Je{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return`${s}${(0,St.styleText)("inverse",i)}${n}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}});var Ti={};Nt(Ti,{MULTISELECT_INSTRUCTIONS:()=>Ai,SELECT_INSTRUCTIONS:()=>cr,S_BAR:()=>C,S_BAR_END:()=>me,S_BAR_END_RIGHT:()=>ir,S_BAR_H:()=>js,S_BAR_START:()=>_i,S_BAR_START_RIGHT:()=>sr,S_CHECKBOX_ACTIVE:()=>ks,S_CHECKBOX_INACTIVE:()=>Mt,S_CHECKBOX_SELECTED:()=>Ct,S_CONNECT_LEFT:()=>rr,S_CORNER_BOTTOM_LEFT:()=>ki,S_CORNER_BOTTOM_RIGHT:()=>xi,S_CORNER_TOP_LEFT:()=>or,S_CORNER_TOP_RIGHT:()=>Si,S_ERROR:()=>Ri,S_INFO:()=>ji,S_PASSWORD_MASK:()=>nr,S_RADIO_ACTIVE:()=>zt,S_RADIO_INACTIVE:()=>Rt,S_STEP_ACTIVE:()=>tr,S_STEP_CANCEL:()=>vi,S_STEP_ERROR:()=>wi,S_STEP_SUBMIT:()=>It,S_SUCCESS:()=>Ci,S_WARN:()=>Oi,autocomplete:()=>lr,autocompleteMultiselect:()=>Sa,box:()=>Ca,cancel:()=>Pa,confirm:()=>Be,date:()=>Oa,formatInstructionFooter:()=>Cs,group:()=>Ta,groupMultiselect:()=>Da,intro:()=>Na,isCI:()=>bi,isCancel:()=>ae,isTTY:()=>er,limitOptions:()=>bt,log:()=>Le,multiline:()=>La,multiselect:()=>Ea,note:()=>Va,outro:()=>Fa,password:()=>qa,path:()=>Wa,progress:()=>Ja,select:()=>ze,selectKey:()=>Ba,settings:()=>M,spinner:()=>Xt,stream:()=>jt,symbol:()=>Ue,symbolBar:()=>Ii,taskLog:()=>Ka,tasks:()=>Ga,text:()=>Te,unicode:()=>xs,unicodeOr:()=>re,updateSettings:()=>Wn});function wa(){return Fe.default.platform!=="win32"?Fe.default.env.TERM!=="linux":!!Fe.default.env.CI||!!Fe.default.env.WT_SESSION||!!Fe.default.env.TERMINUS_SUBLIME||Fe.default.env.ConEmuTask==="{cmd::Cmder}"||Fe.default.env.TERM_PROGRAM==="Terminus-Sublime"||Fe.default.env.TERM_PROGRAM==="vscode"||Fe.default.env.TERM==="xterm-256color"||Fe.default.env.TERM==="alacritty"||Fe.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Cs(t,e){let s=[`${e?`${(0,m.styleText)("cyan",C)} `:""}${t.join(" \u2022 ")}`];return e&&s.push((0,m.styleText)("cyan",me)),s}function zn(t){return t.label??String(t.value??"")}function ar(t,e){if(!t)return!0;let s=(e.label??String(e.value??"")).toLowerCase(),i=(e.hint??"").toLowerCase(),n=String(e.value).toLowerCase(),r=t.toLowerCase();return s.includes(r)||i.includes(r)||n.includes(r)}function _a(t,e){let s=[];for(let i of e)t.includes(i.value)&&s.push(i);return s}function Xn(t,e,s,i){let n=s,r=s;return i==="center"?n=Math.floor((e-t)/2):i==="right"&&(n=e-t-s),r=e-n-t,[n,r]}function Ra(t,e){let s=t.segmentValues,i=t.segmentCursor;if(e==="submit"||e==="cancel")return t.formattedValue;let n=(0,m.styleText)("gray",t.separator);return t.segments.map((r,o)=>{let a=o===i.segmentIndex&&!["submit","cancel"].includes(e),l=Aa[r.type];return Ia(s[r.type],{isActive:a,label:l})}).join(n)}function Ia(t,e){let s=!t||t.replace(/_/g,"")==="";return e.isActive?(0,m.styleText)("inverse",s?e.label:t.replace(/_/g," ")):s?(0,m.styleText)("dim",e.label):t.replace(/_/g,(0,m.styleText)("dim"," "))}function Ja({style:t="heavy",max:e=100,size:s=40,...i}={}){let n=Xt(i),r=0,o="",a=Math.max(1,e),l=Math.max(1,s),c=$=>{switch($){case"initial":case"active":return w=>(0,m.styleText)("magenta",w);case"error":case"cancel":return w=>(0,m.styleText)("red",w);case"submit":return w=>(0,m.styleText)("green",w);default:return w=>(0,m.styleText)("magenta",w)}},d=($,w)=>{let g=Math.floor(r/a*l);return`${c($)(Zn[t].repeat(g))}${(0,m.styleText)("dim",Zn[t].repeat(l-g))} ${w}`},f=($="")=>{o=$,n.start(d("initial",$))},p=($=1,w)=>{r=Math.min(a,$+r),n.message(d("active",w??o)),o=w??o};return{start:f,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:p,isCancelled:n.isCancelled,message:$=>p(0,$)}}var m,Fe,Ot,Kt,Ut,xs,bi,er,re,tr,vi,wi,It,_i,C,me,sr,ir,zt,Rt,ks,Ct,Mt,nr,js,Si,rr,xi,ki,or,ji,Ci,Oi,Ri,Ue,Ii,Kn,bt,lr,Sa,xa,ka,ja,Ca,Be,Oa,Aa,Ta,Ai,Yt,Ea,Da,Le,Pa,Na,Fa,La,Ua,Ma,Va,qa,Wa,Ha,Xt,Zn,cr,Ss,ze,Ba,Qn,jt,Ga,Ya,Ka,Te,De=xe(()=>{yi();yi();m=require("node:util"),Fe=F(require("node:process"),1);li();ni();Ot=require("node:fs"),Kt=require("node:path"),Ut=F(di(),1);xs=wa(),bi=()=>process.env.CI==="true",er=t=>t.isTTY===!0,re=(t,e)=>xs?t:e,tr=re("\u25C6","*"),vi=re("\u25A0","x"),wi=re("\u25B2","x"),It=re("\u25C7","o"),_i=re("\u250C","T"),C=re("\u2502","|"),me=re("\u2514","\u2014"),sr=re("\u2510","T"),ir=re("\u2518","\u2014"),zt=re("\u25CF",">"),Rt=re("\u25CB"," "),ks=re("\u25FB","[\u2022]"),Ct=re("\u25FC","[+]"),Mt=re("\u25FB","[ ]"),nr=re("\u25AA","\u2022"),js=re("\u2500","-"),Si=re("\u256E","+"),rr=re("\u251C","+"),xi=re("\u256F","+"),ki=re("\u2570","+"),or=re("\u256D","+"),ji=re("\u25CF","\u2022"),Ci=re("\u25C6","*"),Oi=re("\u25B2","!"),Ri=re("\u25A0","x"),Ue=t=>{switch(t){case"initial":case"active":return(0,m.styleText)("cyan",tr);case"cancel":return(0,m.styleText)("red",vi);case"error":return(0,m.styleText)("yellow",wi);case"submit":return(0,m.styleText)("green",It)}},Ii=t=>{switch(t){case"initial":case"active":return(0,m.styleText)("cyan",C);case"cancel":return(0,m.styleText)("red",C);case"error":return(0,m.styleText)("yellow",C);case"submit":return(0,m.styleText)("green",C)}};Kn=(t,e,s,i,n,r=!1)=>{let o=e,a=0;if(r)for(let l=i-1;l>=s;l--){let c=t[l];if(c&&(o-=c.length),a++,o<=n)break}else for(let l=s;l<i;l++){let c=t[l];if(c&&(o-=c.length),a++,o<=n)break}return{lineCount:o,removals:a}},bt=({cursor:t,options:e,style:s,output:i=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=kt(i)-r,l=gi(i),c=(0,m.styleText)("dim","..."),d=Math.max(l-o,0),f=Math.max(Math.min(n,d),5),p=0;t>=f-3&&(p=Math.max(Math.min(t-f+3,e.length-f),0));let $=f<e.length&&p>0,w=f<e.length&&p+f<e.length,g=Math.min(p+f,e.length),_=[],S=0;$&&S++,w&&S++;let R=p+($?1:0),N=g-(w?1:0);for(let U=R;U<N;U++){let le=e[U],Q=le?s(le,U===t):"",J=Ke(Q,a,{hard:!0,trim:!1}).split(`
47
- `);_.push(J),S+=J.length}if(S>d){let U=0,le=0,Q=S,J=t-R,A=d,te=()=>Kn(_,Q,0,J,A),B=()=>Kn(_,Q,J+1,_.length,A,!0);$?({lineCount:Q,removals:U}=te(),Q>A&&(w||(A-=1),{lineCount:Q,removals:le}=B())):(w||(A-=1),{lineCount:Q,removals:le}=B(),Q>A&&(A-=1,{lineCount:Q,removals:U}=te())),U>0&&($=!0,_.splice(0,U)),le>0&&(w=!0,_.splice(_.length-le,le))}let V=[];$&&V.push(c);for(let U of _)for(let le of U)V.push(le);return w&&V.push(c),V};lr=t=>new $i({options:t.options,initialValue:t.initialValue?[t.initialValue]:void 0,initialUserInput:t.initialUserInput,placeholder:t.placeholder,filter:t.filter??((e,s)=>ar(e,s)),signal:t.signal,input:t.input,output:t.output,validate:t.validate,render(){let e=t.withGuide??M.withGuide,s=e?[`${(0,m.styleText)("gray",C)}`,`${Ue(this.state)} ${t.message}`]:[`${Ue(this.state)} ${t.message}`],i=this.userInput,n=this.options,r=t.placeholder,o=i===""&&r!==void 0,a=(l,c)=>{let d=zn(l),f=l.hint&&l.value===this.focusedValue?(0,m.styleText)("dim",` (${l.hint})`):"";switch(c){case"active":return`${(0,m.styleText)("green",zt)} ${d}${f}`;case"inactive":return`${(0,m.styleText)("dim",Rt)} ${(0,m.styleText)("dim",d)}`;case"disabled":return`${(0,m.styleText)("gray",Rt)} ${(0,m.styleText)(["strikethrough","gray"],d)}`}};switch(this.state){case"submit":{let l=_a(this.selectedValues,n),c=l.length>0?` ${(0,m.styleText)("dim",l.map(zn).join(", "))}`:"",d=e?(0,m.styleText)("gray",C):"";return`${s.join(`
46
+ `),this._cursor++,!1)}constructor(e){let s=e.initialUserInput??e.initialValue;super({...e,initialUserInput:s},!1),s!==void 0&&(this._cursor=s.length),this.#n=e.showSubmit??!1,this.on("key",(i,n)=>{if(n?.name&&Ca.has(n.name)){this.#t=!1,this.#r(n.name);return}if(i===" "&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(n?.name!=="return"){if(this.#t=!1,n?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(n?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}i&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(i??""),this._cursor++)}}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}},ws=class extends Be{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,s=this.value!==void 0&&this.value.length===e.length;this.value=s?[]:e.map(i=>i.value)}toggleInvert(){let e=this.value;if(!e)return;let s=this._enabledOptions.filter(i=>!e.includes(i.value));this.value=s.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(s=>s!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let s=Math.max(this.options.findIndex(({value:i})=>i===e.cursorAt),0);this.cursor=this.options[s]?.disabled?lt(s,1,this.options):s,this.on("key",(i,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=lt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Xn=class extends Be{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${(0,xt.styleText)(["inverse","hidden"],"_")}`;let s=this.masked,i=s.slice(0,this.cursor),n=s.slice(this.cursor,this.cursor+1),r=s.slice(this.cursor+1);return`${i}${(0,xt.styleText)("inverse",n)}${r}`}clear(){this._clearUserInput()}constructor({mask:e,...s}){super(s),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value===void 0&&(this.value="")})}},Zn=class extends Be{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let s=this.options.findIndex(({value:n})=>n===e.initialValue),i=s===-1?0:s;this.cursor=this.options[i]?.disabled?lt(i,1,this.options):i,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=lt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lt(this.cursor,1,this.options);break}this.changeValue()})}},_s=class extends Be{options;cursor=0;constructor(e){super(e,!1),this.options=e.options;let s=e.caseSensitive===!0,i=this.options.map(({value:[n]})=>s?n:n?.toLowerCase());this.cursor=Math.max(i.indexOf(e.initialValue),0),this.on("key",n=>{if(!n)return;let r=s?n:n.toLowerCase();if(!i.includes(r))return;let o=this.options.find(({value:[a]})=>s?a===r:a?.toLowerCase()===r);o&&(this.value=o.value,this.state="submit",this.emit("submit"))})}},Ss=class extends Be{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let s=e.slice(0,this.cursor),i=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return`${s}${(0,xt.styleText)("inverse",i)}${n}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}});var Pi={};Ft(Pi,{MULTISELECT_INSTRUCTIONS:()=>Di,SELECT_INSTRUCTIONS:()=>fr,S_BAR:()=>R,S_BAR_END:()=>fe,S_BAR_END_RIGHT:()=>ar,S_BAR_H:()=>Cs,S_BAR_START:()=>ki,S_BAR_START_RIGHT:()=>or,S_CHECKBOX_ACTIVE:()=>js,S_CHECKBOX_INACTIVE:()=>Vt,S_CHECKBOX_SELECTED:()=>Ot,S_CONNECT_LEFT:()=>cr,S_CORNER_BOTTOM_LEFT:()=>Oi,S_CORNER_BOTTOM_RIGHT:()=>Ci,S_CORNER_TOP_LEFT:()=>dr,S_CORNER_TOP_RIGHT:()=>ji,S_ERROR:()=>Ti,S_INFO:()=>Ri,S_PASSWORD_MASK:()=>lr,S_RADIO_ACTIVE:()=>Xt,S_RADIO_INACTIVE:()=>It,S_STEP_ACTIVE:()=>rr,S_STEP_CANCEL:()=>Si,S_STEP_ERROR:()=>xi,S_STEP_SUBMIT:()=>At,S_SUCCESS:()=>Ii,S_WARN:()=>Ai,autocomplete:()=>mr,autocompleteMultiselect:()=>Ia,box:()=>Da,cancel:()=>qa,confirm:()=>Ge,date:()=>Pa,formatInstructionFooter:()=>Os,group:()=>Ua,groupMultiselect:()=>Va,intro:()=>Wa,isCI:()=>_i,isCancel:()=>ae,isTTY:()=>nr,limitOptions:()=>vt,log:()=>Ue,multiline:()=>Ja,multiselect:()=>Ma,note:()=>Ya,outro:()=>Ha,password:()=>Ka,path:()=>za,progress:()=>Za,select:()=>Xe,selectKey:()=>Qa,settings:()=>M,spinner:()=>Zt,stream:()=>Ct,symbol:()=>Me,symbolBar:()=>Ei,taskLog:()=>sl,tasks:()=>el,text:()=>Te,unicode:()=>ks,unicodeOr:()=>re,updateSettings:()=>Gn});function Oa(){return Le.default.platform!=="win32"?Le.default.env.TERM!=="linux":!!Le.default.env.CI||!!Le.default.env.WT_SESSION||!!Le.default.env.TERMINUS_SUBLIME||Le.default.env.ConEmuTask==="{cmd::Cmder}"||Le.default.env.TERM_PROGRAM==="Terminus-Sublime"||Le.default.env.TERM_PROGRAM==="vscode"||Le.default.env.TERM==="xterm-256color"||Le.default.env.TERM==="alacritty"||Le.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Os(t,e){let s=[`${e?`${(0,m.styleText)("cyan",R)} `:""}${t.join(" \u2022 ")}`];return e&&s.push((0,m.styleText)("cyan",fe)),s}function er(t){return t.label??String(t.value??"")}function ur(t,e){if(!t)return!0;let s=(e.label??String(e.value??"")).toLowerCase(),i=(e.hint??"").toLowerCase(),n=String(e.value).toLowerCase(),r=t.toLowerCase();return s.includes(r)||i.includes(r)||n.includes(r)}function Ra(t,e){let s=[];for(let i of e)t.includes(i.value)&&s.push(i);return s}function tr(t,e,s,i){let n=s,r=s;return i==="center"?n=Math.floor((e-t)/2):i==="right"&&(n=e-t-s),r=e-n-t,[n,r]}function Na(t,e){let s=t.segmentValues,i=t.segmentCursor;if(e==="submit"||e==="cancel")return t.formattedValue;let n=(0,m.styleText)("gray",t.separator);return t.segments.map((r,o)=>{let a=o===i.segmentIndex&&!["submit","cancel"].includes(e),l=La[r.type];return Fa(s[r.type],{isActive:a,label:l})}).join(n)}function Fa(t,e){let s=!t||t.replace(/_/g,"")==="";return e.isActive?(0,m.styleText)("inverse",s?e.label:t.replace(/_/g," ")):s?(0,m.styleText)("dim",e.label):t.replace(/_/g,(0,m.styleText)("dim"," "))}function Za({style:t="heavy",max:e=100,size:s=40,...i}={}){let n=Zt(i),r=0,o="",a=Math.max(1,e),l=Math.max(1,s),c=y=>{switch(y){case"initial":case"active":return w=>(0,m.styleText)("magenta",w);case"error":case"cancel":return w=>(0,m.styleText)("red",w);case"submit":return w=>(0,m.styleText)("green",w);default:return w=>(0,m.styleText)("magenta",w)}},u=(y,w)=>{let $=Math.floor(r/a*l);return`${c(y)(sr[t].repeat($))}${(0,m.styleText)("dim",sr[t].repeat(l-$))} ${w}`},f=(y="")=>{o=y,n.start(u("initial",y))},p=(y=1,w)=>{r=Math.min(a,y+r),n.message(u("active",w??o)),o=w??o};return{start:f,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:p,isCancelled:n.isCancelled,message:y=>p(0,y)}}var m,Le,Rt,zt,Mt,ks,_i,nr,re,rr,Si,xi,At,ki,R,fe,or,ar,Xt,It,js,Ot,Vt,lr,Cs,ji,cr,Ci,Oi,dr,Ri,Ii,Ai,Ti,Me,Ei,Qn,vt,mr,Ia,Aa,Ta,Ea,Da,Ge,Pa,La,Ua,Di,Kt,Ma,Va,Ue,qa,Wa,Ha,Ja,Ba,Ga,Ya,Ka,za,Xa,Zt,sr,fr,xs,Xe,Qa,ir,Ct,el,tl,sl,Te,De=xe(()=>{wi();wi();m=require("node:util"),Le=F(require("node:process"),1);ui();ai();Rt=require("node:fs"),zt=require("node:path"),Mt=F(fi(),1);ks=Oa(),_i=()=>process.env.CI==="true",nr=t=>t.isTTY===!0,re=(t,e)=>ks?t:e,rr=re("\u25C6","*"),Si=re("\u25A0","x"),xi=re("\u25B2","x"),At=re("\u25C7","o"),ki=re("\u250C","T"),R=re("\u2502","|"),fe=re("\u2514","\u2014"),or=re("\u2510","T"),ar=re("\u2518","\u2014"),Xt=re("\u25CF",">"),It=re("\u25CB"," "),js=re("\u25FB","[\u2022]"),Ot=re("\u25FC","[+]"),Vt=re("\u25FB","[ ]"),lr=re("\u25AA","\u2022"),Cs=re("\u2500","-"),ji=re("\u256E","+"),cr=re("\u251C","+"),Ci=re("\u256F","+"),Oi=re("\u2570","+"),dr=re("\u256D","+"),Ri=re("\u25CF","\u2022"),Ii=re("\u25C6","*"),Ai=re("\u25B2","!"),Ti=re("\u25A0","x"),Me=t=>{switch(t){case"initial":case"active":return(0,m.styleText)("cyan",rr);case"cancel":return(0,m.styleText)("red",Si);case"error":return(0,m.styleText)("yellow",xi);case"submit":return(0,m.styleText)("green",At)}},Ei=t=>{switch(t){case"initial":case"active":return(0,m.styleText)("cyan",R);case"cancel":return(0,m.styleText)("red",R);case"error":return(0,m.styleText)("yellow",R);case"submit":return(0,m.styleText)("green",R)}};Qn=(t,e,s,i,n,r=!1)=>{let o=e,a=0;if(r)for(let l=i-1;l>=s;l--){let c=t[l];if(c&&(o-=c.length),a++,o<=n)break}else for(let l=s;l<i;l++){let c=t[l];if(c&&(o-=c.length),a++,o<=n)break}return{lineCount:o,removals:a}},vt=({cursor:t,options:e,style:s,output:i=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=jt(i)-r,l=bi(i),c=(0,m.styleText)("dim","..."),u=Math.max(l-o,0),f=Math.max(Math.min(n,u),5),p=0;t>=f-3&&(p=Math.max(Math.min(t-f+3,e.length-f),0));let y=f<e.length&&p>0,w=f<e.length&&p+f<e.length,$=Math.min(p+f,e.length),_=[],S=0;y&&S++,w&&S++;let I=p+(y?1:0),N=$-(w?1:0);for(let U=I;U<N;U++){let le=e[U],Q=le?s(le,U===t):"",J=ze(Q,a,{hard:!0,trim:!1}).split(`
47
+ `);_.push(J),S+=J.length}if(S>u){let U=0,le=0,Q=S,J=t-I,A=u,te=()=>Qn(_,Q,0,J,A),B=()=>Qn(_,Q,J+1,_.length,A,!0);y?({lineCount:Q,removals:U}=te(),Q>A&&(w||(A-=1),{lineCount:Q,removals:le}=B())):(w||(A-=1),{lineCount:Q,removals:le}=B(),Q>A&&(A-=1,{lineCount:Q,removals:U}=te())),U>0&&(y=!0,_.splice(0,U)),le>0&&(w=!0,_.splice(_.length-le,le))}let q=[];y&&q.push(c);for(let U of _)for(let le of U)q.push(le);return w&&q.push(c),q};mr=t=>new vi({options:t.options,initialValue:t.initialValue?[t.initialValue]:void 0,initialUserInput:t.initialUserInput,placeholder:t.placeholder,filter:t.filter??((e,s)=>ur(e,s)),signal:t.signal,input:t.input,output:t.output,validate:t.validate,render(){let e=t.withGuide??M.withGuide,s=e?[`${(0,m.styleText)("gray",R)}`,`${Me(this.state)} ${t.message}`]:[`${Me(this.state)} ${t.message}`],i=this.userInput,n=this.options,r=t.placeholder,o=i===""&&r!==void 0,a=(l,c)=>{let u=er(l),f=l.hint&&l.value===this.focusedValue?(0,m.styleText)("dim",` (${l.hint})`):"";switch(c){case"active":return`${(0,m.styleText)("green",Xt)} ${u}${f}`;case"inactive":return`${(0,m.styleText)("dim",It)} ${(0,m.styleText)("dim",u)}`;case"disabled":return`${(0,m.styleText)("gray",It)} ${(0,m.styleText)(["strikethrough","gray"],u)}`}};switch(this.state){case"submit":{let l=Ra(this.selectedValues,n),c=l.length>0?` ${(0,m.styleText)("dim",l.map(er).join(", "))}`:"",u=e?(0,m.styleText)("gray",R):"";return`${s.join(`
48
48
  `)}
49
- ${d}${c}`}case"cancel":{let l=i?` ${(0,m.styleText)(["strikethrough","dim"],i)}`:"",c=e?(0,m.styleText)("gray",C):"";return`${s.join(`
49
+ ${u}${c}`}case"cancel":{let l=i?` ${(0,m.styleText)(["strikethrough","dim"],i)}`:"",c=e?(0,m.styleText)("gray",R):"";return`${s.join(`
50
50
  `)}
51
- ${c}${l}`}default:{let l=this.state==="error"?"yellow":"cyan",c=e?`${(0,m.styleText)(l,C)} `:"",d=e?(0,m.styleText)(l,me):"",f="";if(this.isNavigating||o){let R=o?r:i;f=R!==""?` ${(0,m.styleText)("dim",R)}`:""}else f=` ${this.userInputWithCursor}`;let p=this.filteredOptions.length!==n.length?(0,m.styleText)("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",$=this.filteredOptions.length===0&&i?[`${c}${(0,m.styleText)("yellow","No matches found")}`]:[],w=this.state==="error"?[`${c}${(0,m.styleText)("yellow",this.error)}`]:[];e&&s.push(`${c.trimEnd()}`),s.push(`${c}${(0,m.styleText)("dim","Search:")}${f}${p}`,...$,...w);let g=[`${(0,m.styleText)("dim","\u2191/\u2193")} to select`,`${(0,m.styleText)("dim","Enter:")} confirm`,`${(0,m.styleText)("dim","Type:")} to search`],_=[`${c}${g.join(" \u2022 ")}`,d],S=this.filteredOptions.length===0?[]:bt({cursor:this.cursor,options:this.filteredOptions,columnPadding:e?3:0,rowPadding:s.length+_.length,style:(R,N)=>a(R,R.disabled?"disabled":N?"active":"inactive"),maxItems:t.maxItems,output:t.output});return[...s,...S.map(R=>`${c}${R}`),..._].join(`
52
- `)}}}}).prompt(),Sa=t=>{let e=(i,n,r,o)=>{let a=r.includes(i.value),l=i.label??String(i.value??""),c=i.hint&&o!==void 0&&i.value===o?(0,m.styleText)("dim",` (${i.hint})`):"",d=a?(0,m.styleText)("green",Ct):(0,m.styleText)("dim",Mt);return i.disabled?`${(0,m.styleText)("gray",Mt)} ${(0,m.styleText)(["strikethrough","gray"],l)}`:n?`${d} ${l}${c}`:`${d} ${(0,m.styleText)("dim",l)}`},s=new $i({options:t.options,multiple:!0,placeholder:t.placeholder,filter:t.filter??((i,n)=>ar(i,n)),validate:()=>{if(t.required&&s.selectedValues.length===0)return"Please select at least one item"},initialValue:t.initialValues,signal:t.signal,input:t.input,output:t.output,render(){let i=t.withGuide??M.withGuide,n=`${i?`${(0,m.styleText)("gray",C)}
53
- `:""}${Ue(this.state)} ${t.message}
54
- `,r=this.userInput,o=t.placeholder,a=r===""&&o!==void 0,l=this.isNavigating||a?(0,m.styleText)("dim",a?o:r):this.userInputWithCursor,c=this.options,d=this.filteredOptions.length!==c.length?(0,m.styleText)("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${n}${i?`${(0,m.styleText)("gray",C)} `:""}${(0,m.styleText)("dim",`${this.selectedValues.length} items selected`)}`;case"cancel":return`${n}${i?`${(0,m.styleText)("gray",C)} `:""}${(0,m.styleText)(["strikethrough","dim"],r)}`;default:{let f=this.state==="error"?"yellow":"cyan",p=i?`${(0,m.styleText)(f,C)} `:"",$=i?(0,m.styleText)(f,me):"",w=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim",this.isNavigating?"Space/Tab:":"Tab:")} select`,`${(0,m.styleText)("dim","Enter:")} confirm`,`${(0,m.styleText)("dim","Type:")} to search`],g=this.filteredOptions.length===0&&r?[`${p}${(0,m.styleText)("yellow","No matches found")}`]:[],_=this.state==="error"?[`${p}${(0,m.styleText)("yellow",this.error)}`]:[],S=[...`${n}${i?(0,m.styleText)(f,C):""}`.split(`
55
- `),`${p}${(0,m.styleText)("dim","Search:")} ${l}${d}`,...g,..._],R=[`${p}${w.join(" \u2022 ")}`,$],N=bt({cursor:this.cursor,options:this.filteredOptions,style:(V,U)=>e(V,U,this.selectedValues,this.focusedValue),maxItems:t.maxItems,output:t.output,rowPadding:S.length+R.length});return[...S,...N.map(V=>`${p}${V}`),...R].join(`
56
- `)}}}});return s.prompt()},xa=[or,Si,ki,xi],ka=[_i,sr,me,ir];ja=t=>t,Ca=(t="",e="",s)=>{let i=s?.output??process.stdout,n=kt(i),r=2,o=s?.titlePadding??1,a=s?.contentPadding??2,l=s?.width===void 0||s.width==="auto"?1:Math.min(1,s.width),c=s?.withGuide??M.withGuide?`${C} `:"",d=s?.formatBorder??ja,f=(s?.rounded?xa:ka).map(d),p=d(js),$=d(C),w=$e(c),g=$e(e),_=n-w,S=Math.floor(n*l)-w;if(s?.width==="auto"){let A=t.split(`
57
- `),te=g+o*2;for(let E of A){let ie=$e(E)+a*2;ie>te&&(te=ie)}let B=te+r;B<S&&(S=B)}S%2!==0&&(S<_?S++:S--);let R=S-r,N=R-o*2,V=g>N?`${e.slice(0,N-3)}...`:e,[U,le]=Xn($e(V),R,o,s?.titleAlign),Q=Ke(t,R-a*2,{hard:!0,trim:!1});i.write(`${c}${f[0]}${p.repeat(U)}${V}${p.repeat(le)}${f[1]}
51
+ ${c}${l}`}default:{let l=this.state==="error"?"yellow":"cyan",c=e?`${(0,m.styleText)(l,R)} `:"",u=e?(0,m.styleText)(l,fe):"",f="";if(this.isNavigating||o){let I=o?r:i;f=I!==""?` ${(0,m.styleText)("dim",I)}`:""}else f=` ${this.userInputWithCursor}`;let p=this.filteredOptions.length!==n.length?(0,m.styleText)("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",y=this.filteredOptions.length===0&&i?[`${c}${(0,m.styleText)("yellow","No matches found")}`]:[],w=this.state==="error"?[`${c}${(0,m.styleText)("yellow",this.error)}`]:[];e&&s.push(`${c.trimEnd()}`),s.push(`${c}${(0,m.styleText)("dim","Search:")}${f}${p}`,...y,...w);let $=[`${(0,m.styleText)("dim","\u2191/\u2193")} to select`,`${(0,m.styleText)("dim","Enter:")} confirm`,`${(0,m.styleText)("dim","Type:")} to search`],_=[`${c}${$.join(" \u2022 ")}`,u],S=this.filteredOptions.length===0?[]:vt({cursor:this.cursor,options:this.filteredOptions,columnPadding:e?3:0,rowPadding:s.length+_.length,style:(I,N)=>a(I,I.disabled?"disabled":N?"active":"inactive"),maxItems:t.maxItems,output:t.output});return[...s,...S.map(I=>`${c}${I}`),..._].join(`
52
+ `)}}}}).prompt(),Ia=t=>{let e=(i,n,r,o)=>{let a=r.includes(i.value),l=i.label??String(i.value??""),c=i.hint&&o!==void 0&&i.value===o?(0,m.styleText)("dim",` (${i.hint})`):"",u=a?(0,m.styleText)("green",Ot):(0,m.styleText)("dim",Vt);return i.disabled?`${(0,m.styleText)("gray",Vt)} ${(0,m.styleText)(["strikethrough","gray"],l)}`:n?`${u} ${l}${c}`:`${u} ${(0,m.styleText)("dim",l)}`},s=new vi({options:t.options,multiple:!0,placeholder:t.placeholder,filter:t.filter??((i,n)=>ur(i,n)),validate:()=>{if(t.required&&s.selectedValues.length===0)return"Please select at least one item"},initialValue:t.initialValues,signal:t.signal,input:t.input,output:t.output,render(){let i=t.withGuide??M.withGuide,n=`${i?`${(0,m.styleText)("gray",R)}
53
+ `:""}${Me(this.state)} ${t.message}
54
+ `,r=this.userInput,o=t.placeholder,a=r===""&&o!==void 0,l=this.isNavigating||a?(0,m.styleText)("dim",a?o:r):this.userInputWithCursor,c=this.options,u=this.filteredOptions.length!==c.length?(0,m.styleText)("dim",` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${n}${i?`${(0,m.styleText)("gray",R)} `:""}${(0,m.styleText)("dim",`${this.selectedValues.length} items selected`)}`;case"cancel":return`${n}${i?`${(0,m.styleText)("gray",R)} `:""}${(0,m.styleText)(["strikethrough","dim"],r)}`;default:{let f=this.state==="error"?"yellow":"cyan",p=i?`${(0,m.styleText)(f,R)} `:"",y=i?(0,m.styleText)(f,fe):"",w=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim",this.isNavigating?"Space/Tab:":"Tab:")} select`,`${(0,m.styleText)("dim","Enter:")} confirm`,`${(0,m.styleText)("dim","Type:")} to search`],$=this.filteredOptions.length===0&&r?[`${p}${(0,m.styleText)("yellow","No matches found")}`]:[],_=this.state==="error"?[`${p}${(0,m.styleText)("yellow",this.error)}`]:[],S=[...`${n}${i?(0,m.styleText)(f,R):""}`.split(`
55
+ `),`${p}${(0,m.styleText)("dim","Search:")} ${l}${u}`,...$,..._],I=[`${p}${w.join(" \u2022 ")}`,y],N=vt({cursor:this.cursor,options:this.filteredOptions,style:(q,U)=>e(q,U,this.selectedValues,this.focusedValue),maxItems:t.maxItems,output:t.output,rowPadding:S.length+I.length});return[...S,...N.map(q=>`${p}${q}`),...I].join(`
56
+ `)}}}});return s.prompt()},Aa=[dr,ji,Oi,Ci],Ta=[ki,or,fe,ar];Ea=t=>t,Da=(t="",e="",s)=>{let i=s?.output??process.stdout,n=jt(i),r=2,o=s?.titlePadding??1,a=s?.contentPadding??2,l=s?.width===void 0||s.width==="auto"?1:Math.min(1,s.width),c=s?.withGuide??M.withGuide?`${R} `:"",u=s?.formatBorder??Ea,f=(s?.rounded?Aa:Ta).map(u),p=u(Cs),y=u(R),w=ye(c),$=ye(e),_=n-w,S=Math.floor(n*l)-w;if(s?.width==="auto"){let A=t.split(`
57
+ `),te=$+o*2;for(let E of A){let ie=ye(E)+a*2;ie>te&&(te=ie)}let B=te+r;B<S&&(S=B)}S%2!==0&&(S<_?S++:S--);let I=S-r,N=I-o*2,q=$>N?`${e.slice(0,N-3)}...`:e,[U,le]=tr(ye(q),I,o,s?.titleAlign),Q=ze(t,I-a*2,{hard:!0,trim:!1});i.write(`${c}${f[0]}${p.repeat(U)}${q}${p.repeat(le)}${f[1]}
58
58
  `);let J=Q.split(`
59
- `);for(let A of J){let[te,B]=Xn($e(A),R,a,s?.contentAlign);i.write(`${c}${$}${" ".repeat(te)}${A}${" ".repeat(B)}${$}
60
- `)}i.write(`${c}${f[2]}${p.repeat(R)}${f[3]}
61
- `)},Be=t=>{let e=t.active??"Yes",s=t.inactive??"No";return new $s({active:e,inactive:s,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let i=t.withGuide??M.withGuide,n=`${Ue(this.state)} `,r=i?`${(0,m.styleText)("gray",C)} `:"",o=pe(t.output,t.message,r,n),a=`${i?`${(0,m.styleText)("gray",C)}
59
+ `);for(let A of J){let[te,B]=tr(ye(A),I,a,s?.contentAlign);i.write(`${c}${y}${" ".repeat(te)}${A}${" ".repeat(B)}${y}
60
+ `)}i.write(`${c}${f[2]}${p.repeat(I)}${f[3]}
61
+ `)},Ge=t=>{let e=t.active??"Yes",s=t.inactive??"No";return new ys({active:e,inactive:s,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let i=t.withGuide??M.withGuide,n=`${Me(this.state)} `,r=i?`${(0,m.styleText)("gray",R)} `:"",o=pe(t.output,t.message,r,n),a=`${i?`${(0,m.styleText)("gray",R)}
62
62
  `:""}${o}
63
- `,l=this.value?e:s;switch(this.state){case"submit":{let c=i?`${(0,m.styleText)("gray",C)} `:"";return`${a}${c}${(0,m.styleText)("dim",l)}`}case"cancel":{let c=i?`${(0,m.styleText)("gray",C)} `:"";return`${a}${c}${(0,m.styleText)(["strikethrough","dim"],l)}${i?`
64
- ${(0,m.styleText)("gray",C)}`:""}`}default:{let c=i?`${(0,m.styleText)("cyan",C)} `:"",d=i?(0,m.styleText)("cyan",me):"";return`${a}${c}${this.value?`${(0,m.styleText)("green",zt)} ${e}`:`${(0,m.styleText)("dim",Rt)} ${(0,m.styleText)("dim",e)}`}${t.vertical?i?`
65
- ${(0,m.styleText)("cyan",C)} `:`
66
- `:` ${(0,m.styleText)("dim","/")} `}${this.value?`${(0,m.styleText)("dim",Rt)} ${(0,m.styleText)("dim",s)}`:`${(0,m.styleText)("green",zt)} ${s}`}
67
- ${d}
68
- `}}}}).prompt()},Oa=t=>{let e=t.validate;return new ys({...t,validate(s){if(s===void 0)return t.defaultValue!==void 0?void 0:e?Gt(e,s):M.date.messages.required;let i=n=>n.toISOString().slice(0,10);if(t.minDate&&i(s)<i(t.minDate))return M.date.messages.afterMin(t.minDate);if(t.maxDate&&i(s)>i(t.maxDate))return M.date.messages.beforeMax(t.maxDate);if(e)return Gt(e,s)},render(){let s=(t?.withGuide??M.withGuide)!==!1,i=`${`${s?`${(0,m.styleText)("gray",C)}
69
- `:""}${Ue(this.state)} `}${t.message}
70
- `,n=this.state!=="initial"?this.state:"active",r=Ra(this,n),o=this.value instanceof Date?this.formattedValue:"";switch(this.state){case"error":{let a=this.error?` ${(0,m.styleText)("yellow",this.error)}`:"",l=s?`${(0,m.styleText)("yellow",C)} `:"",c=s?(0,m.styleText)("yellow",me):"";return`${i.trim()}
63
+ `,l=this.value?e:s;switch(this.state){case"submit":{let c=i?`${(0,m.styleText)("gray",R)} `:"";return`${a}${c}${(0,m.styleText)("dim",l)}`}case"cancel":{let c=i?`${(0,m.styleText)("gray",R)} `:"";return`${a}${c}${(0,m.styleText)(["strikethrough","dim"],l)}${i?`
64
+ ${(0,m.styleText)("gray",R)}`:""}`}default:{let c=i?`${(0,m.styleText)("cyan",R)} `:"",u=i?(0,m.styleText)("cyan",fe):"";return`${a}${c}${this.value?`${(0,m.styleText)("green",Xt)} ${e}`:`${(0,m.styleText)("dim",It)} ${(0,m.styleText)("dim",e)}`}${t.vertical?i?`
65
+ ${(0,m.styleText)("cyan",R)} `:`
66
+ `:` ${(0,m.styleText)("dim","/")} `}${this.value?`${(0,m.styleText)("dim",It)} ${(0,m.styleText)("dim",s)}`:`${(0,m.styleText)("green",Xt)} ${s}`}
67
+ ${u}
68
+ `}}}}).prompt()},Pa=t=>{let e=t.validate;return new bs({...t,validate(s){if(s===void 0)return t.defaultValue!==void 0?void 0:e?Yt(e,s):M.date.messages.required;let i=n=>n.toISOString().slice(0,10);if(t.minDate&&i(s)<i(t.minDate))return M.date.messages.afterMin(t.minDate);if(t.maxDate&&i(s)>i(t.maxDate))return M.date.messages.beforeMax(t.maxDate);if(e)return Yt(e,s)},render(){let s=(t?.withGuide??M.withGuide)!==!1,i=`${`${s?`${(0,m.styleText)("gray",R)}
69
+ `:""}${Me(this.state)} `}${t.message}
70
+ `,n=this.state!=="initial"?this.state:"active",r=Na(this,n),o=this.value instanceof Date?this.formattedValue:"";switch(this.state){case"error":{let a=this.error?` ${(0,m.styleText)("yellow",this.error)}`:"",l=s?`${(0,m.styleText)("yellow",R)} `:"",c=s?(0,m.styleText)("yellow",fe):"";return`${i.trim()}
71
71
  ${l}${r}
72
72
  ${c}${a}
73
- `}case"submit":{let a=o?` ${(0,m.styleText)("dim",o)}`:"",l=s?(0,m.styleText)("gray",C):"";return`${i}${l}${a}`}case"cancel":{let a=o?` ${(0,m.styleText)(["strikethrough","dim"],o)}`:"",l=s?(0,m.styleText)("gray",C):"";return`${i}${l}${a}${o.trim()?`
74
- ${l}`:""}`}default:{let a=s?`${(0,m.styleText)("cyan",C)} `:"",l=s?(0,m.styleText)("cyan",me):"",c=s?`${(0,m.styleText)("cyan",C)} `:"",d=this.inlineError?`
75
- ${c}${(0,m.styleText)("yellow",this.inlineError)}`:"";return`${i}${a}${r}${d}
73
+ `}case"submit":{let a=o?` ${(0,m.styleText)("dim",o)}`:"",l=s?(0,m.styleText)("gray",R):"";return`${i}${l}${a}`}case"cancel":{let a=o?` ${(0,m.styleText)(["strikethrough","dim"],o)}`:"",l=s?(0,m.styleText)("gray",R):"";return`${i}${l}${a}${o.trim()?`
74
+ ${l}`:""}`}default:{let a=s?`${(0,m.styleText)("cyan",R)} `:"",l=s?(0,m.styleText)("cyan",fe):"",c=s?`${(0,m.styleText)("cyan",R)} `:"",u=this.inlineError?`
75
+ ${c}${(0,m.styleText)("yellow",this.inlineError)}`:"";return`${i}${a}${r}${u}
76
76
  ${l}
77
- `}}}}).prompt()};Aa={year:"yyyy",month:"mm",day:"dd"},Ta=async(t,e)=>{let s={},i=Object.keys(t);for(let n of i){let r=t[n],o=await r({results:s})?.catch(a=>{throw a});if(typeof e?.onCancel=="function"&&ae(o)){s[n]="canceled",e.onCancel({results:s});continue}s[n]=o}return s},Ai=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim","Space:")} select`,`${(0,m.styleText)("dim","Enter:")} confirm`],Yt=(t,e)=>t.split(`
77
+ `}}}}).prompt()};La={year:"yyyy",month:"mm",day:"dd"},Ua=async(t,e)=>{let s={},i=Object.keys(t);for(let n of i){let r=t[n],o=await r({results:s})?.catch(a=>{throw a});if(typeof e?.onCancel=="function"&&ae(o)){s[n]="canceled",e.onCancel({results:s});continue}s[n]=o}return s},Di=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim","Space:")} select`,`${(0,m.styleText)("dim","Enter:")} confirm`],Kt=(t,e)=>t.split(`
78
78
  `).map(s=>e(s)).join(`
79
- `),Ea=t=>{let e=(n,r)=>{let o=n.label??String(n.value);return r==="disabled"?`${(0,m.styleText)("gray",Mt)} ${Yt(o,a=>(0,m.styleText)(["strikethrough","gray"],a))}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint??"disabled"})`)}`:""}`:r==="active"?`${(0,m.styleText)("cyan",ks)} ${o}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="selected"?`${(0,m.styleText)("green",Ct)} ${Yt(o,a=>(0,m.styleText)("dim",a))}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="cancelled"?`${Yt(o,a=>(0,m.styleText)(["strikethrough","dim"],a))}`:r==="active-selected"?`${(0,m.styleText)("green",Ct)} ${o}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="submitted"?`${Yt(o,a=>(0,m.styleText)("dim",a))}`:`${(0,m.styleText)("dim",Mt)} ${Yt(o,a=>(0,m.styleText)("dim",a))}`},s=t.required??!0,i=t.showInstructions??!0;return new vs({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:s,cursorAt:t.cursorAt,validate(n){if(s&&(n===void 0||n.length===0))return`Please select at least one option.
80
- ${(0,m.styleText)("reset",(0,m.styleText)("dim",`Press ${(0,m.styleText)(["gray","bgWhite","inverse"]," space ")} to select, ${(0,m.styleText)("gray",(0,m.styleText)("bgWhite",(0,m.styleText)("inverse"," enter ")))} to submit`))}`},render(){let n=t.withGuide??M.withGuide,r=pe(t.output,t.message,n?`${Ii(this.state)} `:"",`${Ue(this.state)} `),o=`${n?`${(0,m.styleText)("gray",C)}
79
+ `),Ma=t=>{let e=(n,r)=>{let o=n.label??String(n.value);return r==="disabled"?`${(0,m.styleText)("gray",Vt)} ${Kt(o,a=>(0,m.styleText)(["strikethrough","gray"],a))}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint??"disabled"})`)}`:""}`:r==="active"?`${(0,m.styleText)("cyan",js)} ${o}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="selected"?`${(0,m.styleText)("green",Ot)} ${Kt(o,a=>(0,m.styleText)("dim",a))}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="cancelled"?`${Kt(o,a=>(0,m.styleText)(["strikethrough","dim"],a))}`:r==="active-selected"?`${(0,m.styleText)("green",Ot)} ${o}${n.hint?` ${(0,m.styleText)("dim",`(${n.hint})`)}`:""}`:r==="submitted"?`${Kt(o,a=>(0,m.styleText)("dim",a))}`:`${(0,m.styleText)("dim",Vt)} ${Kt(o,a=>(0,m.styleText)("dim",a))}`},s=t.required??!0,i=t.showInstructions??!0;return new ws({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:s,cursorAt:t.cursorAt,validate(n){if(s&&(n===void 0||n.length===0))return`Please select at least one option.
80
+ ${(0,m.styleText)("reset",(0,m.styleText)("dim",`Press ${(0,m.styleText)(["gray","bgWhite","inverse"]," space ")} to select, ${(0,m.styleText)("gray",(0,m.styleText)("bgWhite",(0,m.styleText)("inverse"," enter ")))} to submit`))}`},render(){let n=t.withGuide??M.withGuide,r=pe(t.output,t.message,n?`${Ei(this.state)} `:"",`${Me(this.state)} `),o=`${n?`${(0,m.styleText)("gray",R)}
81
81
  `:""}${r}
82
- `,a=this.value??[],l=(c,d)=>{if(c.disabled)return e(c,"disabled");let f=a.includes(c.value);return d&&f?e(c,"active-selected"):f?e(c,"selected"):e(c,d?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:f})=>a.includes(f)).map(f=>e(f,"submitted")).join((0,m.styleText)("dim",", "))||(0,m.styleText)("dim","none"),d=pe(t.output,c,n?`${(0,m.styleText)("gray",C)} `:"");return`${o}${d}`}case"cancel":{let c=this.options.filter(({value:f})=>a.includes(f)).map(f=>e(f,"cancelled")).join((0,m.styleText)("dim",", "));if(c.trim()==="")return`${o}${(0,m.styleText)("gray",C)}`;let d=pe(t.output,c,n?`${(0,m.styleText)("gray",C)} `:"");return`${o}${d}${n?`
83
- ${(0,m.styleText)("gray",C)}`:""}`}case"error":{let c=n?`${(0,m.styleText)("yellow",C)} `:"",d=this.error.split(`
84
- `).map(($,w)=>w===0?`${n?`${(0,m.styleText)("yellow",me)} `:""}${(0,m.styleText)("yellow",$)}`:` ${$}`).join(`
82
+ `,a=this.value??[],l=(c,u)=>{if(c.disabled)return e(c,"disabled");let f=a.includes(c.value);return u&&f?e(c,"active-selected"):f?e(c,"selected"):e(c,u?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:f})=>a.includes(f)).map(f=>e(f,"submitted")).join((0,m.styleText)("dim",", "))||(0,m.styleText)("dim","none"),u=pe(t.output,c,n?`${(0,m.styleText)("gray",R)} `:"");return`${o}${u}`}case"cancel":{let c=this.options.filter(({value:f})=>a.includes(f)).map(f=>e(f,"cancelled")).join((0,m.styleText)("dim",", "));if(c.trim()==="")return`${o}${(0,m.styleText)("gray",R)}`;let u=pe(t.output,c,n?`${(0,m.styleText)("gray",R)} `:"");return`${o}${u}${n?`
83
+ ${(0,m.styleText)("gray",R)}`:""}`}case"error":{let c=n?`${(0,m.styleText)("yellow",R)} `:"",u=this.error.split(`
84
+ `).map((y,w)=>w===0?`${n?`${(0,m.styleText)("yellow",fe)} `:""}${(0,m.styleText)("yellow",y)}`:` ${y}`).join(`
85
85
  `),f=o.split(`
86
- `).length,p=d.split(`
87
- `).length+1;return`${o}${c}${bt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:c.length,rowPadding:f+p,style:l}).join(`
86
+ `).length,p=u.split(`
87
+ `).length+1;return`${o}${c}${vt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:c.length,rowPadding:f+p,style:l}).join(`
88
88
  ${c}`)}
89
- ${d}
90
- `}default:{let c=n?`${(0,m.styleText)("cyan",C)} `:"",d=o.split(`
91
- `).length,f=i?Cs(Ai,n):n?[(0,m.styleText)("cyan",me)]:[],p=f.join(`
92
- `),$=f.length+1;return`${o}${c}${bt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:c.length,rowPadding:d+$,style:l}).join(`
89
+ ${u}
90
+ `}default:{let c=n?`${(0,m.styleText)("cyan",R)} `:"",u=o.split(`
91
+ `).length,f=i?Os(Di,n):n?[(0,m.styleText)("cyan",fe)]:[],p=f.join(`
92
+ `),y=f.length+1;return`${o}${c}${vt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:c.length,rowPadding:u+y,style:l}).join(`
93
93
  ${c}`)}
94
94
  ${p}
95
- `}}}}).prompt()},Da=t=>{let{selectableGroups:e=!0,groupSpacing:s=0}=t,i=(o,a,l=[])=>{let c=o.label??String(o.value),d=typeof o.group=="string",f=d&&(l[l.indexOf(o)+1]??{group:!0}),p=d&&f&&f.group===!0,$="",w="";d&&(e?($=p?`${me} `:`${C} `,w=p?" ":`${C} `):$=" ");let g="";if(s>0&&!d&&(g=`
96
- `.repeat(s)),a==="active")return pe(t.output,`${c}${o.hint?` ${(0,m.styleText)("dim",`(${o.hint})`)}`:""}`,`${g}${(0,m.styleText)("dim",$)} `,`${g}${(0,m.styleText)("dim",$)}${(0,m.styleText)("cyan",ks)} `,`${g}${(0,m.styleText)("dim",w)} `);if(a==="group-active")return pe(t.output,c,`${g}${$} `,`${g}${$}${(0,m.styleText)("cyan",ks)} `,`${g}${w} `,S=>(0,m.styleText)("dim",S));if(a==="group-active-selected")return pe(t.output,c,`${g}${$} `,`${g}${$}${(0,m.styleText)("green",Ct)} `,`${g}${w} `,S=>(0,m.styleText)("dim",S));if(a==="selected"){let S=d||e?(0,m.styleText)("green",Ct):"";return pe(t.output,`${c}${o.hint?` (${o.hint})`:""}`,`${g}${(0,m.styleText)("dim",$)} `,`${g}${(0,m.styleText)("dim",$)}${S} `,`${g}${(0,m.styleText)("dim",w)} `,R=>(0,m.styleText)("dim",R))}if(a==="cancelled")return`${(0,m.styleText)(["strikethrough","dim"],c)}`;if(a==="active-selected")return pe(t.output,`${c}${o.hint?` ${(0,m.styleText)("dim",`(${o.hint})`)}`:""}`,`${g}${(0,m.styleText)("dim",$)} `,`${g}${(0,m.styleText)("dim",$)}${(0,m.styleText)("green",Ct)} `,`${g}${(0,m.styleText)("dim",w)} `);if(a==="submitted")return`${(0,m.styleText)("dim",c)}`;let _=d||e?(0,m.styleText)("dim",Mt):"";return pe(t.output,c,`${g}${(0,m.styleText)("dim",$)} `,`${g}${(0,m.styleText)("dim",$)}${_} `,`${g}${(0,m.styleText)("dim",w)} `,S=>(0,m.styleText)("dim",S))},n=t.required??!0,r=t.showInstructions??!0;return new Bn({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,selectableGroups:e,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
97
- ${(0,m.styleText)("reset",(0,m.styleText)("dim",`Press ${(0,m.styleText)(["gray","bgWhite","inverse"]," space ")} to select, ${(0,m.styleText)("gray",(0,m.styleText)(["bgWhite","inverse"]," enter "))} to submit`))}`},render(){let o=t.withGuide??M.withGuide,a=`${o?`${(0,m.styleText)("gray",C)}
98
- `:""}${Ue(this.state)} ${t.message}
99
- `,l=this.value??[],c=(d,f)=>{let p=this.options,$=l.includes(d.value)||d.group===!0&&this.isGroupSelected(`${d.value}`);return!f&&typeof d.group=="string"&&this.options[this.cursor]?.value===d.group?i(d,$?"group-active-selected":"group-active",p):f&&$?i(d,"active-selected",p):$?i(d,"selected",p):i(d,f?"active":"inactive",p)};switch(this.state){case"submit":{let d=this.options.filter(({value:p})=>l.includes(p)).map(p=>i(p,"submitted")),f=d.length===0?"":` ${d.join((0,m.styleText)("dim",", "))}`;return`${a}${o?(0,m.styleText)("gray",C):""}${f}`}case"cancel":{let d=this.options.filter(({value:f})=>l.includes(f)).map(f=>i(f,"cancelled")).join((0,m.styleText)("dim",", "));return`${a}${o?`${(0,m.styleText)("gray",C)} `:""}${d.trim()?`${d}${o?`
100
- ${(0,m.styleText)("gray",C)}`:""}`:""}`}case"error":{let d=o?`${(0,m.styleText)("yellow",C)} `:"",f=this.error.split(`
101
- `).map((g,_)=>_===0?`${o?`${(0,m.styleText)("yellow",me)} `:""}${(0,m.styleText)("yellow",g)}`:` ${g}`).join(`
95
+ `}}}}).prompt()},Va=t=>{let{selectableGroups:e=!0,groupSpacing:s=0}=t,i=(o,a,l=[])=>{let c=o.label??String(o.value),u=typeof o.group=="string",f=u&&(l[l.indexOf(o)+1]??{group:!0}),p=u&&f&&f.group===!0,y="",w="";u&&(e?(y=p?`${fe} `:`${R} `,w=p?" ":`${R} `):y=" ");let $="";if(s>0&&!u&&($=`
96
+ `.repeat(s)),a==="active")return pe(t.output,`${c}${o.hint?` ${(0,m.styleText)("dim",`(${o.hint})`)}`:""}`,`${$}${(0,m.styleText)("dim",y)} `,`${$}${(0,m.styleText)("dim",y)}${(0,m.styleText)("cyan",js)} `,`${$}${(0,m.styleText)("dim",w)} `);if(a==="group-active")return pe(t.output,c,`${$}${y} `,`${$}${y}${(0,m.styleText)("cyan",js)} `,`${$}${w} `,S=>(0,m.styleText)("dim",S));if(a==="group-active-selected")return pe(t.output,c,`${$}${y} `,`${$}${y}${(0,m.styleText)("green",Ot)} `,`${$}${w} `,S=>(0,m.styleText)("dim",S));if(a==="selected"){let S=u||e?(0,m.styleText)("green",Ot):"";return pe(t.output,`${c}${o.hint?` (${o.hint})`:""}`,`${$}${(0,m.styleText)("dim",y)} `,`${$}${(0,m.styleText)("dim",y)}${S} `,`${$}${(0,m.styleText)("dim",w)} `,I=>(0,m.styleText)("dim",I))}if(a==="cancelled")return`${(0,m.styleText)(["strikethrough","dim"],c)}`;if(a==="active-selected")return pe(t.output,`${c}${o.hint?` ${(0,m.styleText)("dim",`(${o.hint})`)}`:""}`,`${$}${(0,m.styleText)("dim",y)} `,`${$}${(0,m.styleText)("dim",y)}${(0,m.styleText)("green",Ot)} `,`${$}${(0,m.styleText)("dim",w)} `);if(a==="submitted")return`${(0,m.styleText)("dim",c)}`;let _=u||e?(0,m.styleText)("dim",Vt):"";return pe(t.output,c,`${$}${(0,m.styleText)("dim",y)} `,`${$}${(0,m.styleText)("dim",y)}${_} `,`${$}${(0,m.styleText)("dim",w)} `,S=>(0,m.styleText)("dim",S))},n=t.required??!0,r=t.showInstructions??!0;return new zn({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,selectableGroups:e,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
97
+ ${(0,m.styleText)("reset",(0,m.styleText)("dim",`Press ${(0,m.styleText)(["gray","bgWhite","inverse"]," space ")} to select, ${(0,m.styleText)("gray",(0,m.styleText)(["bgWhite","inverse"]," enter "))} to submit`))}`},render(){let o=t.withGuide??M.withGuide,a=`${o?`${(0,m.styleText)("gray",R)}
98
+ `:""}${Me(this.state)} ${t.message}
99
+ `,l=this.value??[],c=(u,f)=>{let p=this.options,y=l.includes(u.value)||u.group===!0&&this.isGroupSelected(`${u.value}`);return!f&&typeof u.group=="string"&&this.options[this.cursor]?.value===u.group?i(u,y?"group-active-selected":"group-active",p):f&&y?i(u,"active-selected",p):y?i(u,"selected",p):i(u,f?"active":"inactive",p)};switch(this.state){case"submit":{let u=this.options.filter(({value:p})=>l.includes(p)).map(p=>i(p,"submitted")),f=u.length===0?"":` ${u.join((0,m.styleText)("dim",", "))}`;return`${a}${o?(0,m.styleText)("gray",R):""}${f}`}case"cancel":{let u=this.options.filter(({value:f})=>l.includes(f)).map(f=>i(f,"cancelled")).join((0,m.styleText)("dim",", "));return`${a}${o?`${(0,m.styleText)("gray",R)} `:""}${u.trim()?`${u}${o?`
100
+ ${(0,m.styleText)("gray",R)}`:""}`:""}`}case"error":{let u=o?`${(0,m.styleText)("yellow",R)} `:"",f=this.error.split(`
101
+ `).map(($,_)=>_===0?`${o?`${(0,m.styleText)("yellow",fe)} `:""}${(0,m.styleText)("yellow",$)}`:` ${$}`).join(`
102
102
  `),p=a.split(`
103
- `).length,$=f.split(`
104
- `).length+1,w=bt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:d.length,rowPadding:p+$,style:c}).join(`
105
- ${d}`);return`${a}${d}${w}
103
+ `).length,y=f.split(`
104
+ `).length+1,w=vt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:p+y,style:c}).join(`
105
+ ${u}`);return`${a}${u}${w}
106
106
  ${f}
107
- `}default:{let d=o?`${(0,m.styleText)("cyan",C)} `:"",f=a.split(`
108
- `).length,p=r?Cs(Ai,o):o?[(0,m.styleText)("cyan",me)]:[],$=p.join(`
109
- `),w=p.length+1,g=bt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:d.length,rowPadding:f+w,style:c}).join(`
110
- ${d}`);return`${a}${d}${g}
111
- ${$}
112
- `}}}}).prompt()},Le={message:(t=[],{symbol:e=(0,m.styleText)("gray",C),secondarySymbol:s=(0,m.styleText)("gray",C),output:i=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??M.withGuide,l=a?s:"",c=a?`${e} `:"",d=a?`${s} `:"";for(let p=0;p<n;p++)o.push(l);let f=Array.isArray(t)?t:t.split(`
113
- `);if(f.length>0){let[p,...$]=f;p.length>0?o.push(`${c}${p}`):o.push(a?e:"");for(let w of $)w.length>0?o.push(`${d}${w}`):o.push(a?s:"")}i.write(`${o.join(`
107
+ `}default:{let u=o?`${(0,m.styleText)("cyan",R)} `:"",f=a.split(`
108
+ `).length,p=r?Os(Di,o):o?[(0,m.styleText)("cyan",fe)]:[],y=p.join(`
109
+ `),w=p.length+1,$=vt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:f+w,style:c}).join(`
110
+ ${u}`);return`${a}${u}${$}
111
+ ${y}
112
+ `}}}}).prompt()},Ue={message:(t=[],{symbol:e=(0,m.styleText)("gray",R),secondarySymbol:s=(0,m.styleText)("gray",R),output:i=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??M.withGuide,l=a?s:"",c=a?`${e} `:"",u=a?`${s} `:"";for(let p=0;p<n;p++)o.push(l);let f=Array.isArray(t)?t:t.split(`
113
+ `);if(f.length>0){let[p,...y]=f;p.length>0?o.push(`${c}${p}`):o.push(a?e:"");for(let w of y)w.length>0?o.push(`${u}${w}`):o.push(a?s:"")}i.write(`${o.join(`
114
114
  `)}
115
- `)},info:(t,e)=>{Le.message(t,{...e,symbol:(0,m.styleText)("blue",ji)})},success:(t,e)=>{Le.message(t,{...e,symbol:(0,m.styleText)("green",Ci)})},step:(t,e)=>{Le.message(t,{...e,symbol:(0,m.styleText)("green",It)})},warn:(t,e)=>{Le.message(t,{...e,symbol:(0,m.styleText)("yellow",Oi)})},warning:(t,e)=>{Le.warn(t,e)},error:(t,e)=>{Le.message(t,{...e,symbol:(0,m.styleText)("red",Ri)})}},Pa=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",me)} `:"";s.write(`${i}${(0,m.styleText)("red",t)}
115
+ `)},info:(t,e)=>{Ue.message(t,{...e,symbol:(0,m.styleText)("blue",Ri)})},success:(t,e)=>{Ue.message(t,{...e,symbol:(0,m.styleText)("green",Ii)})},step:(t,e)=>{Ue.message(t,{...e,symbol:(0,m.styleText)("green",At)})},warn:(t,e)=>{Ue.message(t,{...e,symbol:(0,m.styleText)("yellow",Ai)})},warning:(t,e)=>{Ue.warn(t,e)},error:(t,e)=>{Ue.message(t,{...e,symbol:(0,m.styleText)("red",Ti)})}},qa=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",fe)} `:"";s.write(`${i}${(0,m.styleText)("red",t)}
116
116
 
117
- `)},Na=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",_i)} `:"";s.write(`${i}${t}
118
- `)},Fa=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",C)}
119
- ${(0,m.styleText)("gray",me)} `:"";s.write(`${i}${t}
117
+ `)},Wa=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",ki)} `:"";s.write(`${i}${t}
118
+ `)},Ha=(t="",e)=>{let s=e?.output??process.stdout,i=e?.withGuide??M.withGuide?`${(0,m.styleText)("gray",R)}
119
+ ${(0,m.styleText)("gray",fe)} `:"";s.write(`${i}${t}
120
120
 
121
- `)},La=t=>new bs({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,showSubmit:t.showSubmit,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??M.withGuide,s=`${`${e?`${(0,m.styleText)("gray",C)}
122
- `:""}${Ue(this.state)} `}${t.message}
121
+ `)},Ja=t=>new vs({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,showSubmit:t.showSubmit,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??M.withGuide,s=`${`${e?`${(0,m.styleText)("gray",R)}
122
+ `:""}${Me(this.state)} `}${t.message}
123
123
  `,i=t.placeholder&&t.placeholder.length>0?(0,m.styleText)("inverse",t.placeholder[0])+(0,m.styleText)("dim",t.placeholder.slice(1)):(0,m.styleText)(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:i,r=this.value??"",o=t.showSubmit?`
124
- ${(0,m.styleText)(this.focused==="submit"?"cyan":"dim","[ submit ]")}`:"";switch(this.state){case"error":{let a=`${(0,m.styleText)("yellow",C)} `,l=e?pe(t.output,n,a,void 0):n,c=(0,m.styleText)("yellow",me);return`${s}${l}
124
+ ${(0,m.styleText)(this.focused==="submit"?"cyan":"dim","[ submit ]")}`:"";switch(this.state){case"error":{let a=`${(0,m.styleText)("yellow",R)} `,l=e?pe(t.output,n,a,void 0):n,c=(0,m.styleText)("yellow",fe);return`${s}${l}
125
125
  ${c} ${(0,m.styleText)("yellow",this.error)}${o}
126
- `}case"submit":{let a=`${(0,m.styleText)("gray",C)} `,l=e?pe(t.output,r,a,void 0,void 0,c=>(0,m.styleText)("dim",c)):r?(0,m.styleText)("dim",r):"";return`${s}${l}`}case"cancel":{let a=`${(0,m.styleText)("gray",C)} `,l=e?pe(t.output,r,a,void 0,void 0,c=>(0,m.styleText)(["strikethrough","dim"],c)):r?(0,m.styleText)(["strikethrough","dim"],r):"";return`${s}${l}`}default:{let a=e?`${(0,m.styleText)("cyan",C)} `:"",l=e?(0,m.styleText)("cyan",me):"",c=e?pe(t.output,n,a):n;return`${s}${c}
126
+ `}case"submit":{let a=`${(0,m.styleText)("gray",R)} `,l=e?pe(t.output,r,a,void 0,void 0,c=>(0,m.styleText)("dim",c)):r?(0,m.styleText)("dim",r):"";return`${s}${l}`}case"cancel":{let a=`${(0,m.styleText)("gray",R)} `,l=e?pe(t.output,r,a,void 0,void 0,c=>(0,m.styleText)(["strikethrough","dim"],c)):r?(0,m.styleText)(["strikethrough","dim"],r):"";return`${s}${l}`}default:{let a=e?`${(0,m.styleText)("cyan",R)} `:"",l=e?(0,m.styleText)("cyan",fe):"",c=e?pe(t.output,n,a):n;return`${s}${c}
127
127
  ${l}${o}
128
- `}}}}).prompt(),Ua=t=>t,Ma=(t,e,s)=>{let i={hard:!0,trim:!1},n=Ke(t,e,i).split(`
129
- `),r=n.reduce((l,c)=>Math.max($e(c),l),0),o=n.map(s).reduce((l,c)=>Math.max($e(c),l),0),a=e-(o-r);return Ke(t,a,i)},Va=(t="",e="",s)=>{let i=s?.output??Fe.default.stdout,n=s?.withGuide??M.withGuide,r=s?.format??Ua,o=["",...Ma(t,kt(i)-6,r).split(`
130
- `).map(r),""],a=$e(e),l=Math.max(o.reduce((p,$)=>{let w=$e($);return w>p?w:p},0),a)+2,c=o.map(p=>`${(0,m.styleText)("gray",C)} ${p}${" ".repeat(l-$e(p))}${(0,m.styleText)("gray",C)}`).join(`
131
- `),d=n?`${(0,m.styleText)("gray",C)}
132
- `:"",f=n?rr:ki;i.write(`${d}${(0,m.styleText)("green",It)} ${(0,m.styleText)("reset",e)} ${(0,m.styleText)("gray",js.repeat(Math.max(l-a-1,1))+Si)}
128
+ `}}}}).prompt(),Ba=t=>t,Ga=(t,e,s)=>{let i={hard:!0,trim:!1},n=ze(t,e,i).split(`
129
+ `),r=n.reduce((l,c)=>Math.max(ye(c),l),0),o=n.map(s).reduce((l,c)=>Math.max(ye(c),l),0),a=e-(o-r);return ze(t,a,i)},Ya=(t="",e="",s)=>{let i=s?.output??Le.default.stdout,n=s?.withGuide??M.withGuide,r=s?.format??Ba,o=["",...Ga(t,jt(i)-6,r).split(`
130
+ `).map(r),""],a=ye(e),l=Math.max(o.reduce((p,y)=>{let w=ye(y);return w>p?w:p},0),a)+2,c=o.map(p=>`${(0,m.styleText)("gray",R)} ${p}${" ".repeat(l-ye(p))}${(0,m.styleText)("gray",R)}`).join(`
131
+ `),u=n?`${(0,m.styleText)("gray",R)}
132
+ `:"",f=n?cr:Oi;i.write(`${u}${(0,m.styleText)("green",At)} ${(0,m.styleText)("reset",e)} ${(0,m.styleText)("gray",Cs.repeat(Math.max(l-a-1,1))+ji)}
133
133
  ${c}
134
- ${(0,m.styleText)("gray",f+js.repeat(l+2)+xi)}
135
- `)},qa=t=>new Gn({validate:t.validate,mask:t.mask??nr,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??M.withGuide,s=`${e?`${(0,m.styleText)("gray",C)}
136
- `:""}${Ue(this.state)} ${t.message}
137
- `,i=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=e?`${(0,m.styleText)("yellow",C)} `:"",o=e?`${(0,m.styleText)("yellow",me)} `:"",a=n??"";return t.clearOnError&&this.clear(),`${s.trim()}
134
+ ${(0,m.styleText)("gray",f+Cs.repeat(l+2)+Ci)}
135
+ `)},Ka=t=>new Xn({validate:t.validate,mask:t.mask??lr,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??M.withGuide,s=`${e?`${(0,m.styleText)("gray",R)}
136
+ `:""}${Me(this.state)} ${t.message}
137
+ `,i=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=e?`${(0,m.styleText)("yellow",R)} `:"",o=e?`${(0,m.styleText)("yellow",fe)} `:"",a=n??"";return t.clearOnError&&this.clear(),`${s.trim()}
138
138
  ${r}${a}
139
139
  ${o}${(0,m.styleText)("yellow",this.error)}
140
- `}case"submit":{let r=e?`${(0,m.styleText)("gray",C)} `:"",o=n?(0,m.styleText)("dim",n):"";return`${s}${r}${o}`}case"cancel":{let r=e?`${(0,m.styleText)("gray",C)} `:"",o=n?(0,m.styleText)(["strikethrough","dim"],n):"";return`${s}${r}${o}${n&&e?`
141
- ${(0,m.styleText)("gray",C)}`:""}`}default:{let r=e?`${(0,m.styleText)("cyan",C)} `:"",o=e?(0,m.styleText)("cyan",me):"";return`${s}${r}${i}
140
+ `}case"submit":{let r=e?`${(0,m.styleText)("gray",R)} `:"",o=n?(0,m.styleText)("dim",n):"";return`${s}${r}${o}`}case"cancel":{let r=e?`${(0,m.styleText)("gray",R)} `:"",o=n?(0,m.styleText)(["strikethrough","dim"],n):"";return`${s}${r}${o}${n&&e?`
141
+ ${(0,m.styleText)("gray",R)}`:""}`}default:{let r=e?`${(0,m.styleText)("cyan",R)} `:"",o=e?(0,m.styleText)("cyan",fe):"";return`${s}${r}${i}
142
142
  ${o}
143
- `}}}}).prompt(),Wa=t=>{let e=t.validate;return lr({...t,initialUserInput:t.initialValue??t.root??process.cwd(),maxItems:5,validate(s){if(!Array.isArray(s)){if(!s)return"Please select a path";if(e)return Gt(e,s)}},options(){let s=this.userInput;if(s==="")return[];try{let i;(0,Ot.existsSync)(s)?(0,Ot.lstatSync)(s).isDirectory()&&(!t.directory||s.endsWith("/"))?i=s:i=(0,Kt.dirname)(s):i=(0,Kt.dirname)(s);let n=s.length>1&&s.endsWith("/")?s.slice(0,-1):s;return(0,Ot.readdirSync)(i).map(r=>{let o=(0,Kt.join)(i,r),a=(0,Ot.lstatSync)(o);return{name:r,path:o,isDirectory:a.isDirectory()}}).filter(({path:r,isDirectory:o})=>r.startsWith(n)&&(o||!t.directory)).map(r=>({value:r.path}))}catch{return[]}}})},Ha=t=>(0,m.styleText)("magenta",t),Xt=({indicator:t="dots",onCancel:e,output:s=process.stdout,cancelMessage:i,errorMessage:n,frames:r=xs?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=xs?80:120,signal:a,...l}={})=>{let c=bi(),d,f,p=!1,$=!1,w="",g,_=performance.now(),S=kt(s),R=l?.styleFrame??Ha,N=P=>{let K=P>1?n??M.messages.error:i??M.messages.cancel;$=P===1,p&&(ie(K,P),$&&typeof e=="function"&&e())},V=()=>N(2),U=()=>N(1),le=()=>{process.on("uncaughtExceptionMonitor",V),process.on("unhandledRejection",V),process.on("SIGINT",U),process.on("SIGTERM",U),process.on("exit",N),a&&a.addEventListener("abort",U)},Q=()=>{process.removeListener("uncaughtExceptionMonitor",V),process.removeListener("unhandledRejection",V),process.removeListener("SIGINT",U),process.removeListener("SIGTERM",U),process.removeListener("exit",N),a&&a.removeEventListener("abort",U)},J=()=>{if(g===void 0)return;c&&s.write(`
144
- `);let P=Ke(g,S,{hard:!0,trim:!1}).split(`
145
- `);P.length>1&&s.write(Ut.cursor.up(P.length-1)),s.write(Ut.cursor.to(0)),s.write(Ut.erase.down())},A=P=>P.replace(/\.+$/,""),te=P=>{let K=(performance.now()-P)/1e3,X=Math.floor(K/60),G=Math.floor(K%60);return X>0?`[${X}m ${G}s]`:`[${G}s]`},B=l.withGuide??M.withGuide,E=(P="")=>{p=!0,d=Hn({output:s}),w=A(P),_=performance.now(),B&&s.write(`${(0,m.styleText)("gray",C)}
146
- `);let K=0,X=0;le(),f=setInterval(()=>{if(c&&w===g)return;J(),g=w;let G=R(r[K]),Ie;if(c)Ie=`${G} ${w}...`;else if(t==="timer")Ie=`${G} ${w} ${te(_)}`;else{let ce=".".repeat(Math.floor(X)).slice(0,3);Ie=`${G} ${w}${ce}`}let We=Ke(Ie,S,{hard:!0,trim:!1});s.write(We),K=K+1<r.length?K+1:0,X=X<4?X+.125:0},o)},ie=(P="",K=0,X=!1)=>{if(!p)return;p=!1,clearInterval(f),J();let G=K===0?(0,m.styleText)("green",It):K===1?(0,m.styleText)("red",vi):(0,m.styleText)("red",wi);w=P??w,X||(t==="timer"?s.write(`${G} ${w} ${te(_)}
143
+ `}}}}).prompt(),za=t=>{let e=t.validate;return mr({...t,initialUserInput:t.initialValue??t.root??process.cwd(),maxItems:5,validate(s){if(!Array.isArray(s)){if(!s)return"Please select a path";if(e)return Yt(e,s)}},options(){let s=this.userInput;if(s==="")return[];try{let i;(0,Rt.existsSync)(s)?(0,Rt.lstatSync)(s).isDirectory()&&(!t.directory||s.endsWith("/"))?i=s:i=(0,zt.dirname)(s):i=(0,zt.dirname)(s);let n=s.length>1&&s.endsWith("/")?s.slice(0,-1):s;return(0,Rt.readdirSync)(i).map(r=>{let o=(0,zt.join)(i,r),a=(0,Rt.lstatSync)(o);return{name:r,path:o,isDirectory:a.isDirectory()}}).filter(({path:r,isDirectory:o})=>r.startsWith(n)&&(o||!t.directory)).map(r=>({value:r.path}))}catch{return[]}}})},Xa=t=>(0,m.styleText)("magenta",t),Zt=({indicator:t="dots",onCancel:e,output:s=process.stdout,cancelMessage:i,errorMessage:n,frames:r=ks?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=ks?80:120,signal:a,...l}={})=>{let c=_i(),u,f,p=!1,y=!1,w="",$,_=performance.now(),S=jt(s),I=l?.styleFrame??Xa,N=P=>{let K=P>1?n??M.messages.error:i??M.messages.cancel;y=P===1,p&&(ie(K,P),y&&typeof e=="function"&&e())},q=()=>N(2),U=()=>N(1),le=()=>{process.on("uncaughtExceptionMonitor",q),process.on("unhandledRejection",q),process.on("SIGINT",U),process.on("SIGTERM",U),process.on("exit",N),a&&a.addEventListener("abort",U)},Q=()=>{process.removeListener("uncaughtExceptionMonitor",q),process.removeListener("unhandledRejection",q),process.removeListener("SIGINT",U),process.removeListener("SIGTERM",U),process.removeListener("exit",N),a&&a.removeEventListener("abort",U)},J=()=>{if($===void 0)return;c&&s.write(`
144
+ `);let P=ze($,S,{hard:!0,trim:!1}).split(`
145
+ `);P.length>1&&s.write(Mt.cursor.up(P.length-1)),s.write(Mt.cursor.to(0)),s.write(Mt.erase.down())},A=P=>P.replace(/\.+$/,""),te=P=>{let K=(performance.now()-P)/1e3,Z=Math.floor(K/60),G=Math.floor(K%60);return Z>0?`[${Z}m ${G}s]`:`[${G}s]`},B=l.withGuide??M.withGuide,E=(P="")=>{p=!0,u=Yn({output:s}),w=A(P),_=performance.now(),B&&s.write(`${(0,m.styleText)("gray",R)}
146
+ `);let K=0,Z=0;le(),f=setInterval(()=>{if(c&&w===$)return;J(),$=w;let G=I(r[K]),Ie;if(c)Ie=`${G} ${w}...`;else if(t==="timer")Ie=`${G} ${w} ${te(_)}`;else{let ce=".".repeat(Math.floor(Z)).slice(0,3);Ie=`${G} ${w}${ce}`}let He=ze(Ie,S,{hard:!0,trim:!1});s.write(He),K=K+1<r.length?K+1:0,Z=Z<4?Z+.125:0},o)},ie=(P="",K=0,Z=!1)=>{if(!p)return;p=!1,clearInterval(f),J();let G=K===0?(0,m.styleText)("green",At):K===1?(0,m.styleText)("red",Si):(0,m.styleText)("red",xi);w=P??w,Z||(t==="timer"?s.write(`${G} ${w} ${te(_)}
147
147
  `):s.write(`${G} ${w}
148
- `)),Q(),d()};return{start:E,stop:(P="")=>ie(P,0),message:(P="")=>{w=A(P??w)},cancel:(P="")=>ie(P,1),error:(P="")=>ie(P,2),clear:()=>ie("",0,!0),get isCancelled(){return $}}},Zn={light:re("\u2500","-"),heavy:re("\u2501","="),block:re("\u2588","#")};cr=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim","Enter:")} confirm`],Ss=(t,e)=>t.includes(`
148
+ `)),Q(),u()};return{start:E,stop:(P="")=>ie(P,0),message:(P="")=>{w=A(P??w)},cancel:(P="")=>ie(P,1),error:(P="")=>ie(P,2),clear:()=>ie("",0,!0),get isCancelled(){return y}}},sr={light:re("\u2500","-"),heavy:re("\u2501","="),block:re("\u2588","#")};fr=[`${(0,m.styleText)("dim","\u2191/\u2193")} to navigate`,`${(0,m.styleText)("dim","Enter:")} confirm`],xs=(t,e)=>t.includes(`
149
149
  `)?t.split(`
150
150
  `).map(s=>e(s)).join(`
151
- `):e(t),ze=t=>{let e=(i,n)=>{if(i===void 0)return"";let r=i.label??String(i.value);switch(n){case"disabled":return`${(0,m.styleText)("gray",Rt)} ${Ss(r,o=>(0,m.styleText)("gray",o))}${i.hint?` ${(0,m.styleText)("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Ss(r,o=>(0,m.styleText)("dim",o))}`;case"active":return`${(0,m.styleText)("green",zt)} ${r}${i.hint?` ${(0,m.styleText)("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Ss(r,o=>(0,m.styleText)(["strikethrough","dim"],o))}`;default:return`${(0,m.styleText)("dim",Rt)} ${Ss(r,o=>(0,m.styleText)("dim",o))}`}},s=t.showInstructions??!0;return new Yn({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let i=t.withGuide??M.withGuide,n=`${Ue(this.state)} `,r=`${Ii(this.state)} `,o=pe(t.output,t.message,r,n),a=`${i?`${(0,m.styleText)("gray",C)}
151
+ `):e(t),Xe=t=>{let e=(i,n)=>{if(i===void 0)return"";let r=i.label??String(i.value);switch(n){case"disabled":return`${(0,m.styleText)("gray",It)} ${xs(r,o=>(0,m.styleText)("gray",o))}${i.hint?` ${(0,m.styleText)("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${xs(r,o=>(0,m.styleText)("dim",o))}`;case"active":return`${(0,m.styleText)("green",Xt)} ${r}${i.hint?` ${(0,m.styleText)("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${xs(r,o=>(0,m.styleText)(["strikethrough","dim"],o))}`;default:return`${(0,m.styleText)("dim",It)} ${xs(r,o=>(0,m.styleText)("dim",o))}`}},s=t.showInstructions??!0;return new Zn({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let i=t.withGuide??M.withGuide,n=`${Me(this.state)} `,r=`${Ei(this.state)} `,o=pe(t.output,t.message,r,n),a=`${i?`${(0,m.styleText)("gray",R)}
152
152
  `:""}${o}
153
- `;switch(this.state){case"submit":{let l=i?`${(0,m.styleText)("gray",C)} `:"",c=pe(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${c}`}case"cancel":{let l=i?`${(0,m.styleText)("gray",C)} `:"",c=pe(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${c}${i?`
154
- ${(0,m.styleText)("gray",C)}`:""}`}default:{let l=i?`${(0,m.styleText)("cyan",C)} `:"",c=a.split(`
155
- `).length,d=s?Cs(cr,i):i?[(0,m.styleText)("cyan",me)]:[],f=d.join(`
156
- `),p=d.length+1;return`${a}${l}${bt({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:c+p,style:($,w)=>e($,$.disabled?"disabled":w?"active":"inactive")}).join(`
153
+ `;switch(this.state){case"submit":{let l=i?`${(0,m.styleText)("gray",R)} `:"",c=pe(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${c}`}case"cancel":{let l=i?`${(0,m.styleText)("gray",R)} `:"",c=pe(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${c}${i?`
154
+ ${(0,m.styleText)("gray",R)}`:""}`}default:{let l=i?`${(0,m.styleText)("cyan",R)} `:"",c=a.split(`
155
+ `).length,u=s?Os(fr,i):i?[(0,m.styleText)("cyan",fe)]:[],f=u.join(`
156
+ `),p=u.length+1;return`${a}${l}${vt({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:c+p,style:(y,w)=>e(y,y.disabled?"disabled":w?"active":"inactive")}).join(`
157
157
  ${l}`)}
158
158
  ${f}
159
- `}}}}).prompt()},Ba=t=>{let e=(s,i="inactive")=>{if(s===void 0)return"";let n=s.label??String(s.value);return i==="selected"?`${(0,m.styleText)("dim",n)}`:i==="cancelled"?`${(0,m.styleText)(["strikethrough","dim"],n)}`:i==="active"?`${(0,m.styleText)(["bgCyan","gray"],` ${s.value} `)} ${n}${s.hint?` ${(0,m.styleText)("dim",`(${s.hint})`)}`:""}`:`${(0,m.styleText)(["gray","bgWhite","inverse"],` ${s.value} `)} ${n}${s.hint?` ${(0,m.styleText)("dim",`(${s.hint})`)}`:""}`};return new ws({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,caseSensitive:t.caseSensitive,render(){let s=t.withGuide??M.withGuide,i=`${s?`${(0,m.styleText)("gray",C)}
160
- `:""}${Ue(this.state)} ${t.message}
161
- `;switch(this.state){case"submit":{let n=s?`${(0,m.styleText)("gray",C)} `:"",r=this.options.find(a=>a.value===this.value)??t.options[0],o=pe(t.output,e(r,"selected"),n);return`${i}${o}`}case"cancel":{let n=s?`${(0,m.styleText)("gray",C)} `:"",r=pe(t.output,e(this.options[0],"cancelled"),n);return`${i}${r}${s?`
162
- ${(0,m.styleText)("gray",C)}`:""}`}default:{let n=s?`${(0,m.styleText)("cyan",C)} `:"",r=s?(0,m.styleText)("cyan",me):"",o=this.options.map((a,l)=>pe(t.output,e(a,l===this.cursor?"active":"inactive"),n)).join(`
159
+ `}}}}).prompt()},Qa=t=>{let e=(s,i="inactive")=>{if(s===void 0)return"";let n=s.label??String(s.value);return i==="selected"?`${(0,m.styleText)("dim",n)}`:i==="cancelled"?`${(0,m.styleText)(["strikethrough","dim"],n)}`:i==="active"?`${(0,m.styleText)(["bgCyan","gray"],` ${s.value} `)} ${n}${s.hint?` ${(0,m.styleText)("dim",`(${s.hint})`)}`:""}`:`${(0,m.styleText)(["gray","bgWhite","inverse"],` ${s.value} `)} ${n}${s.hint?` ${(0,m.styleText)("dim",`(${s.hint})`)}`:""}`};return new _s({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,caseSensitive:t.caseSensitive,render(){let s=t.withGuide??M.withGuide,i=`${s?`${(0,m.styleText)("gray",R)}
160
+ `:""}${Me(this.state)} ${t.message}
161
+ `;switch(this.state){case"submit":{let n=s?`${(0,m.styleText)("gray",R)} `:"",r=this.options.find(a=>a.value===this.value)??t.options[0],o=pe(t.output,e(r,"selected"),n);return`${i}${o}`}case"cancel":{let n=s?`${(0,m.styleText)("gray",R)} `:"",r=pe(t.output,e(this.options[0],"cancelled"),n);return`${i}${r}${s?`
162
+ ${(0,m.styleText)("gray",R)}`:""}`}default:{let n=s?`${(0,m.styleText)("cyan",R)} `:"",r=s?(0,m.styleText)("cyan",fe):"",o=this.options.map((a,l)=>pe(t.output,e(a,l===this.cursor?"active":"inactive"),n)).join(`
163
163
  `);return`${i}${o}
164
164
  ${r}
165
- `}}}}).prompt()},Qn=`${(0,m.styleText)("gray",C)} `,jt={message:async(t,{symbol:e=(0,m.styleText)("gray",C)}={})=>{process.stdout.write(`${(0,m.styleText)("gray",C)}
165
+ `}}}}).prompt()},ir=`${(0,m.styleText)("gray",R)} `,Ct={message:async(t,{symbol:e=(0,m.styleText)("gray",R)}={})=>{process.stdout.write(`${(0,m.styleText)("gray",R)}
166
166
  ${e} `);let s=3;for await(let i of t){i=i.replace(/\n/g,`
167
- ${Qn}`),i.includes(`
167
+ ${ir}`),i.includes(`
168
168
  `)&&(s=3+(0,m.stripVTControlCharacters)(i.slice(i.lastIndexOf(`
169
169
  `))).length);let n=(0,m.stripVTControlCharacters)(i).length;s+n<process.stdout.columns?(s+=n,process.stdout.write(i)):(process.stdout.write(`
170
- ${Qn}${i.trimStart()}`),s=3+(0,m.stripVTControlCharacters)(i.trimStart()).length)}process.stdout.write(`
171
- `)},info:t=>jt.message(t,{symbol:(0,m.styleText)("blue",ji)}),success:t=>jt.message(t,{symbol:(0,m.styleText)("green",Ci)}),step:t=>jt.message(t,{symbol:(0,m.styleText)("green",It)}),warn:t=>jt.message(t,{symbol:(0,m.styleText)("yellow",Oi)}),warning:t=>jt.warn(t),error:t=>jt.message(t,{symbol:(0,m.styleText)("red",Ri)})},Ga=async(t,e)=>{for(let s of t){if(s.enabled===!1)continue;let i=Xt(e);i.start(s.title);let n=await s.task(i.message);i.stop(n||s.title)}},Ya=t=>t.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Ka=t=>{let e=t.output??process.stdout,s=kt(e),i=(0,m.styleText)("gray",C),n=t.spacing??1,r=3,o=t.retainLog===!0,a=!bi()&&er(e);e.write(`${i}
172
- `),e.write(`${(0,m.styleText)("green",It)} ${t.title}
170
+ ${ir}${i.trimStart()}`),s=3+(0,m.stripVTControlCharacters)(i.trimStart()).length)}process.stdout.write(`
171
+ `)},info:t=>Ct.message(t,{symbol:(0,m.styleText)("blue",Ri)}),success:t=>Ct.message(t,{symbol:(0,m.styleText)("green",Ii)}),step:t=>Ct.message(t,{symbol:(0,m.styleText)("green",At)}),warn:t=>Ct.message(t,{symbol:(0,m.styleText)("yellow",Ai)}),warning:t=>Ct.warn(t),error:t=>Ct.message(t,{symbol:(0,m.styleText)("red",Ti)})},el=async(t,e)=>{for(let s of t){if(s.enabled===!1)continue;let i=Zt(e);i.start(s.title);let n=await s.task(i.message);i.stop(n||s.title)}},tl=t=>t.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),sl=t=>{let e=t.output??process.stdout,s=jt(e),i=(0,m.styleText)("gray",R),n=t.spacing??1,r=3,o=t.retainLog===!0,a=!_i()&&nr(e);e.write(`${i}
172
+ `),e.write(`${(0,m.styleText)("green",At)} ${t.title}
173
173
  `);for(let _=0;_<n;_++)e.write(`${i}
174
- `);let l=[{value:"",full:""}],c=!1,d=_=>{if(l.length===0)return;let S=0;_&&(S+=n+2);for(let R of l){let{value:N,result:V}=R,U=V?.message??N;if(U.length===0)continue;V===void 0&&R.header!==void 0&&R.header!==""&&(U+=`
175
- ${R.header}`);let le=U.split(`
176
- `).reduce((Q,J)=>J===""?Q+1:Q+Math.ceil((J.length+r)/s),0);S+=le}S>0&&(S+=1,e.write(Ut.erase.lines(S)))},f=(_,S,R)=>{let N=R?`${_.full}
177
- ${_.value}`:_.value;_.header!==void 0&&_.header!==""&&Le.message(_.header.split(`
178
- `).map(V=>(0,m.styleText)("bold",V)),{output:e,secondarySymbol:i,symbol:i,spacing:0}),Le.message(N.split(`
179
- `).map(V=>(0,m.styleText)("dim",V)),{output:e,secondarySymbol:i,symbol:i,spacing:S??n})},p=()=>{for(let _ of l){let{header:S,value:R,full:N}=_;(S===void 0||S.length===0)&&R.length===0||f(_,void 0,o===!0&&N.length>0)}},$=(_,S,R)=>{if(d(!1),(R?.raw!==!0||!c)&&_.value!==""&&(_.value+=`
180
- `),_.value+=Ya(S),c=R?.raw===!0,t.limit!==void 0){let N=_.value.split(`
181
- `),V=N.length-t.limit;if(V>0){let U=N.splice(0,V);o&&(_.full+=(_.full===""?"":`
174
+ `);let l=[{value:"",full:""}],c=!1,u=_=>{if(l.length===0)return;let S=0;_&&(S+=n+2);for(let I of l){let{value:N,result:q}=I,U=q?.message??N;if(U.length===0)continue;q===void 0&&I.header!==void 0&&I.header!==""&&(U+=`
175
+ ${I.header}`);let le=U.split(`
176
+ `).reduce((Q,J)=>J===""?Q+1:Q+Math.ceil((J.length+r)/s),0);S+=le}S>0&&(S+=1,e.write(Mt.erase.lines(S)))},f=(_,S,I)=>{let N=I?`${_.full}
177
+ ${_.value}`:_.value;_.header!==void 0&&_.header!==""&&Ue.message(_.header.split(`
178
+ `).map(q=>(0,m.styleText)("bold",q)),{output:e,secondarySymbol:i,symbol:i,spacing:0}),Ue.message(N.split(`
179
+ `).map(q=>(0,m.styleText)("dim",q)),{output:e,secondarySymbol:i,symbol:i,spacing:S??n})},p=()=>{for(let _ of l){let{header:S,value:I,full:N}=_;(S===void 0||S.length===0)&&I.length===0||f(_,void 0,o===!0&&N.length>0)}},y=(_,S,I)=>{if(u(!1),(I?.raw!==!0||!c)&&_.value!==""&&(_.value+=`
180
+ `),_.value+=tl(S),c=I?.raw===!0,t.limit!==void 0){let N=_.value.split(`
181
+ `),q=N.length-t.limit;if(q>0){let U=N.splice(0,q);o&&(_.full+=(_.full===""?"":`
182
182
  `)+U.join(`
183
183
  `))}_.value=N.join(`
184
- `)}a&&w()},w=()=>{for(let _ of l)_.result?_.result.status==="error"?Le.error(_.result.message,{output:e,secondarySymbol:i,spacing:0}):Le.success(_.result.message,{output:e,secondarySymbol:i,spacing:0}):_.value!==""&&f(_,0)},g=(_,S)=>{d(!1),_.result=S,a&&w()};return{message(_,S){$(l[0],_,S)},group(_){let S={header:_,value:"",full:""};return l.push(S),{message(R,N){$(S,R,N)},error(R){g(S,{status:"error",message:R})},success(R){g(S,{status:"success",message:R})}}},error(_,S){d(!0),Le.error(_,{output:e,secondarySymbol:i,spacing:1}),S?.showLog!==!1&&p(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(_,S){d(!0),Le.success(_,{output:e,secondarySymbol:i,spacing:1}),S?.showLog===!0&&p(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Te=t=>new _s({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??M.withGuide,s=`${`${e?`${(0,m.styleText)("gray",C)}
185
- `:""}${Ue(this.state)} `}${t.message}
186
- `,i=t.placeholder&&t.placeholder.length>0?(0,m.styleText)("inverse",t.placeholder[0])+(0,m.styleText)("dim",t.placeholder.slice(1)):(0,m.styleText)(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:i,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${(0,m.styleText)("yellow",this.error)}`:"",a=e?`${(0,m.styleText)("yellow",C)} `:"",l=e?(0,m.styleText)("yellow",me):"";return`${s.trim()}
184
+ `)}a&&w()},w=()=>{for(let _ of l)_.result?_.result.status==="error"?Ue.error(_.result.message,{output:e,secondarySymbol:i,spacing:0}):Ue.success(_.result.message,{output:e,secondarySymbol:i,spacing:0}):_.value!==""&&f(_,0)},$=(_,S)=>{u(!1),_.result=S,a&&w()};return{message(_,S){y(l[0],_,S)},group(_){let S={header:_,value:"",full:""};return l.push(S),{message(I,N){y(S,I,N)},error(I){$(S,{status:"error",message:I})},success(I){$(S,{status:"success",message:I})}}},error(_,S){u(!0),Ue.error(_,{output:e,secondarySymbol:i,spacing:1}),S?.showLog!==!1&&p(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(_,S){u(!0),Ue.success(_,{output:e,secondarySymbol:i,spacing:1}),S?.showLog===!0&&p(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Te=t=>new Ss({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??M.withGuide,s=`${`${e?`${(0,m.styleText)("gray",R)}
185
+ `:""}${Me(this.state)} `}${t.message}
186
+ `,i=t.placeholder&&t.placeholder.length>0?(0,m.styleText)("inverse",t.placeholder[0])+(0,m.styleText)("dim",t.placeholder.slice(1)):(0,m.styleText)(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:i,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${(0,m.styleText)("yellow",this.error)}`:"",a=e?`${(0,m.styleText)("yellow",R)} `:"",l=e?(0,m.styleText)("yellow",fe):"";return`${s.trim()}
187
187
  ${a}${n}
188
188
  ${l}${o}
189
- `}case"submit":{let o=r?` ${(0,m.styleText)("dim",r)}`:"",a=e?(0,m.styleText)("gray",C):"";return`${s}${a}${o}`}case"cancel":{let o=r?` ${(0,m.styleText)(["strikethrough","dim"],r)}`:"",a=e?(0,m.styleText)("gray",C):"";return`${s}${a}${o}${r.trim()?`
190
- ${a}`:""}`}default:{let o=e?`${(0,m.styleText)("cyan",C)} `:"",a=e?(0,m.styleText)("cyan",me):"";return`${s}${o}${n}
189
+ `}case"submit":{let o=r?` ${(0,m.styleText)("dim",r)}`:"",a=e?(0,m.styleText)("gray",R):"";return`${s}${a}${o}`}case"cancel":{let o=r?` ${(0,m.styleText)(["strikethrough","dim"],r)}`:"",a=e?(0,m.styleText)("gray",R):"";return`${s}${a}${o}${r.trim()?`
190
+ ${a}`:""}`}default:{let o=e?`${(0,m.styleText)("cyan",R)} `:"",a=e?(0,m.styleText)("cyan",fe):"";return`${s}${o}${n}
191
191
  ${a}
192
- `}}}}).prompt()});function za(t){return!!(t.json||!je)}function O(t,e=50){console.log(),console.log(` ${L.default.bold(t)}`),console.log(` ${L.default.dim("\u2500".repeat(e))}`)}function y(t,e,s=2){let i=" ".repeat(s);console.log(`${i}${L.default.dim(t.padEnd(16))} ${e}`)}function u(){console.log()}function lt(t){console.log(` ${L.default.dim(t)}`)}function I(t,e){console.log(` ${L.default.dim(t)} ${L.default.cyan(e)}`)}function fr(t){return t.split(/(https?:\/\/[^\s]+)/g).map(s=>/^https?:\/\//.test(s)?`\x1B]8;;${s}\x1B\\${L.default.underline(L.default.cyan(s))}\x1B]8;;\x1B\\`:L.default.dim(s)).join("")}function Di(t,e){console.error(` ${b.error} ${L.default.red(t)}`),e&&console.error(` ${fr(e)}`)}function k(t=!0){return t?Xt():Xa}function hr(t){return t.replace(Za,"")}function Os(t,e){let s=hr(t).length,i=Math.max(0,e-s);return t+" ".repeat(i)}function fe(t,e,s){let i=s||t.map((o,a)=>{let l=e.reduce((c,d)=>Math.max(c,hr(d[a]||"").length),0);return Math.max(o.length,l)+2}),n=t.map((o,a)=>L.default.dim(o.padEnd(i[a]))).join(" "),r=i.map(o=>L.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of e){let a=o.map((l,c)=>Os(l,i[c])).join(" ");console.log(` ${a}`)}}function Qa(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Ei(t){if(Array.isArray(t))return t.map(Ei);if(t&&typeof t=="object"&&!(t instanceof Date)){let e={};for(let[s,i]of Object.entries(t))e[Qa(s)]=Ei(i);return e}return t}function x(t,e){let s=Ei(t);if(!e){console.log(JSON.stringify(s,null,2));return}let i=e.split(",").map(n=>n.trim()).filter(Boolean);if(Array.isArray(s)){let n=s.map(r=>dr(r,i));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(s&&typeof s=="object"?dr(s,i):s,null,2))}function dr(t,e){let s={};for(let i of e)i in t&&(s[i]=t[i]);if(Object.keys(s).length===0){for(let[i,n]of Object.entries(t))if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"){let r=n.map(o=>{let a={};for(let l of e)l in o&&(a[l]=o[l]);return a});Object.keys(r[0]).length>0&&(s[i]=r)}}return s}function At(t){return!!(t.yes||za(t))}function Y(t,e,s,i){if(s){x({dry_run:!0,action:t,...e},i);return}console.log(),console.log(` ${L.default.yellow("\u25B8 DRY RUN")} ${L.default.dim("- no changes made")}`),console.log(` ${L.default.dim("Action:")} ${L.default.bold(t)}`);for(let[n,r]of Object.entries(e))r!=null&&(Array.isArray(r)?console.log(` ${L.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${L.default.dim(n+":")} ${JSON.stringify(r)}`:` ${L.default.dim(n+":")} ${String(r)}`));console.log()}function tl(t,e,s){return e===401||e===403?"auth_required":e===402||s?"payment_required":e===404?"not_found":e===409?"conflict":e===422?"validation_error":e===429?"rate_limited":/contact/i.test(t)?"contact_required":"error"}function h(t,e){let s=t||`Request failed${e?.status?` (${e.status})`:""}`,i=e?.code||tl(s,e?.status,e?.fixUrl),n=e?.fixCommand||el[i];if(e?.json){let r={error:s,code:i};e.hint&&(r.hint=e.hint),n&&(r.fix_command=n),e.fixUrl&&(r.fix_url=e.fixUrl),x(r,e.fields)}else Di(s,e?.hint),n?console.error(` ${L.default.dim("Or run:")} ${L.default.cyan(n)}`):e?.fixUrl&&console.error(` ${fr(`Add a payment method at ${e.fixUrl}`)}`);process.exit(1)}function Xe(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,mr.execFile)(e,[t])}function Tt(t){return new Promise(e=>setTimeout(e,t))}function Et(t,e,s,i=!0){let n=process.stdout.isTTY??!1;if(!i)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+e.length;function l(){let p=" "+t.map((g,_)=>L.default.dim(g.padEnd(s[_]))).join(" "),$=" "+s.map(g=>L.default.dim("\u2500".repeat(g))).join(" "),w=[p,$];for(let g of e){let _=g.status==="done"?g.icon??b.success:L.default.cyan(ur[r%ur.length]),S=g.cells.map((R,N)=>Os(R,s[N])).join(" ");w.push(` ${_} ${S}`)}return w}let c=!1,d=()=>process.stdout.write("\x1B[?25h");function f(){let p=l();if(c&&n){process.stdout.write(`\x1B[${a}A`);for(let $ of p)process.stdout.write(`\x1B[2K${$}
193
- `)}else{for(let $ of p)console.log($);c=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",d)),f(),n&&(o=setInterval(()=>{r++,f()},80))},markDone(p,$){e[p].status="done",$!==void 0&&(e[p].icon=$),n&&f()},stop(){o&&clearInterval(o);for(let p of e)p.status="done";f(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",d))}}}var L,mr,je,b,v,Xa,Za,el,ur,q=xe(()=>{"use strict";L=F(W(),1),mr=require("child_process");De();je=process.stdout.isTTY??!1;b={success:L.default.green("\u2713"),error:L.default.red("\u2717"),warning:L.default.yellow("!"),info:L.default.cyan("\u25CF"),arrow:L.default.dim("\u2192"),dot:L.default.dim("\xB7"),dash:L.default.dim("\u2500")},v={domain:t=>L.default.bold(L.default.white(t)),price:t=>L.default.green(`$${t}`),label:t=>L.default.dim(t),value:t=>L.default.white(t),dim:t=>L.default.dim(t),bold:t=>L.default.bold(t),success:t=>L.default.green(t),error:t=>L.default.red(t),warn:t=>L.default.yellow(t),cyan:t=>L.default.cyan(t),url:t=>`\x1B]8;;${t}\x1B\\${L.default.underline(L.default.cyan(t))}\x1B]8;;\x1B\\`};Xa={start:()=>{},stop:()=>{},message:()=>{}};Za=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;el={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};ur=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});async function pr(){if(Ni)return;let t=process.argv.includes("--json")||!ii,e=Ye(),s=gt();try{if((await(await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${s}`}})).json()).plan==="pro"){Ni=!0;return}}catch{}t&&(console.log(JSON.stringify({error:"Pro plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),u(),console.log(` ${ve.default.dim("This feature requires")} ${ve.default.bold("Pro")} ${ve.default.dim("($9/month).")}`),console.log(` ${ve.default.dim("Opening billing page")} ${b.arrow} ${ve.default.cyan("domani.run/settings")}`),Xe(`${e.replace("http://localhost:3000","https://domani.run")}/settings`),u();let i=k(!0);i.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{if((await(await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${s}`}})).json()).plan==="pro"){Ni=!0,i.stop(`${b.success} Upgraded to Pro! Continuing...`),u();return}}catch{}}i.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No upgrade detected. Visit ${ve.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function gr(){if(Pi||gt()){Pi=!0;return}(process.argv.includes("--json")||!ii)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),u(),console.log(` ${ve.default.dim("You're not logged in.")} Starting authentication...`),u();let e=Ye(),s=k(!0);s.start("Requesting auth code");let i;try{i=await fetch(`${e}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{s.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Could not reach ${e}. Check your connection.`),process.exit(1)}if(!i.ok){s.stop("Failed");let o=`Server error (${i.status})`;try{let a=await i.json();o=a.error||a.message||o}catch{}console.error(` ${ve.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await i.json())}catch{s.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Invalid response from server.`),process.exit(1)}s.stop(`${b.success} Auth code ready`),u(),console.log(` ${ve.default.dim("Verification code:")} ${ve.default.bold(ve.default.cyan(n))}`),console.log(` ${ve.default.dim("Opening browser")} ${b.arrow} ${v.url(r)}`),Xe(r),u(),s.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(c=>setTimeout(c,5e3));let a=await fetch(`${e}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){Lt({...ot(),token:l.token,email:l.email,api_url:e}),Pi=!0,s.stop(`${b.success} Logged in as ${ve.default.bold(l.email)}`),u();return}}s.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No approval received. Run ${ve.default.cyan("domani login")} to try again.`),process.exit(1)}var ve,Pi,Ni,Fi=xe(()=>{"use strict";ve=F(W(),1);$t();q();Pi=!1,Ni=!1});function br(t){return t.json=async()=>{let e=await t.clone().text();try{return JSON.parse(e)}catch{let s=e.trim().slice(0,120);return t.ok?(Object.defineProperty(t,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${t.status})`,hint:`The server replied but not with JSON${s?` (got: "${s}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${t.status})`,hint:"The server returned an unexpected response. Try again later."}}},t}async function j(t,e={},s=!1){let i=gt(),n=`${Ye()}${t}`,r=await fetch(n,{...e,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...e.headers}});if(!s){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await pr(),j(t,e,!0)}catch{}}return br(r)}async function ye(t,e={}){let s=`${Ye()}${t}`,i=gt(),n=await fetch(s,{...e,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...i?{Authorization:`Bearer ${i}`}:{},...e.headers}});return br(n)}var Z=xe(()=>{"use strict";$t();Fi()});function wt(){return{ok:!0}}function ct(t,e,s){return{ok:!1,error:{message:t,code:e,hint:s}}}function _r(t){return sl.test(t)?ct("Input contains control characters","invalid_input","Remove non-printable characters from the input"):wt()}function ll(t){return il.test(t)?ct("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):wt()}function cl(t){return nl.test(t)?ct("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):wt()}function dl(t){return rl.test(t)?ct("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):wt()}function Sr(t){if(!t)return ct("Domain name is required","validation_error");if(t.length>wr)return ct(`Domain name too long (${t.length} chars, max ${wr})`,"validation_error");for(let e of[_r,ll,cl,dl]){let s=e(t);if(!s.ok)return s}return ol.test(t)?wt():ct(`Invalid domain name: ${t}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function ul(t){if(!t)return ct("TLD is required","validation_error");let e=_r(t);return e.ok?al.test(t)?wt():ct(`Invalid TLD: ${t}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):e}function ml(t){for(let e of t){let s=Sr(e);if(!s.ok)return s}return wt()}function fl(t){for(let e of t){let s=ul(e);if(!s.ok)return s}return wt()}function z(t,e){let s=Sr(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}function xr(t,e){let s=ml(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}function Rs(t,e){let s=fl(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}var sl,il,nl,rl,ol,al,wr,be=xe(()=>{"use strict";q();sl=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,il=/\.\.[/\\]/,nl=/[?#]/,rl=/%[0-9a-fA-F]{2}/,ol=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,al=/^\.?[a-zA-Z]{2,63}$/,wr=253});async function ue(){je||h("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let t=k(!0);t.start("Loading your domains");let e=await j("/api/domains"),s=await e.json();e.ok||(t.stop("Failed"),Di(s.error,s.hint),process.exit(1));let i=s.domains||[];i.length===0&&(t.stop("No domains"),u(),console.log(` ${Ui.default.dim("No domains yet.")} Use: ${Ui.default.cyan("domani buy <domain>")}`),u(),process.exit(0)),t.stop(`${i.length} domain(s)`);let n=await ze({message:"Which domain?",options:i.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return ae(n)&&process.exit(0),n}var Ui,Ge=xe(()=>{"use strict";Z();De();Ui=F(W(),1);q()});var jr={};Nt(jr,{connect:()=>Mi});async function Mi(t,e,s){t||(t=await ue()),z(t,s);let i;if(e&&!s.provider?e.includes(".")?i=e:s.provider=e:i=e,!i&&!s.provider&&!s.list&&s.dryRun)return Y("connect",{domain:t,note:"No provider specified. Pass --provider <name> to connect."},s.json,s.fields);if(!i&&!s.provider&&!s.list){let n=k(!s.json);n.start(`Loading providers for ${v.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s.json,fields:s.fields})),n.stop("Providers loaded"),s.json){x(o,s.fields);return}let a=[];for(let g of["hosting","email"]){let _=o.providers?.[g]||[];for(let S of _)a.push({value:`${g}:${S.name}`,label:S.name,hint:g})}a.length===0&&h("No providers available",{code:"not_found",json:s.json,fields:s.fields});let l=await ze({message:"Choose a provider",options:a});ae(l)&&process.exit(0);let[c,d]=l.split(":"),p=(o.providers?.[c]||[]).find(g=>g.name===d),$;if(p&&p.methods.length>1){let g=await ze({message:"Choose a method",options:p.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});ae(g)&&process.exit(0),$=g}let w;if(c==="hosting"&&p?.requires_target){p.notes?.setup&&lt(p.notes.setup);let g=await Te({message:"Target hostname or IP"});ae(g)&&process.exit(0),w=g.trim()}return kr(t,{target:w,provider:d,method:$,dryRun:s.dryRun,json:!1})}if(s.list){let n=k(!s.json);n.start(`Loading providers for ${v.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s.json,fields:s.fields})),n.stop("Providers loaded"),s.json){x(o,s.fields);return}O(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){u(),console.log(` ${de.default.bold(a.toUpperCase())}`);for(let c of l){let d=c.methods.map(f=>f.default?de.default.green(`${f.name} (default)`):de.default.dim(f.name)).join(de.default.dim(", "));console.log(` ${de.default.cyan(c.name.padEnd(20))} ${d}`)}}}u();return}return kr(t,s)}async function kr(t,e){let s={};if(e.target&&(s.target=e.target),e.provider&&(s.provider=e.provider),e.method&&(s.method=e.method),e.dryRun)return Y("connect",{domain:t,...s},e.json,e.fields);let i=k(!e.json);i.start(`Connecting ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Connection failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.status==="manual_setup_required";if(i.stop(o?`${b.success} DNS instructions for ${de.default.cyan(r.provider)}`:`${b.success} Connected to ${de.default.cyan(r.provider)}`),e.json){x(r,e.fields);return}if(O(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),y("Provider",de.default.cyan(r.provider)),y("Method",r.method),r.records?.length){let a=[8,22,40];u(),console.log(` ${de.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((d,f)=>de.default.dim(d.padEnd(a[f]))).join(" "),c=a.map(d=>de.default.dim("\u2500".repeat(d))).join(" ");console.log(` ${l}`),console.log(` ${c}`);for(let d of r.records){let f=d.record,p=d.status!=="already_set";process.stdout.isTTY&&p&&await Tt(50);let w=[de.default.yellow(f.type),f.name,de.default.cyan(f.value)+(f.priority?de.default.dim(` pri=${f.priority}`):"")].map((S,R)=>Os(S,a[R])).join(" "),g=d.status==="already_set"?de.default.dim("\u2713"):d.status==="updated"?de.default.yellow("\u21BA"):d.status==="pending"?de.default.yellow("\u2192"):b.success,_=d.status==="already_set"?de.default.dim(" already set"):d.status==="updated"?de.default.dim(" updated"):d.status==="pending"?de.default.dim(" add this"):"";console.log(` ${g} ${w}${_}`)}}u(),r.next_steps?.length?(console.log(` ${de.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${de.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${de.default.dim(r.hint)}`),r.docs&&console.log(` ${de.default.dim("Docs:")} ${v.url(r.docs)}`),u()}var de,Vi=xe(()=>{"use strict";Z();de=F(W(),1);De();q();be();Ge()});var Tr={};Nt(Tr,{email:()=>Qt});function gl(t){return[D.default.yellow(t.type),t.name,D.default.cyan(t.value)+(t.priority?D.default.dim(` pri=${t.priority}`):"")]}function qi(t){return pl[t]||t}function $l(t,e){if(t&&t.includes("@")){let[s,i]=t.split("@",2);!e.slug&&s&&(e.slug=s),!e.domain&&i&&(e.domain=i)}}async function dt(t){return t.domain?(z(t.domain,t),t.domain):ue()}async function Qt(t,e,s){if(t&&t.includes(".")&&!hl.includes(t))return s.check?Or(t,!!s.json,s.fields):e?Rr(t,e,!!s.json,s.fields):Ir(t,!!s.json,s.fields);if($l(e,s),s.body&&!s.text&&(s.text=s.body),s.title&&!s.subject&&(s.subject=s.title),s.from&&s.from.includes("@")){let[i,n]=s.from.split("@",2);!s.slug&&i&&(s.slug=i),!s.domain&&n&&(s.domain=n)}switch(t){case void 0:return Cr(s);case"list":return Cr(s);case"inbox":return xl(s);case"setup":return yl(s);case"status":return bl(s);case"remove":return vl(s);case"create":return wl(s);case"delete":return _l(s);case"send":return Sl(s);case"webhook":return kl(s);case"forward":return jl(s);case"check":return Or(s.domain||await ue(),!!s.json,s.fields);case"connect":return Rr(s.domain||await ue(),e||void 0,!!s.json,s.fields);default:h(`Unknown action: ${t}`,{hint:"Actions: list, inbox, create, delete, send, forward, webhook, setup, status, check, connect",code:"validation_error",json:s.json,fields:s.fields})}}async function yl(t){let e=await dt(t);if(t.dryRun)return Y("email_setup",{domain:e},t.json,t.fields);let s=k(!t.json);s.start(`Setting up email on ${v.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/setup`,{method:"POST"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),t.json){x(n,t.fields);return}if(n.records?.length){u(),O(`Email DNS Records ${v.domain(e)}`);let r=n.records.map(o=>[D.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?D.default.green(o.status):D.default.yellow(o.status)]);fe(["Type","Name","Value","Status"],r,[8,28,44,12])}u(),n.hint&&lt(n.hint),I("Check status:",`domani email status --domain ${e}`),u()}async function bl(t){let e=await dt(t),s=k(!t.json);s.start(`Checking email status for ${v.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Status loaded`),t.json){x(n,t.fields);return}if(O(`Email ${v.domain(e)}`),y("Enabled",n.enabled?D.default.green("yes"):D.default.dim("no")),n.enabled&&(y("Verified",n.verified?D.default.green("yes"):D.default.yellow("pending")),y("Mailboxes",String(n.mailbox_count))),u(),!n.enabled)I("Set up email:",`domani email setup --domain ${e}`),u();else if(!n.verified&&n.records?.length){console.log(` ${D.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${D.default.yellow(r.type)} ${r.name} ${D.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);u()}}async function vl(t){let e=await dt(t);if(t.dryRun)return Y("email_remove",{domain:e},t.json,t.fields);let s=k(!t.json);s.start(`Removing email from ${v.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/setup`,{method:"DELETE"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Email disabled`),t.json){x(n,t.fields);return}n.mailboxes_deleted>0&&console.log(` ${D.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),u()}async function Cr(t){let e=k(!t.json);e.start("Loading mailboxes");let s=t.domain?`?domain=${encodeURIComponent(t.domain)}`:"",i=await j(`/api/emails${s}`),n=await i.json();i.ok||(e.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields}));let r=n.mailboxes||[];if(e.stop(`${b.success} ${r.length} mailbox(es)`),t.json){x(n,t.fields);return}if(r.length===0){u(),console.log(` ${D.default.dim("No mailboxes.")}`),u(),I("Create one:","domani email create hello@example.com"),u();return}u(),O("Mailboxes");let o=r.map(a=>[D.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):D.default.dim("-"),D.default.dim(new Date(a.created_at).toLocaleDateString())]);fe(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),u()}async function wl(t){let e=await dt(t);if(t.dryRun)return Y("email_create_mailbox",{domain:e,slug:t.slug},t.json,t.fields);let s=t.slug;if(!s&&!t.json){let c=await Te({message:`Email handle for @${e}:`,placeholder:"hello"});ae(c)&&process.exit(0),s=c}s||h("Slug required",{hint:`Usage: domani email create hello@${e}`,code:"validation_error",json:t.json,fields:t.fields});let i=`${s}@${e}`,n=k(!t.json);n.start("Creating mailbox");let r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:i})}),o=await r.json();if(r.status===202&&!t.json){n.stop("");let c=o.txt_record,d=o.email_records||[],f=[{type:"TXT",name:c?.name||"@",value:c?.value||"",note:"ownership proof"},...d];u(),console.log(" Add these records at your DNS provider:"),u();for(let S of f){let R=S.priority!==void 0?` ${D.default.dim(`priority: ${S.priority}`)}`:"",N=S.note?` ${D.default.dim(`(${S.note})`)}`:"";console.log(` ${D.default.yellow(S.type)} ${D.default.bold(S.name)}${R}${N}`),console.log(` ${D.default.dim("\u2192")} ${D.default.cyan(S.value)}`),u()}lt("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),u();let p=f.map(S=>({cells:[D.default.yellow(S.type),S.name,S.note?D.default.dim(`(${S.note})`):""],status:"pending"})),$=Et(["Type","Name",""],p,[6,24,16]);$.start();let w=0;for(;r.status===202&&w<60;)await Tt(15e3),w++,r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:i})}),o=await r.json(),r.status!==202&&!r.ok&&($.stop(),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields}));r.status===202&&($.stop(),h("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${i}`,code:"timeout",json:t.json,fields:t.fields})),$.markDone(0);let g=S=>`${S.type}:${S.name}`,_=new Map;f.slice(1).forEach((S,R)=>_.set(g(S),R+1));for(let S=0;S<60;S++){await Tt(15e3);let R=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),N=await R.json();if(R.ok&&N.records){for(let V of N.records)if(V.status==="verified"||V.status==="created"){let U=_.get(g(V));U!==void 0&&$.markDone(U)}}if(R.ok&&N.verified)break}$.stop(),u()}if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${b.success} ${D.default.cyan(o.address)} created`),t.json){x(o,t.fields);return}let a=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),l=await a.json();u(),a.ok&&l.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${Jt}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${e}`),I("Web inbox:",`${Jt}/inbox?address=${encodeURIComponent(o.address)}`)),u()}async function _l(t){let e=await dt(t);if(t.slug||h("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_delete_mailbox",{domain:e,address:`${t.slug}@${e}`},t.json,t.fields);let s=k(!t.json);s.start(`Deleting ${t.slug}@${e}`);let i=encodeURIComponent(`${t.slug}@${e}`),n=await j(`/api/emails/${i}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(s.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Mailbox deleted`),t.json){x(r,t.fields);return}console.log(` ${D.default.dim(`${r.address} and all messages deleted.`)}`),u()}async function Sl(t){let e=await dt(t);if(t.slug||h("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:t.json,fields:t.fields}),t.to||h("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_send",{from:`${t.slug}@${e}`,to:t.to,subject:t.subject},t.json,t.fields);let s=k(!t.json);s.start(`Sending from ${t.slug}@${e}`);let i={to:t.to};t.cc&&(i.cc=t.cc),t.bcc&&(i.bcc=t.bcc),t.subject&&(i.subject=t.subject),t.text&&(i.text=t.text),t.inReplyTo&&(i.in_reply_to=t.inReplyTo),t.references&&(i.references=t.references);let n=encodeURIComponent(`${t.slug}@${e}`),r=await j(`/api/emails/${n}/send`,{method:"POST",body:JSON.stringify(i)}),o=await r.json();if(!r.ok){s.stop("Failed");let l=o.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${D.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:o.hint;h(o.error||o.message,{hint:l,status:r.status,json:t.json,fields:t.fields})}let a=Array.isArray(o.to)?o.to.join(", "):o.to;if(s.stop(`${b.success} Sent to ${D.default.cyan(a)}`),t.json){x(o,t.fields);return}}async function xl(t){let e=await dt(t);t.slug||h("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:t.json,fields:t.fields});let s=new URLSearchParams;t.direction&&s.set("direction",t.direction),t.limit&&s.set("limit",t.limit);let i=s.toString()?`?${s}`:"",n=k(!t.json);n.start(`Loading messages for ${t.slug}@${e}`);let r=encodeURIComponent(`${t.slug}@${e}`),o=await j(`/api/emails/${r}/messages${i}`),a=await o.json();o.ok||(n.stop("Failed"),h(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}));let l=a.messages||[];if(t.json){n.stop(`${b.success} ${l.length} message(s)`),x(a,t.fields);return}if(l.length===0){n.stop(`${D.default.dim("No messages")}`);return}let c=l.length>1?"s":"";n.stop(`${b.success} ${D.default.cyan(`${t.slug}@${e}`)} ${D.default.dim("\xB7 "+l.length+" message"+c)}`);for(let d of l){let f=d.direction==="in"?D.default.green("in "):D.default.dim("out"),p=d.direction==="in"?d.from:d.to,$=d.subject||"(no subject)",w=D.default.dim(new Date(d.created_at).toLocaleString()),g=$;if(d.text){let _=d.text.replace(/\s+/g," ").trim(),S=_.length>60?_.slice(0,60)+"\u2026":_;g=`${$} ${D.default.dim("- "+S)}`}console.log(` ${f} ${p.padEnd(30)} ${g} ${w}`)}a.next_cursor&&console.log(` ${D.default.dim("\u2026 more available, use --limit to paginate")}`)}async function kl(t){let e=await dt(t);t.slug||h("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:t.json,fields:t.fields});let s=`${t.slug}@${e}`,i=encodeURIComponent(s);if(t.dryRun)return Y("email_webhook",{address:s,webhook_url:t.url||null},t.json,t.fields);let n=k(!t.json);if(t.url){n.start(`Setting webhook for ${s}`);let r=await j(`/api/emails/${i}/webhook`,{method:"PUT",body:JSON.stringify({url:t.url})}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${b.success} Webhook set`),t.json){x(o,t.fields);return}O(`Mailbox ${o.address}`),y("Webhook",v.url(o.webhook_url)),y("Signing secret",D.default.dim(o.signing_secret)),u()}else{n.start(`Removing webhook for ${s}`);let r=await j(`/api/emails/${i}/webhook`,{method:"DELETE"}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${b.success} Webhook removed`),t.json){x(o,t.fields);return}O(`Mailbox ${o.address}`),y("Webhook",D.default.dim("none")),u()}}async function jl(t){let e=await dt(t);if(t.slug||h("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_forward",{address:`${t.slug}@${e}`,forward_to:t.forwardTo||null},t.json,t.fields);let s=k(!t.json),i=t.forwardTo||null;s.start(`Updating forward for ${t.slug}@${e}`);let n=encodeURIComponent(`${t.slug}@${e}`),r=await j(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:i})}),o=await r.json();if(r.ok||(s.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Forward ${i?"set":"removed"}`),t.json){x(o,t.fields);return}O(`Mailbox ${o.address}`),y("Forward to",o.forward_to?D.default.cyan(o.forward_to):D.default.dim("none")),u()}async function Or(t,e,s){let i=k(!e);i.start(`Checking email health for ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/email/check`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop("Email health checked"),e){x(r,s);return}if(O(`Email Health ${v.domain(r.domain)}`),r.provider?y("Provider",D.default.cyan(qi(r.provider))):y("Provider",D.default.dim("unknown")),r.mx.configured?y("MX",`${b.success} ${D.default.green("propagated")} ${D.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):y("MX",`${b.error} ${D.default.red("not configured")}`),r.spf.configured?y("SPF",`${b.success} ${D.default.green(r.spf.value)}`):y("SPF",`${b.error} ${D.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;y("DMARC",`${b.success} ${D.default.green(o)}`)}else y("DMARC",`${b.error} ${D.default.red("missing")}`);r.dkim.configured?y("DKIM",`${b.success} ${D.default.green("found")} ${D.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):y("DKIM",`${b.warning} ${D.default.yellow("not found")}`),u(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(lt("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),u()):(I("Set up email:",`domani email ${t} google`),u())}async function Rr(t,e,s,i){return e?Ar(t,e,s,i):Ir(t,s,i)}async function Ir(t,e,s){let i=k(!e);i.start("Loading email providers");let n=await j(`/api/domains/${encodeURIComponent(t)}/connect`),r=await n.json();n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&h("No email providers available",{code:"not_found",json:e,fields:s});let a=await ze({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:qi(l.name)}))});return ae(a)&&process.exit(0),Ar(t,a,e,s)}async function Ar(t,e,s,i){if(s){let c=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),d=await c.json();c.ok||h(d.error||d.message,{hint:d.hint,status:c.status,json:s,fields:i}),x(d,i);return}let n=await j(`/api/domains/${encodeURIComponent(t)}/connect?provider=${encodeURIComponent(e)}`);if(!n.ok){let c=await n.json();h(c.error||c.message,{hint:c.hint,status:n.status,json:s,fields:i})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??e,l=qi(a);if(O(`Email ${v.domain(t)}`),y("Provider",D.default.cyan(l)),o.length){u(),console.log(` ${D.default.bold("DNS Records")}`);let c=[8,24,40],d=Et(["Type","Name","Value"],o.map(S=>({cells:gl(S),status:"pending"})),c);d.start();let f=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),p=await f.json();f.ok||(d.stop(),u(),h(p.error||p.message,{hint:p.hint,status:f.status,json:s,fields:i}));let $=p.records||[];for(let S=0;S<o.length;S++)$.find(N=>N.record.type===o[S].type&&N.record.name===o[S].name&&N.record.value===o[S].value)?.status==="already_set"||await Tt(60),d.markDone(S);await Tt(80),d.stop();let w=$.filter(S=>S.status==="created"||S.status==="updated").length,g=$.filter(S=>S.status==="already_set").length,_;g===$.length?_=`All ${g} records already set`:g>0?_=`${w} created, ${g} already set`:_=`${w} DNS records set`,u(),console.log(` ${b.success} ${D.default.green(`Email configured - ${_}`)}`)}else{let c=k(!0);c.start("Setting DNS records");let d=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),f=await d.json();d.ok||(c.stop("Failed"),h(f.error||f.message,{hint:f.hint,status:d.status,json:s,fields:i})),c.stop(`${b.success} Email configured via ${D.default.cyan(l)}`)}u(),I("Verify propagation:",`domani email ${t} --check`),u()}var D,hl,pl,Wi=xe(()=>{"use strict";Z();Bt();D=F(W(),1);De();q();be();Ge();hl=["setup","status","remove","list","create","delete","send","inbox","webhook","forward","check","connect"],pl={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var Er={};Nt(Er,{dns:()=>Ji});async function Ji(t,e,s,i,n,r){t||(t=await ue()),z(t,r);let o=r?.json??!1,a=r?.type||s,l=r?.name||i,c=r?.value||n;if(!e||e==="get"){let d=k(!o);d.start(`Loading DNS for ${v.domain(t)}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns`),p=await f.json();if(f.ok||(d.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields})),d.stop(`${p.records.length} record(s)`),o){x(p,r?.fields);return}if(p.records.length===0){u(),console.log(` ${Ce.default.dim(`No DNS records for ${t}`)}`),u(),I("Auto-configure DNS:",`domani connect ${t}`),u();return}let $=[8,24,40,8];O(`DNS ${v.domain(t)}`,$.reduce((g,_)=>g+_,0)+$.length-1);let w=p.records.map(g=>{let _=g.priority?Ce.default.dim(` pri=${g.priority}`):"";return[Ce.default.yellow(g.type),g.name,Ce.default.cyan(g.value)+_,Ce.default.dim(String(g.ttl))]});fe(["Type","Name","Value","TTL"],w,$),u();return}if(e==="set"){if((!a||!l||!c)&&h("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return Y("dns_set",{domain:t,record:{type:a.toUpperCase(),name:l,value:c,ttl:3600}},o,r?.fields);let d=k(!o);d.start(`Setting ${Ce.default.yellow(a.toUpperCase())} record`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns`),p=await f.json(),w=(f.ok?p.records:[]).filter(S=>!(S.type===a.toUpperCase()&&S.name===l));w.push({type:a.toUpperCase(),name:l,value:c,ttl:3600});let g=await j(`/api/domains/${encodeURIComponent(t)}/dns`,{method:"PUT",body:JSON.stringify({records:w})}),_=await g.json();g.ok||(d.stop("Failed"),h(_.error||_.message,{hint:_.hint,status:g.status,json:o,fields:r?.fields})),d.stop(`${b.success} ${Ce.default.yellow(a.toUpperCase())} ${l} ${b.arrow} ${Ce.default.cyan(c)}`),o?x(_,r?.fields):(u(),I("Check propagation:",`domani status ${t}`),u());return}if(e==="delete"){if((!a||!l)&&h("Missing arguments for dns delete",{hint:"Usage: domani dns <domain> delete --type A --name www",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return Y("dns_delete",{domain:t,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let d=k(!o);d.start(`Deleting ${Ce.default.yellow(a.toUpperCase())} ${l}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),p=await f.json();f.ok||(d.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields})),d.stop(`${b.success} Deleted ${Ce.default.yellow(a.toUpperCase())} ${l}`),o?x(p,r?.fields):(u(),I("Check propagation:",`domani status ${t}`),u());return}if(e==="snapshot"){if(r?.dryRun)return Y("dns_snapshot",{domain:t},o,r?.fields);let d=k(!o);d.start(`Capturing DNS snapshot for ${v.domain(t)}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns/snapshot`,{method:"POST"}),p=await f.json();f.ok||(d.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields}));let $=p.records?.length??0;if(d.stop(`${b.success} Captured ${$} record(s)`),o){x(p,r?.fields);return}let w=`${t}.dns.json`,g=(0,Hi.resolve)(process.cwd(),w);(0,Is.writeFileSync)(g,JSON.stringify(p,null,2)+`
194
- `),O("DNS Snapshot"),y("Domain",v.domain(p.domain)),y("Records",String($)),y("Subdomains",String(p.subdomains?.length??0)),y("Sources",(p.sources||[]).join(", ")||"none"),y("Captured",p.capturedAt||p.captured_at||"now"),y("Saved to",Ce.default.cyan(w)),u(),I("Restore from this snapshot:",`domani dns ${t} restore --file ${w}`),u();return}if(e==="restore"){if(r?.dryRun)return Y("dns_restore",{domain:t,source:r?.file||"server_backup"},o,r?.fields);let d=k(!o),f;if(r?.file){let w=(0,Hi.resolve)(process.cwd(),r.file);w.startsWith(process.cwd())||h("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let g=(0,Is.readFileSync)(w,"utf-8"),_=JSON.parse(g);f=JSON.stringify({snapshot:_}),d.start(`Restoring DNS for ${v.domain(t)} from ${Ce.default.cyan(r.file)}`)}catch(g){h(`Failed to read snapshot file: ${g instanceof Error?g.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else d.start(`Restoring DNS for ${v.domain(t)} from server backup`);let p=await j(`/api/domains/${encodeURIComponent(t)}/dns/restore`,{method:"POST",...f?{body:f}:{}}),$=await p.json();if(p.ok||(d.stop("Failed"),h($.error||$.message,{hint:$.hint,status:p.status,json:o,fields:r?.fields})),d.stop(`${b.success} Restored DNS`),o){x($,r?.fields);return}if(O("DNS Restored"),y("Domain",v.domain($.domain)),y("Applied",Ce.default.green(String($.applied??0))),y("Skipped",Ce.default.dim(String($.skipped??0))),$.errors?.length>0){y("Errors",Ce.default.red(String($.errors.length)));for(let w of $.errors)console.log(` ${Ce.default.red("\u2022")} ${w}`)}u(),I("Verify DNS records:",`domani dns ${t}`),u();return}h(`Unknown action: ${e}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ce,Is,Hi,Bi=xe(()=>{"use strict";Z();Ce=F(W(),1);q();be();Ge();Is=require("node:fs"),Hi=require("node:path")});var Dr={};Nt(Dr,{status:()=>Gi});function Cl(t){return[Ze.default.yellow(t.type),t.name,Ze.default.cyan(t.value)+(t.priority?Ze.default.dim(` pri=${t.priority}`):"")]}function Ol(t){if(O(`Status ${v.domain(t.domain)}`),t.expires){let e=new Date(t.expires).toLocaleDateString(),s=t.days_until_expiry,i=s!=null&&s<30?Ze.default.red:s!=null&&s<90?Ze.default.yellow:Ze.default.green;y("Expires",`${e} ${Ze.default.dim("(")}${i(`${s} days`)}${Ze.default.dim(")")}`)}}async function Gi(t,e){if(t||(t=await ue()),z(t,e),e.json){let f=await j(`/api/domains/${encodeURIComponent(t)}/status`),p=await f.json();f.ok||h(p.error||p.message,{hint:p.hint,status:f.status,json:e.json,fields:e.fields}),x(p,e.fields);return}let s=k(!0);s.start(`Checking ${v.domain(t)}`);let i;try{i=await j(`/api/domains/${encodeURIComponent(t)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(e.timeout?parseInt(e.timeout,10)*1e3:3e4)})}catch{s.stop("Failed"),h("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:e.json,fields:e.fields})}if(!i.ok){s.stop("Failed");try{let f=await i.json();h(f.error||f.message,{hint:f.hint,status:i.status,json:e.json,fields:e.fields})}catch{h(`Server error (${i.status})`,{status:i.status,json:e.json,fields:e.fields})}}let n=i.body;n||(s.stop("Failed"),h("Empty response"));let r=new TextDecoder,o="",a=null,l=[],c=!1,d="";try{for await(let f of n){o+=r.decode(f,{stream:!0});let p=o.split(`
195
- `);o=p.pop()??"";for(let $ of p)if($.startsWith("event: "))d=$.slice(7);else if($.startsWith("data: ")){let w=JSON.parse($.slice(6));if(d==="info"&&(s.stop("Status retrieved"),c=!0,Ol(w)),d==="records")if(l=w,l.length>0){u(),console.log(` ${Ze.default.bold("DNS Records")}`);let g=[8,10,34];a=Et(["Type","Name","Value"],l.map(_=>({cells:Cl(_),status:"pending"})),g),a.start()}else u(),y("DNS",Ze.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${t}`);if(d==="propagation"&&a){let{index:g,propagated:_}=w,S=_?b.success:`${b.warning}`;a.markDone(g,S)}d==="done"&&a&&a.stop(),d==="error"&&(c||s.stop("Failed"),a&&a.stop(),h(w.message||"Status check failed"))}}}catch{c||s.stop("Failed"),a&&a.stop(),h("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:e.json,fields:e.fields})}c||s.stop("Done"),u()}var Ze,Yi=xe(()=>{"use strict";Z();Ze=F(W(),1);q();be();Ge()});var es={};Nt(es,{buy:()=>zi});async function Ki(t){let e=await ze({message:`What's next for ${Pe.default.cyan(t)}?`,options:[{value:"connect",label:"Connect to a service",hint:"domani connect"},{value:"email",label:"Set up email",hint:"domani email setup"},{value:"dns",label:"Configure DNS",hint:"domani dns"},{value:"status",label:"Check status & DNS propagation",hint:"domani status"},{value:"done",label:"Done"}]});if(ae(e)||e==="done"){u();return}if(u(),e==="connect"){let{connect:s}=await Promise.resolve().then(()=>(Vi(),jr));await s(t,void 0,{})}else if(e==="email"){let s=await Te({message:`Mailbox name for ${Pe.default.cyan(t)}`,placeholder:"e.g. hey, hello, contact"});if(ae(s)||!s){u();return}u();let{email:i}=await Promise.resolve().then(()=>(Wi(),Tr));await i("create",void 0,{domain:t,slug:s})}else if(e==="dns"){let{dns:s}=await Promise.resolve().then(()=>(Bi(),Er));await s(t)}else if(e==="status"){let{status:s}=await Promise.resolve().then(()=>(Yi(),Dr));await s(t,{})}}async function Rl(t,e){z(t,e);let s;if(e.preChecked)s={available:!0,...e.preChecked};else{let d=k(!e.json);d.start(`Checking ${v.domain(t)}`);let f=await j(`/api/domains/search?q=${encodeURIComponent(t)}`);s=await f.json(),f.ok||(d.stop("Search failed"),h(s.error,{hint:s.hint,status:f.status,json:e.json,fields:e.fields})),s.available||(d.stop(`${b.error} ${v.domain(t)} is not available`),h(`${t} is not available`,{code:"not_available",json:e.json,fields:e.fields})),d.stop(`${b.success} ${v.domain(t)} ${b.dot} available ${b.dot} ${v.price(s.price)}/yr`)}if(e.dryRun)return Y("buy",{domain:t,available:!0,price:s.price,currency:s.currency||"USD"},e.json,e.fields);if(!At(e)){let d=await Be({message:`Purchase ${Pe.default.bold(t)} for ${v.price(s.price)}/yr?`});if(!d||typeof d=="symbol"){console.log(` ${Pe.default.dim("Cancelled.")}`);return}}let i=k(!e.json);i.start("Purchasing");let n=await j("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:t})});if(!n.ok||!n.body){i.stop("Purchase failed");let d=await n.json().catch(()=>({}));h(d.error||d.message,{hint:d.hint,fixUrl:d.setup_url||d.payment_options?.card?.setup_url,status:n.status,json:e.json,fields:e.fields})}let r={},o=new TextDecoder,a="",l="";for await(let d of n.body){a+=o.decode(d,{stream:!0});let f=a.split(`
196
- `);a=f.pop()??"";for(let p of f)if(p.startsWith("event: "))l=p.slice(7).trim();else if(p.startsWith("data: ")){let $=JSON.parse(p.slice(6));l==="checking"?i.message(`Checking ${v.domain($.domain)}`):l==="payment"?i.message(`Charging ${v.price($.total)}`):l==="registering"?i.message(`Registering ${v.domain($.domain)}`):l==="registered"?r=$:l==="error"&&(i.stop("Purchase failed"),h($.error,{hint:$.hint,fixUrl:$.setup_url,status:n.status,json:e.json,fields:e.fields}))}}let c=r.expires?Pe.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(i.stop(`${b.success} ${v.domain(r.domain)} is yours!${c}`),e.json){x(r,e.fields);return}je?await Ki(r.domain):(I("Connect to a service:",`domani connect ${r.domain}`),I("Set up email:",`domani email setup ${r.domain}`),I("Configure DNS:",`domani dns ${r.domain}`),u())}async function Il(t,e){xr(t,e);let s=!!e.json,i=k(!s);i.start(`Checking ${t.length} domains`);let n=await Promise.all(t.map(async g=>{try{let _=await j(`/api/domains/search?q=${encodeURIComponent(g)}`),S=await _.json();return{domain:g,available:_.ok&&S.available,price:S.price}}catch{return{domain:g,available:!1,price:void 0}}})),r=n.filter(g=>g.available),o=n.filter(g=>!g.available);r.length===0&&(i.stop(`${b.error} None of the ${t.length} domains are available`),process.exit(1));let a=r.reduce((g,_)=>g+(_.price||0),0);if(i.stop(`${b.success} ${r.length}/${t.length} available ${b.dot} ${v.price(a.toFixed(2))} total`),o.length>0)for(let g of o)console.log(` ${b.error} ${v.domain(g.domain)} ${Pe.default.dim("not available")}`);if(e.dryRun)return Y("buy_bulk",{domains:r.map(g=>({domain:g.domain,price:g.price})),unavailable:o.map(g=>g.domain),total_price:parseFloat(a.toFixed(2))},e.json,e.fields);if(!At(e)){let g=await Be({message:`Purchase ${Pe.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${v.price(a.toFixed(2))}?`});if(!g||typeof g=="symbol"){console.log(` ${Pe.default.dim("Cancelled.")}`);return}}u();let l=r.map(g=>({cells:[v.domain(g.domain),g.price?`${v.price(g.price.toFixed(2))}/yr`:""],status:"pending"})),c=Et(["Domain","Price"],l,[30,12],!s);c.start();let f=await(await j("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(g=>g.domain)})})).json(),p=new Set((f.results||[]).map(g=>g.domain));for(let g=0;g<r.length;g++){let _=r[g].domain.toLowerCase().trim();p.has(_)?c.markDone(g,b.success):c.markDone(g,b.error)}if(c.stop(),s){x(f,e.fields);return}u();let $=f.summary?.succeeded??0,w=f.summary?.failed??0;if($>0&&console.log(` ${b.success} ${Pe.default.green(`${$} domain${$>1?"s":""} registered`)}`),w>0){console.log(` ${b.error} ${Pe.default.red(`${w} failed`)}`);for(let g of f.errors||[])console.log(` ${Pe.default.dim("\u2500")} ${v.domain(g.domain)}: ${Pe.default.dim(g.error)}${g.hint?` ${Pe.default.dim(`(${g.hint})`)}`:""}`)}if(u(),$>0&&je){let g=(f.results||[]).filter(_=>_.success).map(_=>_.domain);if(g.length===1)await Ki(g[0]);else{let _=await ze({message:"Set up one of your new domains?",options:[...g.map(S=>({value:S,label:Pe.default.cyan(S)})),{value:"done",label:"Done"}]});!ae(_)&&_!=="done"?(u(),await Ki(_)):u()}}else $>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),u())}async function zi(t,e){let s=t.filter(Boolean);if(s.length===0){je||h("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:e.json});let i=await Te({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(ae(i)||!i)&&process.exit(0),s=i.split(/\s+/).filter(Boolean)}return s.length===1?Rl(s[0],e):Il(s,e)}var Pe,Vt=xe(()=>{"use strict";Z();De();Pe=F(W(),1);q();be()});var fn=F(mn(),1),{program:yc,createCommand:bc,createArgument:vc,createOption:wc,CommanderError:_c,InvalidArgumentError:Sc,InvalidOptionArgumentError:xc,Command:hn,Argument:kc,Option:jc,Help:Cc}=fn.default;var st=F(W(),1);$t();Fi();q();Bt();$t();var vt=F(W(),1);q();async function $r(t){let e=Ye(),s=k(!t.json),i=ot();if(i.token){s.start("Checking session");try{let c=await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${i.token}`}});if(c.ok){let d=await c.json();s.stop(`Already logged in as ${vt.default.bold(d.email)}`),t.json&&x({status:"already_logged_in",email:d.email});return}}catch{}s.stop("Session expired, re-authenticating"),u()}s.start("Requesting auth code");let n=await fetch(`${e}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){s.stop("Failed to initiate login");try{let c=await n.json();h(c.error||c.message||`Server error (${n.status})`,{hint:c.hint,code:"login_failed",json:t.json})}catch{h(`Could not reach ${e}. Check your connection and try again.`,{code:"network_error",json:t.json})}}let{code:r,auth_url:o,expires_in:a}=await n.json();if(s.stop("Auth code received"),t.json){x({status:"awaiting_approval",code:r,auth_url:o,expires_in:a});return}u(),console.log(` ${vt.default.dim("Verification code:")} ${vt.default.bold(vt.default.cyan(r))}`),t.open!==!1?(console.log(` ${vt.default.dim("Opening browser")} ${b.arrow} ${v.url(o)}`),Xe(o)):console.log(` ${vt.default.dim("Open this URL to approve:")} ${v.url(o)}`),u(),s.start("Waiting for approval");let l=120;for(let c=0;c<l;c++){await new Promise(p=>setTimeout(p,5e3));let d=await fetch(`${e}/api/auth/cli/poll?code=${r}`);!d.ok&&d.status!==202&&(s.stop("Login failed"),h(`Server error (${d.status})`,{code:"login_failed"}));let f=await d.json();if(f.status==="complete"){Lt({...ot(),token:f.token,email:f.email,api_url:e}),s.stop(`Logged in as ${vt.default.bold(f.email)}`),u(),I("Get started:","domani search"),u();return}f.error&&(s.stop("Login failed"),h(f.error||f.message,{hint:f.hint,code:"login_failed"}))}s.stop("Login timed out"),h("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}$t();var Li=F(W(),1);q();async function yr(t){let e=ot();if(!e.token){t.json?x({status:"not_logged_in"}):console.log(` ${Li.default.dim("Not logged in.")}`);return}let{api_url:s}=e;wn(),s&&Lt({api_url:s}),t.json?x({status:"logged_out",email:e.email||null}):console.log(` ${b.success} Logged out${e.email?` ${Li.default.dim(`(${e.email})`)}`:""}`)}Z();var Zt=F(W(),1);q();async function vr(t){let e=await j("/api/me"),s=await e.json();if(e.ok||h(s.error||s.message,{hint:s.hint,status:e.status,json:t.json,fields:t.fields}),t.json){x(s,t.fields);return}O("Account"),y("Email",Zt.default.bold(s.email)),y("Payment",s.has_payment_method?`${b.success} ${Zt.default.green("active")}`:`${b.error} ${Zt.default.dim("none")}`),y("Domains",String(s.domain_count)),y("API tokens",String(s.token_count)),y("Referral code",s.referral_code||Zt.default.dim("-")),y("Created",new Date(s.created_at).toLocaleDateString()),u()}Z();De();var T=F(W(),1);q();be();var Me=10,qt=200,As=["com","io","ai","dev","app","co","net","org","xyz","sh","me","cc","tech","run","cloud","so","gg","fm","tv","pro","one","inc","ltd","llc","biz","group","global","ventures","capital","fund","agency","store","shop","market","sale","deals","auction","trade","studio","design","art","space","style","fashion","luxury","brand","media","digital","site","online","live","show","world","zone","land","place","city","town","blog","news","social","chat","link","page","fun","lol","meme","wtf","tools","build","works","work","team","solutions","services","systems","network","software","music","video","photo","photos","game","games","club","stream","film","movie","pizza","coffee","beer","bar","pub","restaurant","cafe","kitchen","food","wine","health","care","clinic","dental","fitness","yoga","bio","life","lifestyle","finance","money","legal","law","cash","academy","university","education","training","courses","science","wiki","guide","us","uk","eu","ca","au","de","fr","it","es","nl","jp","sg","nz","mx","house","homes","realty","estate","garden","nyc","london","berlin","paris","guru","ninja","rocks","fail","party","vip","gold","black","pink","red","events","travel","sport","jobs","careers","consulting","energy","eco","green","support","help","info","new","now","today","day"],Ts=null;async function Pr(){if(Ts)return Ts;try{let t=await ye("/api/tlds?sort=price&order=asc&limit=1000");if(t.ok){let s=(await t.json()).tlds.map(i=>i.tld);if(s.length>0){let i=new Set(As),n=new Set(s),r=[...As.filter(o=>n.has(o)),...s.filter(o=>!i.has(o))];return Ts=r,r}}}catch{}return Ts=As,As}async function Al(t,e,s,i,n){let r=[],o=[],a=Me,l=0,c=!0,d=0,f=0,p=!1,$=!1,w=null,g="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=0,R=setInterval(()=>{$||!c||(S=(S+1)%_.length,J())},80);function N(){d>0&&(process.stdout.write(`\x1B[${d}A\x1B[0J`),d=0)}function V(){if(c)return[];let P=Me+f*Me;return r.length>a||i&&P<n.length?["more","new","skip"]:["new","skip"]}function U(){return r.slice(0,a)}function le(){let P=V();return Math.max(0,U().length+P.length-1)}let Q=6;function J(){N();let P=[],K=U(),X=!c&&K.length===0&&o.length>0,G=X?o.slice(0,Q):K,Ie=G.reduce((ce,oe)=>Math.max(ce,oe.domain.length),0),We=V();for(let ce=0;ce<G.length;ce++){let oe=G[ce];if(X)P.push(`${T.default.dim("\u2502")} ${T.default.dim("\u2715")} ${T.default.dim(oe.domain.padEnd(Ie))} ${T.default.dim("taken")}`);else{let Se=ce===l,it=Se?T.default.green("\u25CF"):T.default.dim("\u25CB"),ee=oe.domain.padEnd(Ie),et=Se?T.default.bold(T.default.cyan(ee)):ee,ht=oe.for_sale?T.default.cyan(`$${oe.for_sale.price} (for sale)`):T.default.dim(`$${oe.price}/yr`);P.push(`${T.default.dim("\u2502")} ${it} ${et} ${ht}`)}}if(X&&o.length>Q&&P.push(`${T.default.dim("\u2502")} ${T.default.dim(`\u2026 and ${o.length-Q} more taken`)}`),c){let ce=g?T.default.dim(`checking ${g}\u2026`):T.default.dim("searching\u2026");P.push(`${T.default.dim("\u2502")} ${T.default.cyan(_[S])} ${ce}`)}else{let ce=Me+f*Me;i&&ce>=n.length&&P.push(`${T.default.dim("\u2502")} ${T.default.dim(`All ${Math.min(ce,n.length)} TLDs searched`)}`);for(let Se=0;Se<We.length;Se++){let et=U().length+Se===l?T.default.green("\u25CF"):T.default.dim("\u25CB"),ht=We[Se]==="more"?T.default.dim("More \u2192"):We[Se]==="new"?T.default.dim("New search \u2192"):T.default.dim("Skip");P.push(`${T.default.dim("\u2502")} ${et} ${ht}`)}P.push(T.default.dim("\u2514"))}process.stdout.write(P.join(`
192
+ `}}}}).prompt()});function il(t){return!!(t.json||!je)}function C(t,e=50){console.log(),console.log(` ${L.default.bold(t)}`),console.log(` ${L.default.dim("\u2500".repeat(e))}`)}function g(t,e,s=2){let i=" ".repeat(s);console.log(`${i}${L.default.dim(t.padEnd(16))} ${e}`)}function d(){console.log()}function ct(t){console.log(` ${L.default.dim(t)}`)}function O(t,e){console.log(` ${L.default.dim(t)} ${L.default.cyan(e)}`)}function $r(t){return t.split(/(https?:\/\/[^\s]+)/g).map(s=>/^https?:\/\//.test(s)?`\x1B]8;;${s}\x1B\\${L.default.underline(L.default.cyan(s))}\x1B]8;;\x1B\\`:L.default.dim(s)).join("")}function Fi(t,e){console.error(` ${v.error} ${L.default.red(t)}`),e&&console.error(` ${$r(e)}`)}function k(t=!0){return t?Zt():nl}function yr(t){return t.replace(rl,"")}function Rs(t,e){let s=yr(t).length,i=Math.max(0,e-s);return t+" ".repeat(i)}function de(t,e,s){let i=s||t.map((o,a)=>{let l=e.reduce((c,u)=>Math.max(c,yr(u[a]||"").length),0);return Math.max(o.length,l)+2}),n=t.map((o,a)=>L.default.dim(o.padEnd(i[a]))).join(" "),r=i.map(o=>L.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of e){let a=o.map((l,c)=>Rs(l,i[c])).join(" ");console.log(` ${a}`)}}function ol(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Ni(t){if(Array.isArray(t))return t.map(Ni);if(t&&typeof t=="object"&&!(t instanceof Date)){let e={};for(let[s,i]of Object.entries(t))e[ol(s)]=Ni(i);return e}return t}function x(t,e){let s=Ni(t);if(!e){console.log(JSON.stringify(s,null,2));return}let i=e.split(",").map(n=>n.trim()).filter(Boolean);if(Array.isArray(s)){let n=s.map(r=>hr(r,i));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(s&&typeof s=="object"?hr(s,i):s,null,2))}function hr(t,e){let s={};for(let i of e)i in t&&(s[i]=t[i]);if(Object.keys(s).length===0){for(let[i,n]of Object.entries(t))if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"){let r=n.map(o=>{let a={};for(let l of e)l in o&&(a[l]=o[l]);return a});Object.keys(r[0]).length>0&&(s[i]=r)}}return s}function Tt(t){return!!(t.yes||il(t))}function Y(t,e,s,i){if(s){x({dry_run:!0,action:t,...e},i);return}console.log(),console.log(` ${L.default.yellow("\u25B8 DRY RUN")} ${L.default.dim("- no changes made")}`),console.log(` ${L.default.dim("Action:")} ${L.default.bold(t)}`);for(let[n,r]of Object.entries(e))r!=null&&(Array.isArray(r)?console.log(` ${L.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${L.default.dim(n+":")} ${JSON.stringify(r)}`:` ${L.default.dim(n+":")} ${String(r)}`));console.log()}function ll(t,e,s){return e===401||e===403?"auth_required":e===402||s?"payment_required":e===404?"not_found":e===409?"conflict":e===422?"validation_error":e===429?"rate_limited":/contact/i.test(t)?"contact_required":"error"}function h(t,e){let s=t||`Request failed${e?.status?` (${e.status})`:""}`,i=e?.code||ll(s,e?.status,e?.fixUrl),n=e?.fixCommand||al[i];if(e?.json){let r={error:s,code:i};e.hint&&(r.hint=e.hint),n&&(r.fix_command=n),e.fixUrl&&(r.fix_url=e.fixUrl),x(r,e.fields)}else Fi(s,e?.hint),n?console.error(` ${L.default.dim("Or run:")} ${L.default.cyan(n)}`):e?.fixUrl&&console.error(` ${$r(`Add a payment method at ${e.fixUrl}`)}`);process.exit(1)}function Ze(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,gr.execFile)(e,[t])}function Et(t){return new Promise(e=>setTimeout(e,t))}function Dt(t,e,s,i=!0){let n=process.stdout.isTTY??!1;if(!i)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+e.length;function l(){let p=" "+t.map(($,_)=>L.default.dim($.padEnd(s[_]))).join(" "),y=" "+s.map($=>L.default.dim("\u2500".repeat($))).join(" "),w=[p,y];for(let $ of e){let _=$.status==="done"?$.icon??v.success:L.default.cyan(pr[r%pr.length]),S=$.cells.map((I,N)=>Rs(I,s[N])).join(" ");w.push(` ${_} ${S}`)}return w}let c=!1,u=()=>process.stdout.write("\x1B[?25h");function f(){let p=l();if(c&&n){process.stdout.write(`\x1B[${a}A`);for(let y of p)process.stdout.write(`\x1B[2K${y}
193
+ `)}else{for(let y of p)console.log(y);c=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",u)),f(),n&&(o=setInterval(()=>{r++,f()},80))},markDone(p,y){e[p].status="done",y!==void 0&&(e[p].icon=y),n&&f()},stop(){o&&clearInterval(o);for(let p of e)p.status="done";f(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",u))}}}var L,gr,je,v,b,nl,rl,al,pr,V=xe(()=>{"use strict";L=F(W(),1),gr=require("child_process");De();je=process.stdout.isTTY??!1;v={success:L.default.green("\u2713"),error:L.default.red("\u2717"),warning:L.default.yellow("!"),info:L.default.cyan("\u25CF"),arrow:L.default.dim("\u2192"),dot:L.default.dim("\xB7"),dash:L.default.dim("\u2500")},b={domain:t=>L.default.bold(L.default.white(t)),price:t=>L.default.green(`$${t}`),label:t=>L.default.dim(t),value:t=>L.default.white(t),dim:t=>L.default.dim(t),bold:t=>L.default.bold(t),success:t=>L.default.green(t),error:t=>L.default.red(t),warn:t=>L.default.yellow(t),cyan:t=>L.default.cyan(t),url:t=>`\x1B]8;;${t}\x1B\\${L.default.underline(L.default.cyan(t))}\x1B]8;;\x1B\\`};nl={start:()=>{},stop:()=>{},message:()=>{}};rl=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;al={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};pr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});async function br(){if(Ui)return;let t=process.argv.includes("--json")||!oi,e=Ke(),s=$t();try{if((await(await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${s}`}})).json()).plan==="pro"){Ui=!0;return}}catch{}t&&(console.log(JSON.stringify({error:"Pro plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),d(),console.log(` ${ve.default.dim("This feature requires")} ${ve.default.bold("Pro")} ${ve.default.dim("($9/month).")}`),console.log(` ${ve.default.dim("Opening billing page")} ${v.arrow} ${ve.default.cyan("domani.run/settings")}`),Ze(`${e.replace("http://localhost:3000","https://domani.run")}/settings`),d();let i=k(!0);i.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{if((await(await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${s}`}})).json()).plan==="pro"){Ui=!0,i.stop(`${v.success} Upgraded to Pro! Continuing...`),d();return}}catch{}}i.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No upgrade detected. Visit ${ve.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function vr(){if(Li||$t()){Li=!0;return}(process.argv.includes("--json")||!oi)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),d(),console.log(` ${ve.default.dim("You're not logged in.")} Starting authentication...`),d();let e=Ke(),s=k(!0);s.start("Requesting auth code");let i;try{i=await fetch(`${e}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{s.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Could not reach ${e}. Check your connection.`),process.exit(1)}if(!i.ok){s.stop("Failed");let o=`Server error (${i.status})`;try{let a=await i.json();o=a.error||a.message||o}catch{}console.error(` ${ve.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await i.json())}catch{s.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Invalid response from server.`),process.exit(1)}s.stop(`${v.success} Auth code ready`),d(),console.log(` ${ve.default.dim("Verification code:")} ${ve.default.bold(ve.default.cyan(n))}`),console.log(` ${ve.default.dim("Opening browser")} ${v.arrow} ${b.url(r)}`),Ze(r),d(),s.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(c=>setTimeout(c,5e3));let a=await fetch(`${e}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){Ut({...at(),token:l.token,email:l.email,api_url:e}),Li=!0,s.stop(`${v.success} Logged in as ${ve.default.bold(l.email)}`),d();return}}s.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No approval received. Run ${ve.default.cyan("domani login")} to try again.`),process.exit(1)}var ve,Li,Ui,Mi=xe(()=>{"use strict";ve=F(W(),1);yt();V();Li=!1,Ui=!1});function Sr(t){return t.json=async()=>{let e=await t.clone().text();try{return JSON.parse(e)}catch{let s=e.trim().slice(0,120);return t.ok?(Object.defineProperty(t,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${t.status})`,hint:`The server replied but not with JSON${s?` (got: "${s}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${t.status})`,hint:"The server returned an unexpected response. Try again later."}}},t}async function j(t,e={},s=!1){let i=$t(),n=`${Ke()}${t}`,r=await fetch(n,{...e,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...e.headers}});if(!s){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await br(),j(t,e,!0)}catch{}}return Sr(r)}async function be(t,e={}){let s=`${Ke()}${t}`,i=$t(),n=await fetch(s,{...e,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...i?{Authorization:`Bearer ${i}`}:{},...e.headers}});return Sr(n)}var X=xe(()=>{"use strict";yt();Mi()});function _t(){return{ok:!0}}function dt(t,e,s){return{ok:!1,error:{message:t,code:e,hint:s}}}function jr(t){return cl.test(t)?dt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):_t()}function pl(t){return dl.test(t)?dt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):_t()}function gl(t){return ul.test(t)?dt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):_t()}function $l(t){return ml.test(t)?dt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):_t()}function Cr(t){if(!t)return dt("Domain name is required","validation_error");if(t.length>kr)return dt(`Domain name too long (${t.length} chars, max ${kr})`,"validation_error");for(let e of[jr,pl,gl,$l]){let s=e(t);if(!s.ok)return s}return fl.test(t)?_t():dt(`Invalid domain name: ${t}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function yl(t){if(!t)return dt("TLD is required","validation_error");let e=jr(t);return e.ok?hl.test(t)?_t():dt(`Invalid TLD: ${t}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):e}function bl(t){for(let e of t){let s=Cr(e);if(!s.ok)return s}return _t()}function vl(t){for(let e of t){let s=yl(e);if(!s.ok)return s}return _t()}function z(t,e){let s=Cr(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}function Or(t,e){let s=bl(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}function Is(t,e){let s=vl(t);s.ok||h(s.error.message,{code:s.error.code,hint:s.error.hint,json:e?.json,fields:e?.fields})}var cl,dl,ul,ml,fl,hl,kr,ge=xe(()=>{"use strict";V();cl=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,dl=/\.\.[/\\]/,ul=/[?#]/,ml=/%[0-9a-fA-F]{2}/,fl=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,hl=/^\.?[a-zA-Z]{2,63}$/,kr=253});async function me(){je||h("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let t=k(!0);t.start("Loading your domains");let e=await j("/api/domains"),s=await e.json();e.ok||(t.stop("Failed"),Fi(s.error,s.hint),process.exit(1));let i=s.domains||[];i.length===0&&(t.stop("No domains"),d(),console.log(` ${qi.default.dim("No domains yet.")} Use: ${qi.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),t.stop(`${i.length} domain(s)`);let n=await Xe({message:"Which domain?",options:i.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return ae(n)&&process.exit(0),n}var qi,Ye=xe(()=>{"use strict";X();De();qi=F(W(),1);V()});var Ir={};Ft(Ir,{connect:()=>Wi});async function Wi(t,e,s){t||(t=await me()),z(t,s);let i;if(e&&!s.provider?e.includes(".")?i=e:s.provider=e:i=e,!i&&!s.provider&&!s.list&&s.dryRun)return Y("connect",{domain:t,note:"No provider specified. Pass --provider <name> to connect."},s.json,s.fields);if(!i&&!s.provider&&!s.list){let n=k(!s.json);n.start(`Loading providers for ${b.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s.json,fields:s.fields})),n.stop("Providers loaded"),s.json){x(o,s.fields);return}let a=[];for(let $ of["hosting","email"]){let _=o.providers?.[$]||[];for(let S of _)a.push({value:`${$}:${S.name}`,label:S.name,hint:$})}a.length===0&&h("No providers available",{code:"not_found",json:s.json,fields:s.fields});let l=await Xe({message:"Choose a provider",options:a});ae(l)&&process.exit(0);let[c,u]=l.split(":"),p=(o.providers?.[c]||[]).find($=>$.name===u),y;if(p&&p.methods.length>1){let $=await Xe({message:"Choose a method",options:p.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});ae($)&&process.exit(0),y=$}let w;if(c==="hosting"&&p?.requires_target){p.notes?.setup&&ct(p.notes.setup);let $=await Te({message:"Target hostname or IP"});ae($)&&process.exit(0),w=$.trim()}return Rr(t,{target:w,provider:u,method:y,dryRun:s.dryRun,json:!1})}if(s.list){let n=k(!s.json);n.start(`Loading providers for ${b.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s.json,fields:s.fields})),n.stop("Providers loaded"),s.json){x(o,s.fields);return}C(`Providers for ${b.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){d(),console.log(` ${ue.default.bold(a.toUpperCase())}`);for(let c of l){let u=c.methods.map(f=>f.default?ue.default.green(`${f.name} (default)`):ue.default.dim(f.name)).join(ue.default.dim(", "));console.log(` ${ue.default.cyan(c.name.padEnd(20))} ${u}`)}}}d();return}return Rr(t,s)}async function Rr(t,e){let s={};if(e.target&&(s.target=e.target),e.provider&&(s.provider=e.provider),e.method&&(s.method=e.method),e.dryRun)return Y("connect",{domain:t,...s},e.json,e.fields);let i=k(!e.json);i.start(`Connecting ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Connection failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.status==="manual_setup_required";if(i.stop(o?`${v.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${v.success} Connected to ${ue.default.cyan(r.provider)}`),e.json){x(r,e.fields);return}if(C(o?`Add these records at your registrar for ${b.domain(r.domain)}`:`Connected ${b.domain(r.domain)}`),g("Provider",ue.default.cyan(r.provider)),g("Method",r.method),r.records?.length){let a=[8,22,40];d(),console.log(` ${ue.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((u,f)=>ue.default.dim(u.padEnd(a[f]))).join(" "),c=a.map(u=>ue.default.dim("\u2500".repeat(u))).join(" ");console.log(` ${l}`),console.log(` ${c}`);for(let u of r.records){let f=u.record,p=u.status!=="already_set";process.stdout.isTTY&&p&&await Et(50);let w=[ue.default.yellow(f.type),f.name,ue.default.cyan(f.value)+(f.priority?ue.default.dim(` pri=${f.priority}`):"")].map((S,I)=>Rs(S,a[I])).join(" "),$=u.status==="already_set"?ue.default.dim("\u2713"):u.status==="updated"?ue.default.yellow("\u21BA"):u.status==="pending"?ue.default.yellow("\u2192"):v.success,_=u.status==="already_set"?ue.default.dim(" already set"):u.status==="updated"?ue.default.dim(" updated"):u.status==="pending"?ue.default.dim(" add this"):"";console.log(` ${$} ${w}${_}`)}}d(),r.next_steps?.length?(console.log(` ${ue.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${ue.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${ue.default.dim(r.hint)}`),r.docs&&console.log(` ${ue.default.dim("Docs:")} ${b.url(r.docs)}`),d()}var ue,Hi=xe(()=>{"use strict";X();ue=F(W(),1);De();V();ge();Ye()});var Nr={};Ft(Nr,{email:()=>es,parseRecipients:()=>As,recipientField:()=>Ts});function Sl(t){return[D.default.yellow(t.type),t.name,D.default.cyan(t.value)+(t.priority?D.default.dim(` pri=${t.priority}`):"")]}function Ji(t){return _l[t]||t}function As(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Ts(t){if(t.length!==0)return t.length===1?t[0]:t}function xl(t,e){if(t&&t.includes("@")){let[s,i]=t.split("@",2);!e.slug&&s&&(e.slug=s),!e.domain&&i&&(e.domain=i)}}async function ut(t){return t.domain?(z(t.domain,t),t.domain):me()}async function es(t,e,s){if(t&&t.includes(".")&&!wl.includes(t))return s.check?Tr(t,!!s.json,s.fields):e?Er(t,e,!!s.json,s.fields):Dr(t,!!s.json,s.fields);if(xl(e,s),s.body&&!s.text&&(s.text=s.body),s.title&&!s.subject&&(s.subject=s.title),s.from&&s.from.includes("@")){let[i,n]=s.from.split("@",2);!s.slug&&i&&(s.slug=i),!s.domain&&n&&(s.domain=n)}switch(t){case void 0:return Ar(s);case"list":return Ar(s);case"inbox":return Al(s);case"setup":return kl(s);case"status":return jl(s);case"remove":return Cl(s);case"create":return Ol(s);case"delete":return Rl(s);case"send":return Il(s);case"webhook":return Tl(s);case"forward":return El(s);case"check":return Tr(s.domain||await me(),!!s.json,s.fields);case"connect":return Er(s.domain||await me(),e||void 0,!!s.json,s.fields);default:h(`Unknown action: ${t}`,{hint:"Actions: list, inbox, create, delete, send, forward, webhook, setup, status, check, connect",code:"validation_error",json:s.json,fields:s.fields})}}async function kl(t){let e=await ut(t);if(t.dryRun)return Y("email_setup",{domain:e},t.json,t.fields);let s=k(!t.json);s.start(`Setting up email on ${b.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/setup`,{method:"POST"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),t.json){x(n,t.fields);return}if(n.records?.length){d(),C(`Email DNS Records ${b.domain(e)}`);let r=n.records.map(o=>[D.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?D.default.green(o.status):D.default.yellow(o.status)]);de(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&ct(n.hint),O("Check status:",`domani email status --domain ${e}`),d()}async function jl(t){let e=await ut(t),s=k(!t.json);s.start(`Checking email status for ${b.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Status loaded`),t.json){x(n,t.fields);return}if(C(`Email ${b.domain(e)}`),g("Enabled",n.enabled?D.default.green("yes"):D.default.dim("no")),n.enabled&&(g("Verified",n.verified?D.default.green("yes"):D.default.yellow("pending")),g("Mailboxes",String(n.mailbox_count))),d(),!n.enabled)O("Set up email:",`domani email setup --domain ${e}`),d();else if(!n.verified&&n.records?.length){console.log(` ${D.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${D.default.yellow(r.type)} ${r.name} ${D.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function Cl(t){let e=await ut(t);if(t.dryRun)return Y("email_remove",{domain:e},t.json,t.fields);let s=k(!t.json);s.start(`Removing email from ${b.domain(e)}`);let i=await j(`/api/domains/${encodeURIComponent(e)}/email/setup`,{method:"DELETE"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Email disabled`),t.json){x(n,t.fields);return}n.mailboxes_deleted>0&&console.log(` ${D.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function Ar(t){let e=k(!t.json);e.start("Loading mailboxes");let s=t.domain?`?domain=${encodeURIComponent(t.domain)}`:"",i=await j(`/api/emails${s}`),n=await i.json();i.ok||(e.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields}));let r=n.mailboxes||[];if(e.stop(`${v.success} ${r.length} mailbox(es)`),t.json){x(n,t.fields);return}if(r.length===0){d(),console.log(` ${D.default.dim("No mailboxes.")}`),d(),O("Create one:","domani email create hello@example.com"),d();return}d(),C("Mailboxes");let o=r.map(a=>[D.default.cyan(a.address),String(a.message_count),a.webhook_url?b.url(a.webhook_url):D.default.dim("-"),D.default.dim(new Date(a.created_at).toLocaleDateString())]);de(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function Ol(t){let e=await ut(t);if(t.dryRun)return Y("email_create_mailbox",{domain:e,slug:t.slug},t.json,t.fields);let s=t.slug;if(!s&&!t.json){let c=await Te({message:`Email handle for @${e}:`,placeholder:"hello"});ae(c)&&process.exit(0),s=c}s||h("Slug required",{hint:`Usage: domani email create hello@${e}`,code:"validation_error",json:t.json,fields:t.fields});let i=`${s}@${e}`,n=k(!t.json);n.start("Creating mailbox");let r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:i})}),o=await r.json();if(r.status===202&&!t.json){n.stop("");let c=o.txt_record,u=o.email_records||[],f=[{type:"TXT",name:c?.name||"@",value:c?.value||"",note:"ownership proof"},...u];d(),console.log(" Add these records at your DNS provider:"),d();for(let S of f){let I=S.priority!==void 0?` ${D.default.dim(`priority: ${S.priority}`)}`:"",N=S.note?` ${D.default.dim(`(${S.note})`)}`:"";console.log(` ${D.default.yellow(S.type)} ${D.default.bold(S.name)}${I}${N}`),console.log(` ${D.default.dim("\u2192")} ${D.default.cyan(S.value)}`),d()}ct("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let p=f.map(S=>({cells:[D.default.yellow(S.type),S.name,S.note?D.default.dim(`(${S.note})`):""],status:"pending"})),y=Dt(["Type","Name",""],p,[6,24,16]);y.start();let w=0;for(;r.status===202&&w<60;)await Et(15e3),w++,r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:i})}),o=await r.json(),r.status!==202&&!r.ok&&(y.stop(),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields}));r.status===202&&(y.stop(),h("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${i}`,code:"timeout",json:t.json,fields:t.fields})),y.markDone(0);let $=S=>`${S.type}:${S.name}`,_=new Map;f.slice(1).forEach((S,I)=>_.set($(S),I+1));for(let S=0;S<60;S++){await Et(15e3);let I=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),N=await I.json();if(I.ok&&N.records){for(let q of N.records)if(q.status==="verified"||q.status==="created"){let U=_.get($(q));U!==void 0&&y.markDone(U)}}if(I.ok&&N.verified)break}y.stop(),d()}if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${v.success} ${D.default.cyan(o.address)} created`),t.json){x(o,t.fields);return}let a=await j(`/api/domains/${encodeURIComponent(e)}/email/status`),l=await a.json();d(),a.ok&&l.verified?(O("Read inbox:",`domani email inbox ${o.address}`),O("Web inbox:",`${Bt}/inbox?address=${encodeURIComponent(o.address)}`)):(O("Check propagation:",`domani email status --domain ${e}`),O("Web inbox:",`${Bt}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function Rl(t){let e=await ut(t);if(t.slug||h("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_delete_mailbox",{domain:e,address:`${t.slug}@${e}`},t.json,t.fields);let s=k(!t.json);s.start(`Deleting ${t.slug}@${e}`);let i=encodeURIComponent(`${t.slug}@${e}`),n=await j(`/api/emails/${i}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(s.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Mailbox deleted`),t.json){x(r,t.fields);return}console.log(` ${D.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function Il(t){let e=await ut(t);if(t.slug||h("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:t.json,fields:t.fields}),t.to||h("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_send",{from:`${t.slug}@${e}`,to:t.to,subject:t.subject},t.json,t.fields);let s=k(!t.json);s.start(`Sending from ${t.slug}@${e}`);let i={to:Ts(As(t.to))},n=Ts(As(t.cc)),r=Ts(As(t.bcc));n&&(i.cc=n),r&&(i.bcc=r),t.subject&&(i.subject=t.subject),t.text&&(i.text=t.text),t.inReplyTo&&(i.in_reply_to=t.inReplyTo),t.references&&(i.references=t.references);let o=encodeURIComponent(`${t.slug}@${e}`),a=await j(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(i)}),l=await a.json();if(!a.ok){s.stop("Failed");let u=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${D.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;h(l.error||l.message,{hint:u,status:a.status,json:t.json,fields:t.fields})}let c=Array.isArray(l.to)?l.to.join(", "):l.to;if(s.stop(`${v.success} Sent to ${D.default.cyan(c)}`),t.json){x(l,t.fields);return}}async function Al(t){let e=await ut(t);t.slug||h("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:t.json,fields:t.fields});let s=new URLSearchParams;t.direction&&s.set("direction",t.direction),t.limit&&s.set("limit",t.limit);let i=s.toString()?`?${s}`:"",n=k(!t.json);n.start(`Loading messages for ${t.slug}@${e}`);let r=encodeURIComponent(`${t.slug}@${e}`),o=await j(`/api/emails/${r}/messages${i}`),a=await o.json();o.ok||(n.stop("Failed"),h(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}));let l=a.messages||[];if(t.json){n.stop(`${v.success} ${l.length} message(s)`),x(a,t.fields);return}if(l.length===0){n.stop(`${D.default.dim("No messages")}`);return}let c=l.length>1?"s":"";n.stop(`${v.success} ${D.default.cyan(`${t.slug}@${e}`)} ${D.default.dim("\xB7 "+l.length+" message"+c)}`);for(let u of l){let f=u.direction==="in"?D.default.green("in "):D.default.dim("out"),p=u.direction==="in"?u.from:u.to,y=u.subject||"(no subject)",w=D.default.dim(new Date(u.created_at).toLocaleString()),$=y;if(u.text){let _=u.text.replace(/\s+/g," ").trim(),S=_.length>60?_.slice(0,60)+"\u2026":_;$=`${y} ${D.default.dim("- "+S)}`}console.log(` ${f} ${p.padEnd(30)} ${$} ${w}`)}a.next_cursor&&console.log(` ${D.default.dim("\u2026 more available, use --limit to paginate")}`)}async function Tl(t){let e=await ut(t);t.slug||h("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:t.json,fields:t.fields});let s=`${t.slug}@${e}`,i=encodeURIComponent(s);if(t.dryRun)return Y("email_webhook",{address:s,webhook_url:t.url||null},t.json,t.fields);let n=k(!t.json);if(t.url){n.start(`Setting webhook for ${s}`);let r=await j(`/api/emails/${i}/webhook`,{method:"PUT",body:JSON.stringify({url:t.url})}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${v.success} Webhook set`),t.json){x(o,t.fields);return}C(`Mailbox ${o.address}`),g("Webhook",b.url(o.webhook_url)),g("Signing secret",D.default.dim(o.signing_secret)),d()}else{n.start(`Removing webhook for ${s}`);let r=await j(`/api/emails/${i}/webhook`,{method:"DELETE"}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${v.success} Webhook removed`),t.json){x(o,t.fields);return}C(`Mailbox ${o.address}`),g("Webhook",D.default.dim("none")),d()}}async function El(t){let e=await ut(t);if(t.slug||h("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("email_forward",{address:`${t.slug}@${e}`,forward_to:t.forwardTo||null},t.json,t.fields);let s=k(!t.json),i=t.forwardTo||null;s.start(`Updating forward for ${t.slug}@${e}`);let n=encodeURIComponent(`${t.slug}@${e}`),r=await j(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:i})}),o=await r.json();if(r.ok||(s.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Forward ${i?"set":"removed"}`),t.json){x(o,t.fields);return}C(`Mailbox ${o.address}`),g("Forward to",o.forward_to?D.default.cyan(o.forward_to):D.default.dim("none")),d()}async function Tr(t,e,s){let i=k(!e);i.start(`Checking email health for ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/email/check`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop("Email health checked"),e){x(r,s);return}if(C(`Email Health ${b.domain(r.domain)}`),r.provider?g("Provider",D.default.cyan(Ji(r.provider))):g("Provider",D.default.dim("unknown")),r.mx.configured?g("MX",`${v.success} ${D.default.green("propagated")} ${D.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):g("MX",`${v.error} ${D.default.red("not configured")}`),r.spf.configured?g("SPF",`${v.success} ${D.default.green(r.spf.value)}`):g("SPF",`${v.error} ${D.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;g("DMARC",`${v.success} ${D.default.green(o)}`)}else g("DMARC",`${v.error} ${D.default.red("missing")}`);r.dkim.configured?g("DKIM",`${v.success} ${D.default.green("found")} ${D.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):g("DKIM",`${v.warning} ${D.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(ct("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),d()):(O("Set up email:",`domani email ${t} google`),d())}async function Er(t,e,s,i){return e?Pr(t,e,s,i):Dr(t,s,i)}async function Dr(t,e,s){let i=k(!e);i.start("Loading email providers");let n=await j(`/api/domains/${encodeURIComponent(t)}/connect`),r=await n.json();n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&h("No email providers available",{code:"not_found",json:e,fields:s});let a=await Xe({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:Ji(l.name)}))});return ae(a)&&process.exit(0),Pr(t,a,e,s)}async function Pr(t,e,s,i){if(s){let c=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),u=await c.json();c.ok||h(u.error||u.message,{hint:u.hint,status:c.status,json:s,fields:i}),x(u,i);return}let n=await j(`/api/domains/${encodeURIComponent(t)}/connect?provider=${encodeURIComponent(e)}`);if(!n.ok){let c=await n.json();h(c.error||c.message,{hint:c.hint,status:n.status,json:s,fields:i})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??e,l=Ji(a);if(C(`Email ${b.domain(t)}`),g("Provider",D.default.cyan(l)),o.length){d(),console.log(` ${D.default.bold("DNS Records")}`);let c=[8,24,40],u=Dt(["Type","Name","Value"],o.map(S=>({cells:Sl(S),status:"pending"})),c);u.start();let f=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),p=await f.json();f.ok||(u.stop(),d(),h(p.error||p.message,{hint:p.hint,status:f.status,json:s,fields:i}));let y=p.records||[];for(let S=0;S<o.length;S++)y.find(N=>N.record.type===o[S].type&&N.record.name===o[S].name&&N.record.value===o[S].value)?.status==="already_set"||await Et(60),u.markDone(S);await Et(80),u.stop();let w=y.filter(S=>S.status==="created"||S.status==="updated").length,$=y.filter(S=>S.status==="already_set").length,_;$===y.length?_=`All ${$} records already set`:$>0?_=`${w} created, ${$} already set`:_=`${w} DNS records set`,d(),console.log(` ${v.success} ${D.default.green(`Email configured - ${_}`)}`)}else{let c=k(!0);c.start("Setting DNS records");let u=await j(`/api/domains/${encodeURIComponent(t)}/connect`,{method:"POST",body:JSON.stringify({target:e})}),f=await u.json();u.ok||(c.stop("Failed"),h(f.error||f.message,{hint:f.hint,status:u.status,json:s,fields:i})),c.stop(`${v.success} Email configured via ${D.default.cyan(l)}`)}d(),O("Verify propagation:",`domani email ${t} --check`),d()}var D,wl,_l,Bi=xe(()=>{"use strict";X();Gt();D=F(W(),1);De();V();ge();Ye();wl=["setup","status","remove","list","create","delete","send","inbox","webhook","forward","check","connect"],_l={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var Fr={};Ft(Fr,{dns:()=>Yi});async function Yi(t,e,s,i,n,r){t||(t=await me()),z(t,r);let o=r?.json??!1,a=r?.type||s,l=r?.name||i,c=r?.value||n;if(!e||e==="get"){let u=k(!o);u.start(`Loading DNS for ${b.domain(t)}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns`),p=await f.json();if(f.ok||(u.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields})),u.stop(`${p.records.length} record(s)`),o){x(p,r?.fields);return}if(p.records.length===0){d(),console.log(` ${Ce.default.dim(`No DNS records for ${t}`)}`),d(),O("Auto-configure DNS:",`domani connect ${t}`),d();return}let y=[8,24,40,8];C(`DNS ${b.domain(t)}`,y.reduce(($,_)=>$+_,0)+y.length-1);let w=p.records.map($=>{let _=$.priority?Ce.default.dim(` pri=${$.priority}`):"";return[Ce.default.yellow($.type),$.name,Ce.default.cyan($.value)+_,Ce.default.dim(String($.ttl))]});de(["Type","Name","Value","TTL"],w,y),d();return}if(e==="set"){if((!a||!l||!c)&&h("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return Y("dns_set",{domain:t,record:{type:a.toUpperCase(),name:l,value:c,ttl:3600}},o,r?.fields);let u=k(!o);u.start(`Setting ${Ce.default.yellow(a.toUpperCase())} record`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns`),p=await f.json(),w=(f.ok?p.records:[]).filter(S=>!(S.type===a.toUpperCase()&&S.name===l));w.push({type:a.toUpperCase(),name:l,value:c,ttl:3600});let $=await j(`/api/domains/${encodeURIComponent(t)}/dns`,{method:"PUT",body:JSON.stringify({records:w})}),_=await $.json();$.ok||(u.stop("Failed"),h(_.error||_.message,{hint:_.hint,status:$.status,json:o,fields:r?.fields})),u.stop(`${v.success} ${Ce.default.yellow(a.toUpperCase())} ${l} ${v.arrow} ${Ce.default.cyan(c)}`),o?x(_,r?.fields):(d(),O("Check propagation:",`domani status ${t}`),d());return}if(e==="delete"){if((!a||!l)&&h("Missing arguments for dns delete",{hint:"Usage: domani dns <domain> delete --type A --name www",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return Y("dns_delete",{domain:t,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let u=k(!o);u.start(`Deleting ${Ce.default.yellow(a.toUpperCase())} ${l}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),p=await f.json();f.ok||(u.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields})),u.stop(`${v.success} Deleted ${Ce.default.yellow(a.toUpperCase())} ${l}`),o?x(p,r?.fields):(d(),O("Check propagation:",`domani status ${t}`),d());return}if(e==="snapshot"){if(r?.dryRun)return Y("dns_snapshot",{domain:t},o,r?.fields);let u=k(!o);u.start(`Capturing DNS snapshot for ${b.domain(t)}`);let f=await j(`/api/domains/${encodeURIComponent(t)}/dns/snapshot`,{method:"POST"}),p=await f.json();f.ok||(u.stop("Failed"),h(p.error||p.message,{hint:p.hint,status:f.status,json:o,fields:r?.fields}));let y=p.records?.length??0;if(u.stop(`${v.success} Captured ${y} record(s)`),o){x(p,r?.fields);return}let w=`${t}.dns.json`,$=(0,Gi.resolve)(process.cwd(),w);(0,Es.writeFileSync)($,JSON.stringify(p,null,2)+`
194
+ `),C("DNS Snapshot"),g("Domain",b.domain(p.domain)),g("Records",String(y)),g("Subdomains",String(p.subdomains?.length??0)),g("Sources",(p.sources||[]).join(", ")||"none"),g("Captured",p.capturedAt||p.captured_at||"now"),g("Saved to",Ce.default.cyan(w)),d(),O("Restore from this snapshot:",`domani dns ${t} restore --file ${w}`),d();return}if(e==="restore"){if(r?.dryRun)return Y("dns_restore",{domain:t,source:r?.file||"server_backup"},o,r?.fields);let u=k(!o),f;if(r?.file){let w=(0,Gi.resolve)(process.cwd(),r.file);w.startsWith(process.cwd())||h("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let $=(0,Es.readFileSync)(w,"utf-8"),_=JSON.parse($);f=JSON.stringify({snapshot:_}),u.start(`Restoring DNS for ${b.domain(t)} from ${Ce.default.cyan(r.file)}`)}catch($){h(`Failed to read snapshot file: ${$ instanceof Error?$.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else u.start(`Restoring DNS for ${b.domain(t)} from server backup`);let p=await j(`/api/domains/${encodeURIComponent(t)}/dns/restore`,{method:"POST",...f?{body:f}:{}}),y=await p.json();if(p.ok||(u.stop("Failed"),h(y.error||y.message,{hint:y.hint,status:p.status,json:o,fields:r?.fields})),u.stop(`${v.success} Restored DNS`),o){x(y,r?.fields);return}if(C("DNS Restored"),g("Domain",b.domain(y.domain)),g("Applied",Ce.default.green(String(y.applied??0))),g("Skipped",Ce.default.dim(String(y.skipped??0))),y.errors?.length>0){g("Errors",Ce.default.red(String(y.errors.length)));for(let w of y.errors)console.log(` ${Ce.default.red("\u2022")} ${w}`)}d(),O("Verify DNS records:",`domani dns ${t}`),d();return}h(`Unknown action: ${e}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ce,Es,Gi,Ki=xe(()=>{"use strict";X();Ce=F(W(),1);V();ge();Ye();Es=require("node:fs"),Gi=require("node:path")});var Lr={};Ft(Lr,{status:()=>zi});function Dl(t){return[Qe.default.yellow(t.type),t.name,Qe.default.cyan(t.value)+(t.priority?Qe.default.dim(` pri=${t.priority}`):"")]}function Pl(t){if(C(`Status ${b.domain(t.domain)}`),t.expires){let e=new Date(t.expires).toLocaleDateString(),s=t.days_until_expiry,i=s!=null&&s<30?Qe.default.red:s!=null&&s<90?Qe.default.yellow:Qe.default.green;g("Expires",`${e} ${Qe.default.dim("(")}${i(`${s} days`)}${Qe.default.dim(")")}`)}}async function zi(t,e){if(t||(t=await me()),z(t,e),e.json){let f=await j(`/api/domains/${encodeURIComponent(t)}/status`),p=await f.json();f.ok||h(p.error||p.message,{hint:p.hint,status:f.status,json:e.json,fields:e.fields}),x(p,e.fields);return}let s=k(!0);s.start(`Checking ${b.domain(t)}`);let i;try{i=await j(`/api/domains/${encodeURIComponent(t)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(e.timeout?parseInt(e.timeout,10)*1e3:3e4)})}catch{s.stop("Failed"),h("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:e.json,fields:e.fields})}if(!i.ok){s.stop("Failed");try{let f=await i.json();h(f.error||f.message,{hint:f.hint,status:i.status,json:e.json,fields:e.fields})}catch{h(`Server error (${i.status})`,{status:i.status,json:e.json,fields:e.fields})}}let n=i.body;n||(s.stop("Failed"),h("Empty response"));let r=new TextDecoder,o="",a=null,l=[],c=!1,u="";try{for await(let f of n){o+=r.decode(f,{stream:!0});let p=o.split(`
195
+ `);o=p.pop()??"";for(let y of p)if(y.startsWith("event: "))u=y.slice(7);else if(y.startsWith("data: ")){let w=JSON.parse(y.slice(6));if(u==="info"&&(s.stop("Status retrieved"),c=!0,Pl(w)),u==="records")if(l=w,l.length>0){d(),console.log(` ${Qe.default.bold("DNS Records")}`);let $=[8,10,34];a=Dt(["Type","Name","Value"],l.map(_=>({cells:Dl(_),status:"pending"})),$),a.start()}else d(),g("DNS",Qe.default.dim("no records")),O("Auto-configure DNS:",`domani connect ${t}`);if(u==="propagation"&&a){let{index:$,propagated:_}=w,S=_?v.success:`${v.warning}`;a.markDone($,S)}u==="done"&&a&&a.stop(),u==="error"&&(c||s.stop("Failed"),a&&a.stop(),h(w.message||"Status check failed"))}}}catch{c||s.stop("Failed"),a&&a.stop(),h("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:e.json,fields:e.fields})}c||s.stop("Done"),d()}var Qe,Xi=xe(()=>{"use strict";X();Qe=F(W(),1);V();ge();Ye()});var ts={};Ft(ts,{buy:()=>Qi});async function Zi(t){let e=await Xe({message:`What's next for ${Pe.default.cyan(t)}?`,options:[{value:"connect",label:"Connect to a service",hint:"domani connect"},{value:"email",label:"Set up email",hint:"domani email setup"},{value:"dns",label:"Configure DNS",hint:"domani dns"},{value:"status",label:"Check status & DNS propagation",hint:"domani status"},{value:"done",label:"Done"}]});if(ae(e)||e==="done"){d();return}if(d(),e==="connect"){let{connect:s}=await Promise.resolve().then(()=>(Hi(),Ir));await s(t,void 0,{})}else if(e==="email"){let s=await Te({message:`Mailbox name for ${Pe.default.cyan(t)}`,placeholder:"e.g. hey, hello, contact"});if(ae(s)||!s){d();return}d();let{email:i}=await Promise.resolve().then(()=>(Bi(),Nr));await i("create",void 0,{domain:t,slug:s})}else if(e==="dns"){let{dns:s}=await Promise.resolve().then(()=>(Ki(),Fr));await s(t)}else if(e==="status"){let{status:s}=await Promise.resolve().then(()=>(Xi(),Lr));await s(t,{})}}async function Nl(t,e){z(t,e);let s;if(e.preChecked)s={available:!0,...e.preChecked};else{let u=k(!e.json);u.start(`Checking ${b.domain(t)}`);let f=await j(`/api/domains/search?q=${encodeURIComponent(t)}`);s=await f.json(),f.ok||(u.stop("Search failed"),h(s.error,{hint:s.hint,status:f.status,json:e.json,fields:e.fields})),s.available||(u.stop(`${v.error} ${b.domain(t)} is not available`),h(`${t} is not available`,{code:"not_available",json:e.json,fields:e.fields})),u.stop(`${v.success} ${b.domain(t)} ${v.dot} available ${v.dot} ${b.price(s.price)}/yr`)}if(e.dryRun)return Y("buy",{domain:t,available:!0,price:s.price,currency:s.currency||"USD"},e.json,e.fields);if(!Tt(e)){let u=await Ge({message:`Purchase ${Pe.default.bold(t)} for ${b.price(s.price)}/yr?`});if(!u||typeof u=="symbol"){console.log(` ${Pe.default.dim("Cancelled.")}`);return}}let i=k(!e.json);i.start("Purchasing");let n=await j("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:t})});if(!n.ok||!n.body){i.stop("Purchase failed");let u=await n.json().catch(()=>({}));h(u.error||u.message,{hint:u.hint,fixUrl:u.setup_url||u.payment_options?.card?.setup_url,status:n.status,json:e.json,fields:e.fields})}let r={},o=new TextDecoder,a="",l="";for await(let u of n.body){a+=o.decode(u,{stream:!0});let f=a.split(`
196
+ `);a=f.pop()??"";for(let p of f)if(p.startsWith("event: "))l=p.slice(7).trim();else if(p.startsWith("data: ")){let y=JSON.parse(p.slice(6));l==="checking"?i.message(`Checking ${b.domain(y.domain)}`):l==="payment"?i.message(`Charging ${b.price(y.total)}`):l==="registering"?i.message(`Registering ${b.domain(y.domain)}`):l==="registered"?r=y:l==="error"&&(i.stop("Purchase failed"),h(y.error,{hint:y.hint,fixUrl:y.setup_url,status:n.status,json:e.json,fields:e.fields}))}}let c=r.expires?Pe.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(i.stop(`${v.success} ${b.domain(r.domain)} is yours!${c}`),e.json){x(r,e.fields);return}je?await Zi(r.domain):(O("Connect to a service:",`domani connect ${r.domain}`),O("Set up email:",`domani email setup ${r.domain}`),O("Configure DNS:",`domani dns ${r.domain}`),d())}async function Fl(t,e){Or(t,e);let s=!!e.json,i=k(!s);i.start(`Checking ${t.length} domains`);let n=await Promise.all(t.map(async $=>{try{let _=await j(`/api/domains/search?q=${encodeURIComponent($)}`),S=await _.json();return{domain:$,available:_.ok&&S.available,price:S.price}}catch{return{domain:$,available:!1,price:void 0}}})),r=n.filter($=>$.available),o=n.filter($=>!$.available);r.length===0&&(i.stop(`${v.error} None of the ${t.length} domains are available`),process.exit(1));let a=r.reduce(($,_)=>$+(_.price||0),0);if(i.stop(`${v.success} ${r.length}/${t.length} available ${v.dot} ${b.price(a.toFixed(2))} total`),o.length>0)for(let $ of o)console.log(` ${v.error} ${b.domain($.domain)} ${Pe.default.dim("not available")}`);if(e.dryRun)return Y("buy_bulk",{domains:r.map($=>({domain:$.domain,price:$.price})),unavailable:o.map($=>$.domain),total_price:parseFloat(a.toFixed(2))},e.json,e.fields);if(!Tt(e)){let $=await Ge({message:`Purchase ${Pe.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${b.price(a.toFixed(2))}?`});if(!$||typeof $=="symbol"){console.log(` ${Pe.default.dim("Cancelled.")}`);return}}d();let l=r.map($=>({cells:[b.domain($.domain),$.price?`${b.price($.price.toFixed(2))}/yr`:""],status:"pending"})),c=Dt(["Domain","Price"],l,[30,12],!s);c.start();let f=await(await j("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map($=>$.domain)})})).json(),p=new Set((f.results||[]).map($=>$.domain));for(let $=0;$<r.length;$++){let _=r[$].domain.toLowerCase().trim();p.has(_)?c.markDone($,v.success):c.markDone($,v.error)}if(c.stop(),s){x(f,e.fields);return}d();let y=f.summary?.succeeded??0,w=f.summary?.failed??0;if(y>0&&console.log(` ${v.success} ${Pe.default.green(`${y} domain${y>1?"s":""} registered`)}`),w>0){console.log(` ${v.error} ${Pe.default.red(`${w} failed`)}`);for(let $ of f.errors||[])console.log(` ${Pe.default.dim("\u2500")} ${b.domain($.domain)}: ${Pe.default.dim($.error)}${$.hint?` ${Pe.default.dim(`(${$.hint})`)}`:""}`)}if(d(),y>0&&je){let $=(f.results||[]).filter(_=>_.success).map(_=>_.domain);if($.length===1)await Zi($[0]);else{let _=await Xe({message:"Set up one of your new domains?",options:[...$.map(S=>({value:S,label:Pe.default.cyan(S)})),{value:"done",label:"Done"}]});!ae(_)&&_!=="done"?(d(),await Zi(_)):d()}}else y>0&&(O("Connect to a service:","domani connect <domain>"),O("Set up email:","domani email setup <domain>"),d())}async function Qi(t,e){let s=t.filter(Boolean);if(s.length===0){je||h("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:e.json});let i=await Te({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(ae(i)||!i)&&process.exit(0),s=i.split(/\s+/).filter(Boolean)}return s.length===1?Nl(s[0],e):Fl(s,e)}var Pe,qt=xe(()=>{"use strict";X();De();Pe=F(W(),1);V();ge()});var $n=F(gn(),1),{program:Cc,createCommand:Oc,createArgument:Rc,createOption:Ic,CommanderError:Ac,InvalidArgumentError:Tc,InvalidOptionArgumentError:Ec,Command:yn,Argument:Dc,Option:Pc,Help:Nc}=$n.default;var it=F(W(),1);yt();Mi();V();Gt();yt();var wt=F(W(),1);V();async function wr(t){let e=Ke(),s=k(!t.json),i=at();if(i.token){s.start("Checking session");try{let c=await fetch(`${e}/api/me`,{headers:{Authorization:`Bearer ${i.token}`}});if(c.ok){let u=await c.json();s.stop(`Already logged in as ${wt.default.bold(u.email)}`),t.json&&x({status:"already_logged_in",email:u.email});return}}catch{}s.stop("Session expired, re-authenticating"),d()}s.start("Requesting auth code");let n=await fetch(`${e}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){s.stop("Failed to initiate login");try{let c=await n.json();h(c.error||c.message||`Server error (${n.status})`,{hint:c.hint,code:"login_failed",json:t.json})}catch{h(`Could not reach ${e}. Check your connection and try again.`,{code:"network_error",json:t.json})}}let{code:r,auth_url:o,expires_in:a}=await n.json();if(s.stop("Auth code received"),t.json){x({status:"awaiting_approval",code:r,auth_url:o,expires_in:a});return}d(),console.log(` ${wt.default.dim("Verification code:")} ${wt.default.bold(wt.default.cyan(r))}`),t.open!==!1?(console.log(` ${wt.default.dim("Opening browser")} ${v.arrow} ${b.url(o)}`),Ze(o)):console.log(` ${wt.default.dim("Open this URL to approve:")} ${b.url(o)}`),d(),s.start("Waiting for approval");let l=120;for(let c=0;c<l;c++){await new Promise(p=>setTimeout(p,5e3));let u=await fetch(`${e}/api/auth/cli/poll?code=${r}`);!u.ok&&u.status!==202&&(s.stop("Login failed"),h(`Server error (${u.status})`,{code:"login_failed"}));let f=await u.json();if(f.status==="complete"){Ut({...at(),token:f.token,email:f.email,api_url:e}),s.stop(`Logged in as ${wt.default.bold(f.email)}`),d(),O("Get started:","domani search"),d();return}f.error&&(s.stop("Login failed"),h(f.error||f.message,{hint:f.hint,code:"login_failed"}))}s.stop("Login timed out"),h("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}yt();var Vi=F(W(),1);V();async function _r(t){let e=at();if(!e.token){t.json?x({status:"not_logged_in"}):console.log(` ${Vi.default.dim("Not logged in.")}`);return}let{api_url:s}=e;kn(),s&&Ut({api_url:s}),t.json?x({status:"logged_out",email:e.email||null}):console.log(` ${v.success} Logged out${e.email?` ${Vi.default.dim(`(${e.email})`)}`:""}`)}X();var Qt=F(W(),1);V();async function xr(t){let e=await j("/api/me"),s=await e.json();if(e.ok||h(s.error||s.message,{hint:s.hint,status:e.status,json:t.json,fields:t.fields}),t.json){x(s,t.fields);return}C("Account"),g("Email",Qt.default.bold(s.email)),g("Payment",s.has_payment_method?`${v.success} ${Qt.default.green("active")}`:`${v.error} ${Qt.default.dim("none")}`),g("Domains",String(s.domain_count)),g("API tokens",String(s.token_count)),g("Referral code",s.referral_code||Qt.default.dim("-")),g("Created",new Date(s.created_at).toLocaleDateString()),d()}X();De();var T=F(W(),1);V();ge();var Ve=10,Wt=200,Ds=["com","io","ai","dev","app","co","net","org","xyz","sh","me","cc","tech","run","cloud","so","gg","fm","tv","pro","one","inc","ltd","llc","biz","group","global","ventures","capital","fund","agency","store","shop","market","sale","deals","auction","trade","studio","design","art","space","style","fashion","luxury","brand","media","digital","site","online","live","show","world","zone","land","place","city","town","blog","news","social","chat","link","page","fun","lol","meme","wtf","tools","build","works","work","team","solutions","services","systems","network","software","music","video","photo","photos","game","games","club","stream","film","movie","pizza","coffee","beer","bar","pub","restaurant","cafe","kitchen","food","wine","health","care","clinic","dental","fitness","yoga","bio","life","lifestyle","finance","money","legal","law","cash","academy","university","education","training","courses","science","wiki","guide","us","uk","eu","ca","au","de","fr","it","es","nl","jp","sg","nz","mx","house","homes","realty","estate","garden","nyc","london","berlin","paris","guru","ninja","rocks","fail","party","vip","gold","black","pink","red","events","travel","sport","jobs","careers","consulting","energy","eco","green","support","help","info","new","now","today","day"],Ps=null;async function Ur(){if(Ps)return Ps;try{let t=await be("/api/tlds?sort=price&order=asc&limit=1000");if(t.ok){let s=(await t.json()).tlds.map(i=>i.tld);if(s.length>0){let i=new Set(Ds),n=new Set(s),r=[...Ds.filter(o=>n.has(o)),...s.filter(o=>!i.has(o))];return Ps=r,r}}}catch{}return Ps=Ds,Ds}async function Ll(t,e,s,i,n){let r=[],o=[],a=Ve,l=0,c=!0,u=0,f=0,p=!1,y=!1,w=null,$="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=0,I=setInterval(()=>{y||!c||(S=(S+1)%_.length,J())},80);function N(){u>0&&(process.stdout.write(`\x1B[${u}A\x1B[0J`),u=0)}function q(){if(c)return[];let P=Ve+f*Ve;return r.length>a||i&&P<n.length?["more","new","skip"]:["new","skip"]}function U(){return r.slice(0,a)}function le(){let P=q();return Math.max(0,U().length+P.length-1)}let Q=6;function J(){N();let P=[],K=U(),Z=!c&&K.length===0&&o.length>0,G=Z?o.slice(0,Q):K,Ie=G.reduce((ce,oe)=>Math.max(ce,oe.domain.length),0),He=q();for(let ce=0;ce<G.length;ce++){let oe=G[ce];if(Z)P.push(`${T.default.dim("\u2502")} ${T.default.dim("\u2715")} ${T.default.dim(oe.domain.padEnd(Ie))} ${T.default.dim("taken")}`);else{let Se=ce===l,nt=Se?T.default.green("\u25CF"):T.default.dim("\u25CB"),ee=oe.domain.padEnd(Ie),tt=Se?T.default.bold(T.default.cyan(ee)):ee,pt=oe.for_sale?T.default.cyan(`$${oe.for_sale.price} (for sale)`):T.default.dim(`$${oe.price}/yr`);P.push(`${T.default.dim("\u2502")} ${nt} ${tt} ${pt}`)}}if(Z&&o.length>Q&&P.push(`${T.default.dim("\u2502")} ${T.default.dim(`\u2026 and ${o.length-Q} more taken`)}`),c){let ce=$?T.default.dim(`checking ${$}\u2026`):T.default.dim("searching\u2026");P.push(`${T.default.dim("\u2502")} ${T.default.cyan(_[S])} ${ce}`)}else{let ce=Ve+f*Ve;i&&ce>=n.length&&P.push(`${T.default.dim("\u2502")} ${T.default.dim(`All ${Math.min(ce,n.length)} TLDs searched`)}`);for(let Se=0;Se<He.length;Se++){let tt=U().length+Se===l?T.default.green("\u25CF"):T.default.dim("\u25CB"),pt=He[Se]==="more"?T.default.dim("More \u2192"):He[Se]==="new"?T.default.dim("New search \u2192"):T.default.dim("Skip");P.push(`${T.default.dim("\u2502")} ${tt} ${pt}`)}P.push(T.default.dim("\u2514"))}process.stdout.write(P.join(`
197
197
  `)+`
198
- `),d=P.length}process.stdout.write(`${T.default.cyan("\u25C6")} Register a domain?
199
- `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let A=P=>{let K=P.toString();if(K==="\x1B[A")l=Math.max(0,l-1),J();else if(K==="\x1B[B")l=Math.min(le(),l+1),J();else if(K==="\r"){let X=U();if(c&&X.length===0)return;if(l<X.length)w=X[l]?.domain??null,$=!0;else{let Ie=V()[l-X.length];Ie==="more"?(a+=Me,r.length<a?p=!0:(l=Math.min(l,le()),J())):(Ie==="new"&&(w="__new__"),$=!0)}}else(K===""||K==="\x1B")&&($=!0)};process.stdin.on("data",A),J();async function te(P){let K=new TextDecoder,X="",G="";for await(let Ie of P){if($)break;X+=K.decode(Ie,{stream:!0});let We=X.split(`
200
- `);X=We.pop()??"";for(let ce of We)if(ce.startsWith("event: "))G=ce.slice(7);else if(ce.startsWith("data: ")){let oe=JSON.parse(ce.slice(6));if(G==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),h(oe.message||oe.error||"Search failed",{code:oe.code||"error"})),G==="result"&&(g=oe.domain),G==="result"&&(oe.available||oe.for_sale||s)){if(f===0){let Se=r.findIndex(it=>it.price>oe.price);Se===-1?r.push(oe):(r.splice(Se,0,oe),Se<=l&&l++)}else r.push(oe);J()}else if(G==="result"&&!oe.available&&!oe.error)o.length<8&&o.push(oe);else if(G==="done"){c=!1,l=Math.min(l,le());let Se=Me+f*Me;r.length<a&&i&&Se<n.length&&(p=!0),p||J()}}}c=!1}for(await te(t);!$;)if(await new Promise(P=>{let K=setInterval(()=>{($||p)&&(clearInterval(K),P())},16)}),p&&!$){p=!1;let P=Me+f*Me,K=n.slice(P,P+Me);f++,c=!0,l=Math.min(l,Math.max(0,r.length-1)),J();let X=new URLSearchParams;X.set("domains",K.map(G=>`${e}.${G}`).join(","));try{let G=await ye(`/api/domains/search?${X}`,{headers:{Accept:"text/event-stream"}});G.ok&&G.body?await te(G.body):(c=!1,J())}catch{c=!1,J()}}clearInterval(R),process.stdin.removeListener("data",A),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),N();let B=w==="__new__",E=B?null:w,ie=E?r.find(P=>P.domain===E)??null:null;return E?process.stdout.write(`${T.default.dim("\u25C7")} Register a domain?
198
+ `),u=P.length}process.stdout.write(`${T.default.cyan("\u25C6")} Register a domain?
199
+ `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let A=P=>{let K=P.toString();if(K==="\x1B[A")l=Math.max(0,l-1),J();else if(K==="\x1B[B")l=Math.min(le(),l+1),J();else if(K==="\r"){let Z=U();if(c&&Z.length===0)return;if(l<Z.length)w=Z[l]?.domain??null,y=!0;else{let Ie=q()[l-Z.length];Ie==="more"?(a+=Ve,r.length<a?p=!0:(l=Math.min(l,le()),J())):(Ie==="new"&&(w="__new__"),y=!0)}}else(K===""||K==="\x1B")&&(y=!0)};process.stdin.on("data",A),J();async function te(P){let K=new TextDecoder,Z="",G="";for await(let Ie of P){if(y)break;Z+=K.decode(Ie,{stream:!0});let He=Z.split(`
200
+ `);Z=He.pop()??"";for(let ce of He)if(ce.startsWith("event: "))G=ce.slice(7);else if(ce.startsWith("data: ")){let oe=JSON.parse(ce.slice(6));if(G==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),h(oe.message||oe.error||"Search failed",{code:oe.code||"error"})),G==="result"&&($=oe.domain),G==="result"&&(oe.available||oe.for_sale||s)){if(f===0){let Se=r.findIndex(nt=>nt.price>oe.price);Se===-1?r.push(oe):(r.splice(Se,0,oe),Se<=l&&l++)}else r.push(oe);J()}else if(G==="result"&&!oe.available&&!oe.error)o.length<8&&o.push(oe);else if(G==="done"){c=!1,l=Math.min(l,le());let Se=Ve+f*Ve;r.length<a&&i&&Se<n.length&&(p=!0),p||J()}}}c=!1}for(await te(t);!y;)if(await new Promise(P=>{let K=setInterval(()=>{(y||p)&&(clearInterval(K),P())},16)}),p&&!y){p=!1;let P=Ve+f*Ve,K=n.slice(P,P+Ve);f++,c=!0,l=Math.min(l,Math.max(0,r.length-1)),J();let Z=new URLSearchParams;Z.set("domains",K.map(G=>`${e}.${G}`).join(","));try{let G=await be(`/api/domains/search?${Z}`,{headers:{Accept:"text/event-stream"}});G.ok&&G.body?await te(G.body):(c=!1,J())}catch{c=!1,J()}}clearInterval(I),process.stdin.removeListener("data",A),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),N();let B=w==="__new__",E=B?null:w,ie=E?r.find(P=>P.domain===E)??null:null;return E?process.stdout.write(`${T.default.dim("\u25C7")} Register a domain?
201
201
  ${T.default.dim("\u2502")} ${T.default.bold(T.default.cyan(E))}
202
202
  ${T.default.dim("\u2514")}
203
203
  `):process.stdout.write(`${T.default.dim("\u2514")}
204
- `),{chosen:E,chosenResult:ie,searchAgain:B,allTaken:r.length===0&&o.length>0,expanded:f>0}}async function Nr(t,e,s){if(!t){je||h("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:s.json});let A=await Te({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(ae(A)||!A)&&process.exit(0),t=A}let i=e.map(A=>A.replace(/^\./,"")),n=s.tlds?.split(",").map(A=>A.trim())||[],r=[...new Set([...i,...n])];if(r.length>0&&Rs(r,s),z(t,s),t.includes(".")&&r.length===0){let A=k(!s.json);A.start(`Checking ${v.domain(t)}`);let[te,B]=await Promise.all([ye(`/api/domains/search?q=${encodeURIComponent(t)}`),ye(`/api/domains/${encodeURIComponent(t)}/og`).catch(()=>null)]),E=await te.json();if(te.ok||(A.stop("Search failed"),h(E.error||E.message,{hint:E.hint,status:te.status,json:s.json,fields:s.fields})),s.json){let ie=E.domain.split(".")[0];x({name:ie,results:[E],total:1,available:E.available?1:0},s.fields);return}if(E.available)if(A.stop(`${b.success} ${v.domain(E.domain)} ${b.dot} available ${b.dot} ${v.price(E.price)}/yr`),je&&!s.json){let{buy:ie}=await Promise.resolve().then(()=>(Vt(),es));await ie([E.domain],{preChecked:{price:E.price,currency:E.currency}})}else u(),I("Register it:",`domani buy ${E.domain}`),u();else if(E.for_sale?.buyable)if(A.stop(`${b.info} ${v.domain(E.domain)} ${b.dot} ${T.default.cyan("for sale")} ${b.dot} ${v.price(E.for_sale.price)}`),je&&!s.json){let{buy:ie}=await Promise.resolve().then(()=>(Vt(),es));await ie([E.domain],{preChecked:{price:E.for_sale.price,currency:E.for_sale.currency,marketplace:!0}})}else u(),I("Buy it:",`domani buy ${E.domain}`),u();else if(E.error)A.stop(`${T.default.dim("?")} ${v.domain(E.domain)} ${b.dot} ${T.default.dim("lookup failed")}`);else{let ie;try{if(B?.ok){let K=await B.json();K?.title&&(ie=K.title)}}catch{}let P=ie?` ${b.dot} ${T.default.dim(`"${ie}"`)}`:"";A.stop(`${b.error} ${v.domain(E.domain)} ${b.dot} ${T.default.red("taken")}${P}`)}return}let o=t.split(".")[0];if(je&&!s.json&&r.length>0){let A=new URLSearchParams;A.set("domains",r.map(ee=>`${o}.${ee}`).join(",")),s.maxPrice&&A.set("max_price",s.maxPrice);let te=await ye(`/api/domains/search?${A}`,{headers:{Accept:"text/event-stream"}});if(!te.ok||!te.body){h("Search failed",{json:s.json});return}let B=[],E=new TextDecoder,ie="",P="",K=k(!0);K.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let ee of te.body){ie+=E.decode(ee,{stream:!0});let et=ie.split(`
205
- `);ie=et.pop()??"";for(let ht of et)ht.startsWith("event: ")?P=ht.slice(7):ht.startsWith("data: ")&&P==="result"&&B.push(JSON.parse(ht.slice(6)))}K.stop("");let X=Math.max(...r.map(ee=>`${o}.${ee}`.length))+2,G=B.filter(ee=>ee.available),Ie=B.filter(ee=>!ee.available&&!ee.error),We=B.filter(ee=>!ee.available&&ee.for_sale);for(let ee of[...G,...We,...Ie.filter(et=>!et.for_sale)])ee.available?console.log(` ${T.default.green("\u2713")} ${T.default.bold(T.default.white(ee.domain.padEnd(X)))} ${T.default.green(v.price(ee.price)+"/yr")}`):ee.for_sale?console.log(` ${T.default.cyan("$")} ${T.default.bold(T.default.white(ee.domain.padEnd(X)))} ${T.default.cyan(v.price(ee.for_sale.price))} ${T.default.dim("(for sale)")}`):console.log(` ${T.default.dim("\u2717")} ${T.default.dim(ee.domain.padEnd(X))} ${T.default.dim("taken")}`);if(G.length===0){console.log(` ${T.default.dim("No domains available")}`),u();return}let{buy:ce}=await Promise.resolve().then(()=>(Vt(),es));if(G.length===1){await ce([G[0].domain],{preChecked:{price:G[0].price,currency:G[0].currency}});return}let{select:oe,isCancel:Se}=await Promise.resolve().then(()=>(De(),Ti)),it=await oe({message:"Register one?",options:[...G.map(ee=>({value:ee.domain,label:v.domain(ee.domain),hint:v.price(ee.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!Se(it)&&it!=="__skip__"){u();let ee=G.find(et=>et.domain===it);await ce([it],{preChecked:ee?{price:ee.price,currency:ee.currency}:void 0})}else u();return}if(je&&!s.json){let A=await Pr();for(s.expand&&A.length>qt&&console.error(T.default.dim(` (--expand: checking the first ${qt} of ${A.length} TLDs - server limit per request)`));;){let te=s.expand?A.slice(0,qt):A.slice(0,Me),B=new URLSearchParams;B.set("domains",te.map(oe=>`${o}.${oe}`).join(",")),s.maxPrice&&B.set("max_price",s.maxPrice);let E=k(!0);E.start(`Searching available domains for ${T.default.bold(o)}`);let ie=await ye(`/api/domains/search?${B}`,{headers:{Accept:"text/event-stream"}});if(!ie.ok||!ie.body){E.stop("Search failed");break}E.stop("");let P=!s.expand,{chosen:K,chosenResult:X,searchAgain:G}=await Al(ie.body,o,s.all??!1,P,A);if(K){u();let{buy:oe}=await Promise.resolve().then(()=>(Vt(),es)),Se=X?{price:X.price,currency:X.currency}:void 0;await oe([K],{preChecked:Se});return}if(!G)break;let{text:Ie,isCancel:We}=await Promise.resolve().then(()=>(De(),Ti)),ce=await Ie({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(We(ce)||!ce)break;o=ce.split(".")[0]}u();return}let a=o,l=await Pr(),c=r.length>0?r:s.expand?l.slice(0,qt):l.slice(0,Me);s.expand&&r.length===0&&l.length>qt&&console.error(`(--expand: checking the first ${qt} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let d=c.map(A=>`${a}.${A}`),f=new URLSearchParams;f.set("domains",d.join(",")),s.maxPrice&&f.set("max_price",s.maxPrice);let p=k(!s.json);p.start(`Searching available domains for ${T.default.bold(a)}`);let $=await ye(`/api/domains/search?${f}`,{headers:{Accept:"text/event-stream"}});if(!$.ok){p.stop("Search failed");try{let A=await $.json();h(A.error||A.message||`Server error (${$.status})`,{hint:A.hint,status:$.status,json:s.json,fields:s.fields})}catch{h(`Server error (${$.status})`,{status:$.status,json:s.json,fields:s.fields})}}let w=$.body;w||(p.stop("Search failed"),h("Empty response",{code:"error",json:s.json,fields:s.fields}));let g=[],_=!1,S=0,R=s.all??!1;function N(){_||(_=!0,p.stop(`Checking TLDs for ${T.default.bold(a)}`),u())}function V(A){N(),A.available?console.log(` ${b.success} ${v.domain(A.domain).padEnd(37)} ${v.price(A.price)}${T.default.dim("/yr")}`):A.for_sale?console.log(` ${b.info} ${v.domain(A.domain).padEnd(37)} ${T.default.cyan(v.price(A.for_sale.price))} ${T.default.dim("(for sale)")}`):A.error||console.log(` ${b.error} ${T.default.dim(A.domain.padEnd(38))} ${T.default.red("taken")}`)}function U(){_||p.message(`Checking TLDs for ${T.default.bold(a)} ${T.default.dim(`(${S} checked)`)}`)}let le=new TextDecoder,Q="",J="";for await(let A of w){Q+=le.decode(A,{stream:!0});let te=Q.split(`
206
- `);Q=te.pop()??"";for(let B of te)if(B.startsWith("event: "))J=B.slice(7);else if(B.startsWith("data: ")){let E=JSON.parse(B.slice(6));if(J==="error")p.stop("Search failed"),h(E.message||E.error||"Search failed",{code:E.code||"error",json:s.json,fields:s.fields});else if(J==="result")S++,E.available||E.for_sale||R?(s.json||V(E),g.push(E)):s.json||U();else if(J==="done"){if(s.json){g.sort((X,G)=>X.price-G.price),x({name:a,results:g,total:E.total,available:E.available},s.fields);return}_&&console.log(` ${T.default.dim("\u2500".repeat(50))}`);let ie=E.total-E.available,P=E.total>=5&&ie/E.total>=.5,K=`Checked ${E.total} TLDs \xB7 ${E.available} available${P?" \xB7 popular name":""}`;console.log(` ${T.default.dim(K)}`),E.available===0&&!s.expand&&r.length===0&&(u(),I("Try more TLDs:",`domani search ${a} --expand`))}}}u()}Vt();Z();var ts=F(W(),1);q();be();async function Fr(t,e){z(t,e);let s={domain:t};if(e.slug&&(s.slug=e.slug),e.name&&(s.name=e.name),e.webhook&&(s.webhook_url=e.webhook),e.years&&(s.years=Number(e.years)),e.paymentMethod&&(s.payment_method=e.paymentMethod),e.dryRun){Y("POST /api/agents/provision",s,e.json,e.fields);return}let i=k(!e.json);i.start(`Provisioning ${v.domain(t)}`);let n=await j("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),r=await n.json();if(n.ok||(i.stop("Provisioning failed"),h(r.error||"Provisioning failed",{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${v.domain(t)} is ready`),e.json){x(r,e.fields);return}if(u(),O("Agent identity"),y("Domain",`${r.domain} (${r.domain_status})`),y("Mailbox",r.mailbox?ts.default.green(r.mailbox.address):ts.default.yellow("pending DNS")),y("Webhook",r.webhook?r.webhook.url:ts.default.dim("none")),r.webhook?.secret&&y("Signing secret",r.webhook.secret),r.warnings?.length){u();for(let o of r.warnings)lt(ts.default.yellow(o))}if(r.next_steps?.length){u(),O("Next");for(let o of r.next_steps)lt(o)}u()}Z();var ut=F(W(),1);q();async function Lr(t){let e=k(!t.json);e.start("Loading domains");let s=await j("/api/domains"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${i.domains.length} domain(s)`),t.json){x({...i,count:i.domains.length},t.fields);return}if(i.domains.length===0){u(),console.log(` ${ut.default.dim("No domains yet.")} Use: ${ut.default.cyan("domani buy <domain>")}`),u();return}let n=[30,12,12,14];O(`Your Domains (${i.domains.length})`,n.reduce((o,a)=>o+a,0)+n.length-1);let r=i.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),l=o.status==="active"?ut.default.green:o.status==="pending"?ut.default.yellow:ut.default.red,c=o.autoRenew?ut.default.green("on"):ut.default.dim("off");return[v.domain(o.domain),l(o.status),c,ut.default.dim(a)]});fe(["Domain","Status","Auto-renew","Expires"],r,n),u()}Bi();Z();var Dt=F(W(),1);q();async function Ur(t){let e=new URLSearchParams;t.maxPrice&&e.set("max_price",t.maxPrice),t.minPrice&&e.set("min_price",t.minPrice),t.sort&&e.set("sort",t.sort),t.search&&e.set("search",t.search),t.limit&&e.set("limit",t.limit),e.set("order","asc");let s=k(!t.json);s.start("Loading TLDs");let i=await ye(`/api/tlds?${e}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${n.total} TLDs loaded`),t.json){x(n,t.fields);return}let r=n.tlds;if(r.length===0){u(),console.log(` ${Dt.default.dim("No TLDs match your filters.")}`),u();return}O("TLD Pricing");let o=r.map(a=>[Dt.default.bold(`.${a.tld}`),v.price(a.registration.toFixed(2))+Dt.default.dim("/yr"),Dt.default.dim("renew ")+v.price(a.renewal.toFixed(2))+Dt.default.dim("/yr")]);fe(["TLD","Register","Renewal"],o,[22,16,20]),u(),console.log(` ${Dt.default.dim(`${n.total} TLDs total`)}`),u()}Z();var Oe=F(W(),1);q();be();async function Mr(t,e){z(t,e);let s=k(!e.json);s.start(`Looking up ${v.domain(t)}`);let[i,n]=await Promise.all([ye(`/api/domains/whois?q=${encodeURIComponent(t)}`),ye(`/api/domains/${encodeURIComponent(t)}/og`).catch(()=>null)]),r=await i.json(),o=null;try{n?.ok&&(o=await n.json())}catch{}if(i.ok||(s.stop("Lookup failed"),h(r.error||r.message,{hint:r.hint,status:i.status,json:e.json,fields:e.fields})),s.stop("WHOIS data retrieved"),e.json){x({...r,...o?{og:o}:{}},e.fields);return}if(O(`WHOIS ${v.domain(r.domain)}`),!r.registered){y("Status",`${b.success} ${Oe.default.green("not registered")}`),u(),I("Register it:",`domani buy ${r.domain}`),u();return}if(y("Status",`${b.error} ${Oe.default.red("registered")}`),(o?.title||o?.description)&&(u(),console.log(` ${Oe.default.bold("Website preview")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),o.title&&y("Title",o.title),o.description&&y("Description",Oe.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),u()),r.registrar&&y("Registrar",r.registrar),r.created&&y("Created",r.created),r.expires&&y("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,c=l<30?Oe.default.red:l<90?Oe.default.yellow:Oe.default.green;y("Days left",c(String(l)))}r.updated&&y("Updated",r.updated),y("DNSSEC",r.dnssec?Oe.default.green("yes"):Oe.default.dim("no")),r.nameservers?.length>0&&y("Nameservers",r.nameservers.map(l=>Oe.default.cyan(l)).join(Oe.default.dim(", "))),r.status?.length>0&&y("Status codes",Oe.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(u(),console.log(` ${Oe.default.bold("Registrant")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),a.name&&y("Name",a.name),a.organization&&y("Organization",a.organization),a.email&&y("Email",v.url(a.email)),a.country&&y("Country",a.country)):r.redacted&&y("Contact",Oe.default.dim("redacted (WHOIS privacy)")),u()}Z();De();var mt=F(W(),1);q();be();async function Vr(t,e){if(!t){je||h("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:e.json});let g=await Te({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(ae(g)||!g)&&process.exit(0),t=g}let s=new URLSearchParams({prompt:t});if(e.count&&s.set("count",e.count),e.tlds&&s.set("tlds",e.tlds),e.tlds&&Rs(e.tlds.split(",").map(g=>g.trim()),e),e.style&&s.set("style",e.style),e.lang&&s.set("lang",e.lang),e.json){let g=k(!1);g.start("Finding available domains");let _=e.timeout?parseInt(e.timeout,10)*1e3:6e4,S;try{S=await ye(`/api/domains/suggest?${s}`,{signal:AbortSignal.timeout(_)})}catch{g.stop("Failed"),h("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:e.json,fields:e.fields})}let R=await S.json();S.ok||(g.stop("Failed"),h(R.error||R.message,{hint:R.hint,status:S.status,json:e.json,fields:e.fields})),x(R,e.fields);return}let i=k(!0);i.start("Finding available domains");let n=e.timeout?parseInt(e.timeout,10)*1e3:6e4,r;try{r=await ye(`/api/domains/suggest?${s}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{i.stop("Failed"),h("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){i.stop("Failed");try{let g=await r.json();h(g.error||g.message||`Server error (${r.status})`,{hint:g.hint,status:r.status})}catch{h(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(i.stop("Failed"),h("Empty response"));let a=[],l=[],c=!1,d=0;function f(){c||(c=!0,i.stop("Finding available domains"),u())}let p=new TextDecoder,$="",w="";for await(let g of o){$+=p.decode(g,{stream:!0});let _=$.split(`
207
- `);$=_.pop()??"";for(let S of _)if(S.startsWith("event: "))w=S.slice(7);else if(S.startsWith("data: "))try{let R=JSON.parse(S.slice(6));if(w==="result")d++,R.available?a.push(R):l.push(R),c||i.message(`Finding available domains ${mt.default.dim(`(${d} checked, ${a.length} available)`)}`);else if(w==="iteration")c||i.message(`Finding available domains ${mt.default.dim(`(round ${R.n})`)}`);else if(w==="done"){f();for(let N of a){let V=N.reason?` ${mt.default.dim(N.reason)}`:"";console.log(` ${b.success} ${v.domain(N.domain).padEnd(37)} ${v.price(N.price)}${mt.default.dim("/yr")}${V}`)}for(let N of l)console.log(` ${b.error} ${mt.default.dim(N.domain.padEnd(38))} ${mt.default.red("taken")}`);console.log(` ${mt.default.dim("\u2500".repeat(50))}`),console.log(` ${mt.default.dim(`Found ${R.total} available \xB7 checked ${R.checked} \xB7 ${R.iterations} round${R.iterations>1?"s":""}`)}`)}else w==="error"&&(c||i.stop("Failed"),h(R.message))}catch{}}a.length===0&&l.length===0&&(c||i.stop("No results"),h("Could not find available domains for this prompt.")),u(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),u())}Vi();Yi();Z();De();var Wt=F(W(),1);q();be();Bt();async function qr(t,e){if(z(t,e),!e.authCode){(e.json||!process.stdout.isTTY)&&h("--auth-code is required",{hint:"Get the EPP/auth code from your current registrar.",code:"validation_error",json:e.json,fields:e.fields});let a=await Te({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});ae(a)&&process.exit(0),e.authCode=a}let s=k(!e.json);s.start(`Checking transfer eligibility for ${v.domain(t)}`);let i=await j(`/api/domains/transfer-check?domain=${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Check failed"),h(n.error,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),n.eligible||(s.stop(`${b.error} Not eligible`),h(n.reason||"Domain is not eligible for transfer.",{hint:n.hint,code:"not_eligible",json:e.json,fields:e.fields})),s.stop(`${b.success} Eligible for transfer`),e.dryRun)return Y("transfer",{domain:t,eligible:!0,price:n.price,currency:n.currency||"USD",includes_renewal:!0},e.json,e.fields);if(!At(e)){let a=n.price!=null?` for ${v.price(n.price.toFixed(2))}`:"",l=await Be({message:`Transfer ${Wt.default.bold(t)} to ${Ft}${a}? (includes 1 year renewal)`});if(!l||typeof l=="symbol"){console.log(` ${Wt.default.dim("Cancelled.")}`);return}}s.start(`Initiating transfer for ${v.domain(t)}`);let r=await j("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:t,auth_code:e.authCode})}),o=await r.json();if(r.ok||(s.stop("Transfer failed"),h(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Transfer initiated`),e.json){x(o,e.fields);return}O("Transfer Initiated"),y("Domain",v.domain(o.domain)),y("Status",Wt.default.yellow(o.status||"pending")),o.price&&y("Price",v.price(o.price)+Wt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&y("Payment",o.payment_method),o.expires&&y("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(u(),console.log(` ${Wt.default.dim(o.hint)}`)),u(),I("Check transfer progress:",`domani status ${o.domain}`),u()}Z();De();var Es=F(W(),1);q();be();Ge();async function Wr(t,e){t||(t=await ue()),z(t,e);let s=e.years?parseInt(e.years,10):1;if((isNaN(s)||s<1||s>10)&&h("--years must be between 1 and 10",{code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return Y("renew",{domain:t,years:s},e.json,e.fields);if(!At(e)){let o=await Be({message:`Renew ${Es.default.bold(t)} for ${s} year${s>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Es.default.dim("Cancelled.")}`);return}}let i=k(!e.json);i.start(`Renewing ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/renew`,{method:"POST",body:JSON.stringify({years:s})}),r=await n.json();if(n.ok||(i.stop("Renewal failed"),h(r.error||r.message,{hint:r.hint,fixUrl:r.setup_url||r.payment_options?.card?.setup_url,status:n.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Domain renewed`),e.json){x(r,e.fields);return}O("Renewal Complete"),y("Domain",v.domain(r.domain)),y("Years",String(r.renewed_years)),y("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&y("Price",v.price(r.price)+Es.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&y("Payment",r.payment_method),u(),I("Verify renewal:",`domani status ${r.domain}`),u()}Z();var tt=F(W(),1);q();be();async function Hr(t,e){t||h("Domain is required",{hint:`Usage: domani import <domain>
208
- domani import <domain> --verify`,code:"validation_error",json:e.json,fields:e.fields}),z(t,e);let s=e.verify?"/api/domains/import/verify":"/api/domains/import",i=k(!e.json);i.start(e.verify?`Verifying ownership of ${v.domain(t)}`:`Initiating import for ${v.domain(t)}`);let n=await j(s,{method:"POST",body:JSON.stringify({domain:t})}),r=await n.json();if(n.ok||(i.stop(e.verify?"Verification failed":"Import failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),e.json){i.stop(""),x(r,e.fields);return}e.verify?(i.stop(`${b.success} ${v.domain(t)} imported!`),O("Domain Imported"),y("Domain",v.domain(r.domain)),y("Status",tt.default.green(r.status||"active")),r.expires_at&&y("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&y("Registrar",r.registrar),u(),I("Check domain health:",`domani status ${r.domain}`),u()):(i.stop(`${b.success} Verification record ready`),O("Import Domain"),y("Domain",v.domain(r.domain)),y("Status",tt.default.yellow("pending verification")),u(),console.log(" Add this TXT record at your DNS provider:"),u(),console.log(` ${tt.default.dim("Type:")} ${tt.default.bold("TXT")}`),console.log(` ${tt.default.dim("Name:")} ${tt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${tt.default.dim("Value:")} ${tt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),u(),console.log(` ${tt.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),u(),I("Once the record is set, verify:",`domani import ${t} --verify`),u())}Wi();$t();q();function Jr(t){let e=gt();e||(u(),h("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:t.json})),t.json?x({token:e}):console.log(e)}Z();var Ve=F(W(),1);q();async function Br(t,e){switch(t){case void 0:case"list":return Tl(e.json,e.fields);case"create":return El(e);case"revoke":return Dl(e);default:h(`Unknown action: ${t}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:e.json,fields:e.fields})}}async function Tl(t,e){let s=k(!t);s.start("Loading tokens");let i=await j("/api/tokens"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${b.success} ${n.tokens.length} token(s)`),t){x(n,e);return}if(n.tokens.length===0){u(),console.log(` ${Ve.default.dim("No tokens.")}`),u(),I("Create one:",'domani tokens create --name "My App"'),u();return}u(),O("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=Ve.default.red("Expired"):o.expiresAt?a=Ve.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Ve.default.dim("No expiration");let l=o.scopes.includes("*")?Ve.default.dim("all"):Ve.default.dim(o.scopes.join(", "));return[Ve.default.dim(o.id),Ve.default.bold(o.name),l,a]});fe(["ID","Name","Scopes","Expiration"],r,[28,16,32,20]),u()}async function El(t){let e={};if(t.name&&(e.name=t.name),t.scopes&&(e.scopes=t.scopes.split(",").map(r=>r.trim())),t.expiresIn){let r=Number(t.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&h("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:t.json,fields:t.fields}),e.expires_in=r}let s=k(!t.json);s.start("Creating token");let i=await j("/api/tokens",{method:"POST",body:JSON.stringify(e)}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Token created`),t.json){x(n,t.fields);return}u(),O("Token Created"),y("ID",n.id),y("Name",n.name),y("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),y("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),u(),console.log(` ${Ve.default.yellow("!")} ${Ve.default.bold("Key:")} ${n.key}`),console.log(` ${Ve.default.dim("Save this key - it will not be shown again.")}`),u()}async function Dl(t){t.tokenId||h("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
209
- Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:t.json,fields:t.fields});let e=k(!t.json);e.start("Revoking token");let s=await j(`/api/tokens/${encodeURIComponent(t.tokenId)}`,{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${b.success} Token revoked`),t.json){x(i,t.fields);return}console.log(` ${Ve.default.dim("Any applications using this key will need a new one.")}`),u()}Z();var Re=F(W(),1);q();be();Ge();async function Gr(t,e){t||(t=await ue()),z(t,e);let s=e.autoRenew!==void 0,i=e.whoisPrivacy!==void 0,n=e.securityLock!==void 0;if(!s&&!i&&!n)return Pl(t,e.json,e.fields);let r={};if(s){let c=Xi(e.autoRenew);c===null&&h("--auto-renew must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.auto_renew=c}if(i){let c=Xi(e.whoisPrivacy);c===null&&h("--whois-privacy must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.whois_privacy=c}if(n){let c=Xi(e.securityLock);c===null&&h("--security-lock must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.security_lock=c}if(e.dryRun)return Y("settings_update",{domain:t,...r},e.json,e.fields);let o=k(!e.json);o.start(`Updating ${v.domain(t)}`);let a=await j(`/api/domains/${encodeURIComponent(t)}/settings`,{method:"PUT",body:JSON.stringify(r)}),l=await a.json();if(a.ok||(o.stop("Failed"),h(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${b.success} Settings updated`),e.json){x(l,e.fields);return}O("Settings Updated"),y("Domain",v.domain(l.domain)),l.auto_renew!==void 0&&y("Auto-renew",l.auto_renew?Re.default.green("on"):Re.default.dim("off")),l.whois_privacy!==void 0&&y("WHOIS privacy",l.whois_privacy?Re.default.green("on"):Re.default.dim("off")),l.security_lock!==void 0&&y("Security lock",l.security_lock?Re.default.green("locked"):Re.default.dim("unlocked")),l.hint&&y("",Re.default.dim(l.hint)),u()}async function Pl(t,e,s){let i=k(!e);i.start(`Loading ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop(`${b.success} ${v.domain(t)}`),e){x(r,s);return}O("Domain Settings"),y("Domain",v.domain(r.domain)),y("Status",r.status==="active"?Re.default.green(r.status):Re.default.yellow(r.status)),y("Auto-renew",r.auto_renew?Re.default.green("on"):Re.default.dim("off")),r.registrar&&(y("WHOIS privacy",r.registrar.whois_privacy?Re.default.green("on"):Re.default.dim("off")),y("Security lock",r.registrar.security_lock?Re.default.green("locked"):Re.default.dim("unlocked"))),y("Expires",new Date(r.expires_at).toLocaleDateString()+Re.default.dim(` (${r.days_until_expiry} days)`)),u(),I("Toggle auto-renew:",`domani settings ${t} --auto-renew off`),I("Toggle WHOIS privacy:",`domani settings ${t} --whois-privacy off`),I("Toggle security lock:",`domani settings ${t} --security-lock off`),I("Get transfer auth code:",`domani auth-code ${t}`),u()}function Xi(t){let e=t.toLowerCase();return e==="on"||e==="true"||e==="1"||e==="enable"?!0:e==="off"||e==="false"||e==="0"||e==="disable"?!1:null}Z();var Pt=F(W(),1);q();be();Ge();async function Yr(t,e){t||(t=await ue()),z(t,e);let s=k(!e.json);s.start(`Getting auth code for ${v.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/auth-code`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Auth code retrieved`),e.json){x(n,e.fields);return}if(O("Auth Code"),y("Domain",v.domain(n.domain)),y("Auth code",Pt.default.bold(Pt.default.green(n.auth_code))),n.was_unlocked&&y("",Pt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(u(),console.log(` ${Pt.default.dim(n.hint)}`)),n.next_steps?.length){u();for(let r of n.next_steps)console.log(` ${Pt.default.dim("\u2192")} ${Pt.default.dim(r)}`)}u(),I("Check transfer status:",`domani transfer-away ${t}`),I("Re-lock domain:",`domani settings ${t} --security-lock on`),u()}Z();var ft=F(W(),1);q();be();Ge();var Nl={none:ft.default.dim,pending:ft.default.yellow,approved:ft.default.yellow,completed:ft.default.green,rejected:ft.default.red,expired:ft.default.red};async function Kr(t,e){t||(t=await ue()),z(t,e);let s=k(!e.json);s.start(`Checking transfer status for ${v.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/transfer-away`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${b.success} ${v.domain(t)}`),e.json){x(n,e.fields);return}O("Transfer Away Status"),y("Domain",v.domain(n.domain));let r=Nl[n.status]||ft.default.dim;y("Status",r(n.status)),n.gaining_registrar&&y("New registrar",n.gaining_registrar),n.request_date&&y("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(u(),console.log(` ${ft.default.dim(n.hint)}`)),u(),n.status==="none"?I("Get auth code to start:",`domani auth-code ${t}`):n.status==="pending"||n.status==="approved"?I("Check again later:",`domani transfer-away ${t}`):n.status==="completed"?I("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${t}`),u()}Z();De();var Ds=F(W(),1);q();async function zr(t,e){return t==="set"?Ll(e):Fl(e)}async function Fl(t){let e=k(!t.json);e.start("Loading contact info");let s=await j("/api/me/contact"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${b.success} Contact info`),t.json){x(i,t.fields);return}if(O("Contact Info"),!i.has_contact){console.log(` ${b.warning} ${Ds.default.yellow("No contact info set.")} Run ${Ds.default.bold("domani contact set")} to add.`),u(),console.log(` ${Ds.default.dim("Contact info is required before purchasing domains.")}`),u();return}let n=i.contact;y("Name",`${n.first_name} ${n.last_name}`),n.org_name&&y("Organization",n.org_name),y("Address",n.address1),n.address2&&y("",n.address2),y("",`${n.city}, ${n.state} ${n.postal_code}`),y("Country",n.country),y("Phone",n.phone),y("Email",n.email),u()}async function Ll(t){let e={},s=t.firstName||t.lastName||t.address1;if(!je&&!s&&h("Missing required flags for contact set",{hint:"Usage: domani contact set --first-name John --last-name Doe --address1 '123 Main St' --city SF --state CA --postal-code 94105 --country US --phone +1.5551234567 --email john@example.com",code:"missing_argument",json:t.json}),s){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},c=a.filter(d=>!t[d]);c.length>0&&h(`Missing required flags: ${c.map(d=>`--${d.replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:t.json});for(let[d,f]of Object.entries(l)){let p=t[d];p&&(e[f]=p)}}else{let a=await j("/api/me/contact"),c=(a.ok?await a.json():null)?.contact,d=[{key:"first_name",message:"First name",placeholder:"John",required:!0},{key:"last_name",message:"Last name",placeholder:"Doe",required:!0},{key:"org_name",message:"Organization (optional, press Enter to skip)",placeholder:"Acme Inc.",required:!1},{key:"address1",message:"Address line 1",placeholder:"123 Main St",required:!0},{key:"address2",message:"Address line 2 (optional)",placeholder:"Suite 100",required:!1},{key:"city",message:"City",placeholder:"San Francisco",required:!0},{key:"state",message:"State / Province",placeholder:"CA",required:!0},{key:"postal_code",message:"Postal / ZIP code",placeholder:"94105",required:!0},{key:"country",message:"Country code (ISO 3166-1 alpha-2)",placeholder:"US",required:!0},{key:"phone",message:"Phone (+CC.NUMBER)",placeholder:"+1.5551234567",required:!0},{key:"email",message:"Contact email",placeholder:"john@example.com",required:!0}];for(let f of d){let p=c?.[f.key]||"",$=await Te({message:f.message,placeholder:f.placeholder,defaultValue:p,validate:f.required?g=>g?.trim()?void 0:`${f.message} is required`:void 0});ae($)&&process.exit(0);let w=$.trim();w&&(e[f.key]=w)}}if(t.dryRun)return Y("contact_set",e,t.json,t.fields);let i=k(!t.json);i.start("Saving contact info");let n=await j("/api/me/contact",{method:"PUT",body:JSON.stringify(e)}),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${b.success} Contact info saved`),t.json){x(r,t.fields);return}O("Contact Saved");let o=r.contact;y("Name",`${o.first_name} ${o.last_name}`),o.org_name&&y("Organization",o.org_name),y("Address",o.address1),o.address2&&y("",o.address2),y("",`${o.city}, ${o.state} ${o.postal_code}`),y("Country",o.country),y("Phone",o.phone),y("Email",o.email),u(),I("Search for a domain:","domani search <name>"),u()}Z();var Ee=F(W(),1);q();be();Ge();async function Qr(t,e,s,i){if(t||(t=await ue()),z(t,i),!e)return Ul(t,i.json,i.fields);switch(e){case"enable":case"on":return i.dryRun?Y("parking_enable",{domain:t},i.json,i.fields):Xr(t,!0,i.json,i.fields);case"disable":case"off":return i.dryRun?Y("parking_disable",{domain:t},i.json,i.fields):Xr(t,!1,i.json,i.fields);case"price":{s||h("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:i.json,fields:i.fields});let n=parseFloat(s);return(isNaN(n)||n<=0)&&h("Price must be a positive number",{hint:`Got: "${s}"`,code:"validation_error",json:i.json,fields:i.fields}),i.dryRun?Y("parking_price",{domain:t,price:n},i.json,i.fields):Zr(t,n,i.json,i.fields)}case"unprice":case"unlist":return i.dryRun?Y("parking_unlist",{domain:t},i.json,i.fields):Zr(t,null,i.json,i.fields);default:h(`Unknown action: ${e}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:i.json,fields:i.fields})}}async function Ul(t,e,s){let i=k(!e);i.start(`Loading ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop(`${b.success} ${v.domain(t)}`),e){x({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},s);return}O("Parking"),y("Domain",v.domain(r.domain)),y("Parking",r.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),y("Listing",r.listing_price?`${v.price(r.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),u(),I("Enable parking:",`domani parking ${t} enable`),I("Set sale price:",`domani parking ${t} price 499`),I("View analytics:",`domani analytics ${t}`),u()}async function Xr(t,e,s,i){let n=k(!s);n.start(`${e?"Enabling":"Disabling"} parking for ${v.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/parking`,{method:"PUT",body:JSON.stringify({enabled:e})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(n.stop(`${b.warning} DNS records will be replaced`),s){x(o,i);return}console.log(`
204
+ `),{chosen:E,chosenResult:ie,searchAgain:B,allTaken:r.length===0&&o.length>0,expanded:f>0}}async function Mr(t,e,s){if(!t){je||h("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:s.json});let A=await Te({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(ae(A)||!A)&&process.exit(0),t=A}let i=e.map(A=>A.replace(/^\./,"")),n=s.tlds?.split(",").map(A=>A.trim())||[],r=[...new Set([...i,...n])];if(r.length>0&&Is(r,s),z(t,s),t.includes(".")&&r.length===0){let A=k(!s.json);A.start(`Checking ${b.domain(t)}`);let[te,B]=await Promise.all([be(`/api/domains/search?q=${encodeURIComponent(t)}`),be(`/api/domains/${encodeURIComponent(t)}/og`).catch(()=>null)]),E=await te.json();if(te.ok||(A.stop("Search failed"),h(E.error||E.message,{hint:E.hint,status:te.status,json:s.json,fields:s.fields})),s.json){let ie=E.domain.split(".")[0];x({name:ie,results:[E],total:1,available:E.available?1:0},s.fields);return}if(E.available)if(A.stop(`${v.success} ${b.domain(E.domain)} ${v.dot} available ${v.dot} ${b.price(E.price)}/yr`),je&&!s.json){let{buy:ie}=await Promise.resolve().then(()=>(qt(),ts));await ie([E.domain],{preChecked:{price:E.price,currency:E.currency}})}else d(),O("Register it:",`domani buy ${E.domain}`),d();else if(E.for_sale?.buyable)if(A.stop(`${v.info} ${b.domain(E.domain)} ${v.dot} ${T.default.cyan("for sale")} ${v.dot} ${b.price(E.for_sale.price)}`),je&&!s.json){let{buy:ie}=await Promise.resolve().then(()=>(qt(),ts));await ie([E.domain],{preChecked:{price:E.for_sale.price,currency:E.for_sale.currency,marketplace:!0}})}else d(),O("Buy it:",`domani buy ${E.domain}`),d();else if(E.error)A.stop(`${T.default.dim("?")} ${b.domain(E.domain)} ${v.dot} ${T.default.dim("lookup failed")}`);else{let ie;try{if(B?.ok){let K=await B.json();K?.title&&(ie=K.title)}}catch{}let P=ie?` ${v.dot} ${T.default.dim(`"${ie}"`)}`:"";A.stop(`${v.error} ${b.domain(E.domain)} ${v.dot} ${T.default.red("taken")}${P}`)}return}let o=t.split(".")[0];if(je&&!s.json&&r.length>0){let A=new URLSearchParams;A.set("domains",r.map(ee=>`${o}.${ee}`).join(",")),s.maxPrice&&A.set("max_price",s.maxPrice);let te=await be(`/api/domains/search?${A}`,{headers:{Accept:"text/event-stream"}});if(!te.ok||!te.body){h("Search failed",{json:s.json});return}let B=[],E=new TextDecoder,ie="",P="",K=k(!0);K.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let ee of te.body){ie+=E.decode(ee,{stream:!0});let tt=ie.split(`
205
+ `);ie=tt.pop()??"";for(let pt of tt)pt.startsWith("event: ")?P=pt.slice(7):pt.startsWith("data: ")&&P==="result"&&B.push(JSON.parse(pt.slice(6)))}K.stop("");let Z=Math.max(...r.map(ee=>`${o}.${ee}`.length))+2,G=B.filter(ee=>ee.available),Ie=B.filter(ee=>!ee.available&&!ee.error),He=B.filter(ee=>!ee.available&&ee.for_sale);for(let ee of[...G,...He,...Ie.filter(tt=>!tt.for_sale)])ee.available?console.log(` ${T.default.green("\u2713")} ${T.default.bold(T.default.white(ee.domain.padEnd(Z)))} ${T.default.green(b.price(ee.price)+"/yr")}`):ee.for_sale?console.log(` ${T.default.cyan("$")} ${T.default.bold(T.default.white(ee.domain.padEnd(Z)))} ${T.default.cyan(b.price(ee.for_sale.price))} ${T.default.dim("(for sale)")}`):console.log(` ${T.default.dim("\u2717")} ${T.default.dim(ee.domain.padEnd(Z))} ${T.default.dim("taken")}`);if(G.length===0){console.log(` ${T.default.dim("No domains available")}`),d();return}let{buy:ce}=await Promise.resolve().then(()=>(qt(),ts));if(G.length===1){await ce([G[0].domain],{preChecked:{price:G[0].price,currency:G[0].currency}});return}let{select:oe,isCancel:Se}=await Promise.resolve().then(()=>(De(),Pi)),nt=await oe({message:"Register one?",options:[...G.map(ee=>({value:ee.domain,label:b.domain(ee.domain),hint:b.price(ee.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!Se(nt)&&nt!=="__skip__"){d();let ee=G.find(tt=>tt.domain===nt);await ce([nt],{preChecked:ee?{price:ee.price,currency:ee.currency}:void 0})}else d();return}if(je&&!s.json){let A=await Ur();for(s.expand&&A.length>Wt&&console.error(T.default.dim(` (--expand: checking the first ${Wt} of ${A.length} TLDs - server limit per request)`));;){let te=s.expand?A.slice(0,Wt):A.slice(0,Ve),B=new URLSearchParams;B.set("domains",te.map(oe=>`${o}.${oe}`).join(",")),s.maxPrice&&B.set("max_price",s.maxPrice);let E=k(!0);E.start(`Searching available domains for ${T.default.bold(o)}`);let ie=await be(`/api/domains/search?${B}`,{headers:{Accept:"text/event-stream"}});if(!ie.ok||!ie.body){E.stop("Search failed");break}E.stop("");let P=!s.expand,{chosen:K,chosenResult:Z,searchAgain:G}=await Ll(ie.body,o,s.all??!1,P,A);if(K){d();let{buy:oe}=await Promise.resolve().then(()=>(qt(),ts)),Se=Z?{price:Z.price,currency:Z.currency}:void 0;await oe([K],{preChecked:Se});return}if(!G)break;let{text:Ie,isCancel:He}=await Promise.resolve().then(()=>(De(),Pi)),ce=await Ie({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(He(ce)||!ce)break;o=ce.split(".")[0]}d();return}let a=o,l=await Ur(),c=r.length>0?r:s.expand?l.slice(0,Wt):l.slice(0,Ve);s.expand&&r.length===0&&l.length>Wt&&console.error(`(--expand: checking the first ${Wt} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let u=c.map(A=>`${a}.${A}`),f=new URLSearchParams;f.set("domains",u.join(",")),s.maxPrice&&f.set("max_price",s.maxPrice);let p=k(!s.json);p.start(`Searching available domains for ${T.default.bold(a)}`);let y=await be(`/api/domains/search?${f}`,{headers:{Accept:"text/event-stream"}});if(!y.ok){p.stop("Search failed");try{let A=await y.json();h(A.error||A.message||`Server error (${y.status})`,{hint:A.hint,status:y.status,json:s.json,fields:s.fields})}catch{h(`Server error (${y.status})`,{status:y.status,json:s.json,fields:s.fields})}}let w=y.body;w||(p.stop("Search failed"),h("Empty response",{code:"error",json:s.json,fields:s.fields}));let $=[],_=!1,S=0,I=s.all??!1;function N(){_||(_=!0,p.stop(`Checking TLDs for ${T.default.bold(a)}`),d())}function q(A){N(),A.available?console.log(` ${v.success} ${b.domain(A.domain).padEnd(37)} ${b.price(A.price)}${T.default.dim("/yr")}`):A.for_sale?console.log(` ${v.info} ${b.domain(A.domain).padEnd(37)} ${T.default.cyan(b.price(A.for_sale.price))} ${T.default.dim("(for sale)")}`):A.error||console.log(` ${v.error} ${T.default.dim(A.domain.padEnd(38))} ${T.default.red("taken")}`)}function U(){_||p.message(`Checking TLDs for ${T.default.bold(a)} ${T.default.dim(`(${S} checked)`)}`)}let le=new TextDecoder,Q="",J="";for await(let A of w){Q+=le.decode(A,{stream:!0});let te=Q.split(`
206
+ `);Q=te.pop()??"";for(let B of te)if(B.startsWith("event: "))J=B.slice(7);else if(B.startsWith("data: ")){let E=JSON.parse(B.slice(6));if(J==="error")p.stop("Search failed"),h(E.message||E.error||"Search failed",{code:E.code||"error",json:s.json,fields:s.fields});else if(J==="result")S++,E.available||E.for_sale||I?(s.json||q(E),$.push(E)):s.json||U();else if(J==="done"){if(s.json){$.sort((Z,G)=>Z.price-G.price),x({name:a,results:$,total:E.total,available:E.available},s.fields);return}_&&console.log(` ${T.default.dim("\u2500".repeat(50))}`);let ie=E.total-E.available,P=E.total>=5&&ie/E.total>=.5,K=`Checked ${E.total} TLDs \xB7 ${E.available} available${P?" \xB7 popular name":""}`;console.log(` ${T.default.dim(K)}`),E.available===0&&!s.expand&&r.length===0&&(d(),O("Try more TLDs:",`domani search ${a} --expand`))}}}d()}qt();X();var ss=F(W(),1);V();ge();async function Vr(t,e){z(t,e);let s={domain:t};if(e.slug&&(s.slug=e.slug),e.name&&(s.name=e.name),e.webhook&&(s.webhook_url=e.webhook),e.years&&(s.years=Number(e.years)),e.paymentMethod&&(s.payment_method=e.paymentMethod),e.dryRun){Y("POST /api/agents/provision",s,e.json,e.fields);return}let i=k(!e.json);i.start(`Provisioning ${b.domain(t)}`);let n=await j("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),r=await n.json();if(n.ok||(i.stop("Provisioning failed"),h(r.error||"Provisioning failed",{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${b.domain(t)} is ready`),e.json){x(r,e.fields);return}if(d(),C("Agent identity"),g("Domain",`${r.domain} (${r.domain_status})`),g("Mailbox",r.mailbox?ss.default.green(r.mailbox.address):ss.default.yellow("pending DNS")),g("Webhook",r.webhook?r.webhook.url:ss.default.dim("none")),r.webhook?.secret&&g("Signing secret",r.webhook.secret),r.warnings?.length){d();for(let o of r.warnings)ct(ss.default.yellow(o))}if(r.next_steps?.length){d(),C("Next");for(let o of r.next_steps)ct(o)}d()}X();var mt=F(W(),1);V();async function qr(t){let e=k(!t.json);e.start("Loading domains");let s=await j("/api/domains"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${i.domains.length} domain(s)`),t.json){x({...i,count:i.domains.length},t.fields);return}if(i.domains.length===0){d(),console.log(` ${mt.default.dim("No domains yet.")} Use: ${mt.default.cyan("domani buy <domain>")}`),d();return}let n=[30,12,12,14];C(`Your Domains (${i.domains.length})`,n.reduce((o,a)=>o+a,0)+n.length-1);let r=i.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),l=o.status==="active"?mt.default.green:o.status==="pending"?mt.default.yellow:mt.default.red,c=o.autoRenew?mt.default.green("on"):mt.default.dim("off");return[b.domain(o.domain),l(o.status),c,mt.default.dim(a)]});de(["Domain","Status","Auto-renew","Expires"],r,n),d()}Ki();X();var Pt=F(W(),1);V();async function Wr(t){let e=new URLSearchParams;t.maxPrice&&e.set("max_price",t.maxPrice),t.minPrice&&e.set("min_price",t.minPrice),t.sort&&e.set("sort",t.sort),t.search&&e.set("search",t.search),t.limit&&e.set("limit",t.limit),e.set("order","asc");let s=k(!t.json);s.start("Loading TLDs");let i=await be(`/api/tlds?${e}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${n.total} TLDs loaded`),t.json){x(n,t.fields);return}let r=n.tlds;if(r.length===0){d(),console.log(` ${Pt.default.dim("No TLDs match your filters.")}`),d();return}C("TLD Pricing");let o=r.map(a=>[Pt.default.bold(`.${a.tld}`),b.price(a.registration.toFixed(2))+Pt.default.dim("/yr"),Pt.default.dim("renew ")+b.price(a.renewal.toFixed(2))+Pt.default.dim("/yr")]);de(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Pt.default.dim(`${n.total} TLDs total`)}`),d()}X();var Oe=F(W(),1);V();ge();async function Hr(t,e){z(t,e);let s=k(!e.json);s.start(`Looking up ${b.domain(t)}`);let[i,n]=await Promise.all([be(`/api/domains/whois?q=${encodeURIComponent(t)}`),be(`/api/domains/${encodeURIComponent(t)}/og`).catch(()=>null)]),r=await i.json(),o=null;try{n?.ok&&(o=await n.json())}catch{}if(i.ok||(s.stop("Lookup failed"),h(r.error||r.message,{hint:r.hint,status:i.status,json:e.json,fields:e.fields})),s.stop("WHOIS data retrieved"),e.json){x({...r,...o?{og:o}:{}},e.fields);return}if(C(`WHOIS ${b.domain(r.domain)}`),!r.registered){g("Status",`${v.success} ${Oe.default.green("not registered")}`),d(),O("Register it:",`domani buy ${r.domain}`),d();return}if(g("Status",`${v.error} ${Oe.default.red("registered")}`),(o?.title||o?.description)&&(d(),console.log(` ${Oe.default.bold("Website preview")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),o.title&&g("Title",o.title),o.description&&g("Description",Oe.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),d()),r.registrar&&g("Registrar",r.registrar),r.created&&g("Created",r.created),r.expires&&g("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,c=l<30?Oe.default.red:l<90?Oe.default.yellow:Oe.default.green;g("Days left",c(String(l)))}r.updated&&g("Updated",r.updated),g("DNSSEC",r.dnssec?Oe.default.green("yes"):Oe.default.dim("no")),r.nameservers?.length>0&&g("Nameservers",r.nameservers.map(l=>Oe.default.cyan(l)).join(Oe.default.dim(", "))),r.status?.length>0&&g("Status codes",Oe.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(d(),console.log(` ${Oe.default.bold("Registrant")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),a.name&&g("Name",a.name),a.organization&&g("Organization",a.organization),a.email&&g("Email",b.url(a.email)),a.country&&g("Country",a.country)):r.redacted&&g("Contact",Oe.default.dim("redacted (WHOIS privacy)")),d()}X();De();var ft=F(W(),1);V();ge();async function Jr(t,e){if(!t){je||h("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:e.json});let $=await Te({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(ae($)||!$)&&process.exit(0),t=$}let s=new URLSearchParams({prompt:t});if(e.count&&s.set("count",e.count),e.tlds&&s.set("tlds",e.tlds),e.tlds&&Is(e.tlds.split(",").map($=>$.trim()),e),e.style&&s.set("style",e.style),e.lang&&s.set("lang",e.lang),e.json){let $=k(!1);$.start("Finding available domains");let _=e.timeout?parseInt(e.timeout,10)*1e3:6e4,S;try{S=await be(`/api/domains/suggest?${s}`,{signal:AbortSignal.timeout(_)})}catch{$.stop("Failed"),h("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:e.json,fields:e.fields})}let I=await S.json();S.ok||($.stop("Failed"),h(I.error||I.message,{hint:I.hint,status:S.status,json:e.json,fields:e.fields})),x(I,e.fields);return}let i=k(!0);i.start("Finding available domains");let n=e.timeout?parseInt(e.timeout,10)*1e3:6e4,r;try{r=await be(`/api/domains/suggest?${s}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{i.stop("Failed"),h("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){i.stop("Failed");try{let $=await r.json();h($.error||$.message||`Server error (${r.status})`,{hint:$.hint,status:r.status})}catch{h(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(i.stop("Failed"),h("Empty response"));let a=[],l=[],c=!1,u=0;function f(){c||(c=!0,i.stop("Finding available domains"),d())}let p=new TextDecoder,y="",w="";for await(let $ of o){y+=p.decode($,{stream:!0});let _=y.split(`
207
+ `);y=_.pop()??"";for(let S of _)if(S.startsWith("event: "))w=S.slice(7);else if(S.startsWith("data: "))try{let I=JSON.parse(S.slice(6));if(w==="result")u++,I.available?a.push(I):l.push(I),c||i.message(`Finding available domains ${ft.default.dim(`(${u} checked, ${a.length} available)`)}`);else if(w==="iteration")c||i.message(`Finding available domains ${ft.default.dim(`(round ${I.n})`)}`);else if(w==="done"){f();for(let N of a){let q=N.reason?` ${ft.default.dim(N.reason)}`:"";console.log(` ${v.success} ${b.domain(N.domain).padEnd(37)} ${b.price(N.price)}${ft.default.dim("/yr")}${q}`)}for(let N of l)console.log(` ${v.error} ${ft.default.dim(N.domain.padEnd(38))} ${ft.default.red("taken")}`);console.log(` ${ft.default.dim("\u2500".repeat(50))}`),console.log(` ${ft.default.dim(`Found ${I.total} available \xB7 checked ${I.checked} \xB7 ${I.iterations} round${I.iterations>1?"s":""}`)}`)}else w==="error"&&(c||i.stop("Failed"),h(I.message))}catch{}}a.length===0&&l.length===0&&(c||i.stop("No results"),h("Could not find available domains for this prompt.")),d(),a.length>0&&(O("Register one:",`domani buy ${a[0].domain}`),d())}Hi();Xi();X();De();var Ht=F(W(),1);V();ge();Gt();async function Br(t,e){if(z(t,e),!e.authCode){(e.json||!process.stdout.isTTY)&&h("--auth-code is required",{hint:"Get the EPP/auth code from your current registrar.",code:"validation_error",json:e.json,fields:e.fields});let a=await Te({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});ae(a)&&process.exit(0),e.authCode=a}let s=k(!e.json);s.start(`Checking transfer eligibility for ${b.domain(t)}`);let i=await j(`/api/domains/transfer-check?domain=${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Check failed"),h(n.error,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),n.eligible||(s.stop(`${v.error} Not eligible`),h(n.reason||"Domain is not eligible for transfer.",{hint:n.hint,code:"not_eligible",json:e.json,fields:e.fields})),s.stop(`${v.success} Eligible for transfer`),e.dryRun)return Y("transfer",{domain:t,eligible:!0,price:n.price,currency:n.currency||"USD",includes_renewal:!0},e.json,e.fields);if(!Tt(e)){let a=n.price!=null?` for ${b.price(n.price.toFixed(2))}`:"",l=await Ge({message:`Transfer ${Ht.default.bold(t)} to ${Lt}${a}? (includes 1 year renewal)`});if(!l||typeof l=="symbol"){console.log(` ${Ht.default.dim("Cancelled.")}`);return}}s.start(`Initiating transfer for ${b.domain(t)}`);let r=await j("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:t,auth_code:e.authCode})}),o=await r.json();if(r.ok||(s.stop("Transfer failed"),h(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:e.json,fields:e.fields})),s.stop(`${v.success} Transfer initiated`),e.json){x(o,e.fields);return}C("Transfer Initiated"),g("Domain",b.domain(o.domain)),g("Status",Ht.default.yellow(o.status||"pending")),o.price&&g("Price",b.price(o.price)+Ht.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&g("Payment",o.payment_method),o.expires&&g("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(d(),console.log(` ${Ht.default.dim(o.hint)}`)),d(),O("Check transfer progress:",`domani status ${o.domain}`),d()}X();De();var Ns=F(W(),1);V();ge();Ye();async function Gr(t,e){t||(t=await me()),z(t,e);let s=e.years?parseInt(e.years,10):1;if((isNaN(s)||s<1||s>10)&&h("--years must be between 1 and 10",{code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return Y("renew",{domain:t,years:s},e.json,e.fields);if(!Tt(e)){let o=await Ge({message:`Renew ${Ns.default.bold(t)} for ${s} year${s>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Ns.default.dim("Cancelled.")}`);return}}let i=k(!e.json);i.start(`Renewing ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/renew`,{method:"POST",body:JSON.stringify({years:s})}),r=await n.json();if(n.ok||(i.stop("Renewal failed"),h(r.error||r.message,{hint:r.hint,fixUrl:r.setup_url||r.payment_options?.card?.setup_url,status:n.status,json:e.json,fields:e.fields})),i.stop(`${v.success} Domain renewed`),e.json){x(r,e.fields);return}C("Renewal Complete"),g("Domain",b.domain(r.domain)),g("Years",String(r.renewed_years)),g("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&g("Price",b.price(r.price)+Ns.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&g("Payment",r.payment_method),d(),O("Verify renewal:",`domani status ${r.domain}`),d()}X();var st=F(W(),1);V();ge();async function Yr(t,e){t||h("Domain is required",{hint:`Usage: domani import <domain>
208
+ domani import <domain> --verify`,code:"validation_error",json:e.json,fields:e.fields}),z(t,e);let s=e.verify?"/api/domains/import/verify":"/api/domains/import",i=k(!e.json);i.start(e.verify?`Verifying ownership of ${b.domain(t)}`:`Initiating import for ${b.domain(t)}`);let n=await j(s,{method:"POST",body:JSON.stringify({domain:t})}),r=await n.json();if(n.ok||(i.stop(e.verify?"Verification failed":"Import failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),e.json){i.stop(""),x(r,e.fields);return}e.verify?(i.stop(`${v.success} ${b.domain(t)} imported!`),C("Domain Imported"),g("Domain",b.domain(r.domain)),g("Status",st.default.green(r.status||"active")),r.expires_at&&g("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&g("Registrar",r.registrar),d(),O("Check domain health:",`domani status ${r.domain}`),d()):(i.stop(`${v.success} Verification record ready`),C("Import Domain"),g("Domain",b.domain(r.domain)),g("Status",st.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${st.default.dim("Type:")} ${st.default.bold("TXT")}`),console.log(` ${st.default.dim("Name:")} ${st.default.bold(r.txt_record?.name||"@")}`),console.log(` ${st.default.dim("Value:")} ${st.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${st.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),O("Once the record is set, verify:",`domani import ${t} --verify`),d())}Bi();yt();V();function Kr(t){let e=$t();e||(d(),h("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:t.json})),t.json?x({token:e}):console.log(e)}X();var qe=F(W(),1);V();async function zr(t,e){switch(t){case void 0:case"list":return Ul(e.json,e.fields);case"create":return Ml(e);case"revoke":return Vl(e);default:h(`Unknown action: ${t}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:e.json,fields:e.fields})}}async function Ul(t,e){let s=k(!t);s.start("Loading tokens");let i=await j("/api/tokens"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${v.success} ${n.tokens.length} token(s)`),t){x(n,e);return}if(n.tokens.length===0){d(),console.log(` ${qe.default.dim("No tokens.")}`),d(),O("Create one:",'domani tokens create --name "My App"'),d();return}d(),C("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=qe.default.red("Expired"):o.expiresAt?a=qe.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=qe.default.dim("No expiration");let l=o.scopes.includes("*")?qe.default.dim("all"):qe.default.dim(o.scopes.join(", "));return[qe.default.dim(o.id),qe.default.bold(o.name),l,a]});de(["ID","Name","Scopes","Expiration"],r,[28,16,32,20]),d()}async function Ml(t){let e={};if(t.name&&(e.name=t.name),t.scopes&&(e.scopes=t.scopes.split(",").map(r=>r.trim())),t.expiresIn){let r=Number(t.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&h("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:t.json,fields:t.fields}),e.expires_in=r}let s=k(!t.json);s.start("Creating token");let i=await j("/api/tokens",{method:"POST",body:JSON.stringify(e)}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Token created`),t.json){x(n,t.fields);return}d(),C("Token Created"),g("ID",n.id),g("Name",n.name),g("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),g("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),d(),console.log(` ${qe.default.yellow("!")} ${qe.default.bold("Key:")} ${n.key}`),console.log(` ${qe.default.dim("Save this key - it will not be shown again.")}`),d()}async function Vl(t){t.tokenId||h("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
209
+ Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:t.json,fields:t.fields});let e=k(!t.json);e.start("Revoking token");let s=await j(`/api/tokens/${encodeURIComponent(t.tokenId)}`,{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${v.success} Token revoked`),t.json){x(i,t.fields);return}console.log(` ${qe.default.dim("Any applications using this key will need a new one.")}`),d()}X();var Re=F(W(),1);V();ge();Ye();async function Xr(t,e){t||(t=await me()),z(t,e);let s=e.autoRenew!==void 0,i=e.whoisPrivacy!==void 0,n=e.securityLock!==void 0;if(!s&&!i&&!n)return ql(t,e.json,e.fields);let r={};if(s){let c=en(e.autoRenew);c===null&&h("--auto-renew must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.auto_renew=c}if(i){let c=en(e.whoisPrivacy);c===null&&h("--whois-privacy must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.whois_privacy=c}if(n){let c=en(e.securityLock);c===null&&h("--security-lock must be on or off",{code:"validation_error",json:e.json,fields:e.fields}),r.security_lock=c}if(e.dryRun)return Y("settings_update",{domain:t,...r},e.json,e.fields);let o=k(!e.json);o.start(`Updating ${b.domain(t)}`);let a=await j(`/api/domains/${encodeURIComponent(t)}/settings`,{method:"PUT",body:JSON.stringify(r)}),l=await a.json();if(a.ok||(o.stop("Failed"),h(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${v.success} Settings updated`),e.json){x(l,e.fields);return}C("Settings Updated"),g("Domain",b.domain(l.domain)),l.auto_renew!==void 0&&g("Auto-renew",l.auto_renew?Re.default.green("on"):Re.default.dim("off")),l.whois_privacy!==void 0&&g("WHOIS privacy",l.whois_privacy?Re.default.green("on"):Re.default.dim("off")),l.security_lock!==void 0&&g("Security lock",l.security_lock?Re.default.green("locked"):Re.default.dim("unlocked")),l.hint&&g("",Re.default.dim(l.hint)),d()}async function ql(t,e,s){let i=k(!e);i.start(`Loading ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop(`${v.success} ${b.domain(t)}`),e){x(r,s);return}C("Domain Settings"),g("Domain",b.domain(r.domain)),g("Status",r.status==="active"?Re.default.green(r.status):Re.default.yellow(r.status)),g("Auto-renew",r.auto_renew?Re.default.green("on"):Re.default.dim("off")),r.registrar&&(g("WHOIS privacy",r.registrar.whois_privacy?Re.default.green("on"):Re.default.dim("off")),g("Security lock",r.registrar.security_lock?Re.default.green("locked"):Re.default.dim("unlocked"))),g("Expires",new Date(r.expires_at).toLocaleDateString()+Re.default.dim(` (${r.days_until_expiry} days)`)),d(),O("Toggle auto-renew:",`domani settings ${t} --auto-renew off`),O("Toggle WHOIS privacy:",`domani settings ${t} --whois-privacy off`),O("Toggle security lock:",`domani settings ${t} --security-lock off`),O("Get transfer auth code:",`domani auth-code ${t}`),d()}function en(t){let e=t.toLowerCase();return e==="on"||e==="true"||e==="1"||e==="enable"?!0:e==="off"||e==="false"||e==="0"||e==="disable"?!1:null}X();var Nt=F(W(),1);V();ge();Ye();async function Zr(t,e){t||(t=await me()),z(t,e);let s=k(!e.json);s.start(`Getting auth code for ${b.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/auth-code`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${v.success} Auth code retrieved`),e.json){x(n,e.fields);return}if(C("Auth Code"),g("Domain",b.domain(n.domain)),g("Auth code",Nt.default.bold(Nt.default.green(n.auth_code))),n.was_unlocked&&g("",Nt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${Nt.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${Nt.default.dim("\u2192")} ${Nt.default.dim(r)}`)}d(),O("Check transfer status:",`domani transfer-away ${t}`),O("Re-lock domain:",`domani settings ${t} --security-lock on`),d()}X();var ht=F(W(),1);V();ge();Ye();var Wl={none:ht.default.dim,pending:ht.default.yellow,approved:ht.default.yellow,completed:ht.default.green,rejected:ht.default.red,expired:ht.default.red};async function Qr(t,e){t||(t=await me()),z(t,e);let s=k(!e.json);s.start(`Checking transfer status for ${b.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/transfer-away`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${v.success} ${b.domain(t)}`),e.json){x(n,e.fields);return}C("Transfer Away Status"),g("Domain",b.domain(n.domain));let r=Wl[n.status]||ht.default.dim;g("Status",r(n.status)),n.gaining_registrar&&g("New registrar",n.gaining_registrar),n.request_date&&g("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(d(),console.log(` ${ht.default.dim(n.hint)}`)),d(),n.status==="none"?O("Get auth code to start:",`domani auth-code ${t}`):n.status==="pending"||n.status==="approved"?O("Check again later:",`domani transfer-away ${t}`):n.status==="completed"?O("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&O("Retry with a new auth code:",`domani auth-code ${t}`),d()}X();De();var Fs=F(W(),1);V();async function eo(t,e){return t==="set"?Jl(e):Hl(e)}async function Hl(t){let e=k(!t.json);e.start("Loading contact info");let s=await j("/api/me/contact"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${v.success} Contact info`),t.json){x(i,t.fields);return}if(C("Contact Info"),!i.has_contact){console.log(` ${v.warning} ${Fs.default.yellow("No contact info set.")} Run ${Fs.default.bold("domani contact set")} to add.`),d(),console.log(` ${Fs.default.dim("Contact info is required before purchasing domains.")}`),d();return}let n=i.contact;g("Name",`${n.first_name} ${n.last_name}`),n.org_name&&g("Organization",n.org_name),g("Address",n.address1),n.address2&&g("",n.address2),g("",`${n.city}, ${n.state} ${n.postal_code}`),g("Country",n.country),g("Phone",n.phone),g("Email",n.email),d()}async function Jl(t){let e={},s=t.firstName||t.lastName||t.address1;if(!je&&!s&&h("Missing required flags for contact set",{hint:"Usage: domani contact set --first-name John --last-name Doe --address1 '123 Main St' --city SF --state CA --postal-code 94105 --country US --phone +1.5551234567 --email john@example.com",code:"missing_argument",json:t.json}),s){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},c=a.filter(u=>!t[u]);c.length>0&&h(`Missing required flags: ${c.map(u=>`--${u.replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:t.json});for(let[u,f]of Object.entries(l)){let p=t[u];p&&(e[f]=p)}}else{let a=await j("/api/me/contact"),c=(a.ok?await a.json():null)?.contact,u=[{key:"first_name",message:"First name",placeholder:"John",required:!0},{key:"last_name",message:"Last name",placeholder:"Doe",required:!0},{key:"org_name",message:"Organization (optional, press Enter to skip)",placeholder:"Acme Inc.",required:!1},{key:"address1",message:"Address line 1",placeholder:"123 Main St",required:!0},{key:"address2",message:"Address line 2 (optional)",placeholder:"Suite 100",required:!1},{key:"city",message:"City",placeholder:"San Francisco",required:!0},{key:"state",message:"State / Province",placeholder:"CA",required:!0},{key:"postal_code",message:"Postal / ZIP code",placeholder:"94105",required:!0},{key:"country",message:"Country code (ISO 3166-1 alpha-2)",placeholder:"US",required:!0},{key:"phone",message:"Phone (+CC.NUMBER)",placeholder:"+1.5551234567",required:!0},{key:"email",message:"Contact email",placeholder:"john@example.com",required:!0}];for(let f of u){let p=c?.[f.key]||"",y=await Te({message:f.message,placeholder:f.placeholder,defaultValue:p,validate:f.required?$=>$?.trim()?void 0:`${f.message} is required`:void 0});ae(y)&&process.exit(0);let w=y.trim();w&&(e[f.key]=w)}}if(t.dryRun)return Y("contact_set",e,t.json,t.fields);let i=k(!t.json);i.start("Saving contact info");let n=await j("/api/me/contact",{method:"PUT",body:JSON.stringify(e)}),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${v.success} Contact info saved`),t.json){x(r,t.fields);return}C("Contact Saved");let o=r.contact;g("Name",`${o.first_name} ${o.last_name}`),o.org_name&&g("Organization",o.org_name),g("Address",o.address1),o.address2&&g("",o.address2),g("",`${o.city}, ${o.state} ${o.postal_code}`),g("Country",o.country),g("Phone",o.phone),g("Email",o.email),d(),O("Search for a domain:","domani search <name>"),d()}X();var Ee=F(W(),1);V();ge();Ye();async function io(t,e,s,i){if(t||(t=await me()),z(t,i),!e)return Bl(t,i.json,i.fields);switch(e){case"enable":case"on":return i.dryRun?Y("parking_enable",{domain:t},i.json,i.fields):to(t,!0,i.json,i.fields);case"disable":case"off":return i.dryRun?Y("parking_disable",{domain:t},i.json,i.fields):to(t,!1,i.json,i.fields);case"price":{s||h("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:i.json,fields:i.fields});let n=parseFloat(s);return(isNaN(n)||n<=0)&&h("Price must be a positive number",{hint:`Got: "${s}"`,code:"validation_error",json:i.json,fields:i.fields}),i.dryRun?Y("parking_price",{domain:t,price:n},i.json,i.fields):so(t,n,i.json,i.fields)}case"unprice":case"unlist":return i.dryRun?Y("parking_unlist",{domain:t},i.json,i.fields):so(t,null,i.json,i.fields);default:h(`Unknown action: ${e}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:i.json,fields:i.fields})}}async function Bl(t,e,s){let i=k(!e);i.start(`Loading ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}`),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e,fields:s})),i.stop(`${v.success} ${b.domain(t)}`),e){x({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},s);return}C("Parking"),g("Domain",b.domain(r.domain)),g("Parking",r.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),g("Listing",r.listing_price?`${b.price(r.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),d(),O("Enable parking:",`domani parking ${t} enable`),O("Set sale price:",`domani parking ${t} price 499`),O("View analytics:",`domani analytics ${t}`),d()}async function to(t,e,s,i){let n=k(!s);n.start(`${e?"Enabling":"Disabling"} parking for ${b.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/parking`,{method:"PUT",body:JSON.stringify({enabled:e})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(n.stop(`${v.warning} DNS records will be replaced`),s){x(o,i);return}console.log(`
210
210
  ${Ee.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${Ee.default.dim(a.type)} ${a.name} ${Ee.default.dim("\u2192")} ${a.value}`);console.log(`
211
- ${Ee.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Ee.default.dim("Or use the dashboard to confirm.")}`),u();return}if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s,fields:i})),n.stop(`${b.success} Parking ${e?"enabled":"disabled"}`),s){x(o,i);return}O("Parking Updated"),y("Domain",v.domain(o.domain)),y("Parking",o.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),o.hint&&y("",Ee.default.dim(o.hint)),u()}async function Zr(t,e,s,i){let n=k(!s);n.start(e!==null?`Setting price for ${v.domain(t)} to ${v.price(e)}`:`Removing listing for ${v.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:e})}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s,fields:i})),n.stop(`${b.success} ${e!==null?"Price set":"Listing removed"}`),s){x(o,i);return}O("Listing Updated"),y("Domain",v.domain(o.domain)),y("Listing",o.listing_price?`${v.price(o.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),o.hint&&y("",Ee.default.dim(o.hint)),u()}Z();var qe=F(W(),1);q();be();Ge();var Ml=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Vl(t){let e=Math.max(...t,1);return t.map(s=>Ml[Math.min(Math.round(s/e*8),8)]).join("")}async function eo(t,e){t||(t=await ue()),z(t,e);let s=k(!e.json);s.start(`Loading analytics for ${v.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/analytics`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop("Analytics loaded"),e.json){x(n,e.fields);return}if(u(),O(`Analytics: ${v.domain(t)}`),y("Views (7d)",qe.default.cyan(n.views_7d.toLocaleString())),y("Views (30d)",qe.default.cyan(n.views_30d.toLocaleString())),y("Inquiries",qe.default.cyan(String(n.inquiries_30d))),y("Conversion",n.conversion_rate>0?qe.default.green(`${n.conversion_rate}%`):qe.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(c=>c.views),o=Vl(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);u(),console.log(` ${qe.default.dim(a)} ${qe.default.cyan(o)} ${qe.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){u(),console.log(` ${qe.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[qe.default.dim(o.email),o.offer?v.price(o.offer):qe.default.dim("-"),qe.default.dim(new Date(o.date).toLocaleDateString())]);fe(["Email","Offer","Date"],r,[30,12,14])}u(),I("Set a listing price:",`domani parking ${t} price <amount>`),I("Set up email:",`domani email setup ${t}`),I("Domain settings:",`domani settings ${t}`),u()}Z();var ge=F(W(),1);q();async function to(t,e){switch(t){case void 0:case"list":return ql(e.json,e.fields);case"create":return Wl(e);case"update":return Hl(e);case"delete":return Jl(e);case"deliveries":return Bl(e);case"events":return Gl(e.json,e.fields);default:h(`Unknown action: ${t}`,{hint:"Actions: list, create, update, delete, deliveries, events",code:"validation_error",json:e.json,fields:e.fields})}}async function ql(t,e){let s=k(!t);s.start("Loading webhooks");let i=await j("/api/webhooks"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${b.success} ${n.webhooks.length} webhook(s)`),t){x(n,e);return}if(n.webhooks.length===0){u(),console.log(` ${ge.default.dim("No webhooks configured.")}`),u(),I("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),I("List events:","domani webhooks events"),u();return}u(),O("Webhooks");let r=n.webhooks.map(o=>[ge.default.dim(o.id),v.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.active?ge.default.green("active"):ge.default.dim("paused")]);fe(["ID","URL","Events","Status"],r,[28,40,24,10]),u()}async function Wl(t){t.url||h("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:t.json,fields:t.fields}),t.events||h("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
212
- Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:t.json,fields:t.fields});let e=t.events.split(",").map(r=>r.trim());if(t.dryRun)return Y("webhook_create",{url:t.url,events:e},t.json,t.fields);let s=k(!t.json);s.start("Creating webhook");let i=await j("/api/webhooks",{method:"POST",body:JSON.stringify({url:t.url,events:e})}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Webhook created`),t.json){x(n,t.fields);return}u(),O("Webhook Created"),y("ID",n.id),y("URL",v.url(n.url)),y("Events",n.events.join(", ")),y("Status",ge.default.green("active")),u(),console.log(` ${ge.default.yellow("!")} ${ge.default.bold("Secret:")} ${n.secret}`),console.log(` ${ge.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${ge.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),u()}async function Hl(t){t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:t.json,fields:t.fields});let e={};if(t.url&&(e.url=t.url),t.events&&(e.events=t.events.split(",").map(r=>r.trim())),t.active!==void 0&&(e.active=t.active==="on"||t.active==="true"),t.dryRun)return Y("webhook_update",{webhook_id:t.webhookId,...e},t.json,t.fields);let s=k(!t.json);s.start("Updating webhook");let i=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}`,{method:"PATCH",body:JSON.stringify(e)}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} Webhook updated`),t.json){x(n,t.fields);return}O("Webhook Updated"),y("ID",n.id),y("URL",v.url(n.url)),y("Events",n.events.join(", ")),y("Status",n.active?ge.default.green("active"):ge.default.dim("paused")),u()}async function Jl(t){if(t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("webhook_delete",{webhook_id:t.webhookId},t.json,t.fields);let e=k(!t.json);e.start("Deleting webhook");let s=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}`,{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${b.success} Webhook deleted`),t.json){x(i,t.fields);return}console.log(` ${ge.default.dim("Pending deliveries have been cancelled.")}`),u()}async function Bl(t){t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:t.json,fields:t.fields});let e=t.limit?`?limit=${t.limit}`:"",s=k(!t.json);s.start("Loading deliveries");let i=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}/deliveries${e}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${b.success} ${n.deliveries.length} delivery(ies)`),t.json){x(n,t.fields);return}if(n.deliveries.length===0){u(),console.log(` ${ge.default.dim("No deliveries yet.")}`),u();return}u(),O("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?ge.default.green("delivered"):o.status==="failed"?ge.default.red("failed"):ge.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):ge.default.dim("-"),String(o.attempts),ge.default.dim(new Date(o.created_at).toLocaleString())]});fe(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),u()}async function Gl(t,e){let s=k(!t);s.start("Loading event types");let i=await ye("/api/webhooks/events"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${b.success} ${n.events.length} event type(s)`),t){x(n,e);return}u(),O("Webhook Event Types");let r=n.events.map(o=>[ge.default.cyan(o.type),ge.default.dim(o.description)]);fe(["Event","Description"],r,[24,50]),u()}Z();var we=F(W(),1);q();be();async function so(t,e){if(t||h("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
211
+ ${Ee.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Ee.default.dim("Or use the dashboard to confirm.")}`),d();return}if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s,fields:i})),n.stop(`${v.success} Parking ${e?"enabled":"disabled"}`),s){x(o,i);return}C("Parking Updated"),g("Domain",b.domain(o.domain)),g("Parking",o.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),o.hint&&g("",Ee.default.dim(o.hint)),d()}async function so(t,e,s,i){let n=k(!s);n.start(e!==null?`Setting price for ${b.domain(t)} to ${b.price(e)}`:`Removing listing for ${b.domain(t)}`);let r=await j(`/api/domains/${encodeURIComponent(t)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:e})}),o=await r.json();if(r.ok||(n.stop("Failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:s,fields:i})),n.stop(`${v.success} ${e!==null?"Price set":"Listing removed"}`),s){x(o,i);return}C("Listing Updated"),g("Domain",b.domain(o.domain)),g("Listing",o.listing_price?`${b.price(o.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),o.hint&&g("",Ee.default.dim(o.hint)),d()}X();var We=F(W(),1);V();ge();Ye();var Gl=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Yl(t){let e=Math.max(...t,1);return t.map(s=>Gl[Math.min(Math.round(s/e*8),8)]).join("")}async function no(t,e){t||(t=await me()),z(t,e);let s=k(!e.json);s.start(`Loading analytics for ${b.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/analytics`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop("Analytics loaded"),e.json){x(n,e.fields);return}if(d(),C(`Analytics: ${b.domain(t)}`),g("Views (7d)",We.default.cyan(n.views_7d.toLocaleString())),g("Views (30d)",We.default.cyan(n.views_30d.toLocaleString())),g("Inquiries",We.default.cyan(String(n.inquiries_30d))),g("Conversion",n.conversion_rate>0?We.default.green(`${n.conversion_rate}%`):We.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(c=>c.views),o=Yl(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${We.default.dim(a)} ${We.default.cyan(o)} ${We.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${We.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[We.default.dim(o.email),o.offer?b.price(o.offer):We.default.dim("-"),We.default.dim(new Date(o.date).toLocaleDateString())]);de(["Email","Offer","Date"],r,[30,12,14])}d(),O("Set a listing price:",`domani parking ${t} price <amount>`),O("Set up email:",`domani email setup ${t}`),O("Domain settings:",`domani settings ${t}`),d()}X();var $e=F(W(),1);V();async function ro(t,e){switch(t){case void 0:case"list":return Kl(e.json,e.fields);case"create":return zl(e);case"update":return Xl(e);case"delete":return Zl(e);case"deliveries":return Ql(e);case"events":return ec(e.json,e.fields);default:h(`Unknown action: ${t}`,{hint:"Actions: list, create, update, delete, deliveries, events",code:"validation_error",json:e.json,fields:e.fields})}}async function Kl(t,e){let s=k(!t);s.start("Loading webhooks");let i=await j("/api/webhooks"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${v.success} ${n.webhooks.length} webhook(s)`),t){x(n,e);return}if(n.webhooks.length===0){d(),console.log(` ${$e.default.dim("No webhooks configured.")}`),d(),O("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),O("List events:","domani webhooks events"),d();return}d(),C("Webhooks");let r=n.webhooks.map(o=>[$e.default.dim(o.id),b.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.active?$e.default.green("active"):$e.default.dim("paused")]);de(["ID","URL","Events","Status"],r,[28,40,24,10]),d()}async function zl(t){t.url||h("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:t.json,fields:t.fields}),t.events||h("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
212
+ Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:t.json,fields:t.fields});let e=t.events.split(",").map(r=>r.trim());if(t.dryRun)return Y("webhook_create",{url:t.url,events:e},t.json,t.fields);let s=k(!t.json);s.start("Creating webhook");let i=await j("/api/webhooks",{method:"POST",body:JSON.stringify({url:t.url,events:e})}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Webhook created`),t.json){x(n,t.fields);return}d(),C("Webhook Created"),g("ID",n.id),g("URL",b.url(n.url)),g("Events",n.events.join(", ")),g("Status",$e.default.green("active")),d(),console.log(` ${$e.default.yellow("!")} ${$e.default.bold("Secret:")} ${n.secret}`),console.log(` ${$e.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${$e.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),d()}async function Xl(t){t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:t.json,fields:t.fields});let e={};if(t.url&&(e.url=t.url),t.events&&(e.events=t.events.split(",").map(r=>r.trim())),t.active!==void 0&&(e.active=t.active==="on"||t.active==="true"),t.dryRun)return Y("webhook_update",{webhook_id:t.webhookId,...e},t.json,t.fields);let s=k(!t.json);s.start("Updating webhook");let i=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}`,{method:"PATCH",body:JSON.stringify(e)}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} Webhook updated`),t.json){x(n,t.fields);return}C("Webhook Updated"),g("ID",n.id),g("URL",b.url(n.url)),g("Events",n.events.join(", ")),g("Status",n.active?$e.default.green("active"):$e.default.dim("paused")),d()}async function Zl(t){if(t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return Y("webhook_delete",{webhook_id:t.webhookId},t.json,t.fields);let e=k(!t.json);e.start("Deleting webhook");let s=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}`,{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),e.stop(`${v.success} Webhook deleted`),t.json){x(i,t.fields);return}console.log(` ${$e.default.dim("Pending deliveries have been cancelled.")}`),d()}async function Ql(t){t.webhookId||h("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:t.json,fields:t.fields});let e=t.limit?`?limit=${t.limit}`:"",s=k(!t.json);s.start("Loading deliveries");let i=await j(`/api/webhooks/${encodeURIComponent(t.webhookId)}/deliveries${e}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields})),s.stop(`${v.success} ${n.deliveries.length} delivery(ies)`),t.json){x(n,t.fields);return}if(n.deliveries.length===0){d(),console.log(` ${$e.default.dim("No deliveries yet.")}`),d();return}d(),C("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?$e.default.green("delivered"):o.status==="failed"?$e.default.red("failed"):$e.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):$e.default.dim("-"),String(o.attempts),$e.default.dim(new Date(o.created_at).toLocaleString())]});de(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),d()}async function ec(t,e){let s=k(!t);s.start("Loading event types");let i=await be("/api/webhooks/events"),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t,fields:e})),s.stop(`${v.success} ${n.events.length} event type(s)`),t){x(n,e);return}d(),C("Webhook Event Types");let r=n.events.map(o=>[$e.default.cyan(o.type),$e.default.dim(o.description)]);de(["Event","Description"],r,[24,50]),d()}X();var we=F(W(),1);V();ge();async function oo(t,e){if(t||h("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
213
213
  domani sell <domain> --verify
214
214
  domani sell <domain> --status
215
- domani sell <domain> --cancel`,code:"validation_error",json:e.json,fields:e.fields}),z(t,e),e.status)return zl(t,e);if(e.verify)return Kl(t,e);if(e.cancel)return Xl(t,e);if(e.transferCode)return Zl(t,e.transferCode,e);if(e.price)return Yl(t,e);h("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
215
+ domani sell <domain> --cancel`,code:"validation_error",json:e.json,fields:e.fields}),z(t,e),e.status)return ic(t,e);if(e.verify)return sc(t,e);if(e.cancel)return nc(t,e);if(e.transferCode)return rc(t,e.transferCode,e);if(e.price)return tc(t,e);h("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
216
216
  domani sell <domain> --verify
217
217
  domani sell <domain> --status
218
218
  domani sell <domain> --cancel
219
- domani sell <domain> --transfer-code <code>`,code:"validation_error",json:e.json,fields:e.fields})}async function Yl(t,e){let s=parseFloat(e.price);(isNaN(s)||s<=0)&&h("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:e.json,fields:e.fields});let i=k(!e.json);i.start(`Listing ${v.domain(t)} for sale`);let n={domain:t,price:s};e.description&&(n.description=e.description);let r=await j("/api/domains/sell",{method:"POST",body:JSON.stringify(n)}),o=await r.json();if(r.ok||(i.stop("Listing failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),e.json){i.stop(""),x(o,e.fields);return}(o.listing?.status??"pending_verification")==="active"?(i.stop(`${b.success} Listed for sale`),O("Sell Domain"),y("Domain",v.domain(o.listing?.domain||t)),y("Price",v.price(s)),y("Status",we.default.green("active")),u(),console.log(` ${we.default.dim("Your listing is live on the marketplace.")}`),u()):(i.stop(`${b.success} Verification record ready`),O("Sell Domain"),y("Domain",v.domain(o.listing?.domain||t)),y("Price",v.price(s)),y("Status",we.default.yellow("pending verification")),u(),console.log(" Add this TXT record at your DNS provider:"),u(),console.log(` ${we.default.dim("Type:")} ${we.default.bold("TXT")}`),console.log(` ${we.default.dim("Name:")} ${we.default.bold(o.txt_record?.name||"@")}`),console.log(` ${we.default.dim("Value:")} ${we.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),u(),console.log(` ${we.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),u(),I("Once the record is set, verify:",`domani sell ${t} --verify`),u())}async function Kl(t,e){let s=k(!e.json);s.start(`Verifying ownership of ${v.domain(t)}`);let i=await j("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:t})}),n=await i.json();if(i.ok||(s.stop("Verification failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){s.stop(""),x(n,e.fields);return}s.stop(`${b.success} ${v.domain(t)} is now listed for sale!`),O("Domain Listed"),y("Domain",v.domain(n.domain||t)),y("Status",we.default.green(n.status||"active")),n.price&&y("Price",v.price(n.price)),u(),I("Check listing status:",`domani sell ${t} --status`),I("View your deals:","domani deals"),u()}async function zl(t,e){let s=k(!e.json);s.start(`Checking listing status for ${v.domain(t)}`);let i=await j(`/api/domains/sell/status?domain=${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Listing status loaded`),e.json){x(n,e.fields);return}let r=n.listing;if(O("Listing Status"),y("Domain",v.domain(n.domain||t)),r){let o=r.status;y("Status",o==="active"?we.default.green(o):we.default.yellow(o||"unknown")),r.price&&y("Price",v.price(r.price)),r.description&&y("Description",r.description),r.created_at&&y("Listed",we.default.dim(new Date(r.created_at).toLocaleDateString()))}else y("Status",we.default.dim("No listing found"));n.deal&&y("Deal",`${n.deal.status} ($${n.deal.price})`),u()}async function Xl(t,e){let s=k(!e.json);s.start(`Removing ${v.domain(t)} from sale`);let i=await j(`/api/domains/sell?domain=${encodeURIComponent(t)}`,{method:"DELETE"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){s.stop(""),x(n,e.fields);return}s.stop(`${b.success} ${v.domain(t)} removed from sale`),u()}async function Zl(t,e,s){let i=k(!s.json);i.start(`Looking up active deal for ${v.domain(t)}`);let n=await j(`/api/deals?role=seller&domain=${encodeURIComponent(t)}&status=active`),r=await n.json();n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:s.json,fields:s.fields}));let a=(r.deals||r.data||[]).filter(f=>f.domain.toLowerCase()===t.toLowerCase());a.length===0&&(i.stop("No active deal found"),h(`No active deal found for ${t}`,{hint:`Make sure you have an active sale for this domain.
220
- Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:s.json,fields:s.fields}));let l=a[0].id;i.message(`Submitting transfer code for deal ${we.default.dim(l)}`);let c=await j(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:e})}),d=await c.json();if(c.ok||(i.stop("Failed"),h(d.error||d.message,{hint:d.hint,status:c.status,json:s.json,fields:s.fields})),s.json){i.stop(""),x(d,s.fields);return}i.stop(`${b.success} Transfer code submitted for ${v.domain(t)}`),O("Transfer Code Submitted"),y("Domain",v.domain(t)),y("Deal",we.default.dim(l)),y("Status",we.default.green(d.status||"code_submitted")),u(),I("Track the deal:",`domani deals ${l}`),u()}Z();var _e=F(W(),1);q();async function io(t,e){return t?ec(t,e):Ql(e)}async function Ql(t){let e=k(!t.json);e.start("Loading deals");let s=new URLSearchParams;t.role&&s.set("role",t.role),t.status&&s.set("status",t.status);let i=s.toString()?`?${s.toString()}`:"",n=await j(`/api/deals${i}`),r=await n.json();n.ok||(e.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.deals||r.data||[];if(e.stop(`${b.success} ${o.length} deal(s)`),t.json){x(r,t.fields);return}if(o.length===0){u(),console.log(` ${_e.default.dim("No deals found.")}`),u(),I("List a domain for sale:","domani sell <domain> --price <amount>"),u();return}u(),O("Deals");let a=o.map(l=>{let c=l.status==="completed"?_e.default.green:l.status==="active"?_e.default.cyan:l.status==="cancelled"?_e.default.red:_e.default.yellow;return[v.domain(l.domain),v.price(l.price),c(l.status),_e.default.dim(l.role||"-"),_e.default.dim(new Date(l.created_at).toLocaleDateString())]});fe(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),u()}async function ec(t,e){let s=k(!e.json);s.start(`Loading deal ${_e.default.dim(t)}`);let i=await j(`/api/deals/${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Deal loaded`),e.json){x(n,e.fields);return}let r=n.deal||n;O("Deal Details"),y("ID",_e.default.dim(r.id)),y("Domain",v.domain(r.domain)),y("Price",v.price(r.price));let o=r.status==="completed"?_e.default.green:r.status==="active"?_e.default.cyan:r.status==="cancelled"?_e.default.red:_e.default.yellow;y("Status",o(r.status)),r.role&&y("Your Role",r.role),r.buyer&&y("Buyer",_e.default.dim(r.buyer)),r.seller&&y("Seller",_e.default.dim(r.seller)),r.created_at&&y("Created",_e.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&y("Updated",_e.default.dim(new Date(r.updated_at).toLocaleDateString())),u();let a=r.events||[];if(a.length>0){O("Timeline");for(let l of a){let c=_e.default.dim(new Date(l.created_at).toLocaleString()),d=l.status==="completed"?b.success:l.status==="expired"||l.status==="refunded"?b.error:b.info;console.log(` ${d} ${c} ${l.detail||l.status}`)}u()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),u())}Z();var he=F(W(),1);q();async function ro(t){return t.read?sc(t):tc(t)}async function tc(t){let e=k(!t.json);e.start("Loading notifications");let s=new URLSearchParams;t.unread&&s.set("unread","true"),t.limit&&s.set("limit",t.limit);let i=s.toString()?`?${s.toString()}`:"",n=await j(`/api/notifications${i}`),r=await n.json();n.ok||(e.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(c=>!c.read).length;if(e.stop(`${b.success} ${o.length} notification(s)${a>0?` ${b.dot} ${he.default.yellow(`${a} unread`)}`:""}`),t.json){x(r,t.fields);return}if(o.length===0){u(),console.log(` ${he.default.dim("No notifications.")}`),u();return}u(),O("Notifications");let l=o.map(c=>{let d=c.read?he.default.dim(b.dot):he.default.cyan(b.info),f=ic(c.type),p=c.read?he.default.dim(c.title):he.default.white(c.title),$=c.body?c.read?he.default.dim(no(c.body,40)):he.default.dim(no(c.body,40)):he.default.dim("-"),w=he.default.dim(new Date(c.created_at).toLocaleDateString());return[d,f,p,$,w]});fe(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),u(),a>0&&(console.log(` ${he.default.dim("Mark all as read:")} ${he.default.cyan("domani notifications --read")}`),u())}async function sc(t){let e=k(!t.json);e.start("Marking all notifications as read");let s=await j("/api/notifications/read-all",{method:"POST"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),t.json){e.stop(""),x(i,t.fields);return}let n=i.count??0;e.stop(`${b.success} ${n} notification(s) marked as read`),u()}function ic(t){let e={deal:he.default.cyan,sale:he.default.green,purchase:he.default.green,transfer:he.default.yellow,expiry:he.default.red,security:he.default.red,billing:he.default.yellow,email:he.default.blue},s=t.split(".")[0].split("_")[0];return(e[s]||he.default.dim)(t)}function no(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}Z();var _t=F(W(),1);q();async function oo(t){let e=t.limit?Number(t.limit):20,s=await j(`/api/billing/invoices?limit=${e}`),i=await s.json();if(s.ok||h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields}),t.json){x({...i,count:i.invoices.length},t.fields);return}if(i.invoices.length===0){console.log(` ${_t.default.dim("No invoices yet.")}`);return}O(`Invoices (${i.invoices.length})`),u();for(let n of i.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${b.success} ${_t.default.bold(a)} ${_t.default.green(r)} ${_t.default.dim(o)}`),n.description&&console.log(` ${_t.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${_t.default.dim(n.hosted_invoice_url)}`)}u(),i.has_more&&(console.log(` ${_t.default.dim(`Showing ${i.invoices.length} most recent. Use --limit to see more.`)}`),u())}Z();var ss=F(W(),1);q();async function ao(t){let e=k(!t?.json);e.start("Setting up billing session");let s=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),i.url||(e.stop("Failed"),h("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:t?.json})),e.stop("Checkout ready"),t?.json){x({url:i.url});return}u(),console.log(` ${ss.default.dim("Opening browser")} ${b.arrow} ${v.url(i.url)}`),u(),Xe(i.url),console.log(` ${b.info} ${ss.default.dim("Complete payment setup in your browser.")}`),console.log(` ${ss.default.dim(" After setup, you can purchase domains with")} ${ss.default.cyan("domani buy")}`),u()}Z();var Zi=F(W(),1);q();async function lo(t){let e=k(!t?.json);e.start("Creating upgrade session");let s=await j("/api/billing/subscribe",{method:"POST"}),i=await s.json();if(!s.ok){e.stop("Failed"),i.code==="ALREADY_PRO"?h("You're already on the Pro plan.",{json:t?.json}):h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json});return}if(e.stop("Ready"),t?.json){x({url:i.url},t?.fields);return}u(),console.log(` ${Zi.default.dim("Opening browser")} ${b.arrow} ${v.url(i.url)}`),u(),Xe(i.url),console.log(` ${b.info} ${Zi.default.dim("Complete your Pro upgrade in the browser.")}`),u()}Z();var Qi=F(W(),1);q();async function co(t){let e=k(!t?.json);e.start("Cancelling subscription");let s=await j("/api/billing/cancel",{method:"POST"}),i=await s.json();if(!s.ok){e.stop("Failed"),i.code==="NOT_PRO"?h("You're not on the Pro plan.",{json:t?.json}):h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json});return}if(e.stop("Done"),t?.json){x(i,t?.fields);return}u();let n=i.cancel_at?new Date(i.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${b.success} ${Qi.default.dim("Subscription cancelled.")} Access continues until ${Qi.default.cyan(n)}.`),u()}Z();var Qe=F(W(),1);q();be();Ge();async function uo(t,e,s){t||(t=await ue()),z(t,s);let i=[];if(e?.length&&i.push(...e),s.set&&i.push(...s.set.split(",").map(n=>n.trim()).filter(Boolean)),i.length>0||s.reset){await rc(t,i,s);return}await nc(t,s)}async function nc(t,e){let s=k(!e.json);s.start(`Fetching nameservers for ${v.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`Nameservers for ${v.domain(t)}`),e.json){x(n,e.fields);return}if(u(),n.nameservers.length===0)console.log(` ${b.warning} ${Qe.default.yellow("No nameservers configured.")}`),console.log(` ${Qe.default.dim("DNS operations (parking, email, connect) will not work.")}`),u(),I("Set default nameservers:",`domani nameservers ${t} --reset`);else{O("Nameservers");for(let r of n.nameservers)console.log(` ${b.success} ${Qe.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(u(),console.log(` ${Qe.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(u(),y("Defaults",n.default_nameservers.map(r=>Qe.default.dim(r)).join(Qe.default.dim(", ")))),u()}async function rc(t,e,s){let i=k(!s.json);if(s.reset){i.start(`Fetching default nameservers for ${v.domain(t)}`);let o=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`),a=await o.json();o.ok||(i.stop("Failed"),h(a.error,{hint:a.hint,status:o.status,json:s.json,fields:s.fields})),a.default_nameservers?.length||(i.stop("No defaults"),h("No default nameservers available for this domain's registrar.",{code:"not_found",json:s.json,fields:s.fields})),e=a.default_nameservers,i.stop(`Using defaults: ${e.map(l=>Qe.default.cyan(l)).join(Qe.default.dim(", "))}`)}if(e.length<2&&h("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:s.json,fields:s.fields}),s.dryRun)return Y("nameservers_set",{domain:t,nameservers:e},s.json,s.fields);i.start(`Setting nameservers for ${v.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:e})}),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:s.json,fields:s.fields})),i.stop(`${b.success} Nameservers updated`),s.json){x(r,s.fields);return}u();for(let o of r.nameservers)console.log(` ${b.success} ${Qe.default.cyan(o)}`);u(),console.log(` ${Qe.default.dim("Changes may take up to 48 hours to propagate.")}`),u(),I("Check propagation:",`domani status ${t}`),u()}var mo=require("crypto"),Ps=F(require("fs"),1);$t();var is=F(W(),1);q();function oc(t,e){let s=t.split(".").map(Number),i=e.split(".").map(Number);for(let n=0;n<3;n++){if((s[n]||0)>(i[n]||0))return 1;if((s[n]||0)<(i[n]||0))return-1}return 0}async function fo(t){let e=k(!t?.json);e.start("Checking for updates");let s=Ye();try{let i=await fetch(`${s}/api/cli/version`);i.ok||(e.stop("Failed"),h("Could not check for updates"));let n=await i.json(),r=n.version,o=n.sha256;if(oc(r,ke)<=0){e.stop(`${b.success} Already up to date (v${ke})`),t?.json&&x({current:ke,latest:r,up_to_date:!0});return}if(t?.json){e.stop(""),x({current:ke,latest:r,up_to_date:!1,hint:"Run `domani update` to upgrade."});return}e.stop(`New version available: ${is.default.cyan(ke)} ${b.arrow} ${is.default.green(r)}`);let a=k();a.start("Downloading update");let l=`${s}/cli/domani.js`,c=await fetch(l);c.ok||(a.stop("Download failed"),h(`Failed to download from ${l}`));let d=await c.text();o&&(0,mo.createHash)("sha256").update(d).digest("hex")!==o&&(a.stop("Integrity check failed"),h("Downloaded file does not match expected hash - update aborted"));let f=process.argv[1];f||(a.stop("Failed"),h("Could not determine binary path"));let p=Ps.default.realpathSync(f),$=p+".tmp";Ps.default.writeFileSync($,d,{mode:493}),Ps.default.renameSync($,p),a.stop(`${b.success} Updated to v${r}`),u(),console.log(` ${is.default.dim("Restart your terminal or run")} domani --version ${is.default.dim("to verify")}`),u()}catch(i){h(`Update failed: ${i instanceof Error?i.message:String(i)}`)}}var Ns=F(require("fs"),1),ho=F(require("path"),1),po=F(require("os"),1);De();var ns=F(W(),1);q();async function go(){let t=process.argv[1],e=t?Ns.default.realpathSync(t):null,s=ho.default.join(po.default.homedir(),".domani");if(u(),console.log(` ${ns.default.bold("This will remove:")}`),e&&console.log(` ${b.dot} CLI binary: ${ns.default.dim(e)}`),console.log(` ${b.dot} Config dir: ${ns.default.dim(s)}`),u(),await Be({message:"Uninstall domani?"})!==!0){console.log(` ${ns.default.dim("Cancelled.")}`);return}Ns.default.rmSync(s,{recursive:!0,force:!0}),e&&Ns.default.unlinkSync(e),u(),console.log(` ${b.success} domani uninstalled.`),u()}Z();var ne=F(W(),1);q();async function yo(t,e){let s=e?.json,i=e?.fields,n=t?`/api/schema?command=${encodeURIComponent(t)}`:"/api/schema",r=k(!s);r.start("Loading schema");let o=await ye(n),a=await o.json();if(o.ok||(r.stop("Failed"),h(a.error||a.message,{hint:a.hint,status:o.status,json:s,fields:i})),r.stop("Schema loaded"),s){x(a,i);return}t?lc(t,a):ac(a.commands)}function ac(t){O("Commands");let e=Object.entries(t).map(([s,i])=>[ne.default.bold(ne.default.cyan(s)),i.description]);fe(["Command","Description"],e,[20,50]),u(),console.log(` ${ne.default.dim("Run")} ${ne.default.cyan("domani schema <command>")} ${ne.default.dim("for full details")}`),u()}function lc(t,e){if(O(`domani ${t}`),console.log(` ${e.description}`),u(),console.log(` ${v.label("Usage:")} ${ne.default.cyan(e.usage)}`),e.arguments&&Object.keys(e.arguments).length>0){u(),console.log(` ${ne.default.bold("Arguments")}`);for(let[s,i]of Object.entries(e.arguments)){let n=i.required?ne.default.red("*"):"",r=ne.default.dim(`(${i.type}${i.variadic?", variadic":""})`);console.log(` ${ne.default.cyan(s)}${n} ${r}`),i.description&&console.log(` ${ne.default.dim(i.description)}`)}}if(e.options&&Object.keys(e.options).length>0){u(),console.log(` ${ne.default.bold("Options")}`);for(let[s,i]of Object.entries(e.options)){let n=i.required?ne.default.red("*"):"",r=ne.default.dim(`(${i.type})`),o=i.choices?ne.default.dim(` [${i.choices.join(", ")}]`):"";console.log(` ${ne.default.cyan(`--${s}`)}${n} ${r}${o}`),console.log(` ${ne.default.dim(i.description)}`)}}if(e.api)if(u(),console.log(` ${ne.default.bold("API")}`),cc(e.api))$o(e.api);else for(let[s,i]of Object.entries(e.api))console.log(` ${ne.default.bold(ne.default.yellow(s))}`),$o(i,6);e.errors&&e.errors.length>0&&(u(),console.log(` ${ne.default.bold("Errors")}`),console.log(` ${e.errors.map(s=>ne.default.dim(s)).join(ne.default.dim(", "))}`)),u()}function cc(t){return typeof t=="object"&&t!==null&&"method"in t&&"path"in t}function $o(t,e=4){let s=" ".repeat(e);if(console.log(`${s}${ne.default.green(t.method)} ${ne.default.white(t.path)}`),t.parameters&&Object.keys(t.parameters).length>0)for(let[i,n]of Object.entries(t.parameters)){let r=n.required?ne.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=ne.default.dim(`(${o.join(", ")})`);console.log(`${s} ${ne.default.cyan(i)}${r} ${a}`),n.description&&console.log(`${s} ${ne.default.dim(n.description)}`)}}Z();var Ne=F(W(),1);De();q();async function bo(t){let e=k(!t.json);e.start("Loading payment method");let s=await j("/api/me"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),t.json){e.stop(""),x(i.card?{has_payment_method:i.has_payment_method,card:i.card}:{has_payment_method:!1},t.fields);return}if(!i.has_payment_method||!i.card){e.stop("No payment method on file"),u(),console.log(` ${Ne.default.dim("Add a card with")} ${Ne.default.cyan("domani card add")}`),u();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=i.card,l=`${String(o).padStart(2,"0")}/${a}`,c=n.charAt(0).toUpperCase()+n.slice(1);e.stop("Payment method loaded"),O("Payment method"),y("Card",`${Ne.default.bold(c)} \u2022\u2022\u2022\u2022 ${Ne.default.bold(r)}`),y("Expires",l),u(),console.log(` ${Ne.default.dim("Update with")} ${Ne.default.cyan("domani card add")}`),u()}async function vo(t){let e=k(!t?.json);e.start("Setting up payment session");let s=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),i.url||(e.stop("Failed"),h("No checkout URL returned",{json:t?.json})),e.stop("Checkout ready"),t?.json){x({url:i.url},t?.fields);return}u(),console.log(` ${Ne.default.dim("Opening browser")} ${b.arrow} ${v.url(i.url)}`),u(),Xe(i.url),console.log(` ${b.info} ${Ne.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Ne.default.dim(" After setup, you can purchase domains with")} ${Ne.default.cyan("domani buy")}`),u()}async function wo(t){if(!t?.yes&&!t?.json){let n=await Be({message:"Remove your saved payment method?"});if(ae(n)||!n){console.log(` ${Ne.default.dim("Cancelled.")}`);return}}let e=k(!t?.json);e.start("Removing payment method");let s=await j("/api/billing/card",{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),e.stop(`${b.success} Payment method removed`),t?.json){x({removed:!0},t?.fields);return}u(),console.log(` ${Ne.default.dim("Add a new card with")} ${Ne.default.cyan("domani card add")}`),u()}process.stdin.setMaxListeners(50);var H=new hn;H.name("domani").description(`Domain names for developers and AI agents - ${Ft}`).version(ke).option("--api-url <url>","Override API base URL").configureOutput({outputError:(t,e)=>{let s=t.replace(/^error:\s*/i,"").trimEnd();if(e(`${st.default.red("\u2717")} ${s}
221
- `),/unknown option|missing required|expected argument/i.test(s)){let i=process.argv[2],n=i&&!i.startsWith("-")?`domani ${i} --help`:"domani --help";e(`${st.default.dim(` Run \`${n}\` to see available options.`)}
222
- `)}}}).hook("preAction",async(t,e)=>{let s=t.opts();s.apiUrl&&bn(s.apiUrl),process.stdout.isTTY||e.options.some(r=>r.long==="--json")&&e.setOptionValue("json",!0),["login","logout","search","suggest","tlds","whois","schema","update","uninstall"].includes(e.name())||await gr()});H.command("login").description(`Log in to ${Ft} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").addHelpText("after",`
219
+ domani sell <domain> --transfer-code <code>`,code:"validation_error",json:e.json,fields:e.fields})}async function tc(t,e){let s=parseFloat(e.price);(isNaN(s)||s<=0)&&h("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:e.json,fields:e.fields});let i=k(!e.json);i.start(`Listing ${b.domain(t)} for sale`);let n={domain:t,price:s};e.description&&(n.description=e.description);let r=await j("/api/domains/sell",{method:"POST",body:JSON.stringify(n)}),o=await r.json();if(r.ok||(i.stop("Listing failed"),h(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),e.json){i.stop(""),x(o,e.fields);return}(o.listing?.status??"pending_verification")==="active"?(i.stop(`${v.success} Listed for sale`),C("Sell Domain"),g("Domain",b.domain(o.listing?.domain||t)),g("Price",b.price(s)),g("Status",we.default.green("active")),d(),console.log(` ${we.default.dim("Your listing is live on the marketplace.")}`),d()):(i.stop(`${v.success} Verification record ready`),C("Sell Domain"),g("Domain",b.domain(o.listing?.domain||t)),g("Price",b.price(s)),g("Status",we.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${we.default.dim("Type:")} ${we.default.bold("TXT")}`),console.log(` ${we.default.dim("Name:")} ${we.default.bold(o.txt_record?.name||"@")}`),console.log(` ${we.default.dim("Value:")} ${we.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),d(),console.log(` ${we.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),O("Once the record is set, verify:",`domani sell ${t} --verify`),d())}async function sc(t,e){let s=k(!e.json);s.start(`Verifying ownership of ${b.domain(t)}`);let i=await j("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:t})}),n=await i.json();if(i.ok||(s.stop("Verification failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){s.stop(""),x(n,e.fields);return}s.stop(`${v.success} ${b.domain(t)} is now listed for sale!`),C("Domain Listed"),g("Domain",b.domain(n.domain||t)),g("Status",we.default.green(n.status||"active")),n.price&&g("Price",b.price(n.price)),d(),O("Check listing status:",`domani sell ${t} --status`),O("View your deals:","domani deals"),d()}async function ic(t,e){let s=k(!e.json);s.start(`Checking listing status for ${b.domain(t)}`);let i=await j(`/api/domains/sell/status?domain=${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${v.success} Listing status loaded`),e.json){x(n,e.fields);return}let r=n.listing;if(C("Listing Status"),g("Domain",b.domain(n.domain||t)),r){let o=r.status;g("Status",o==="active"?we.default.green(o):we.default.yellow(o||"unknown")),r.price&&g("Price",b.price(r.price)),r.description&&g("Description",r.description),r.created_at&&g("Listed",we.default.dim(new Date(r.created_at).toLocaleDateString()))}else g("Status",we.default.dim("No listing found"));n.deal&&g("Deal",`${n.deal.status} ($${n.deal.price})`),d()}async function nc(t,e){let s=k(!e.json);s.start(`Removing ${b.domain(t)} from sale`);let i=await j(`/api/domains/sell?domain=${encodeURIComponent(t)}`,{method:"DELETE"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){s.stop(""),x(n,e.fields);return}s.stop(`${v.success} ${b.domain(t)} removed from sale`),d()}async function rc(t,e,s){let i=k(!s.json);i.start(`Looking up active deal for ${b.domain(t)}`);let n=await j(`/api/deals?role=seller&domain=${encodeURIComponent(t)}&status=active`),r=await n.json();n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:s.json,fields:s.fields}));let a=(r.deals||r.data||[]).filter(f=>f.domain.toLowerCase()===t.toLowerCase());a.length===0&&(i.stop("No active deal found"),h(`No active deal found for ${t}`,{hint:`Make sure you have an active sale for this domain.
220
+ Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:s.json,fields:s.fields}));let l=a[0].id;i.message(`Submitting transfer code for deal ${we.default.dim(l)}`);let c=await j(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:e})}),u=await c.json();if(c.ok||(i.stop("Failed"),h(u.error||u.message,{hint:u.hint,status:c.status,json:s.json,fields:s.fields})),s.json){i.stop(""),x(u,s.fields);return}i.stop(`${v.success} Transfer code submitted for ${b.domain(t)}`),C("Transfer Code Submitted"),g("Domain",b.domain(t)),g("Deal",we.default.dim(l)),g("Status",we.default.green(u.status||"code_submitted")),d(),O("Track the deal:",`domani deals ${l}`),d()}X();var _e=F(W(),1);V();async function ao(t,e){return t?ac(t,e):oc(e)}async function oc(t){let e=k(!t.json);e.start("Loading deals");let s=new URLSearchParams;t.role&&s.set("role",t.role),t.status&&s.set("status",t.status);let i=s.toString()?`?${s.toString()}`:"",n=await j(`/api/deals${i}`),r=await n.json();n.ok||(e.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.deals||r.data||[];if(e.stop(`${v.success} ${o.length} deal(s)`),t.json){x(r,t.fields);return}if(o.length===0){d(),console.log(` ${_e.default.dim("No deals found.")}`),d(),O("List a domain for sale:","domani sell <domain> --price <amount>"),d();return}d(),C("Deals");let a=o.map(l=>{let c=l.status==="completed"?_e.default.green:l.status==="active"?_e.default.cyan:l.status==="cancelled"?_e.default.red:_e.default.yellow;return[b.domain(l.domain),b.price(l.price),c(l.status),_e.default.dim(l.role||"-"),_e.default.dim(new Date(l.created_at).toLocaleDateString())]});de(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function ac(t,e){let s=k(!e.json);s.start(`Loading deal ${_e.default.dim(t)}`);let i=await j(`/api/deals/${encodeURIComponent(t)}`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${v.success} Deal loaded`),e.json){x(n,e.fields);return}let r=n.deal||n;C("Deal Details"),g("ID",_e.default.dim(r.id)),g("Domain",b.domain(r.domain)),g("Price",b.price(r.price));let o=r.status==="completed"?_e.default.green:r.status==="active"?_e.default.cyan:r.status==="cancelled"?_e.default.red:_e.default.yellow;g("Status",o(r.status)),r.role&&g("Your Role",r.role),r.buyer&&g("Buyer",_e.default.dim(r.buyer)),r.seller&&g("Seller",_e.default.dim(r.seller)),r.created_at&&g("Created",_e.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&g("Updated",_e.default.dim(new Date(r.updated_at).toLocaleDateString())),d();let a=r.events||[];if(a.length>0){C("Timeline");for(let l of a){let c=_e.default.dim(new Date(l.created_at).toLocaleString()),u=l.status==="completed"?v.success:l.status==="expired"||l.status==="refunded"?v.error:v.info;console.log(` ${u} ${c} ${l.detail||l.status}`)}d()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(O("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),d())}X();var Ne=F(W(),1);V();ge();async function uo(t,e,s){switch(t){case void 0:case"list":case"ls":return lc(s);case"request":case"acquire":case"new":return lo(e,s);case"status":case"get":return co(e,s);case"cancel":case"rm":return cc(e,s);default:return t.includes(".")?lo(t,s):co(t,s)}}async function lo(t,e){t||h("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:e.json}),z(t,{json:e.json});let s=k(!e.json);s.start(`Requesting acquisition of ${b.domain(t)}`);let i={domain:t};if(e.maxBudget){let a=Number(e.maxBudget);(!Number.isFinite(a)||a<=0)&&h("--max-budget must be a positive number (USD).",{json:e.json}),i.max_budget=a}let n=await j("/api/broker",{method:"POST",body:JSON.stringify(i)}),r=await n.json();n.ok||(s.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.request||r;if(s.stop(`${v.success} Acquisition requested`),e.json)return x(r,e.fields);C("Broker request"),g("Domain",b.domain(o.domain)),g("Status",tn(o.status)),o.max_budget!=null&&g("Max budget",b.price(o.max_budget)),g("ID",Ne.default.dim(o.id)),d(),console.log(` ${Ne.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),d(),O("Check progress:",`domani broker status ${o.id}`),d()}async function lc(t){let e=k(!t.json);e.start("Loading broker requests");let s=t.status?`?status=${encodeURIComponent(t.status)}`:"",i=await j(`/api/broker${s}`),n=await i.json();i.ok||(e.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:t.json,fields:t.fields}));let r=n.requests||n.data||[];if(e.stop(`${v.success} ${r.length} request(s)`),t.json)return x(n,t.fields);if(r.length===0){d(),console.log(` ${Ne.default.dim("No broker requests yet.")}`),d(),O("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),d();return}d(),C("Broker requests"),de(["Domain","Status","Budget","ID"],r.map(o=>[b.domain(o.domain),tn(o.status),o.max_budget!=null?b.price(o.max_budget):Ne.default.dim("-"),Ne.default.dim(o.id)])),d()}async function co(t,e){t||h("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:e.json});let s=k(!e.json);s.start("Loading request");let i=await j(`/api/broker/${encodeURIComponent(t)}`),n=await i.json();i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields}));let r=n.request||n;if(s.stop(`${v.success} ${b.domain(r.domain)}`),e.json)return x(n,e.fields);C("Broker request"),g("Domain",b.domain(r.domain)),g("Status",tn(r.status)),r.max_budget!=null&&g("Max budget",b.price(r.max_budget)),g("Contacted",r.contacted?Ne.default.green("yes"):Ne.default.dim("not yet")),r.failure_reason&&g("Reason",Ne.default.yellow(r.failure_reason)),g("ID",Ne.default.dim(r.id)),d(),r.negotiation_id?(console.log(` ${Ne.default.dim("The owner responded - an anonymous negotiation is open.")}`),d(),O("Review the offer:","domani deals"),d()):["sourcing","contacted","negotiating"].includes(r.status)&&(O("Cancel this request:",`domani broker cancel ${r.id}`),d())}async function cc(t,e){t||h("A request ID is required.",{hint:"domani broker cancel <id>",json:e.json});let s=k(!e.json);s.start("Cancelling request");let i=await j(`/api/broker/${encodeURIComponent(t)}`,{method:"DELETE"}),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`${v.success} Request cancelled`),e.json)return x(n,e.fields);d()}function tn(t){return["completed","agreed"].includes(t)?Ne.default.green(t):["negotiating","contacted","sourcing"].includes(t)?Ne.default.cyan(t):["declined","no_contact","failed","expired","cancelled"].includes(t)?Ne.default.dim(t):t}X();var he=F(W(),1);V();async function fo(t){return t.read?uc(t):dc(t)}async function dc(t){let e=k(!t.json);e.start("Loading notifications");let s=new URLSearchParams;t.unread&&s.set("unread","true"),t.limit&&s.set("limit",t.limit);let i=s.toString()?`?${s.toString()}`:"",n=await j(`/api/notifications${i}`),r=await n.json();n.ok||(e.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(c=>!c.read).length;if(e.stop(`${v.success} ${o.length} notification(s)${a>0?` ${v.dot} ${he.default.yellow(`${a} unread`)}`:""}`),t.json){x(r,t.fields);return}if(o.length===0){d(),console.log(` ${he.default.dim("No notifications.")}`),d();return}d(),C("Notifications");let l=o.map(c=>{let u=c.read?he.default.dim(v.dot):he.default.cyan(v.info),f=mc(c.type),p=c.read?he.default.dim(c.title):he.default.white(c.title),y=c.body?c.read?he.default.dim(mo(c.body,40)):he.default.dim(mo(c.body,40)):he.default.dim("-"),w=he.default.dim(new Date(c.created_at).toLocaleDateString());return[u,f,p,y,w]});de(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${he.default.dim("Mark all as read:")} ${he.default.cyan("domani notifications --read")}`),d())}async function uc(t){let e=k(!t.json);e.start("Marking all notifications as read");let s=await j("/api/notifications/read-all",{method:"POST"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),t.json){e.stop(""),x(i,t.fields);return}let n=i.count??0;e.stop(`${v.success} ${n} notification(s) marked as read`),d()}function mc(t){let e={deal:he.default.cyan,sale:he.default.green,purchase:he.default.green,transfer:he.default.yellow,expiry:he.default.red,security:he.default.red,billing:he.default.yellow,email:he.default.blue},s=t.split(".")[0].split("_")[0];return(e[s]||he.default.dim)(t)}function mo(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}X();var St=F(W(),1);V();async function ho(t){let e=t.limit?Number(t.limit):20,s=await j(`/api/billing/invoices?limit=${e}`),i=await s.json();if(s.ok||h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields}),t.json){x({...i,count:i.invoices.length},t.fields);return}if(i.invoices.length===0){console.log(` ${St.default.dim("No invoices yet.")}`);return}C(`Invoices (${i.invoices.length})`),d();for(let n of i.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${v.success} ${St.default.bold(a)} ${St.default.green(r)} ${St.default.dim(o)}`),n.description&&console.log(` ${St.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${St.default.dim(n.hosted_invoice_url)}`)}d(),i.has_more&&(console.log(` ${St.default.dim(`Showing ${i.invoices.length} most recent. Use --limit to see more.`)}`),d())}X();var is=F(W(),1);V();async function po(t){let e=k(!t?.json);e.start("Setting up billing session");let s=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),i.url||(e.stop("Failed"),h("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:t?.json})),e.stop("Checkout ready"),t?.json){x({url:i.url});return}d(),console.log(` ${is.default.dim("Opening browser")} ${v.arrow} ${b.url(i.url)}`),d(),Ze(i.url),console.log(` ${v.info} ${is.default.dim("Complete payment setup in your browser.")}`),console.log(` ${is.default.dim(" After setup, you can purchase domains with")} ${is.default.cyan("domani buy")}`),d()}X();var sn=F(W(),1);V();async function go(t){let e=k(!t?.json);e.start("Creating upgrade session");let s=await j("/api/billing/subscribe",{method:"POST"}),i=await s.json();if(!s.ok){e.stop("Failed"),i.code==="ALREADY_PRO"?h("You're already on the Pro plan.",{json:t?.json}):h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json});return}if(e.stop("Ready"),t?.json){x({url:i.url},t?.fields);return}d(),console.log(` ${sn.default.dim("Opening browser")} ${v.arrow} ${b.url(i.url)}`),d(),Ze(i.url),console.log(` ${v.info} ${sn.default.dim("Complete your Pro upgrade in the browser.")}`),d()}X();var nn=F(W(),1);V();async function $o(t){let e=k(!t?.json);e.start("Cancelling subscription");let s=await j("/api/billing/cancel",{method:"POST"}),i=await s.json();if(!s.ok){e.stop("Failed"),i.code==="NOT_PRO"?h("You're not on the Pro plan.",{json:t?.json}):h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json});return}if(e.stop("Done"),t?.json){x(i,t?.fields);return}d();let n=i.cancel_at?new Date(i.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${v.success} ${nn.default.dim("Subscription cancelled.")} Access continues until ${nn.default.cyan(n)}.`),d()}X();var et=F(W(),1);V();ge();Ye();async function yo(t,e,s){t||(t=await me()),z(t,s);let i=[];if(e?.length&&i.push(...e),s.set&&i.push(...s.set.split(",").map(n=>n.trim()).filter(Boolean)),i.length>0||s.reset){await hc(t,i,s);return}await fc(t,s)}async function fc(t,e){let s=k(!e.json);s.start(`Fetching nameservers for ${b.domain(t)}`);let i=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`),n=await i.json();if(i.ok||(s.stop("Failed"),h(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),s.stop(`Nameservers for ${b.domain(t)}`),e.json){x(n,e.fields);return}if(d(),n.nameservers.length===0)console.log(` ${v.warning} ${et.default.yellow("No nameservers configured.")}`),console.log(` ${et.default.dim("DNS operations (parking, email, connect) will not work.")}`),d(),O("Set default nameservers:",`domani nameservers ${t} --reset`);else{C("Nameservers");for(let r of n.nameservers)console.log(` ${v.success} ${et.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(d(),console.log(` ${et.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(d(),g("Defaults",n.default_nameservers.map(r=>et.default.dim(r)).join(et.default.dim(", ")))),d()}async function hc(t,e,s){let i=k(!s.json);if(s.reset){i.start(`Fetching default nameservers for ${b.domain(t)}`);let o=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`),a=await o.json();o.ok||(i.stop("Failed"),h(a.error,{hint:a.hint,status:o.status,json:s.json,fields:s.fields})),a.default_nameservers?.length||(i.stop("No defaults"),h("No default nameservers available for this domain's registrar.",{code:"not_found",json:s.json,fields:s.fields})),e=a.default_nameservers,i.stop(`Using defaults: ${e.map(l=>et.default.cyan(l)).join(et.default.dim(", "))}`)}if(e.length<2&&h("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:s.json,fields:s.fields}),s.dryRun)return Y("nameservers_set",{domain:t,nameservers:e},s.json,s.fields);i.start(`Setting nameservers for ${b.domain(t)}`);let n=await j(`/api/domains/${encodeURIComponent(t)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:e})}),r=await n.json();if(n.ok||(i.stop("Failed"),h(r.error||r.message,{hint:r.hint,status:n.status,json:s.json,fields:s.fields})),i.stop(`${v.success} Nameservers updated`),s.json){x(r,s.fields);return}d();for(let o of r.nameservers)console.log(` ${v.success} ${et.default.cyan(o)}`);d(),console.log(` ${et.default.dim("Changes may take up to 48 hours to propagate.")}`),d(),O("Check propagation:",`domani status ${t}`),d()}var bo=require("crypto"),Ls=F(require("fs"),1);yt();var ns=F(W(),1);V();function pc(t,e){let s=t.split(".").map(Number),i=e.split(".").map(Number);for(let n=0;n<3;n++){if((s[n]||0)>(i[n]||0))return 1;if((s[n]||0)<(i[n]||0))return-1}return 0}async function vo(t){let e=k(!t?.json);e.start("Checking for updates");let s=Ke();try{let i=await fetch(`${s}/api/cli/version`);i.ok||(e.stop("Failed"),h("Could not check for updates"));let n=await i.json(),r=n.version,o=n.sha256;if(pc(r,ke)<=0){e.stop(`${v.success} Already up to date (v${ke})`),t?.json&&x({current:ke,latest:r,up_to_date:!0});return}if(t?.json){e.stop(""),x({current:ke,latest:r,up_to_date:!1,hint:"Run `domani update` to upgrade."});return}e.stop(`New version available: ${ns.default.cyan(ke)} ${v.arrow} ${ns.default.green(r)}`);let a=k();a.start("Downloading update");let l=`${s}/cli/domani.js`,c=await fetch(l);c.ok||(a.stop("Download failed"),h(`Failed to download from ${l}`));let u=await c.text();o&&(0,bo.createHash)("sha256").update(u).digest("hex")!==o&&(a.stop("Integrity check failed"),h("Downloaded file does not match expected hash - update aborted"));let f=process.argv[1];f||(a.stop("Failed"),h("Could not determine binary path"));let p=Ls.default.realpathSync(f),y=p+".tmp";Ls.default.writeFileSync(y,u,{mode:493}),Ls.default.renameSync(y,p),a.stop(`${v.success} Updated to v${r}`),d(),console.log(` ${ns.default.dim("Restart your terminal or run")} domani --version ${ns.default.dim("to verify")}`),d()}catch(i){h(`Update failed: ${i instanceof Error?i.message:String(i)}`)}}var Us=F(require("fs"),1),wo=F(require("path"),1),_o=F(require("os"),1);De();var rs=F(W(),1);V();async function So(){let t=process.argv[1],e=t?Us.default.realpathSync(t):null,s=wo.default.join(_o.default.homedir(),".domani");if(d(),console.log(` ${rs.default.bold("This will remove:")}`),e&&console.log(` ${v.dot} CLI binary: ${rs.default.dim(e)}`),console.log(` ${v.dot} Config dir: ${rs.default.dim(s)}`),d(),await Ge({message:"Uninstall domani?"})!==!0){console.log(` ${rs.default.dim("Cancelled.")}`);return}Us.default.rmSync(s,{recursive:!0,force:!0}),e&&Us.default.unlinkSync(e),d(),console.log(` ${v.success} domani uninstalled.`),d()}X();var ne=F(W(),1);V();async function ko(t,e){let s=e?.json,i=e?.fields,n=t?`/api/schema?command=${encodeURIComponent(t)}`:"/api/schema",r=k(!s);r.start("Loading schema");let o=await be(n),a=await o.json();if(o.ok||(r.stop("Failed"),h(a.error||a.message,{hint:a.hint,status:o.status,json:s,fields:i})),r.stop("Schema loaded"),s){x(a,i);return}t?$c(t,a):gc(a.commands)}function gc(t){C("Commands");let e=Object.entries(t).map(([s,i])=>[ne.default.bold(ne.default.cyan(s)),i.description]);de(["Command","Description"],e,[20,50]),d(),console.log(` ${ne.default.dim("Run")} ${ne.default.cyan("domani schema <command>")} ${ne.default.dim("for full details")}`),d()}function $c(t,e){if(C(`domani ${t}`),console.log(` ${e.description}`),d(),console.log(` ${b.label("Usage:")} ${ne.default.cyan(e.usage)}`),e.arguments&&Object.keys(e.arguments).length>0){d(),console.log(` ${ne.default.bold("Arguments")}`);for(let[s,i]of Object.entries(e.arguments)){let n=i.required?ne.default.red("*"):"",r=ne.default.dim(`(${i.type}${i.variadic?", variadic":""})`);console.log(` ${ne.default.cyan(s)}${n} ${r}`),i.description&&console.log(` ${ne.default.dim(i.description)}`)}}if(e.options&&Object.keys(e.options).length>0){d(),console.log(` ${ne.default.bold("Options")}`);for(let[s,i]of Object.entries(e.options)){let n=i.required?ne.default.red("*"):"",r=ne.default.dim(`(${i.type})`),o=i.choices?ne.default.dim(` [${i.choices.join(", ")}]`):"";console.log(` ${ne.default.cyan(`--${s}`)}${n} ${r}${o}`),console.log(` ${ne.default.dim(i.description)}`)}}if(e.api)if(d(),console.log(` ${ne.default.bold("API")}`),yc(e.api))xo(e.api);else for(let[s,i]of Object.entries(e.api))console.log(` ${ne.default.bold(ne.default.yellow(s))}`),xo(i,6);e.errors&&e.errors.length>0&&(d(),console.log(` ${ne.default.bold("Errors")}`),console.log(` ${e.errors.map(s=>ne.default.dim(s)).join(ne.default.dim(", "))}`)),d()}function yc(t){return typeof t=="object"&&t!==null&&"method"in t&&"path"in t}function xo(t,e=4){let s=" ".repeat(e);if(console.log(`${s}${ne.default.green(t.method)} ${ne.default.white(t.path)}`),t.parameters&&Object.keys(t.parameters).length>0)for(let[i,n]of Object.entries(t.parameters)){let r=n.required?ne.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=ne.default.dim(`(${o.join(", ")})`);console.log(`${s} ${ne.default.cyan(i)}${r} ${a}`),n.description&&console.log(`${s} ${ne.default.dim(n.description)}`)}}X();var Fe=F(W(),1);De();V();async function jo(t){let e=k(!t.json);e.start("Loading payment method");let s=await j("/api/me"),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t.json,fields:t.fields})),t.json){e.stop(""),x(i.card?{has_payment_method:i.has_payment_method,card:i.card}:{has_payment_method:!1},t.fields);return}if(!i.has_payment_method||!i.card){e.stop("No payment method on file"),d(),console.log(` ${Fe.default.dim("Add a card with")} ${Fe.default.cyan("domani card add")}`),d();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=i.card,l=`${String(o).padStart(2,"0")}/${a}`,c=n.charAt(0).toUpperCase()+n.slice(1);e.stop("Payment method loaded"),C("Payment method"),g("Card",`${Fe.default.bold(c)} \u2022\u2022\u2022\u2022 ${Fe.default.bold(r)}`),g("Expires",l),d(),console.log(` ${Fe.default.dim("Update with")} ${Fe.default.cyan("domani card add")}`),d()}async function Co(t){let e=k(!t?.json);e.start("Setting up payment session");let s=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),i.url||(e.stop("Failed"),h("No checkout URL returned",{json:t?.json})),e.stop("Checkout ready"),t?.json){x({url:i.url},t?.fields);return}d(),console.log(` ${Fe.default.dim("Opening browser")} ${v.arrow} ${b.url(i.url)}`),d(),Ze(i.url),console.log(` ${v.info} ${Fe.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Fe.default.dim(" After setup, you can purchase domains with")} ${Fe.default.cyan("domani buy")}`),d()}async function Oo(t){if(!t?.yes&&!t?.json){let n=await Ge({message:"Remove your saved payment method?"});if(ae(n)||!n){console.log(` ${Fe.default.dim("Cancelled.")}`);return}}let e=k(!t?.json);e.start("Removing payment method");let s=await j("/api/billing/card",{method:"DELETE"}),i=await s.json();if(s.ok||(e.stop("Failed"),h(i.error||i.message,{hint:i.hint,status:s.status,json:t?.json})),e.stop(`${v.success} Payment method removed`),t?.json){x({removed:!0},t?.fields);return}d(),console.log(` ${Fe.default.dim("Add a new card with")} ${Fe.default.cyan("domani card add")}`),d()}process.stdin.setMaxListeners(50);var H=new yn;H.name("domani").description(`Domain names for developers and AI agents - ${Lt}`).version(ke).option("--api-url <url>","Override API base URL").configureOutput({outputError:(t,e)=>{let s=t.replace(/^error:\s*/i,"").trimEnd();if(e(`${it.default.red("\u2717")} ${s}
221
+ `),/unknown option|missing required|expected argument/i.test(s)){let i=process.argv[2],n=i&&!i.startsWith("-")?`domani ${i} --help`:"domani --help";e(`${it.default.dim(` Run \`${n}\` to see available options.`)}
222
+ `)}}}).hook("preAction",async(t,e)=>{let s=t.opts();s.apiUrl&&Sn(s.apiUrl),process.stdout.isTTY||e.options.some(r=>r.long==="--json")&&e.setOptionValue("json",!0),["login","logout","search","suggest","tlds","whois","schema","update","uninstall"].includes(e.name())||await vr()});H.command("login").description(`Log in to ${Lt} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").addHelpText("after",`
223
223
  Examples:
224
224
  domani login # interactive login (opens browser)
225
225
  domani login --json # non-interactive (returns auth_url)
226
226
  domani login --no-open # print login URL without opening browser
227
- DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action($r);H.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(yr);H.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
227
+ DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(wr);H.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(_r);H.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
228
228
  Examples:
229
229
  domani me # show account overview
230
230
  domani me --json # machine-readable account info
231
- domani me --json --fields email,plan # just email and plan`).action(vr);H.command("invoices").description("List payment invoices").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--limit <n>","Max invoices to show (default 20)").action(oo);H.command("card [action]").description("Manage payment methods (list, add, remove)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--yes","Skip confirmation prompt (for remove)").action(async(t,e)=>{if(!t||t==="list")return bo(e);if(t==="add")return vo(e);if(t==="remove")return wo(e);h(`Unknown action: ${t}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});H.command("upgrade").description("Upgrade to Pro \u2014 10,000 emails/month, unlimited mailboxes, API/MCP/CLI access").option("--json","Output as JSON (returns checkout URL)").action(lo);H.command("cancel").description("Cancel Pro subscription (access continues until end of billing period)").option("--json","Output as JSON").action(co);H.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(ao);H.command("token").description("Print your API key").option("--json","Output as JSON").action(Jr);H.command("tokens [action]").description("Manage API tokens (list/create/revoke)").option("--name <name>","Token name (for create)").option("--scopes <scopes>","Comma-separated permission scopes (for create)").option("--expires-in <seconds>","Token lifetime in seconds (for create, min 3600)").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
231
+ domani me --json --fields email,plan # just email and plan`).action(xr);H.command("invoices").description("List payment invoices").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--limit <n>","Max invoices to show (default 20)").action(ho);H.command("card [action]").description("Manage payment methods (list, add, remove)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--yes","Skip confirmation prompt (for remove)").action(async(t,e)=>{if(!t||t==="list")return jo(e);if(t==="add")return Co(e);if(t==="remove")return Oo(e);h(`Unknown action: ${t}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});H.command("upgrade").description("Upgrade to Pro \u2014 10,000 emails/month, unlimited mailboxes, API/MCP/CLI access").option("--json","Output as JSON (returns checkout URL)").action(go);H.command("cancel").description("Cancel Pro subscription (access continues until end of billing period)").option("--json","Output as JSON").action($o);H.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(po);H.command("token").description("Print your API key").option("--json","Output as JSON").action(Kr);H.command("tokens [action]").description("Manage API tokens (list/create/revoke)").option("--name <name>","Token name (for create)").option("--scopes <scopes>","Comma-separated permission scopes (for create)").option("--expires-in <seconds>","Token lifetime in seconds (for create, min 3600)").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
232
232
  Examples:
233
233
  domani tokens list # list all tokens
234
234
  domani tokens create --name "CI" --scopes "domains:read,search"
235
- domani tokens revoke --token-id tok_abc123`).action(Br);H.command("search [domain] [tlds...]").description("Check availability - domani search myapp .io .fm .xyz").option("--tlds <tlds>","Comma-separated TLDs (e.g. com,io,dev)").option("--max-price <price>","Maximum price filter").option("--all","Show taken domains too").option("--expand","Check 30+ TLDs including creative/exotic extensions").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
235
+ domani tokens revoke --token-id tok_abc123`).action(zr);H.command("search [domain] [tlds...]").description("Check availability - domani search myapp .io .fm .xyz").option("--tlds <tlds>","Comma-separated TLDs (e.g. com,io,dev)").option("--max-price <price>","Maximum price filter").option("--all","Show taken domains too").option("--expand","Check 30+ TLDs including creative/exotic extensions").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
236
236
  Examples:
237
237
  domani search myapp # check popular TLDs
238
238
  domani search myapp .io .fm .xyz # specific TLDs
239
239
  domani search myapp --expand # check 30+ TLDs
240
240
  domani search myapp --max-price 20 # only affordable options
241
- domani search myapp --json # machine-readable output`).action(Nr);H.command("tlds").description("List all TLDs with pricing").option("--max-price <price>","Maximum registration price").option("--min-price <price>","Minimum registration price").option("--sort <field>","Sort by: price, tld, renewal (default: tld)").option("--search <term>","Filter TLDs by name").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Ur);H.command("whois <domain>").description("WHOIS/RDAP lookup for any domain").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Mr);H.command("suggest [prompt]").description("AI-powered domain name suggestions").option("--count <n>","Number of suggestions (1-20, default 10)").option("--tlds <tlds>","Preferred TLDs, comma-separated (e.g. com,dev,ai)").option("--style <style>","Name style: single, creative, short, brandable, keyword").option("--lang <lang>","Language inspiration: japanese, spanish, french, italian, latin, nordic, arabic, sanskrit").option("--timeout <seconds>","Request timeout in seconds (default: 60)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
241
+ domani search myapp --json # machine-readable output`).action(Mr);H.command("tlds").description("List all TLDs with pricing").option("--max-price <price>","Maximum registration price").option("--min-price <price>","Minimum registration price").option("--sort <field>","Sort by: price, tld, renewal (default: tld)").option("--search <term>","Filter TLDs by name").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Wr);H.command("whois <domain>").description("WHOIS/RDAP lookup for any domain").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Hr);H.command("suggest [prompt]").description("AI-powered domain name suggestions").option("--count <n>","Number of suggestions (1-20, default 10)").option("--tlds <tlds>","Preferred TLDs, comma-separated (e.g. com,dev,ai)").option("--style <style>","Name style: single, creative, short, brandable, keyword").option("--lang <lang>","Language inspiration: japanese, spanish, french, italian, latin, nordic, arabic, sanskrit").option("--timeout <seconds>","Request timeout in seconds (default: 60)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
242
242
  Examples:
243
243
  domani suggest "cat sitting marketplace"
244
244
  domani suggest "AI code editor" --style creative --tlds ai,dev
245
- domani suggest "meditation app" --lang japanese --count 5`).action(Vr);H.command("buy [domains...]").description("Purchase one or more domains").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
245
+ domani suggest "meditation app" --lang japanese --count 5`).action(Jr);H.command("buy [domains...]").description("Purchase one or more domains").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
246
246
  Examples:
247
247
  domani buy myapp.dev # buy one domain
248
248
  domani buy myapp.dev myapp.com myapp.ai # buy multiple
249
249
  domani buy myapp.dev --dry-run # preview without buying
250
250
  domani buy myapp.dev --yes # skip confirmation
251
- domani buy myapp.dev --json # machine-readable output`).action(zi);H.command("provision <domain>").description("Give an agent a full identity: domain + mailbox + webhook in one call").option("--slug <slug>","Mailbox local part (e.g. 'hi' for hi@domain). Default 'hi'").option("--name <name>","Display name for outbound email").option("--webhook <url>","HTTPS URL to receive inbound email + domain events").option("--years <n>","Registration years (1-10, default 1)").option("--payment-method <method>","card, usdc, or balance").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
251
+ domani buy myapp.dev --json # machine-readable output`).action(Qi);H.command("provision <domain>").description("Give an agent a full identity: domain + mailbox + webhook in one call").option("--slug <slug>","Mailbox local part (e.g. 'hi' for hi@domain). Default 'hi'").option("--name <name>","Display name for outbound email").option("--webhook <url>","HTTPS URL to receive inbound email + domain events").option("--years <n>","Registration years (1-10, default 1)").option("--payment-method <method>","card, usdc, or balance").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
252
252
  Examples:
253
253
  domani provision myagent.run # domain + hi@ mailbox
254
254
  domani provision myagent.run --slug hey --name "My Agent" # custom mailbox
255
255
  domani provision myagent.run --webhook https://me.dev/inbox # + inbound webhook
256
- domani provision myagent.run --dry-run # preview`).action(Fr);H.command("transfer <domain>").description("Transfer a domain from another registrar").option("--auth-code <code>","EPP/auth code from current registrar").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
256
+ domani provision myagent.run --dry-run # preview`).action(Vr);H.command("transfer <domain>").description("Transfer a domain from another registrar").option("--auth-code <code>","EPP/auth code from current registrar").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
257
257
  Examples:
258
258
  domani transfer myapp.com --auth-code ABC123XYZ
259
259
  domani transfer myapp.com --auth-code ABC123XYZ --dry-run
260
- domani transfer myapp.com --auth-code ABC123XYZ --yes`).action(qr);H.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Wr);H.command("import <domain>").description("Import a domain you own at another registrar").option("--verify","Verify DNS ownership and complete import").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
260
+ domani transfer myapp.com --auth-code ABC123XYZ --yes`).action(Br);H.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Gr);H.command("import <domain>").description("Import a domain you own at another registrar").option("--verify","Verify DNS ownership and complete import").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
261
261
  Examples:
262
262
  domani import myapp.com # start import (shows TXT record to add)
263
- domani import myapp.com --verify # verify TXT record and complete import`).action(Hr);H.command("sell <domain>").description("List a domain for sale (verify ownership via TXT record)").option("--price <amount>","Sale price in USD").option("--verify","Verify DNS ownership and activate listing").option("--transfer-code <code>","Submit transfer/auth code for an active deal").option("--cancel","Remove domain from sale").option("--status","Check listing status").option("--description <text>","Listing description").option("--yes","Skip confirmation").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
263
+ domani import myapp.com --verify # verify TXT record and complete import`).action(Yr);H.command("sell <domain>").description("List a domain for sale (verify ownership via TXT record)").option("--price <amount>","Sale price in USD").option("--verify","Verify DNS ownership and activate listing").option("--transfer-code <code>","Submit transfer/auth code for an active deal").option("--cancel","Remove domain from sale").option("--status","Check listing status").option("--description <text>","Listing description").option("--yes","Skip confirmation").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
264
264
  Examples:
265
265
  domani sell myapp.dev --price 5000 # list for $5,000
266
266
  domani sell myapp.dev --price 5000 --description "Great brand name"
@@ -268,16 +268,16 @@ Examples:
268
268
  domani sell external.com --verify # verify TXT record
269
269
  domani sell myapp.dev --status # check listing status
270
270
  domani sell myapp.dev --cancel # remove from sale
271
- domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(so);H.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
271
+ domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(oo);H.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
272
272
  Examples:
273
273
  domani list # list all domains
274
274
  domani domains # alias for list
275
- domani list --json --fields domain,expires_at`).action(Lr);H.command("status [domain]").description("Check domain health (DNS, SSL, email, expiry)").option("--timeout <seconds>","Request timeout in seconds (default: 30)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Gi);H.command("connect [domain] [target]").description("Connect domain to a hosting/email provider").option("--provider <name>","Provider name (e.g. vercel, google-workspace)").option("--method <name>","Connection method (e.g. cname-only)").option("--list","List available providers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
275
+ domani list --json --fields domain,expires_at`).action(qr);H.command("status [domain]").description("Check domain health (DNS, SSL, email, expiry)").option("--timeout <seconds>","Request timeout in seconds (default: 30)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(zi);H.command("connect [domain] [target]").description("Connect domain to a hosting/email provider").option("--provider <name>","Provider name (e.g. vercel, google-workspace)").option("--method <name>","Connection method (e.g. cname-only)").option("--list","List available providers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
276
276
  Examples:
277
277
  domani connect --list # list providers
278
278
  domani connect myapp.dev vercel # connect to Vercel
279
279
  domani connect myapp.dev --provider google-workspace # connect Google Workspace
280
- domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(Mi);H.command("email [action] [arg2]").description("Manage email: list, inbox, create, delete, send, forward, webhook, setup, status, check, connect").addHelpText("after",`
280
+ domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(Wi);H.command("email [action] [arg2]").description("Manage email: list, inbox, create, delete, send, forward, webhook, setup, status, check, connect").addHelpText("after",`
281
281
  Examples:
282
282
  domani email list # list all mailboxes
283
283
  domani email create --domain myapp.dev --slug hi # create hi@myapp.dev
@@ -285,41 +285,52 @@ Examples:
285
285
  domani email send --from hi@myapp.dev --to bob@x.com --subject "Hello" --text "Hi Bob"
286
286
  domani email setup myapp.dev # setup email for domain
287
287
  domani email status myapp.dev # check email DNS health
288
- domani email delete --domain myapp.dev --slug hi # delete mailbox`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--from <email>","Sender address user@domain (alternative to --domain + --slug)").option("--to <email>","Recipient email address (for send)").option("--cc <emails>","CC recipients, comma-separated (for send)").option("--bcc <emails>","BCC recipients, comma-separated (for send)").option("--subject <s>","Email subject (for send)").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text (for send)").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to (for threading)").option("--references <message-ids>","Space-separated Message-ID chain (for threading)").option("--url <url>","Webhook URL (for webhook)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--check","Verify email DNS health (MX, SPF, DKIM, DMARC)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Qt);H.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/delete/snapshot/restore)").option("--type <type>","Record type: A, AAAA, CNAME, MX, TXT, NS, SRV").option("--name <name>","Record name (e.g. www, @, _dmarc)").option("--value <value>","Record value").option("--file <path>","Snapshot file path (for restore)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
288
+ domani email delete --domain myapp.dev --slug hi # delete mailbox`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--from <email>","Sender address user@domain (alternative to --domain + --slug)").option("--to <email>","Recipient email address (for send)").option("--cc <emails>","CC recipients, comma-separated (for send)").option("--bcc <emails>","BCC recipients, comma-separated (for send)").option("--subject <s>","Email subject (for send)").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text (for send)").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to (for threading)").option("--references <message-ids>","Space-separated Message-ID chain (for threading)").option("--url <url>","Webhook URL (for webhook)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--check","Verify email DNS health (MX, SPF, DKIM, DMARC)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(es);H.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/delete/snapshot/restore)").option("--type <type>","Record type: A, AAAA, CNAME, MX, TXT, NS, SRV").option("--name <name>","Record name (e.g. www, @, _dmarc)").option("--value <value>","Record value").option("--file <path>","Snapshot file path (for restore)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
289
289
  Examples:
290
290
  domani dns myapp.dev get # list all records
291
291
  domani dns myapp.dev set --type A --name @ --value 76.76.21.21 # add A record
292
292
  domani dns myapp.dev set --type CNAME --name www --value cname.vercel-dns.com
293
293
  domani dns myapp.dev delete --type A --name @
294
294
  domani dns myapp.dev snapshot # export DNS as JSON
295
- domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(Ji);H.command("nameservers [domain] [ns...]").alias("ns").description("Get or set nameservers (--reset for defaults)").option("--set <ns>","Comma-separated nameservers to set").option("--reset","Reset to registrar default nameservers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(uo);H.command("settings [domain]").description("View or update domain settings (auto-renew, WHOIS privacy, security lock)").option("--auto-renew <on|off>","Enable or disable auto-renew").option("--whois-privacy <on|off>","Enable or disable WHOIS privacy").option("--security-lock <on|off>","Lock or unlock domain transfers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
295
+ domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(Yi);H.command("nameservers [domain] [ns...]").alias("ns").description("Get or set nameservers (--reset for defaults)").option("--set <ns>","Comma-separated nameservers to set").option("--reset","Reset to registrar default nameservers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(yo);H.command("settings [domain]").description("View or update domain settings (auto-renew, WHOIS privacy, security lock)").option("--auto-renew <on|off>","Enable or disable auto-renew").option("--whois-privacy <on|off>","Enable or disable WHOIS privacy").option("--security-lock <on|off>","Lock or unlock domain transfers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
296
296
  Examples:
297
297
  domani settings myapp.dev # view current settings
298
298
  domani settings myapp.dev --auto-renew on # enable auto-renew
299
299
  domani settings myapp.dev --whois-privacy on # enable WHOIS privacy
300
- domani settings myapp.dev --security-lock off # unlock for transfer`).action(Gr);H.command("auth-code [domain]").description("Get EPP auth code to transfer domain to another registrar").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Yr);H.command("transfer-away [domain]").description("Check status of an outbound domain transfer").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Kr);H.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
300
+ domani settings myapp.dev --security-lock off # unlock for transfer`).action(Xr);H.command("auth-code [domain]").description("Get EPP auth code to transfer domain to another registrar").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Zr);H.command("transfer-away [domain]").description("Check status of an outbound domain transfer").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Qr);H.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
301
301
  Examples:
302
302
  domani contact # view current contact info
303
303
  domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
304
- --city "San Francisco" --state CA --postal-code 94102 --country US --phone +1.5551234567 --email john@example.com`).option("--first-name <name>","First name (for set)").option("--last-name <name>","Last name (for set)").option("--org-name <name>","Organization name (for set, optional)").option("--address1 <addr>","Address line 1 (for set)").option("--address2 <addr>","Address line 2 (for set, optional)").option("--city <city>","City (for set)").option("--state <state>","State/Province (for set)").option("--postal-code <code>","Postal/ZIP code (for set)").option("--country <code>","Country code ISO 3166-1 alpha-2 (for set)").option("--phone <phone>","Phone +CC.NUMBER (for set)").option("--email <email>","Contact email (for set)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(zr);H.command("parking [domain] [action] [value]").description("Manage parking page (enable/disable/price)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
304
+ --city "San Francisco" --state CA --postal-code 94102 --country US --phone +1.5551234567 --email john@example.com`).option("--first-name <name>","First name (for set)").option("--last-name <name>","Last name (for set)").option("--org-name <name>","Organization name (for set, optional)").option("--address1 <addr>","Address line 1 (for set)").option("--address2 <addr>","Address line 2 (for set, optional)").option("--city <city>","City (for set)").option("--state <state>","State/Province (for set)").option("--postal-code <code>","Postal/ZIP code (for set)").option("--country <code>","Country code ISO 3166-1 alpha-2 (for set)").option("--phone <phone>","Phone +CC.NUMBER (for set)").option("--email <email>","Contact email (for set)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(eo);H.command("parking [domain] [action] [value]").description("Manage parking page (enable/disable/price)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
305
305
  Examples:
306
306
  domani parking myapp.dev # view parking status
307
307
  domani parking myapp.dev enable # enable parking page
308
308
  domani parking myapp.dev disable # disable parking page
309
- domani parking myapp.dev price 500 # set for-sale price to $500`).action(Qr);H.command("analytics [domain]").alias("stats").description("View parking analytics (views, inquiries, conversion)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(eo);H.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/events)").addHelpText("after",`
309
+ domani parking myapp.dev price 500 # set for-sale price to $500`).action(io);H.command("analytics [domain]").alias("stats").description("View parking analytics (views, inquiries, conversion)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(no);H.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/events)").addHelpText("after",`
310
310
  Examples:
311
311
  domani webhooks list
312
312
  domani webhooks create --url https://example.com/hook --events domain.purchased,domain.expiring
313
313
  domani webhooks update --webhook-id wh_abc --active off
314
314
  domani webhooks delete --webhook-id wh_abc
315
315
  domani webhooks deliveries --webhook-id wh_abc
316
- domani webhooks events # list available event types`).option("--url <url>","Webhook HTTPS URL").option("--events <events>","Comma-separated event types").option("--webhook-id <id>","Webhook ID (for update/delete/deliveries)").option("--active <on|off>","Enable or disable webhook").option("--limit <n>","Limit deliveries returned").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(to);H.command("deals [id]").description("List marketplace deals or view deal details").option("--role <role>","Filter by role: buyer or seller").option("--status <status>","Filter by status: active, completed, or all").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
316
+ domani webhooks events # list available event types`).option("--url <url>","Webhook HTTPS URL").option("--events <events>","Comma-separated event types").option("--webhook-id <id>","Webhook ID (for update/delete/deliveries)").option("--active <on|off>","Enable or disable webhook").option("--limit <n>","Limit deliveries returned").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ro);H.command("deals [id]").description("List marketplace deals or view deal details").option("--role <role>","Filter by role: buyer or seller").option("--status <status>","Filter by status: active, completed, or all").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
317
317
  Examples:
318
318
  domani deals # list all your deals
319
319
  domani deals --role seller --status active # your active sales
320
320
  domani deals deal_abc123 # view specific deal
321
- domani deals --json # machine-readable output`).action(io);H.command("notifications").alias("notifs").description("View notifications or mark all as read").option("--read","Mark all notifications as read").option("--unread","Show only unread notifications").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ro);H.command("send [arg2]").description("Send an email - shortcut for: domani email send").option("--from <email>","Sender address user@domain").option("--to <email>","Recipient email address").option("--cc <emails>","CC recipients, comma-separated").option("--bcc <emails>","BCC recipients, comma-separated").option("--subject <s>","Email subject").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to").option("--references <message-ids>","Space-separated Message-ID chain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((t,e)=>Qt("send",t,e));H.command("inbox [arg2]").description("View email inbox - shortcut for: domani email inbox").option("--from <email>","Sender address user@domain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((t,e)=>Qt("inbox",t,e));H.command("schema [command]").description("Show command schemas for AI agent integration").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(yo);H.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").action(fo);H.command("uninstall").description("Remove domani CLI and config from this machine").action(go);(async()=>{let t=_n();await H.parseAsync();let e=await t;e?.forced?(console.error(`
322
- ${st.default.red("!")} CLI v${ke} is no longer supported. Run ${st.default.bold("domani update")} to upgrade to v${e.update}
321
+ domani deals --json # machine-readable output`).action(ao);H.command("broker [action] [arg]").description("Acquire a taken, unlisted domain (broker sources + negotiates on your behalf)").option("--max-budget <amount>","Your ceiling in USD for a request").option("--status <status>","Filter the list by status").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
322
+ Actions:
323
+ request <domain> ask domani to acquire a taken domain (commission-only)
324
+ list (default) list your acquisition requests
325
+ status <id> view one request's progress
326
+ cancel <id> cancel an active request
327
+
328
+ Examples:
329
+ domani broker request dream.com --max-budget 5000
330
+ domani broker # list your requests
331
+ domani broker status brq_abc123
332
+ domani broker cancel brq_abc123`).action((t,e,s)=>uo(t,e,s));H.command("notifications").alias("notifs").description("View notifications or mark all as read").option("--read","Mark all notifications as read").option("--unread","Show only unread notifications").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(fo);H.command("send [arg2]").description("Send an email - shortcut for: domani email send").option("--from <email>","Sender address user@domain").option("--to <email>","Recipient email address").option("--cc <emails>","CC recipients, comma-separated").option("--bcc <emails>","BCC recipients, comma-separated").option("--subject <s>","Email subject").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to").option("--references <message-ids>","Space-separated Message-ID chain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((t,e)=>es("send",t,e));H.command("inbox [arg2]").description("View email inbox - shortcut for: domani email inbox").option("--from <email>","Sender address user@domain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((t,e)=>es("inbox",t,e));H.command("schema [command]").description("Show command schemas for AI agent integration").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ko);H.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").action(vo);H.command("uninstall").description("Remove domani CLI and config from this machine").action(So);(async()=>{let t=jn();await H.parseAsync();let e=await t;e?.forced?(console.error(`
333
+ ${it.default.red("!")} CLI v${ke} is no longer supported. Run ${it.default.bold("domani update")} to upgrade to v${e.update}
323
334
  `),process.exit(1)):e?.update&&console.error(`
324
- ${st.default.yellow("!")} Update available: ${st.default.dim(ke)} ${st.default.dim("\u2192")} ${st.default.green(e.update)} Run ${st.default.bold("domani update")}
335
+ ${it.default.yellow("!")} Update available: ${it.default.dim(ke)} ${it.default.dim("\u2192")} ${it.default.green(e.update)} Run ${it.default.bold("domani update")}
325
336
  `)})();