domani-cli 0.4.89 → 0.4.90

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 +172 -166
  2. package/package.json +1 -1
package/dist/domani.cjs CHANGED
@@ -1,227 +1,227 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Wd=Object.create;var Xi=Object.defineProperty;var Hd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Bd=Object.getPrototypeOf,Gd=Object.prototype.hasOwnProperty;var je=(e,t)=>()=>(e&&(t=e(e=0)),t);var _t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),mn=(e,t)=>{for(var n in t)Xi(e,n,{get:t[n],enumerable:!0})},Kd=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Jd(t))!Gd.call(e,s)&&s!==n&&Xi(e,s,{get:()=>t[s],enumerable:!(i=Hd(t,s))||i.enumerable});return e};var N=(e,t,n)=>(n=e!=null?Wd(Bd(e)):{},Kd(t||!e||!e.__esModule?Xi(n,"default",{value:e,enumerable:!0}):n,e));var Sn=_t(Qi=>{var ti=class extends Error{constructor(t,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},Zi=class extends ti{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Qi.CommanderError=ti;Qi.InvalidArgumentError=Zi});var ni=_t(ts=>{var{InvalidArgumentError:zd}=Sn(),es=class{constructor(t,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new zd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Yd(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}ts.Argument=es;ts.humanReadableArgName=Yd});var ss=_t(is=>{var{humanReadableArgName:Xd}=ni(),ns=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let n=t.commands.filter(s=>!s._hidden),i=t._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((s,r)=>s.name().localeCompare(r.name())),n}compareOptions(t,n){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(t).localeCompare(i(n))}visibleOptions(t){let n=t.options.filter(s=>!s.hidden),i=t._getHelpOption();if(i&&!i.hidden){let s=i.short&&t._findOption(i.short),r=i.long&&t._findOption(i.long);!s&&!r?n.push(i):i.long&&!r?n.push(t.createOption(i.long,i.description)):i.short&&!s&&n.push(t.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let i=t.parent;i;i=i.parent){let s=i.options.filter(r=>!r.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(n=>{n.description=n.description||t._argsDescription[n.name()]||""}),t.registeredArguments.find(n=>n.description)?t.registeredArguments:[]}subcommandTerm(t){let n=t.registeredArguments.map(i=>Xd(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,n){return n.visibleCommands(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(s)))),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(s)))),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let i="";for(let s=t.parent;s;s=s.parent)i=s.name()+" "+i;return i+n+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let n=[];return t.argChoices&&n.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&n.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&n.push(`env: ${t.envVar}`),n.length>0?`${t.description} (${n.join(", ")})`:t.description}argumentDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatHelp(t,n){let i=n.padWidth(t,n),s=n.helpWidth??80;function r(p,g){return n.formatItem(p,i,g,n)}let o=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(t))}`,""],a=n.commandDescription(t);a.length>0&&(o=o.concat([n.boxWrap(n.styleCommandDescription(a),s),""]));let d=n.visibleArguments(t).map(p=>r(n.styleArgumentTerm(n.argumentTerm(p)),n.styleArgumentDescription(n.argumentDescription(p))));d.length>0&&(o=o.concat([n.styleTitle("Arguments:"),...d,""]));let m=n.visibleOptions(t).map(p=>r(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));if(m.length>0&&(o=o.concat([n.styleTitle("Options:"),...m,""])),n.showGlobalOptions){let p=n.visibleGlobalOptions(t).map(g=>r(n.styleOptionTerm(n.optionTerm(g)),n.styleOptionDescription(n.optionDescription(g))));p.length>0&&(o=o.concat([n.styleTitle("Global Options:"),...p,""]))}let f=n.visibleCommands(t).map(p=>r(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));return f.length>0&&(o=o.concat([n.styleTitle("Commands:"),...f,""])),o.join(`
3
- `)}displayWidth(t){return Pr(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,n){return Math.max(n.longestOptionTermLength(t,n),n.longestGlobalOptionTermLength(t,n),n.longestSubcommandTermLength(t,n),n.longestArgumentTermLength(t,n))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,n,i,s){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(n+t.length-s.displayWidth(t)),d=2,f=(this.helpWidth??80)-n-d-2,p;return f<this.minWidthToWrap||s.preformatted(i)?p=i:p=s.boxWrap(i,f).replace(/\n/g,`
2
+ "use strict";var il=Object.create;var es=Object.defineProperty;var sl=Object.getOwnPropertyDescriptor;var rl=Object.getOwnPropertyNames;var ol=Object.getPrototypeOf,al=Object.prototype.hasOwnProperty;var _e=(e,t)=>()=>(e&&(t=e(e=0)),t);var _t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fn=(e,t)=>{for(var n in t)es(e,n,{get:t[n],enumerable:!0})},dl=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rl(t))!al.call(e,s)&&s!==n&&es(e,s,{get:()=>t[s],enumerable:!(i=sl(t,s))||i.enumerable});return e};var N=(e,t,n)=>(n=e!=null?il(ol(e)):{},dl(t||!e||!e.__esModule?es(n,"default",{value:e,enumerable:!0}):n,e));var Cn=_t(ns=>{var ii=class extends Error{constructor(t,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},ts=class extends ii{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ns.CommanderError=ii;ns.InvalidArgumentError=ts});var si=_t(ss=>{var{InvalidArgumentError:ll}=Cn(),is=class{constructor(t,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new ll(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function cl(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}ss.Argument=is;ss.humanReadableArgName=cl});var as=_t(os=>{var{humanReadableArgName:ul}=si(),rs=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let n=t.commands.filter(s=>!s._hidden),i=t._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((s,r)=>s.name().localeCompare(r.name())),n}compareOptions(t,n){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(t).localeCompare(i(n))}visibleOptions(t){let n=t.options.filter(s=>!s.hidden),i=t._getHelpOption();if(i&&!i.hidden){let s=i.short&&t._findOption(i.short),r=i.long&&t._findOption(i.long);!s&&!r?n.push(i):i.long&&!r?n.push(t.createOption(i.long,i.description)):i.short&&!s&&n.push(t.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let i=t.parent;i;i=i.parent){let s=i.options.filter(r=>!r.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(n=>{n.description=n.description||t._argsDescription[n.name()]||""}),t.registeredArguments.find(n=>n.description)?t.registeredArguments:[]}subcommandTerm(t){let n=t.registeredArguments.map(i=>ul(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,n){return n.visibleCommands(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(s)))),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(s)))),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let i="";for(let s=t.parent;s;s=s.parent)i=s.name()+" "+i;return i+n+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let n=[];return t.argChoices&&n.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&n.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&n.push(`env: ${t.envVar}`),n.length>0?`${t.description} (${n.join(", ")})`:t.description}argumentDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatHelp(t,n){let i=n.padWidth(t,n),s=n.helpWidth??80;function r(p,g){return n.formatItem(p,i,g,n)}let o=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(t))}`,""],a=n.commandDescription(t);a.length>0&&(o=o.concat([n.boxWrap(n.styleCommandDescription(a),s),""]));let d=n.visibleArguments(t).map(p=>r(n.styleArgumentTerm(n.argumentTerm(p)),n.styleArgumentDescription(n.argumentDescription(p))));d.length>0&&(o=o.concat([n.styleTitle("Arguments:"),...d,""]));let m=n.visibleOptions(t).map(p=>r(n.styleOptionTerm(n.optionTerm(p)),n.styleOptionDescription(n.optionDescription(p))));if(m.length>0&&(o=o.concat([n.styleTitle("Options:"),...m,""])),n.showGlobalOptions){let p=n.visibleGlobalOptions(t).map(g=>r(n.styleOptionTerm(n.optionTerm(g)),n.styleOptionDescription(n.optionDescription(g))));p.length>0&&(o=o.concat([n.styleTitle("Global Options:"),...p,""]))}let f=n.visibleCommands(t).map(p=>r(n.styleSubcommandTerm(n.subcommandTerm(p)),n.styleSubcommandDescription(n.subcommandDescription(p))));return f.length>0&&(o=o.concat([n.styleTitle("Commands:"),...f,""])),o.join(`
3
+ `)}displayWidth(t){return Mr(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,n){return Math.max(n.longestOptionTermLength(t,n),n.longestGlobalOptionTermLength(t,n),n.longestSubcommandTermLength(t,n),n.longestArgumentTermLength(t,n))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,n,i,s){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(n+t.length-s.displayWidth(t)),d=2,f=(this.helpWidth??80)-n-d-2,p;return f<this.minWidthToWrap||s.preformatted(i)?p=i:p=s.boxWrap(i,f).replace(/\n/g,`
4
4
  `+" ".repeat(n+d)),o+a+" ".repeat(d)+p.replace(/\n/g,`
5
5
  ${o}`)}boxWrap(t,n){if(n<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,r=[];return i.forEach(o=>{let a=o.match(s);if(a===null){r.push("");return}let d=[a.shift()],m=this.displayWidth(d[0]);a.forEach(f=>{let p=this.displayWidth(f);if(m+p<=n){d.push(f),m+=p;return}r.push(d.join(""));let g=f.trimStart();d=[g],m=this.displayWidth(g)}),r.push(d.join(""))}),r.join(`
6
- `)}};function Pr(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}is.Help=ns;is.stripColor=Pr});var ds=_t(as=>{var{InvalidArgumentError:Zd}=Sn(),rs=class{constructor(t,n){this.flags=t,this.description=n||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=Qd(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let n=t;return typeof t=="string"&&(n={[t]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new Zd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Dr(this.name().replace(/^no-/,"")):Dr(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},os=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let s=this.negativeOptions.get(i).presetArg,r=s!==void 0?s:!1;return n.negate===(r===t)}};function Dr(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Qd(e){let t,n,i=/^-[^-]$/,s=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(t=r.shift()),s.test(r[0])&&(n=r.shift()),!t&&i.test(r[0])&&(t=r.shift()),!t&&s.test(r[0])&&(t=n,n=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${e}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
6
+ `)}};function Mr(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}os.Help=rs;os.stripColor=Mr});var us=_t(cs=>{var{InvalidArgumentError:ml}=Cn(),ds=class{constructor(t,n){this.flags=t,this.description=n||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=fl(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let n=t;return typeof t=="string"&&(n={[t]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,i)=>{if(!this.argChoices.includes(n))throw new ml(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Fr(this.name().replace(/^no-/,"")):Fr(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ls=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let s=this.negativeOptions.get(i).presetArg,r=s!==void 0?s:!1;return n.negate===(r===t)}};function Fr(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function fl(e){let t,n,i=/^-[^-]$/,s=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(t=r.shift()),s.test(r[0])&&(n=r.shift()),!t&&i.test(r[0])&&(t=r.shift()),!t&&s.test(r[0])&&(t=n,n=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${e}'`;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`):s.test(o)?new Error(`${a}
11
11
  - too many long flags`):new Error(`${a}
12
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}as.Option=rs;as.DualOptions=os});var Ur=_t(Nr=>{function el(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let i=0;i<=e.length;i++)n[i]=[i];for(let i=0;i<=t.length;i++)n[0][i]=i;for(let i=1;i<=t.length;i++)for(let s=1;s<=e.length;s++){let r=1;e[s-1]===t[i-1]?r=0:r=1,n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r),s>1&&i>1&&e[s-1]===t[i-2]&&e[s-2]===t[i-1]&&(n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1))}return n[e.length][t.length]}function tl(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let i=[],s=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=el(e,o),d=Math.max(e.length,o.length);(d-a)/d>r&&(a<s?(s=a,i=[o]):a===s&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),n&&(i=i.map(o=>`--${o}`)),i.length>1?`
12
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}cs.Option=ds;cs.DualOptions=ls});var Vr=_t(Lr=>{function pl(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let i=0;i<=e.length;i++)n[i]=[i];for(let i=0;i<=t.length;i++)n[0][i]=i;for(let i=1;i<=t.length;i++)for(let s=1;s<=e.length;s++){let r=1;e[s-1]===t[i-1]?r=0:r=1,n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r),s>1&&i>1&&e[s-1]===t[i-2]&&e[s-2]===t[i-1]&&(n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1))}return n[e.length][t.length]}function hl(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let i=[],s=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=pl(e,o),d=Math.max(e.length,o.length);(d-a)/d>r&&(a<s?(s=a,i=[o]):a===s&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),n&&(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]}?)`:""}Nr.suggestSimilar=tl});var Lr=_t(fs=>{var nl=require("node:events").EventEmitter,ls=require("node:child_process"),kt=require("node:path"),ii=require("node:fs"),se=require("node:process"),{Argument:il,humanReadableArgName:sl}=ni(),{CommanderError:cs}=Sn(),{Help:rl,stripColor:ol}=ss(),{Option:qr,DualOptions:al}=ds(),{suggestSimilar:Mr}=Ur(),us=class e extends nl{constructor(t){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=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>se.stdout.write(n),writeErr:n=>se.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,getOutHasColors:()=>ms()??(se.stdout.isTTY&&se.stdout.hasColors?.()),getErrHasColors:()=>ms()??(se.stderr.isTTY&&se.stderr.hasColors?.()),stripColor:n=>ol(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let n=this;n;n=n.parent)t.push(n);return t}command(t,n,i){let s=n,r=i;typeof s=="object"&&s!==null&&(r=s,s=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),d=this.createCommand(o);return s&&(d.description(s),d._executableHandler=!0),r.isDefault&&(this._defaultCommandName=d._name),d._hidden=!!(r.noHelp||r.hidden),d._executableFile=r.executableFile||null,a&&d.arguments(a),this._registerCommand(d),d.parent=this,d.copyInheritedSettings(this),s?this:d}createCommand(t){return new e(t)}createHelp(){return Object.assign(new rl,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,n){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new il(t,n)}argument(t,n,i,s){let r=this.createArgument(t,n);return typeof i=="function"?r.default(s).argParser(i):r.default(i),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(t){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,n){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,i,s]=t.match(/([^ ]+) *(.*)/),r=n??"display help for command",o=this.createCommand(i);return o.helpOption(!1),s&&o.arguments(s),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,n){return typeof t!="object"?(this.helpCommand(t,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,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(t,n){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
16
- Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,i){this._exitCallback&&this._exitCallback(new cs(t,n,i)),se.exit(t)}action(t){let n=i=>{let s=this.registeredArguments.length,r=i.slice(0,s);return this._storeOptionsAsProperties?r[s]=this:r[s]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=n,this}createOption(t,n){return new qr(t,n)}_callParseArg(t,n,i,s){try{return t.parseArg(n,i)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${s} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
17
- - already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=s=>[s.name()].concat(s.aliases()),i=n(t).find(s=>this._findCommand(s));if(i){let s=n(this._findCommand(i)).join("|"),r=n(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),i=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let s=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let d=this.getOptionValue(i);r!==null&&t.parseArg?r=this._callParseArg(t,r,d,o):r!==null&&t.variadic&&(r=t._concatValue(r,d)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,a)};return this.on("option:"+n,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;s(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+n,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;s(r,o,"env")}),this}_optionEx(t,n,i,s,r){if(typeof n=="object"&&n instanceof qr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,i);if(o.makeOptionMandatory(!!t.mandatory),typeof s=="function")o.default(r).argParser(s);else if(s instanceof RegExp){let a=s;s=(d,m)=>{let f=a.exec(d);return f?f[0]:m},o.default(r).argParser(s)}else o.default(s);return this.addOption(o)}option(t,n,i,s){return this._optionEx({},t,n,i,s)}requiredOption(t,n,i,s){return this._optionEx({mandatory:!0},t,n,i,s)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,n){return this.setOptionValueWithSource(t,n,void 0)}setOptionValueWithSource(t,n,i){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(n=i.getOptionValueSource(t))}),n}_prepareUserArgs(t,n){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},t===void 0&&n.from===void 0){se.versions?.electron&&(n.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}t===void 0&&(t=se.argv),this.rawArgs=t.slice();let i;switch(n.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,n){this._prepareForParse();let i=this._prepareUserArgs(t,n);return this._parseCommand([],i),this}async parseAsync(t,n){this._prepareForParse();let i=this._prepareUserArgs(t,n);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(t,n,i){if(ii.existsSync(t))return;let s=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${t}' does not exist
14
+ (Did you mean ${i[0]}?)`:""}Lr.suggestSimilar=hl});var Br=_t(gs=>{var gl=require("node:events").EventEmitter,ms=require("node:child_process"),xt=require("node:path"),ri=require("node:fs"),se=require("node:process"),{Argument:yl,humanReadableArgName:bl}=si(),{CommanderError:fs}=Cn(),{Help:wl,stripColor:vl}=as(),{Option:Wr,DualOptions:$l}=us(),{suggestSimilar:Hr}=Vr(),ps=class e extends gl{constructor(t){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=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>se.stdout.write(n),writeErr:n=>se.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,getOutHasColors:()=>hs()??(se.stdout.isTTY&&se.stdout.hasColors?.()),getErrHasColors:()=>hs()??(se.stderr.isTTY&&se.stderr.hasColors?.()),stripColor:n=>vl(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let n=this;n;n=n.parent)t.push(n);return t}command(t,n,i){let s=n,r=i;typeof s=="object"&&s!==null&&(r=s,s=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),d=this.createCommand(o);return s&&(d.description(s),d._executableHandler=!0),r.isDefault&&(this._defaultCommandName=d._name),d._hidden=!!(r.noHelp||r.hidden),d._executableFile=r.executableFile||null,a&&d.arguments(a),this._registerCommand(d),d.parent=this,d.copyInheritedSettings(this),s?this:d}createCommand(t){return new e(t)}createHelp(){return Object.assign(new wl,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,n){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new yl(t,n)}argument(t,n,i,s){let r=this.createArgument(t,n);return typeof i=="function"?r.default(s).argParser(i):r.default(i),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(t){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,n){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,i,s]=t.match(/([^ ]+) *(.*)/),r=n??"display help for command",o=this.createCommand(i);return o.helpOption(!1),s&&o.arguments(s),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,n){return typeof t!="object"?(this.helpCommand(t,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,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(t,n){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
16
+ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,i){this._exitCallback&&this._exitCallback(new fs(t,n,i)),se.exit(t)}action(t){let n=i=>{let s=this.registeredArguments.length,r=i.slice(0,s);return this._storeOptionsAsProperties?r[s]=this:r[s]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=n,this}createOption(t,n){return new Wr(t,n)}_callParseArg(t,n,i,s){try{return t.parseArg(n,i)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${s} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
17
+ - already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=s=>[s.name()].concat(s.aliases()),i=n(t).find(s=>this._findCommand(s));if(i){let s=n(this._findCommand(i)).join("|"),r=n(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),i=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(i,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let s=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let d=this.getOptionValue(i);r!==null&&t.parseArg?r=this._callParseArg(t,r,d,o):r!==null&&t.variadic&&(r=t._concatValue(r,d)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(i,r,a)};return this.on("option:"+n,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;s(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+n,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;s(r,o,"env")}),this}_optionEx(t,n,i,s,r){if(typeof n=="object"&&n instanceof Wr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,i);if(o.makeOptionMandatory(!!t.mandatory),typeof s=="function")o.default(r).argParser(s);else if(s instanceof RegExp){let a=s;s=(d,m)=>{let f=a.exec(d);return f?f[0]:m},o.default(r).argParser(s)}else o.default(s);return this.addOption(o)}option(t,n,i,s){return this._optionEx({},t,n,i,s)}requiredOption(t,n,i,s){return this._optionEx({mandatory:!0},t,n,i,s)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!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=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,n){return this.setOptionValueWithSource(t,n,void 0)}setOptionValueWithSource(t,n,i){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(n=i.getOptionValueSource(t))}),n}_prepareUserArgs(t,n){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},t===void 0&&n.from===void 0){se.versions?.electron&&(n.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}t===void 0&&(t=se.argv),this.rawArgs=t.slice();let i;switch(n.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,n){this._prepareForParse();let i=this._prepareUserArgs(t,n);return this._parseCommand([],i),this}async parseAsync(t,n){this._prepareForParse();let i=this._prepareUserArgs(t,n);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(t,n,i){if(ri.existsSync(t))return;let s=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${t}' 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
- - ${s}`;throw new Error(r)}_executeSubCommand(t,n){n=n.slice();let i=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function r(f,p){let g=kt.resolve(f,p);if(ii.existsSync(g))return g;if(s.includes(kt.extname(p)))return;let $=s.find(k=>ii.existsSync(`${g}${k}`));if($)return`${g}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=ii.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=kt.resolve(kt.dirname(f),a)}if(a){let f=r(a,o);if(!f&&!t._executableFile&&this._scriptPath){let p=kt.basename(this._scriptPath,kt.extname(this._scriptPath));p!==this._name&&(f=r(a,`${p}-${t._name}`))}o=f||o}i=s.includes(kt.extname(o));let d;se.platform!=="win32"?i?(n.unshift(o),n=Fr(se.execArgv).concat(n),d=ls.spawn(se.argv[0],n,{stdio:"inherit"})):d=ls.spawn(o,n,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),n.unshift(o),n=Fr(se.execArgv).concat(n),d=ls.spawn(se.execPath,n,{stdio:"inherit"})),d.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{se.on(p,()=>{d.killed===!1&&d.exitCode===null&&d.kill(p)})});let m=this._exitCallback;d.on("close",f=>{f=f??1,m?m(new cs(f,"commander.executeSubCommandAsync","(close)")):se.exit(f)}),d.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!m)se.exit(1);else{let p=new cs(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,m(p)}}),this.runningCommand=d}_dispatchSubcommand(t,n,i){let s=this._findCommand(t);s||this.help({error:!0}),s._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,s,"preSubcommand"),r=this._chainOrCall(r,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(i));else return s._parseCommand(n,i)}),r}_dispatchHelpCommand(t){t||this.help();let n=this._findCommand(t);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,n)=>{t.required&&this.args[n]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,s,r)=>{let o=s;if(s!==null&&i.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,s,r,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((i,s)=>{let r=i.defaultValue;i.variadic?s<this.args.length?(r=this.args.slice(s),i.parseArg&&(r=r.reduce((o,a)=>t(i,a,o),i.defaultValue))):r===void 0&&(r=[]):s<this.args.length&&(r=this.args[s],i.parseArg&&(r=t(i,r,i.defaultValue))),n[s]=r}),this.processedArgs=n}_chainOrCall(t,n){return t&&t.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let i=t,s=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[n]!==void 0).forEach(r=>{r._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:r,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,n,i){let s=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{s=this._chainOrCall(s,()=>r(this,n))}),s}_parseCommand(t,n){let i=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),n=i.unknown,this.args=t.concat(n),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),n);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,t,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){s(),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,t,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))s(),this._processArguments(),this.parent.emit(r,t,n);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,n);this.listenerCount("command:*")?this.emit("command:*",t,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(n=>n._name===t||n._aliases.includes(t))}_findOption(t){return this.options.find(n=>n.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(n=>{n.mandatory&&t.getOptionValue(n.attributeName())===void 0&&t.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let s=i.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let s=t.find(r=>i.conflictsWith.includes(r.attributeName()));s&&this._conflictingOption(i,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],i=[],s=n,r=t.slice();function o(d){return d.length>1&&d[0]==="-"}let a=null;for(;r.length;){let d=r.shift();if(d==="--"){s===i&&s.push(d),s.push(...r);break}if(a&&!o(d)){this.emit(`option:${a.name()}`,d);continue}if(a=null,o(d)){let m=this._findOption(d);if(m){if(m.required){let f=r.shift();f===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,f)}else if(m.optional){let f=null;r.length>0&&!o(r[0])&&(f=r.shift()),this.emit(`option:${m.name()}`,f)}else this.emit(`option:${m.name()}`);a=m.variadic?m:null;continue}}if(d.length>2&&d[0]==="-"&&d[1]!=="-"){let m=this._findOption(`-${d[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,d.slice(2)):(this.emit(`option:${m.name()}`),r.unshift(`-${d.slice(2)}`));continue}}if(/^--[^=]+=/.test(d)){let m=d.indexOf("="),f=this._findOption(d.slice(0,m));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,d.slice(m+1));continue}}if(o(d)&&(s=i),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&i.length===0){if(this._findCommand(d)){n.push(d),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&d===this._getHelpCommand().name()){n.push(d),r.length>0&&n.push(...r);break}else if(this._defaultCommandName){i.push(d),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){s.push(d),r.length>0&&s.push(...r);break}s.push(d)}return{operands:n,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let i=0;i<n;i++){let s=this.options[i].attributeName();t[s]=s===this._versionOptionName?this._version:this[s]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
21
+ - ${s}`;throw new Error(r)}_executeSubCommand(t,n){n=n.slice();let i=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function r(f,p){let g=xt.resolve(f,p);if(ri.existsSync(g))return g;if(s.includes(xt.extname(p)))return;let $=s.find(_=>ri.existsSync(`${g}${_}`));if($)return`${g}${$}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=ri.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=xt.resolve(xt.dirname(f),a)}if(a){let f=r(a,o);if(!f&&!t._executableFile&&this._scriptPath){let p=xt.basename(this._scriptPath,xt.extname(this._scriptPath));p!==this._name&&(f=r(a,`${p}-${t._name}`))}o=f||o}i=s.includes(xt.extname(o));let d;se.platform!=="win32"?i?(n.unshift(o),n=Jr(se.execArgv).concat(n),d=ms.spawn(se.argv[0],n,{stdio:"inherit"})):d=ms.spawn(o,n,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),n.unshift(o),n=Jr(se.execArgv).concat(n),d=ms.spawn(se.execPath,n,{stdio:"inherit"})),d.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{se.on(p,()=>{d.killed===!1&&d.exitCode===null&&d.kill(p)})});let m=this._exitCallback;d.on("close",f=>{f=f??1,m?m(new fs(f,"commander.executeSubCommandAsync","(close)")):se.exit(f)}),d.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!m)se.exit(1);else{let p=new fs(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,m(p)}}),this.runningCommand=d}_dispatchSubcommand(t,n,i){let s=this._findCommand(t);s||this.help({error:!0}),s._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,s,"preSubcommand"),r=this._chainOrCall(r,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(i));else return s._parseCommand(n,i)}),r}_dispatchHelpCommand(t){t||this.help();let n=this._findCommand(t);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,n)=>{t.required&&this.args[n]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,s,r)=>{let o=s;if(s!==null&&i.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,s,r,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((i,s)=>{let r=i.defaultValue;i.variadic?s<this.args.length?(r=this.args.slice(s),i.parseArg&&(r=r.reduce((o,a)=>t(i,a,o),i.defaultValue))):r===void 0&&(r=[]):s<this.args.length&&(r=this.args[s],i.parseArg&&(r=t(i,r,i.defaultValue))),n[s]=r}),this.processedArgs=n}_chainOrCall(t,n){return t&&t.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let i=t,s=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[n]!==void 0).forEach(r=>{r._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:r,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,n,i){let s=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{s=this._chainOrCall(s,()=>r(this,n))}),s}_parseCommand(t,n){let i=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),n=i.unknown,this.args=t.concat(n),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),n);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,t,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){s(),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,t,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))s(),this._processArguments(),this.parent.emit(r,t,n);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,n);this.listenerCount("command:*")?this.emit("command:*",t,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(n=>n._name===t||n._aliases.includes(t))}_findOption(t){return this.options.find(n=>n.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(n=>{n.mandatory&&t.getOptionValue(n.attributeName())===void 0&&t.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let s=i.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let s=t.find(r=>i.conflictsWith.includes(r.attributeName()));s&&this._conflictingOption(i,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],i=[],s=n,r=t.slice();function o(d){return d.length>1&&d[0]==="-"}let a=null;for(;r.length;){let d=r.shift();if(d==="--"){s===i&&s.push(d),s.push(...r);break}if(a&&!o(d)){this.emit(`option:${a.name()}`,d);continue}if(a=null,o(d)){let m=this._findOption(d);if(m){if(m.required){let f=r.shift();f===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,f)}else if(m.optional){let f=null;r.length>0&&!o(r[0])&&(f=r.shift()),this.emit(`option:${m.name()}`,f)}else this.emit(`option:${m.name()}`);a=m.variadic?m:null;continue}}if(d.length>2&&d[0]==="-"&&d[1]!=="-"){let m=this._findOption(`-${d[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,d.slice(2)):(this.emit(`option:${m.name()}`),r.unshift(`-${d.slice(2)}`));continue}}if(/^--[^=]+=/.test(d)){let m=d.indexOf("="),f=this._findOption(d.slice(0,m));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,d.slice(m+1));continue}}if(o(d)&&(s=i),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&i.length===0){if(this._findCommand(d)){n.push(d),r.length>0&&i.push(...r);break}else if(this._getHelpCommand()&&d===this._getHelpCommand().name()){n.push(d),r.length>0&&n.push(...r);break}else if(this._defaultCommandName){i.push(d),r.length>0&&i.push(...r);break}}if(this._passThroughOptions){s.push(d),r.length>0&&s.push(...r);break}s.push(d)}return{operands:n,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let i=0;i<n;i++){let s=this.options[i].attributeName();t[s]=s===this._versionOptionName?this._version:this[s]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
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=n||{},s=i.exitCode||1,r=i.code||"commander.error";this._exit(s,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in se.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,se.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new al(this.options),n=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&n(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"implied")})})}missingArgument(t){let n=`error: missing required argument '${t}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(t){let n=`error: option '${t.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let n=`error: required option '${t.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,n){let i=o=>{let a=o.attributeName(),d=this.getOptionValue(a),m=this.options.find(p=>p.negate&&a===p.attributeName()),f=this.options.find(p=>!p.negate&&a===p.attributeName());return m&&(m.presetArg===void 0&&d===!1||m.presetArg!==void 0&&d===m.presetArg)?m:f||o},s=o=>{let a=i(o),d=a.attributeName();return this.getOptionValueSource(d)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${s(t)} cannot be used with ${s(n)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);s=s.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);n=Mr(t,s)}let i=`error: unknown option '${t}'${n}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,i=n===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${i} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(r=>{s.push(r.name()),r.alias()&&s.push(r.alias())}),n=Mr(t,s)}let i=`error: unknown command '${t}'${n}`;this.error(i,{code:"commander.unknownCommand"})}version(t,n,i){if(t===void 0)return this._version;this._version=t,n=n||"-V, --version",i=i||"output the version number";let s=this.createOption(n,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${t}
25
- `),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),t===n._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(i=>sl(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=kt.basename(t,kt.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let n=this.createHelp(),i=this._getOutputContext(t);n.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let s=n.formatHelp(this,n);return i.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(t){t=t||{};let n=!!t.error,i,s,r;return n?(i=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:s,helpWidth:r}}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let i=this._getOutputContext(t),s={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation({error:i.error});if(n&&(r=n(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",s),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",s))}helpOption(t,n){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(t,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let n=Number(se.exitCode??0);n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
24
+ `),this.outputHelp({error:!0}));let i=n||{},s=i.exitCode||1,r=i.code||"commander.error";this._exit(s,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in se.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,se.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new $l(this.options),n=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&n(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"implied")})})}missingArgument(t){let n=`error: missing required argument '${t}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(t){let n=`error: option '${t.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let n=`error: required option '${t.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,n){let i=o=>{let a=o.attributeName(),d=this.getOptionValue(a),m=this.options.find(p=>p.negate&&a===p.attributeName()),f=this.options.find(p=>!p.negate&&a===p.attributeName());return m&&(m.presetArg===void 0&&d===!1||m.presetArg!==void 0&&d===m.presetArg)?m:f||o},s=o=>{let a=i(o),d=a.attributeName();return this.getOptionValueSource(d)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${s(t)} cannot be used with ${s(n)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);s=s.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);n=Hr(t,s)}let i=`error: unknown option '${t}'${n}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,i=n===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${i} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(r=>{s.push(r.name()),r.alias()&&s.push(r.alias())}),n=Hr(t,s)}let i=`error: unknown command '${t}'${n}`;this.error(i,{code:"commander.unknownCommand"})}version(t,n,i){if(t===void 0)return this._version;this._version=t,n=n||"-V, --version",i=i||"output the version number";let s=this.createOption(n,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${t}
25
+ `),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),t===n._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(i=>bl(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=xt.basename(t,xt.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let n=this.createHelp(),i=this._getOutputContext(t);n.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let s=n.formatHelp(this,n);return i.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(t){t=t||{};let n=!!t.error,i,s,r;return n?(i=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:s,helpWidth:r}}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let i=this._getOutputContext(t),s={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation({error:i.error});if(n&&(r=n(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",s),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",s))}helpOption(t,n){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(t,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let n=Number(se.exitCode??0);n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
26
26
  Expecting one of '${i.join("', '")}'`);let s=`${t}Help`;return this.on(s,r=>{let o;typeof n=="function"?o=n({error:r.error,command:r.command}):o=n,o&&r.write(`${o}
27
- `)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Fr(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,i="127.0.0.1",s="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?n=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=r[1],/^\d+$/.test(r[3])?s=r[3]:i=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=r[1],i=r[3],s=r[4]),n&&s!=="0"?`${n}=${i}:${parseInt(s)+1}`:t})}function ms(){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}fs.Command=us;fs.useColor=ms});var Jr=_t(et=>{var{Argument:Vr}=ni(),{Command:ps}=Lr(),{CommanderError:dl,InvalidArgumentError:Wr}=Sn(),{Help:ll}=ss(),{Option:Hr}=ds();et.program=new ps;et.createCommand=e=>new ps(e);et.createOption=(e,t)=>new Hr(e,t);et.createArgument=(e,t)=>new Vr(e,t);et.Command=ps;et.Option=Hr;et.Argument=Vr;et.Help=ll;et.CommanderError=dl;et.InvalidArgumentError=Wr;et.InvalidOptionArgumentError=Wr});var Et,si=je(()=>{Et={mailProductName:"Mailzero",domaniProductName:"Domani",mailProductHost:"mailzero.run"}});var F=_t((pf,hs)=>{var oi=process||{},Kr=oi.argv||[],ri=oi.env||{},ul=!(ri.NO_COLOR||Kr.includes("--no-color"))&&(!!ri.FORCE_COLOR||Kr.includes("--color")||oi.platform==="win32"||(oi.stdout||{}).isTTY&&ri.TERM!=="dumb"||!!ri.CI),ml=(e,t,n=e)=>i=>{let s=""+i,r=s.indexOf(t,e.length);return~r?e+fl(s,t,n,r)+t:e+s+t},fl=(e,t,n,i)=>{let s="",r=0;do s+=e.substring(r,i)+n,r=i+t.length,i=e.indexOf(t,r);while(~i);return s+e.substring(r)},zr=(e=ul)=>{let t=e?ml:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};hs.exports=zr();hs.exports.createColors=zr});var fn,On,Cn=je(()=>{"use strict";fn="domani.run",On=`https://${fn}`});function Jt(e,t,n){try{let i=(0,Yr.spawnSync)(e,t,{encoding:"utf-8",input:n,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:i.status===0,stdout:(i.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function Xr(){return ai.available()}function Zr(e,t={}){if(!t.refresh&&An.has(e))return An.get(e)??void 0;let n=ai.get(e);return An.set(e,n??null),n}function Qr(e,t){let n=ai.set(e,t);return n&&An.set(e,t),n}function di(e){ai.delete(e),An.set(e,null)}var Yr,pn,pl,ai,An,gs=je(()=>{"use strict";Yr=require("child_process"),pn="domani-cli";pl={available(){return process.platform==="darwin"?!0:process.platform==="linux"?Jt("secret-tool",["--help"]).ok:!1},get(e){if(process.platform==="darwin"){let t=Jt("security",["find-generic-password","-s",pn,"-a",e,"-w"]);return t.ok&&t.stdout?t.stdout:void 0}if(process.platform==="linux"){let t=Jt("secret-tool",["lookup","service",pn,"account",e]);return t.ok&&t.stdout?t.stdout:void 0}},set(e,t){return process.platform==="darwin"?Jt("security",["add-generic-password","-U","-s",pn,"-a",e,"-w",t]).ok:process.platform==="linux"?Jt("secret-tool",["store",`--label=domani CLI token (${e})`,"service",pn,"account",e],t+`
28
- `).ok:!1},delete(e){process.platform==="darwin"?Jt("security",["delete-generic-password","-s",pn,"-a",e]):process.platform==="linux"&&Jt("secret-tool",["clear","service",pn,"account",e])}},ai=pl,An=new Map});function In(){return process.env.DOMANI_CONFIG_DIR||Rn.default.join(eo.default.homedir(),".domani")}function to(){return Rn.default.join(In(),"config.json")}function no(e){ys=e}function ci(e){return gl.test(e)}function Be(){let e;try{e=JSON.parse(Bt.default.readFileSync(to(),"utf-8"))}catch{return{}}if(!e||typeof e!="object")return{};let{token:t,email:n,token_in_keychain:i,...s}=e,r={...s,accounts:{...e.accounts??{}}};return!e.accounts&&(t||n||i)&&(r.accounts={[bs]:{email:n,api_url:e.api_url,...t?{token:t}:{},...i?{token_in_keychain:i}:{}}},r.active_account=bs),r}function vs(e){Bt.default.mkdirSync(In(),{recursive:!0,mode:448}),Bt.default.writeFileSync(to(),JSON.stringify(e,null,2),{mode:384})}function io(e){ws=e}function Tn(){return process.env.DOMANI_API_KEY?{source:"api_key_env"}:Pt()}function Pt(){if(ws)return{name:ws,source:"flag"};if(process.env.DOMANI_ACCOUNT)return{name:process.env.DOMANI_ACCOUNT,source:"env"};let e=Be().active_account;return e?{name:e,source:"active"}:{source:"none"}}function hn(){return Pt().name??bs}function so(e){return Be().accounts?.[e]}function rt(){let e=Be().accounts??{};return Object.keys(e).sort().map(t=>({name:t,...e[t]}))}function $s(e,t={}){let n=so(e);if(n){if(n.token)return n.token;if(n.token_in_keychain)return Zr(e,{refresh:t.refreshKeychain})}}function ui(e,t){let n=Be(),i=Xr()&&Qr(e,t.token)?{email:t.email,api_url:t.api_url,token_in_keychain:!0}:{email:t.email,api_url:t.api_url,token:t.token};n.accounts={...n.accounts??{},[e]:i},(!n.active_account||!n.accounts[n.active_account])&&(n.active_account=e),vs(n)}function ro(e){let t=Be(),n=t.accounts?.[e];if(n)return n.token_in_keychain&&di(e),delete t.accounts[e],t.active_account===e&&delete t.active_account,vs(t),n}function oo(e){let t=Be();return t.accounts?.[e]?(t.active_account=e,vs(t),!0):!1}function xt(){let e=Tn();if(e.source==="api_key_env")return"DOMANI_API_KEY";if(!e.name)return;let t=so(e.name)?.email;return rt().length<=1&&e.source==="active"?t:t?`${e.name} (${t})`:e.name}function Ge(){if(ys)return ys;let e=Be(),{name:t}=Pt();return t&&e.accounts?.[t]?.api_url||e.api_url||On}function ot(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let{name:t}=Pt();return t?$s(t,e):void 0}function yl(){try{let e=Bt.default.readFileSync(Rn.default.join(In(),"version-check.json"),"utf-8");return JSON.parse(e)}catch{return null}}function bl(e){try{Bt.default.mkdirSync(In(),{recursive:!0,mode:448}),Bt.default.writeFileSync(Rn.default.join(In(),"version-check.json"),JSON.stringify(e),{mode:384})}catch{}}function li(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(i[s]||0))return 1;if((n[s]||0)<(i[s]||0))return-1}return 0}async function ao(){let e=yl();if(e&&Date.now()-e.checkedAt<hl)return li(e.version,Ie)>0?{update:e.version,forced:li(Ie,e.min)<0}:null;try{let t=Ge(),n=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let i=await n.json();if(bl({version:i.version,min:i.min,checkedAt:Date.now()}),li(i.version,Ie)>0)return{update:i.version,forced:li(Ie,i.min)<0}}catch{}return null}var Bt,Rn,eo,ys,hl,bs,gl,ws,_s,Ie,De=je(()=>{"use strict";Bt=N(require("fs"),1),Rn=N(require("path"),1),eo=N(require("os"),1);Cn();gs();hl=1440*60*1e3,bs="default",gl=/^[a-z0-9][a-z0-9._-]{0,62}$/i;_s=process.stdout.isTTY??!1,Ie="0.4.89"});var xs=_t((vf,lo)=>{"use strict";var ks={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let n="";return e<0?n+=`\x1B[${-e}D`:e>0&&(n+=`\x1B[${e}C`),t<0?n+=`\x1B[${-t}A`:t>0&&(n+=`\x1B[${t}B`),n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},wl={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},vl={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?ks.up():"");return e&&(t+=ks.left),t}};lo.exports={cursor:ks,scroll:wl,erase:vl,beep:"\x07"}});function jt(e,t,n){if(!n.some(o=>!o.disabled))return e;let i=e+t,s=Math.max(n.length-1,0),r=i<0?s:i>s?0:i;return n[r].disabled?jt(r,t<0?-1:1,n):r}function As(e,t,n){return String(e).normalize().replaceAll(`\r
27
+ `)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Jr(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,i="127.0.0.1",s="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?n=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=r[1],/^\d+$/.test(r[3])?s=r[3]:i=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=r[1],i=r[3],s=r[4]),n&&s!=="0"?`${n}=${i}:${parseInt(s)+1}`:t})}function hs(){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}gs.Command=ps;gs.useColor=hs});var Yr=_t(tt=>{var{Argument:Gr}=si(),{Command:ys}=Br(),{CommanderError:kl,InvalidArgumentError:Kr}=Cn(),{Help:_l}=as(),{Option:zr}=us();tt.program=new ys;tt.createCommand=e=>new ys(e);tt.createOption=(e,t)=>new zr(e,t);tt.createArgument=(e,t)=>new Gr(e,t);tt.Command=ys;tt.Option=zr;tt.Argument=Gr;tt.Help=_l;tt.CommanderError=kl;tt.InvalidArgumentError=Kr;tt.InvalidOptionArgumentError=Kr});var Pt,oi=_e(()=>{Pt={mailProductName:"Mailzero",domaniProductName:"Domani",mailProductHost:"mailzero.run"}});var F=_t((Ef,bs)=>{var di=process||{},Qr=di.argv||[],ai=di.env||{},jl=!(ai.NO_COLOR||Qr.includes("--no-color"))&&(!!ai.FORCE_COLOR||Qr.includes("--color")||di.platform==="win32"||(di.stdout||{}).isTTY&&ai.TERM!=="dumb"||!!ai.CI),Sl=(e,t,n=e)=>i=>{let s=""+i,r=s.indexOf(t,e.length);return~r?e+Cl(s,t,n,r)+t:e+s+t},Cl=(e,t,n,i)=>{let s="",r=0;do s+=e.substring(r,i)+n,r=i+t.length,i=e.indexOf(t,r);while(~i);return s+e.substring(r)},eo=(e=jl)=>{let t=e?Sl:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};bs.exports=eo();bs.exports.createColors=eo});var pn,On,In=_e(()=>{"use strict";pn="domani.run",On=`https://${pn}`});function Bt(e,t,n){try{let i=(0,to.spawnSync)(e,t,{encoding:"utf-8",input:n,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:i.status===0,stdout:(i.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function no(){return li.available()}function io(e,t={}){if(!t.refresh&&An.has(e))return An.get(e)??void 0;let n=li.get(e);return An.set(e,n??null),n}function so(e,t){let n=li.set(e,t);return n&&An.set(e,t),n}function ci(e){li.delete(e),An.set(e,null)}var to,hn,Ol,li,An,ws=_e(()=>{"use strict";to=require("child_process"),hn="domani-cli";Ol={available(){return process.platform==="darwin"?!0:process.platform==="linux"?Bt("secret-tool",["--help"]).ok:!1},get(e){if(process.platform==="darwin"){let t=Bt("security",["find-generic-password","-s",hn,"-a",e,"-w"]);return t.ok&&t.stdout?t.stdout:void 0}if(process.platform==="linux"){let t=Bt("secret-tool",["lookup","service",hn,"account",e]);return t.ok&&t.stdout?t.stdout:void 0}},set(e,t){return process.platform==="darwin"?Bt("security",["add-generic-password","-U","-s",hn,"-a",e,"-w",t]).ok:process.platform==="linux"?Bt("secret-tool",["store",`--label=domani CLI token (${e})`,"service",hn,"account",e],t+`
28
+ `).ok:!1},delete(e){process.platform==="darwin"?Bt("security",["delete-generic-password","-s",hn,"-a",e]):process.platform==="linux"&&Bt("secret-tool",["clear","service",hn,"account",e])}},li=Ol,An=new Map});function Rn(){return process.env.DOMANI_CONFIG_DIR||Tn.default.join(ro.default.homedir(),".domani")}function oo(){return Tn.default.join(Rn(),"config.json")}function ao(e){vs=e}function mi(e){return Al.test(e)}function Ge(){let e;try{e=JSON.parse(Gt.default.readFileSync(oo(),"utf-8"))}catch{return{}}if(!e||typeof e!="object")return{};let{token:t,email:n,token_in_keychain:i,...s}=e,r={...s,accounts:{...e.accounts??{}}};return!e.accounts&&(t||n||i)&&(r.accounts={[$s]:{email:n,api_url:e.api_url,...t?{token:t}:{},...i?{token_in_keychain:i}:{}}},r.active_account=$s),r}function _s(e){Gt.default.mkdirSync(Rn(),{recursive:!0,mode:448}),Gt.default.writeFileSync(oo(),JSON.stringify(e,null,2),{mode:384})}function lo(e){ks=e}function En(){return process.env.DOMANI_API_KEY?{source:"api_key_env"}:Dt()}function Dt(){if(ks)return{name:ks,source:"flag"};if(process.env.DOMANI_ACCOUNT)return{name:process.env.DOMANI_ACCOUNT,source:"env"};let e=Ge().active_account;return e?{name:e,source:"active"}:{source:"none"}}function gn(){return Dt().name??$s}function co(e){return Ge().accounts?.[e]}function ot(){let e=Ge().accounts??{};return Object.keys(e).sort().map(t=>({name:t,...e[t]}))}function xs(e,t={}){let n=co(e);if(n){if(n.token)return n.token;if(n.token_in_keychain)return io(e,{refresh:t.refreshKeychain})}}function fi(e,t){let n=Ge(),i=no()&&so(e,t.token)?{email:t.email,api_url:t.api_url,token_in_keychain:!0}:{email:t.email,api_url:t.api_url,token:t.token};n.accounts={...n.accounts??{},[e]:i},(!n.active_account||!n.accounts[n.active_account])&&(n.active_account=e),_s(n)}function uo(e){let t=Ge(),n=t.accounts?.[e];if(n)return n.token_in_keychain&&ci(e),delete t.accounts[e],t.active_account===e&&delete t.active_account,_s(t),n}function mo(e){let t=Ge();return t.accounts?.[e]?(t.active_account=e,_s(t),!0):!1}function jt(){let e=En();if(e.source==="api_key_env")return"DOMANI_API_KEY";if(!e.name)return;let t=co(e.name)?.email;return ot().length<=1&&e.source==="active"?t:t?`${e.name} (${t})`:e.name}function Ke(){if(vs)return vs;let e=Ge(),{name:t}=Dt();return t&&e.accounts?.[t]?.api_url||e.api_url||On}function at(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let{name:t}=Dt();return t?xs(t,e):void 0}function Rl(){try{let e=Gt.default.readFileSync(Tn.default.join(Rn(),"version-check.json"),"utf-8");return JSON.parse(e)}catch{return null}}function Tl(e){try{Gt.default.mkdirSync(Rn(),{recursive:!0,mode:448}),Gt.default.writeFileSync(Tn.default.join(Rn(),"version-check.json"),JSON.stringify(e),{mode:384})}catch{}}function ui(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(i[s]||0))return 1;if((n[s]||0)<(i[s]||0))return-1}return 0}async function fo(){let e=Rl();if(e&&Date.now()-e.checkedAt<Il)return ui(e.version,Ae)>0?{update:e.version,forced:ui(Ae,e.min)<0}:null;try{let t=Ke(),n=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let i=await n.json();if(Tl({version:i.version,min:i.min,checkedAt:Date.now()}),ui(i.version,Ae)>0)return{update:i.version,forced:ui(Ae,i.min)<0}}catch{}return null}var Gt,Tn,ro,vs,Il,$s,Al,ks,js,Ae,De=_e(()=>{"use strict";Gt=N(require("fs"),1),Tn=N(require("path"),1),ro=N(require("os"),1);In();ws();Il=1440*60*1e3,$s="default",Al=/^[a-z0-9][a-z0-9._-]{0,62}$/i;js=process.stdout.isTTY??!1,Ae="0.4.90"});var Cs=_t((Mf,po)=>{"use strict";var Ss={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let n="";return e<0?n+=`\x1B[${-e}D`:e>0&&(n+=`\x1B[${e}C`),t<0?n+=`\x1B[${-t}A`:t>0&&(n+=`\x1B[${t}B`),n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},El={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Pl={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Ss.up():"");return e&&(t+=Ss.left),t}};po.exports={cursor:Ss,scroll:El,erase:Pl,beep:"\x07"}});function St(e,t,n){if(!n.some(o=>!o.disabled))return e;let i=e+t,s=Math.max(n.length-1,0),r=i<0?s:i>s?0:i;return n[r].disabled?St(r,t<0?-1:1,n):r}function Ts(e,t,n){return String(e).normalize().replaceAll(`\r
29
29
  `,`
30
30
  `).split(`
31
- `).map(i=>Tl(i,t,n)).join(`
32
- `)}function bo(e){if(e.aliases!==void 0){let t=e.aliases;for(let n in t){if(!Object.hasOwn(t,n))continue;let i=t[n];me.actions.has(i)&&(me.aliases.has(n)||me.aliases.set(n,i))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(me.messages.cancel=t.cancel),t.error!==void 0&&(me.messages.error=t.error)}e.withGuide!==void 0&&(me.withGuide=e.withGuide!==!1)}function Es(e,t){if(typeof e=="string")return me.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Es(n,t))return!0;return!1}function Pl(e,t){if(e===t)return;let n=e.split(`
31
+ `).map(i=>Bl(i,t,n)).join(`
32
+ `)}function _o(e){if(e.aliases!==void 0){let t=e.aliases;for(let n in t){if(!Object.hasOwn(t,n))continue;let i=t[n];fe.actions.has(i)&&(fe.aliases.has(n)||fe.aliases.set(n,i))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(fe.messages.cancel=t.cancel),t.error!==void 0&&(fe.messages.error=t.error)}e.withGuide!==void 0&&(fe.withGuide=e.withGuide!==!1)}function Ns(e,t){if(typeof e=="string")return fe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Ns(n,t))return!0;return!1}function Kl(e,t){if(e===t)return;let n=e.split(`
33
33
  `),i=t.split(`
34
- `),s=Math.max(n.length,i.length),r=[];for(let o=0;o<s;o++)n[o]!==i[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:i.length,numLines:s}}function de(e){return e===Is}function hi(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function wo({input:e=Gt.stdin,output:t=Gt.stdout,overwrite:n=!0,hideCursor:i=!0}={}){let s=Nt.createInterface({input:e,output:t,prompt:"",tabSize:1});Nt.emitKeypressEvents(e,s),e instanceof Cs.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:d})=>{let m=String(o);if(Es([m,a,d],"cancel")){i&&t.write(Ne.cursor.show),process.exit(0);return}if(!n)return;Nt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Nt.clearLine(t,1,()=>{e.once("keypress",r)})})};return i&&t.write(Ne.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),i&&t.write(Ne.cursor.show),e instanceof Cs.ReadStream&&e.isTTY&&!Dl&&e.setRawMode(!1),s.terminal=!1,s.close()}}function ft(e,t,n,i=n){let s=Kt(e??Gt.stdout);return As(t,s-n.length,{hard:!0,trim:!1}).split(`
34
+ `),s=Math.max(n.length,i.length),r=[];for(let o=0;o<s;o++)n[o]!==i[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:i.length,numLines:s}}function de(e){return e===Es}function yi(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function xo({input:e=Kt.stdin,output:t=Kt.stdout,overwrite:n=!0,hideCursor:i=!0}={}){let s=Ut.createInterface({input:e,output:t,prompt:"",tabSize:1});Ut.emitKeypressEvents(e,s),e instanceof Rs.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:d})=>{let m=String(o);if(Ns([m,a,d],"cancel")){i&&t.write(Ne.cursor.show),process.exit(0);return}if(!n)return;Ut.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Ut.clearLine(t,1,()=>{e.once("keypress",r)})})};return i&&t.write(Ne.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),i&&t.write(Ne.cursor.show),e instanceof Rs.ReadStream&&e.isTTY&&!zl&&e.setRawMode(!1),s.terminal=!1,s.close()}}function pt(e,t,n,i=n){let s=zt(e??Kt.stdout);return Ts(t,s-n.length,{hard:!0,trim:!1}).split(`
35
35
  `).map((r,o)=>`${o===0?i:n}${r}`).join(`
36
- `)}function Nl(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex(i=>i.value===e);return n!==-1?n:0}function Ul(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function ql(e,t){if(t)return e?t:t[0]}var Dt,Gt,Nt,fo,Ne,Cs,$l,_l,kl,js,mi,fi,Ss,pi,xl,jl,po,Sl,En,_i,ho,Ol,Rs,go,Cl,yo,Ts,co,Al,uo,mo,Il,Os,Rl,Tl,El,me,Dl,Is,Kt,Ps,mt,Pn,gi,yi,bi,vo,wi,vi,$i,Ds=je(()=>{Dt=N(F(),1),Gt=require("node:process"),Nt=N(require("node:readline"),1),fo=N(require("node:readline"),1),Ne=N(xs(),1),Cs=require("node:tty");$l=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,_l=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,kl=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,js=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,mi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fi=/\t{1,1000}/y,Ss=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"),pi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,xl=new RegExp("\\p{M}+","gu"),jl={limit:1/0,ellipsis:""},po=(e,t={},n={})=>{let i=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?po(s,jl,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,d=n.tabWidth??8,m=n.ambiguousWidth??1,f=n.emojiWidth??2,p=n.fullWidthWidth??2,g=n.regularWidth??1,$=n.wideWidth??2,k=0,w=0,_=e.length,S=0,C=!1,R=_,M=Math.max(0,i-r),H=0,ee=0,q=0,U=0;e:for(;;){if(ee>H||w>=_&&w>k){let ce=e.slice(H,ee)||e.slice(k,w);S=0;for(let le of ce.replaceAll(xl,"")){let P=le.codePointAt(0)||0;if(_l(P)?U=p:kl(P)?U=$:m!==g&&$l(P)?U=m:U=g,q+U>M&&(R=Math.min(R,Math.max(H,k)+S)),q+U>i){C=!0;break e}S+=le.length,q+=U}H=ee=0}if(w>=_)break;if(pi.lastIndex=w,pi.test(e)){if(S=pi.lastIndex-w,U=S*g,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/g))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=pi.lastIndex;continue}if(js.lastIndex=w,js.test(e)){if(q+o>M&&(R=Math.min(R,w)),q+o>i){C=!0;break}q+=o,H=k,ee=w,w=k=js.lastIndex;continue}if(mi.lastIndex=w,mi.test(e)){if(S=mi.lastIndex-w,U=S*a,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/a))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=mi.lastIndex;continue}if(fi.lastIndex=w,fi.test(e)){if(S=fi.lastIndex-w,U=S*d,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/d))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=fi.lastIndex;continue}if(Ss.lastIndex=w,Ss.test(e)){if(q+f>M&&(R=Math.min(R,w)),q+f>i){C=!0;break}q+=f,H=k,ee=w,w=k=Ss.lastIndex;continue}w+=1}return{width:C?M:q,index:C?R:_,truncated:C,ellipsed:C&&i>=r}},Sl={limit:1/0,ellipsis:"",ellipsisWidth:0},En=(e,t={})=>po(e,Sl,t).width,_i="\x1B",ho="\x9B",Ol=39,Rs="\x07",go="[",Cl="]",yo="m",Ts=`${Cl}8;;`,co=new RegExp(`(?:\\${go}(?<code>\\d+)m|\\${Ts}(?<uri>.*)${Rs})`,"y"),Al=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},uo=e=>`${_i}${go}${e}${yo}`,mo=e=>`${_i}${Ts}${e}${Rs}`,Il=e=>e.map(t=>En(t)),Os=(e,t,n)=>{let i=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:En(o),d=i.next(),m=i.next(),f=0;for(;!d.done;){let p=d.value,g=En(p);a+g<=n?e[e.length-1]+=p:(e.push(p),a=0),(p===_i||p===ho)&&(s=!0,r=t.startsWith(Ts,f+1)),s?r?p===Rs&&(s=!1,r=!1):p===yo&&(s=!1):(a+=g,a===n&&!m.done&&(e.push(""),a=0)),d=m,m=i.next(),f+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Rl=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(En(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},Tl=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",s,r,o=e.split(" "),a=Il(o),d=[""];for(let[k,w]of o.entries()){n.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let _=En(d.at(-1)??"");if(k!==0&&(_>=t&&(n.wordWrap===!1||n.trim===!1)&&(d.push(""),_=0),(_>0||n.trim===!1)&&(d[d.length-1]+=" ",_++)),n.hard&&a[k]>t){let S=t-_,C=1+Math.floor((a[k]-S-1)/t);Math.floor((a[k]-1)/t)<C&&d.push(""),Os(d,w,t);continue}if(_+a[k]>t&&_>0&&a[k]>0){if(n.wordWrap===!1&&_<t){Os(d,w,t);continue}d.push("")}if(_+a[k]>t&&n.wordWrap===!1){Os(d,w,t);continue}d[d.length-1]+=w}n.trim!==!1&&(d=d.map(k=>Rl(k)));let m=d.join(`
37
- `),f=m[Symbol.iterator](),p=f.next(),g=f.next(),$=0;for(;!p.done;){let k=p.value,w=g.value;if(i+=k,k===_i||k===ho){co.lastIndex=$+1;let S=co.exec(m)?.groups;if(S?.code!==void 0){let C=Number.parseFloat(S.code);s=C===Ol?void 0:C}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let _=s?Al(s):void 0;w===`
38
- `?(r&&(i+=mo("")),s&&_&&(i+=uo(_))):k===`
39
- `&&(s&&_&&(i+=uo(s)),r&&(i+=mo(r))),$+=k.length,p=g,g=f.next()}return i};El=["up","down","left","right","space","enter","cancel"],me={actions:new Set(El),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Dl=globalThis.process.platform.startsWith("win"),Is=Symbol("clack:cancel");Kt=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ps=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;mt=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=!0){let{input:i=Gt.stdin,output:s=Gt.stdout,render:r,signal:o,...a}=t;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=n,this._abortSignal=o,this.input=i,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let i=this._subscribers.get(t)??[];i.push(n),this._subscribers.set(t,i)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let i=this._subscribers.get(t)??[],s=[];for(let r of i)r.cb(...n),r.once&&s.push(()=>i.splice(i.indexOf(r),1));for(let r of s)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Is);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=fo.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),hi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ne.cursor.show),this.output.off("resize",this.render),hi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Ne.cursor.show),this.output.off("resize",this.render),hi(this.input,!1),t(Is)})})}_isActionKey(t,n){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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(t,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&me.aliases.has(n.name)&&this.emit("cursor",me.aliases.get(n.name)),me.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),n),n?.name==="return"){if(this.opts.validate){let i=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")}Es([t,n?.name,n?.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(`
40
- `),hi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=As(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
- `).length-1;this.output.write(Ne.cursor.move(-999,t*-1))}render(){let t=As(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Ne.cursor.hide);else{let n=Pl(this._prevFrame,t),i=Ps(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-i),r=Math.max(0,n.numLinesBefore-i),o=n.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(Ne.cursor.move(0,o-r)),this.output.write(Ne.erase.lines(1));let a=t.split(`
36
+ `)}function Yl(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex(i=>i.value===e);return n!==-1?n:0}function Xl(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Zl(e,t){if(t)return e?t:t[0]}var Nt,Kt,Ut,bo,Ne,Rs,Dl,Nl,Ul,Os,pi,hi,Is,gi,ql,Ml,wo,Fl,Pn,xi,vo,Ll,Ps,$o,Vl,ko,Ds,ho,Wl,go,yo,Hl,As,Jl,Bl,Gl,fe,zl,Es,zt,Us,ft,Dn,bi,wi,vi,jo,$i,ki,_i,qs=_e(()=>{Nt=N(F(),1),Kt=require("node:process"),Ut=N(require("node:readline"),1),bo=N(require("node:readline"),1),Ne=N(Cs(),1),Rs=require("node:tty");Dl=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Nl=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ul=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Os=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,pi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,hi=/\t{1,1000}/y,Is=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"),gi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ql=new RegExp("\\p{M}+","gu"),Ml={limit:1/0,ellipsis:""},wo=(e,t={},n={})=>{let i=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?wo(s,Ml,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,d=n.tabWidth??8,m=n.ambiguousWidth??1,f=n.emojiWidth??2,p=n.fullWidthWidth??2,g=n.regularWidth??1,$=n.wideWidth??2,_=0,w=0,k=e.length,S=0,O=!1,R=k,M=Math.max(0,i-r),H=0,ee=0,q=0,U=0;e:for(;;){if(ee>H||w>=k&&w>_){let ce=e.slice(H,ee)||e.slice(_,w);S=0;for(let le of ce.replaceAll(ql,"")){let P=le.codePointAt(0)||0;if(Nl(P)?U=p:Ul(P)?U=$:m!==g&&Dl(P)?U=m:U=g,q+U>M&&(R=Math.min(R,Math.max(H,_)+S)),q+U>i){O=!0;break e}S+=le.length,q+=U}H=ee=0}if(w>=k)break;if(gi.lastIndex=w,gi.test(e)){if(S=gi.lastIndex-w,U=S*g,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/g))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=gi.lastIndex;continue}if(Os.lastIndex=w,Os.test(e)){if(q+o>M&&(R=Math.min(R,w)),q+o>i){O=!0;break}q+=o,H=_,ee=w,w=_=Os.lastIndex;continue}if(pi.lastIndex=w,pi.test(e)){if(S=pi.lastIndex-w,U=S*a,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/a))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=pi.lastIndex;continue}if(hi.lastIndex=w,hi.test(e)){if(S=hi.lastIndex-w,U=S*d,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/d))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=hi.lastIndex;continue}if(Is.lastIndex=w,Is.test(e)){if(q+f>M&&(R=Math.min(R,w)),q+f>i){O=!0;break}q+=f,H=_,ee=w,w=_=Is.lastIndex;continue}w+=1}return{width:O?M:q,index:O?R:k,truncated:O,ellipsed:O&&i>=r}},Fl={limit:1/0,ellipsis:"",ellipsisWidth:0},Pn=(e,t={})=>wo(e,Fl,t).width,xi="\x1B",vo="\x9B",Ll=39,Ps="\x07",$o="[",Vl="]",ko="m",Ds=`${Vl}8;;`,ho=new RegExp(`(?:\\${$o}(?<code>\\d+)m|\\${Ds}(?<uri>.*)${Ps})`,"y"),Wl=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},go=e=>`${xi}${$o}${e}${ko}`,yo=e=>`${xi}${Ds}${e}${Ps}`,Hl=e=>e.map(t=>Pn(t)),As=(e,t,n)=>{let i=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:Pn(o),d=i.next(),m=i.next(),f=0;for(;!d.done;){let p=d.value,g=Pn(p);a+g<=n?e[e.length-1]+=p:(e.push(p),a=0),(p===xi||p===vo)&&(s=!0,r=t.startsWith(Ds,f+1)),s?r?p===Ps&&(s=!1,r=!1):p===ko&&(s=!1):(a+=g,a===n&&!m.done&&(e.push(""),a=0)),d=m,m=i.next(),f+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Jl=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Pn(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},Bl=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",s,r,o=e.split(" "),a=Hl(o),d=[""];for(let[_,w]of o.entries()){n.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let k=Pn(d.at(-1)??"");if(_!==0&&(k>=t&&(n.wordWrap===!1||n.trim===!1)&&(d.push(""),k=0),(k>0||n.trim===!1)&&(d[d.length-1]+=" ",k++)),n.hard&&a[_]>t){let S=t-k,O=1+Math.floor((a[_]-S-1)/t);Math.floor((a[_]-1)/t)<O&&d.push(""),As(d,w,t);continue}if(k+a[_]>t&&k>0&&a[_]>0){if(n.wordWrap===!1&&k<t){As(d,w,t);continue}d.push("")}if(k+a[_]>t&&n.wordWrap===!1){As(d,w,t);continue}d[d.length-1]+=w}n.trim!==!1&&(d=d.map(_=>Jl(_)));let m=d.join(`
37
+ `),f=m[Symbol.iterator](),p=f.next(),g=f.next(),$=0;for(;!p.done;){let _=p.value,w=g.value;if(i+=_,_===xi||_===vo){ho.lastIndex=$+1;let S=ho.exec(m)?.groups;if(S?.code!==void 0){let O=Number.parseFloat(S.code);s=O===Ll?void 0:O}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let k=s?Wl(s):void 0;w===`
38
+ `?(r&&(i+=yo("")),s&&k&&(i+=go(k))):_===`
39
+ `&&(s&&k&&(i+=go(s)),r&&(i+=yo(r))),$+=_.length,p=g,g=f.next()}return i};Gl=["up","down","left","right","space","enter","cancel"],fe={actions:new Set(Gl),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};zl=globalThis.process.platform.startsWith("win"),Es=Symbol("clack:cancel");zt=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Us=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;ft=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=!0){let{input:i=Kt.stdin,output:s=Kt.stdout,render:r,signal:o,...a}=t;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=n,this._abortSignal=o,this.input=i,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let i=this._subscribers.get(t)??[];i.push(n),this._subscribers.set(t,i)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let i=this._subscribers.get(t)??[],s=[];for(let r of i)r.cb(...n),r.once&&s.push(()=>i.splice(i.indexOf(r),1));for(let r of s)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Es);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=bo.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),yi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ne.cursor.show),this.output.off("resize",this.render),yi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Ne.cursor.show),this.output.off("resize",this.render),yi(this.input,!1),t(Es)})})}_isActionKey(t,n){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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(t,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&fe.aliases.has(n.name)&&this.emit("cursor",fe.aliases.get(n.name)),fe.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),n),n?.name==="return"){if(this.opts.validate){let i=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")}Ns([t,n?.name,n?.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(`
40
+ `),yi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Ts(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
+ `).length-1;this.output.write(Ne.cursor.move(-999,t*-1))}render(){let t=Ts(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Ne.cursor.hide);else{let n=Kl(this._prevFrame,t),i=Us(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-i),r=Math.max(0,n.numLinesBefore-i),o=n.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(Ne.cursor.move(0,o-r)),this.output.write(Ne.erase.lines(1));let a=t.split(`
42
42
  `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Ne.cursor.move(0,a.length-o-1));return}else if(n.lines.length>1){if(s<r)o=s;else{let d=o-r;d>0&&this.output.write(Ne.cursor.move(0,d))}this.output.write(Ne.erase.down());let a=t.split(`
43
43
  `).slice(o);this.output.write(a.join(`
44
- `)),this._prevFrame=t;return}}this.output.write(Ne.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};Pn=class extends mt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#n="";#i;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return Dt.default.inverse(Dt.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[n,...i]=this.userInput.slice(this._cursor);return`${t}${Dt.default.inverse(n)}${i.join("")}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(t){super(t),this.#t=t.options;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#i=t.filter??Ul;let i;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?i=t.initialValue:i=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0].value]),i)for(let s of i){let r=n.findIndex(o=>o.value===s);r!==-1&&(this.toggleSelected(s),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(s,r)=>this.#s(s,r)),this.on("userInput",s=>this.#r(s))}_isActionKey(t,n){return t===" "||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#s(t,n){let i=n.name==="up",s=n.name==="down",r=n.name==="return";i||s?(this.#e=jt(this.#e,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=ql(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter(n=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#n){this.#n=t;let n=this.options;t?this.filteredOptions=n.filter(r=>this.#i(t,r)):this.filteredOptions=[...n];let i=Nl(this.focusedValue,this.filteredOptions);this.#e=jt(i,0,this.filteredOptions);let s=this.filteredOptions[this.#e];s&&!s.disabled?this.focusedValue=s.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},gi=class extends mt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Ne.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},yi=class extends mt{options;cursor=0;#e;getGroupItems(t){return this.options.filter(n=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),i=this.value;return i===void 0?!1:n.every(s=>i.includes(s.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,i=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter(s=>i.findIndex(r=>r.value===s)===-1):this.value=[...this.value,...i.map(s=>s.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter(i=>i!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#e=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([i,s])=>[{value:i,group:!0,label:i},...s.map(r=>({...r,group:i}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===t.cursorAt),this.#e?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 s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(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 s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},bi=class extends mt{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,n=this.value!==void 0&&this.value.length===t.length;this.value=n?[]:t.map(i=>i.value)}toggleInvert(){let t=this.value;if(!t)return;let n=this._enabledOptions.filter(i=>!t.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===t.cursorAt),0);this.cursor=this.options[n].disabled?jt(n,1,this.options):n,this.on("key",i=>{i==="a"&&this.toggleAll(),i==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=jt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=jt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},vo=class extends mt{_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}${Dt.default.inverse(Dt.default.hidden("_"))}`;let t=this.masked,n=t.slice(0,this.cursor),i=t.slice(this.cursor);return`${n}${Dt.default.inverse(i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",n=>{this._setValue(n)})}},wi=class extends mt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:s})=>s===t.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?jt(i,1,this.options):i,this.changeValue(),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=jt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=jt(this.cursor,1,this.options);break}this.changeValue()})}},vi=class extends mt{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let n=t.caseSensitive===!0,i=this.options.map(({value:[s]})=>n?s:s?.toLowerCase());this.cursor=Math.max(i.indexOf(t.initialValue),0),this.on("key",(s,r)=>{if(!s)return;let o=n&&r.shift?s.toUpperCase():s;if(!i.includes(o))return;let a=this.options.find(({value:[d]})=>n?d===o:d?.toLowerCase()===s);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},$i=class extends mt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let n=t.slice(0,this.cursor),[i,...s]=t.slice(this.cursor);return`${n}${Dt.default.inverse(i)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var Qs={};mn(Qs,{S_BAR:()=>D,S_BAR_END:()=>Re,S_BAR_END_RIGHT:()=>Ro,S_BAR_H:()=>Ii,S_BAR_START:()=>Vs,S_BAR_START_RIGHT:()=>Io,S_CHECKBOX_ACTIVE:()=>Ai,S_CHECKBOX_INACTIVE:()=>yn,S_CHECKBOX_SELECTED:()=>Yt,S_CONNECT_LEFT:()=>Eo,S_CORNER_BOTTOM_LEFT:()=>Js,S_CORNER_BOTTOM_RIGHT:()=>Hs,S_CORNER_TOP_LEFT:()=>Po,S_CORNER_TOP_RIGHT:()=>Ws,S_ERROR:()=>zs,S_INFO:()=>Bs,S_PASSWORD_MASK:()=>To,S_RADIO_ACTIVE:()=>Un,S_RADIO_INACTIVE:()=>Zt,S_STEP_ACTIVE:()=>Ao,S_STEP_CANCEL:()=>Fs,S_STEP_ERROR:()=>Ls,S_STEP_SUBMIT:()=>Qt,S_SUCCESS:()=>Gs,S_WARN:()=>Ks,autocomplete:()=>Fo,autocompleteMultiselect:()=>ec,box:()=>sc,cancel:()=>ac,confirm:()=>We,group:()=>rc,groupMultiselect:()=>oc,intro:()=>dc,isCI:()=>Ms,isCancel:()=>de,isTTY:()=>Co,limitOptions:()=>wn,log:()=>ze,multiselect:()=>cc,note:()=>fc,outro:()=>lc,password:()=>pc,path:()=>hc,progress:()=>yc,select:()=>dt,selectKey:()=>bc,settings:()=>me,spinner:()=>qn,stream:()=>zt,symbol:()=>at,symbolBar:()=>Ys,taskLog:()=>$c,tasks:()=>wc,text:()=>Ue,unicode:()=>Ci,unicodeOr:()=>oe,updateSettings:()=>bo});function Ml(){return Ke.default.platform!=="win32"?Ke.default.env.TERM!=="linux":!!Ke.default.env.CI||!!Ke.default.env.WT_SESSION||!!Ke.default.env.TERMINUS_SUBLIME||Ke.default.env.ConEmuTask==="{cmd::Cmder}"||Ke.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ke.default.env.TERM_PROGRAM==="vscode"||Ke.default.env.TERM==="xterm-256color"||Ke.default.env.TERM==="alacritty"||Ke.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function bn(e,t,n){return String(e).normalize().replaceAll(`\r
44
+ `)),this._prevFrame=t;return}}this.output.write(Ne.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};Dn=class extends ft{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#n="";#i;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return Nt.default.inverse(Nt.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[n,...i]=this.userInput.slice(this._cursor);return`${t}${Nt.default.inverse(n)}${i.join("")}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(t){super(t),this.#t=t.options;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#i=t.filter??Xl;let i;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?i=t.initialValue:i=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0].value]),i)for(let s of i){let r=n.findIndex(o=>o.value===s);r!==-1&&(this.toggleSelected(s),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(s,r)=>this.#s(s,r)),this.on("userInput",s=>this.#r(s))}_isActionKey(t,n){return t===" "||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#s(t,n){let i=n.name==="up",s=n.name==="down",r=n.name==="return";i||s?(this.#e=St(this.#e,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=Zl(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter(n=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#n){this.#n=t;let n=this.options;t?this.filteredOptions=n.filter(r=>this.#i(t,r)):this.filteredOptions=[...n];let i=Yl(this.focusedValue,this.filteredOptions);this.#e=St(i,0,this.filteredOptions);let s=this.filteredOptions[this.#e];s&&!s.disabled?this.focusedValue=s.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},bi=class extends ft{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Ne.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},wi=class extends ft{options;cursor=0;#e;getGroupItems(t){return this.options.filter(n=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),i=this.value;return i===void 0?!1:n.every(s=>i.includes(s.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,i=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter(s=>i.findIndex(r=>r.value===s)===-1):this.value=[...this.value,...i.map(s=>s.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter(i=>i!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#e=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([i,s])=>[{value:i,group:!0,label:i},...s.map(r=>({...r,group:i}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===t.cursorAt),this.#e?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 s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(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 s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},vi=class extends ft{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,n=this.value!==void 0&&this.value.length===t.length;this.value=n?[]:t.map(i=>i.value)}toggleInvert(){let t=this.value;if(!t)return;let n=this._enabledOptions.filter(i=>!t.includes(i.value));this.value=n.map(i=>i.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter(n=>n!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let n=Math.max(this.options.findIndex(({value:i})=>i===t.cursorAt),0);this.cursor=this.options[n].disabled?St(n,1,this.options):n,this.on("key",i=>{i==="a"&&this.toggleAll(),i==="i"&&this.toggleInvert()}),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=St(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=St(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},jo=class extends ft{_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}${Nt.default.inverse(Nt.default.hidden("_"))}`;let t=this.masked,n=t.slice(0,this.cursor),i=t.slice(this.cursor);return`${n}${Nt.default.inverse(i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",n=>{this._setValue(n)})}},$i=class extends ft{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:s})=>s===t.initialValue),i=n===-1?0:n;this.cursor=this.options[i].disabled?St(i,1,this.options):i,this.changeValue(),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=St(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=St(this.cursor,1,this.options);break}this.changeValue()})}},ki=class extends ft{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let n=t.caseSensitive===!0,i=this.options.map(({value:[s]})=>n?s:s?.toLowerCase());this.cursor=Math.max(i.indexOf(t.initialValue),0),this.on("key",(s,r)=>{if(!s)return;let o=n&&r.shift?s.toUpperCase():s;if(!i.includes(o))return;let a=this.options.find(({value:[d]})=>n?d===o:d?.toLowerCase()===s);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},_i=class extends ft{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let n=t.slice(0,this.cursor),[i,...s]=t.slice(this.cursor);return`${n}${Nt.default.inverse(i)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",n=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var nr={};fn(nr,{S_BAR:()=>D,S_BAR_END:()=>Re,S_BAR_END_RIGHT:()=>No,S_BAR_H:()=>Ti,S_BAR_START:()=>Js,S_BAR_START_RIGHT:()=>Do,S_CHECKBOX_ACTIVE:()=>Ri,S_CHECKBOX_INACTIVE:()=>bn,S_CHECKBOX_SELECTED:()=>Xt,S_CONNECT_LEFT:()=>qo,S_CORNER_BOTTOM_LEFT:()=>Ks,S_CORNER_BOTTOM_RIGHT:()=>Gs,S_CORNER_TOP_LEFT:()=>Mo,S_CORNER_TOP_RIGHT:()=>Bs,S_ERROR:()=>Zs,S_INFO:()=>zs,S_PASSWORD_MASK:()=>Uo,S_RADIO_ACTIVE:()=>qn,S_RADIO_INACTIVE:()=>Qt,S_STEP_ACTIVE:()=>Po,S_STEP_CANCEL:()=>Ws,S_STEP_ERROR:()=>Hs,S_STEP_SUBMIT:()=>en,S_SUCCESS:()=>Ys,S_WARN:()=>Xs,autocomplete:()=>Jo,autocompleteMultiselect:()=>pc,box:()=>bc,cancel:()=>$c,confirm:()=>He,group:()=>wc,groupMultiselect:()=>vc,intro:()=>kc,isCI:()=>Vs,isCancel:()=>de,isTTY:()=>Eo,limitOptions:()=>vn,log:()=>Ye,multiselect:()=>xc,note:()=>Cc,outro:()=>_c,password:()=>Oc,path:()=>Ic,progress:()=>Rc,select:()=>lt,selectKey:()=>Tc,settings:()=>fe,spinner:()=>Mn,stream:()=>Yt,symbol:()=>dt,symbolBar:()=>Qs,taskLog:()=>Dc,tasks:()=>Ec,text:()=>Ue,unicode:()=>Ai,unicodeOr:()=>oe,updateSettings:()=>_o});function Ql(){return ze.default.platform!=="win32"?ze.default.env.TERM!=="linux":!!ze.default.env.CI||!!ze.default.env.WT_SESSION||!!ze.default.env.TERMINUS_SUBLIME||ze.default.env.ConEmuTask==="{cmd::Cmder}"||ze.default.env.TERM_PROGRAM==="Terminus-Sublime"||ze.default.env.TERM_PROGRAM==="vscode"||ze.default.env.TERM==="xterm-256color"||ze.default.env.TERM==="alacritty"||ze.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function wn(e,t,n){return String(e).normalize().replaceAll(`\r
45
45
  `,`
46
46
  `).split(`
47
- `).map(i=>Xl(i,t,n)).join(`
48
- `)}function xo(e){return e.label??String(e.value??"")}function Mo(e,t){if(!e)return!0;let n=(t.label??String(t.value??"")).toLowerCase(),i=(t.hint??"").toLowerCase(),s=String(t.value).toLowerCase(),r=e.toLowerCase();return n.includes(r)||i.includes(r)||s.includes(r)}function Ql(e,t){let n=[];for(let i of t)e.includes(i.value)&&n.push(i);return n}function jo(e,t,n,i){let s=n,r=n;return i==="center"?s=Math.floor((t-e)/2):i==="right"&&(s=t-e-n),r=t-s-e,[s,r]}function yc({style:e="heavy",max:t=100,size:n=40,...i}={}){let s=qn(i),r=0,o="",a=Math.max(1,t),d=Math.max(1,n),m=$=>{switch($){case"initial":case"active":return h.default.magenta;case"error":case"cancel":return h.default.red;case"submit":return h.default.green;default:return h.default.magenta}},f=($,k)=>{let w=Math.floor(r/a*d);return`${m($)(So[e].repeat(w))}${h.default.dim(So[e].repeat(d-w))} ${k}`},p=($="")=>{o=$,s.start(f("initial",$))},g=($=1,k)=>{r=Math.min(a,$+r),s.message(f("active",k??o)),o=k??o};return{start:p,stop:s.stop,cancel:s.cancel,error:s.error,clear:s.clear,advance:g,isCancelled:s.isCancelled,message:$=>g(0,$)}}var h,Ke,Xt,Nn,gn,Oi,Ci,Ms,Co,oe,Ao,Fs,Ls,Qt,Vs,D,Re,Io,Ro,Un,Zt,Ai,Yt,yn,To,Ii,Ws,Eo,Hs,Js,Po,Bs,Gs,Ks,zs,at,Ys,Fl,Ll,Vl,Ns,ki,xi,Us,ji,Wl,Hl,Do,Jl,Fe,Ri,No,Bl,Xs,Uo,Gl,qo,Zs,$o,Kl,_o,ko,zl,qs,Yl,Xl,Zl,wn,Fo,ec,tc,nc,ic,sc,We,rc,oc,ze,ac,dc,lc,Dn,cc,uc,mc,fc,pc,hc,gc,qn,So,Si,dt,bc,Oo,zt,wc,vc,$c,Ue,qe=je(()=>{Ds();Ds();h=N(F(),1),Ke=N(require("node:process"),1),Xt=require("node:fs"),Nn=require("node:path"),gn=N(xs(),1),Oi=require("node:util");Ci=Ml(),Ms=()=>process.env.CI==="true",Co=e=>e.isTTY===!0,oe=(e,t)=>Ci?e:t,Ao=oe("\u25C6","*"),Fs=oe("\u25A0","x"),Ls=oe("\u25B2","x"),Qt=oe("\u25C7","o"),Vs=oe("\u250C","T"),D=oe("\u2502","|"),Re=oe("\u2514","\u2014"),Io=oe("\u2510","T"),Ro=oe("\u2518","\u2014"),Un=oe("\u25CF",">"),Zt=oe("\u25CB"," "),Ai=oe("\u25FB","[\u2022]"),Yt=oe("\u25FC","[+]"),yn=oe("\u25FB","[ ]"),To=oe("\u25AA","\u2022"),Ii=oe("\u2500","-"),Ws=oe("\u256E","+"),Eo=oe("\u251C","+"),Hs=oe("\u256F","+"),Js=oe("\u2570","+"),Po=oe("\u256D","+"),Bs=oe("\u25CF","\u2022"),Gs=oe("\u25C6","*"),Ks=oe("\u25B2","!"),zs=oe("\u25A0","x"),at=e=>{switch(e){case"initial":case"active":return h.default.cyan(Ao);case"cancel":return h.default.red(Fs);case"error":return h.default.yellow(Ls);case"submit":return h.default.green(Qt)}},Ys=e=>{switch(e){case"initial":case"active":return h.default.cyan(D);case"cancel":return h.default.red(D);case"error":return h.default.yellow(D);case"submit":return h.default.green(D)}},Fl=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Ll=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Vl=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Ns=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ki=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,xi=/\t{1,1000}/y,Us=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"),ji=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Wl=new RegExp("\\p{M}+","gu"),Hl={limit:1/0,ellipsis:""},Do=(e,t={},n={})=>{let i=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?Do(s,Hl,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,d=n.tabWidth??8,m=n.ambiguousWidth??1,f=n.emojiWidth??2,p=n.fullWidthWidth??2,g=n.regularWidth??1,$=n.wideWidth??2,k=0,w=0,_=e.length,S=0,C=!1,R=_,M=Math.max(0,i-r),H=0,ee=0,q=0,U=0;e:for(;;){if(ee>H||w>=_&&w>k){let ce=e.slice(H,ee)||e.slice(k,w);S=0;for(let le of ce.replaceAll(Wl,"")){let P=le.codePointAt(0)||0;if(Ll(P)?U=p:Vl(P)?U=$:m!==g&&Fl(P)?U=m:U=g,q+U>M&&(R=Math.min(R,Math.max(H,k)+S)),q+U>i){C=!0;break e}S+=le.length,q+=U}H=ee=0}if(w>=_)break;if(ji.lastIndex=w,ji.test(e)){if(S=ji.lastIndex-w,U=S*g,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/g))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=ji.lastIndex;continue}if(Ns.lastIndex=w,Ns.test(e)){if(q+o>M&&(R=Math.min(R,w)),q+o>i){C=!0;break}q+=o,H=k,ee=w,w=k=Ns.lastIndex;continue}if(ki.lastIndex=w,ki.test(e)){if(S=ki.lastIndex-w,U=S*a,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/a))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=ki.lastIndex;continue}if(xi.lastIndex=w,xi.test(e)){if(S=xi.lastIndex-w,U=S*d,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/d))),q+U>i){C=!0;break}q+=U,H=k,ee=w,w=k=xi.lastIndex;continue}if(Us.lastIndex=w,Us.test(e)){if(q+f>M&&(R=Math.min(R,w)),q+f>i){C=!0;break}q+=f,H=k,ee=w,w=k=Us.lastIndex;continue}w+=1}return{width:C?M:q,index:C?R:_,truncated:C,ellipsed:C&&i>=r}},Jl={limit:1/0,ellipsis:"",ellipsisWidth:0},Fe=(e,t={})=>Do(e,Jl,t).width,Ri="\x1B",No="\x9B",Bl=39,Xs="\x07",Uo="[",Gl="]",qo="m",Zs=`${Gl}8;;`,$o=new RegExp(`(?:\\${Uo}(?<code>\\d+)m|\\${Zs}(?<uri>.*)${Xs})`,"y"),Kl=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},_o=e=>`${Ri}${Uo}${e}${qo}`,ko=e=>`${Ri}${Zs}${e}${Xs}`,zl=e=>e.map(t=>Fe(t)),qs=(e,t,n)=>{let i=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:Fe(o),d=i.next(),m=i.next(),f=0;for(;!d.done;){let p=d.value,g=Fe(p);a+g<=n?e[e.length-1]+=p:(e.push(p),a=0),(p===Ri||p===No)&&(s=!0,r=t.startsWith(Zs,f+1)),s?r?p===Xs&&(s=!1,r=!1):p===qo&&(s=!1):(a+=g,a===n&&!m.done&&(e.push(""),a=0)),d=m,m=i.next(),f+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Yl=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Fe(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},Xl=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",s,r,o=e.split(" "),a=zl(o),d=[""];for(let[k,w]of o.entries()){n.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let _=Fe(d.at(-1)??"");if(k!==0&&(_>=t&&(n.wordWrap===!1||n.trim===!1)&&(d.push(""),_=0),(_>0||n.trim===!1)&&(d[d.length-1]+=" ",_++)),n.hard&&a[k]>t){let S=t-_,C=1+Math.floor((a[k]-S-1)/t);Math.floor((a[k]-1)/t)<C&&d.push(""),qs(d,w,t);continue}if(_+a[k]>t&&_>0&&a[k]>0){if(n.wordWrap===!1&&_<t){qs(d,w,t);continue}d.push("")}if(_+a[k]>t&&n.wordWrap===!1){qs(d,w,t);continue}d[d.length-1]+=w}n.trim!==!1&&(d=d.map(k=>Yl(k)));let m=d.join(`
49
- `),f=m[Symbol.iterator](),p=f.next(),g=f.next(),$=0;for(;!p.done;){let k=p.value,w=g.value;if(i+=k,k===Ri||k===No){$o.lastIndex=$+1;let S=$o.exec(m)?.groups;if(S?.code!==void 0){let C=Number.parseFloat(S.code);s=C===Bl?void 0:C}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let _=s?Kl(s):void 0;w===`
50
- `?(r&&(i+=ko("")),s&&_&&(i+=_o(_))):k===`
51
- `&&(s&&_&&(i+=_o(s)),r&&(i+=ko(r))),$+=k.length,p=g,g=f.next()}return i};Zl=(e,t,n,i,s)=>{let r=t,o=0;for(let a=n;a<i;a++){let d=e[a];if(r=r-d.length,o++,r<=s)break}return{lineCount:r,removals:o}},wn=e=>{let{cursor:t,options:n,style:i}=e,s=e.output??process.stdout,r=Kt(s),o=e.columnPadding??0,a=e.rowPadding??4,d=r-o,m=Ps(s),f=h.default.dim("..."),p=e.maxItems??Number.POSITIVE_INFINITY,g=Math.max(m-a,0),$=Math.max(Math.min(p,g),5),k=0;t>=$-3&&(k=Math.max(Math.min(t-$+3,n.length-$),0));let w=$<n.length&&k>0,_=$<n.length&&k+$<n.length,S=Math.min(k+$,n.length),C=[],R=0;w&&R++,_&&R++;let M=k+(w?1:0),H=S-(_?1:0);for(let q=M;q<H;q++){let U=bn(i(n[q],q===t),d,{hard:!0,trim:!1}).split(`
52
- `);C.push(U),R+=U.length}if(R>g){let q=0,U=0,ce=R,le=t-M,P=(he,ie)=>Zl(C,ce,he,ie,g);w?({lineCount:ce,removals:q}=P(0,le),ce>g&&({lineCount:ce,removals:U}=P(le+1,C.length))):({lineCount:ce,removals:U}=P(le+1,C.length),ce>g&&({lineCount:ce,removals:q}=P(0,le))),q>0&&(w=!0,C.splice(0,q)),U>0&&(_=!0,C.splice(C.length-U,U))}let ee=[];w&&ee.push(f);for(let q of C)for(let U of q)ee.push(U);return _&&ee.push(f),ee};Fo=e=>new Pn({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,n)=>Mo(t,n)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??me.withGuide,n=t?[`${h.default.gray(D)}`,`${at(this.state)} ${e.message}`]:[`${at(this.state)} ${e.message}`],i=this.userInput,s=this.options,r=e.placeholder,o=i===""&&r!==void 0,a=(d,m)=>{let f=xo(d),p=d.hint&&d.value===this.focusedValue?h.default.dim(` (${d.hint})`):"";switch(m){case"active":return`${h.default.green(Un)} ${f}${p}`;case"inactive":return`${h.default.dim(Zt)} ${h.default.dim(f)}`;case"disabled":return`${h.default.gray(Zt)} ${h.default.strikethrough(h.default.gray(f))}`}};switch(this.state){case"submit":{let d=Ql(this.selectedValues,s),m=d.length>0?` ${h.default.dim(d.map(xo).join(", "))}`:"",f=t?h.default.gray(D):"";return`${n.join(`
47
+ `).map(i=>uc(i,t,n)).join(`
48
+ `)}function Io(e){return e.label??String(e.value??"")}function Ho(e,t){if(!e)return!0;let n=(t.label??String(t.value??"")).toLowerCase(),i=(t.hint??"").toLowerCase(),s=String(t.value).toLowerCase(),r=e.toLowerCase();return n.includes(r)||i.includes(r)||s.includes(r)}function fc(e,t){let n=[];for(let i of t)e.includes(i.value)&&n.push(i);return n}function Ao(e,t,n,i){let s=n,r=n;return i==="center"?s=Math.floor((t-e)/2):i==="right"&&(s=t-e-n),r=t-s-e,[s,r]}function Rc({style:e="heavy",max:t=100,size:n=40,...i}={}){let s=Mn(i),r=0,o="",a=Math.max(1,t),d=Math.max(1,n),m=$=>{switch($){case"initial":case"active":return h.default.magenta;case"error":case"cancel":return h.default.red;case"submit":return h.default.green;default:return h.default.magenta}},f=($,_)=>{let w=Math.floor(r/a*d);return`${m($)(Ro[e].repeat(w))}${h.default.dim(Ro[e].repeat(d-w))} ${_}`},p=($="")=>{o=$,s.start(f("initial",$))},g=($=1,_)=>{r=Math.min(a,$+r),s.message(f("active",_??o)),o=_??o};return{start:p,stop:s.stop,cancel:s.cancel,error:s.error,clear:s.clear,advance:g,isCancelled:s.isCancelled,message:$=>g(0,$)}}var h,ze,Zt,Un,yn,Ii,Ai,Vs,Eo,oe,Po,Ws,Hs,en,Js,D,Re,Do,No,qn,Qt,Ri,Xt,bn,Uo,Ti,Bs,qo,Gs,Ks,Mo,zs,Ys,Xs,Zs,dt,Qs,ec,tc,nc,Ms,ji,Si,Fs,Ci,ic,sc,Fo,rc,Le,Ei,Lo,oc,er,Vo,ac,Wo,tr,So,dc,Co,Oo,lc,Ls,cc,uc,mc,vn,Jo,pc,hc,gc,yc,bc,He,wc,vc,Ye,$c,kc,_c,Nn,xc,jc,Sc,Cc,Oc,Ic,Ac,Mn,Ro,Oi,lt,Tc,To,Yt,Ec,Pc,Dc,Ue,qe=_e(()=>{qs();qs();h=N(F(),1),ze=N(require("node:process"),1),Zt=require("node:fs"),Un=require("node:path"),yn=N(Cs(),1),Ii=require("node:util");Ai=Ql(),Vs=()=>process.env.CI==="true",Eo=e=>e.isTTY===!0,oe=(e,t)=>Ai?e:t,Po=oe("\u25C6","*"),Ws=oe("\u25A0","x"),Hs=oe("\u25B2","x"),en=oe("\u25C7","o"),Js=oe("\u250C","T"),D=oe("\u2502","|"),Re=oe("\u2514","\u2014"),Do=oe("\u2510","T"),No=oe("\u2518","\u2014"),qn=oe("\u25CF",">"),Qt=oe("\u25CB"," "),Ri=oe("\u25FB","[\u2022]"),Xt=oe("\u25FC","[+]"),bn=oe("\u25FB","[ ]"),Uo=oe("\u25AA","\u2022"),Ti=oe("\u2500","-"),Bs=oe("\u256E","+"),qo=oe("\u251C","+"),Gs=oe("\u256F","+"),Ks=oe("\u2570","+"),Mo=oe("\u256D","+"),zs=oe("\u25CF","\u2022"),Ys=oe("\u25C6","*"),Xs=oe("\u25B2","!"),Zs=oe("\u25A0","x"),dt=e=>{switch(e){case"initial":case"active":return h.default.cyan(Po);case"cancel":return h.default.red(Ws);case"error":return h.default.yellow(Hs);case"submit":return h.default.green(en)}},Qs=e=>{switch(e){case"initial":case"active":return h.default.cyan(D);case"cancel":return h.default.red(D);case"error":return h.default.yellow(D);case"submit":return h.default.green(D)}},ec=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,tc=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,nc=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Ms=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ji=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Si=/\t{1,1000}/y,Fs=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"),Ci=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ic=new RegExp("\\p{M}+","gu"),sc={limit:1/0,ellipsis:""},Fo=(e,t={},n={})=>{let i=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?Fo(s,sc,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,d=n.tabWidth??8,m=n.ambiguousWidth??1,f=n.emojiWidth??2,p=n.fullWidthWidth??2,g=n.regularWidth??1,$=n.wideWidth??2,_=0,w=0,k=e.length,S=0,O=!1,R=k,M=Math.max(0,i-r),H=0,ee=0,q=0,U=0;e:for(;;){if(ee>H||w>=k&&w>_){let ce=e.slice(H,ee)||e.slice(_,w);S=0;for(let le of ce.replaceAll(ic,"")){let P=le.codePointAt(0)||0;if(tc(P)?U=p:nc(P)?U=$:m!==g&&ec(P)?U=m:U=g,q+U>M&&(R=Math.min(R,Math.max(H,_)+S)),q+U>i){O=!0;break e}S+=le.length,q+=U}H=ee=0}if(w>=k)break;if(Ci.lastIndex=w,Ci.test(e)){if(S=Ci.lastIndex-w,U=S*g,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/g))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=Ci.lastIndex;continue}if(Ms.lastIndex=w,Ms.test(e)){if(q+o>M&&(R=Math.min(R,w)),q+o>i){O=!0;break}q+=o,H=_,ee=w,w=_=Ms.lastIndex;continue}if(ji.lastIndex=w,ji.test(e)){if(S=ji.lastIndex-w,U=S*a,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/a))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=ji.lastIndex;continue}if(Si.lastIndex=w,Si.test(e)){if(S=Si.lastIndex-w,U=S*d,q+U>M&&(R=Math.min(R,w+Math.floor((M-q)/d))),q+U>i){O=!0;break}q+=U,H=_,ee=w,w=_=Si.lastIndex;continue}if(Fs.lastIndex=w,Fs.test(e)){if(q+f>M&&(R=Math.min(R,w)),q+f>i){O=!0;break}q+=f,H=_,ee=w,w=_=Fs.lastIndex;continue}w+=1}return{width:O?M:q,index:O?R:k,truncated:O,ellipsed:O&&i>=r}},rc={limit:1/0,ellipsis:"",ellipsisWidth:0},Le=(e,t={})=>Fo(e,rc,t).width,Ei="\x1B",Lo="\x9B",oc=39,er="\x07",Vo="[",ac="]",Wo="m",tr=`${ac}8;;`,So=new RegExp(`(?:\\${Vo}(?<code>\\d+)m|\\${tr}(?<uri>.*)${er})`,"y"),dc=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Co=e=>`${Ei}${Vo}${e}${Wo}`,Oo=e=>`${Ei}${tr}${e}${er}`,lc=e=>e.map(t=>Le(t)),Ls=(e,t,n)=>{let i=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:Le(o),d=i.next(),m=i.next(),f=0;for(;!d.done;){let p=d.value,g=Le(p);a+g<=n?e[e.length-1]+=p:(e.push(p),a=0),(p===Ei||p===Lo)&&(s=!0,r=t.startsWith(tr,f+1)),s?r?p===er&&(s=!1,r=!1):p===Wo&&(s=!1):(a+=g,a===n&&!m.done&&(e.push(""),a=0)),d=m,m=i.next(),f+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},cc=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Le(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},uc=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",s,r,o=e.split(" "),a=lc(o),d=[""];for(let[_,w]of o.entries()){n.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let k=Le(d.at(-1)??"");if(_!==0&&(k>=t&&(n.wordWrap===!1||n.trim===!1)&&(d.push(""),k=0),(k>0||n.trim===!1)&&(d[d.length-1]+=" ",k++)),n.hard&&a[_]>t){let S=t-k,O=1+Math.floor((a[_]-S-1)/t);Math.floor((a[_]-1)/t)<O&&d.push(""),Ls(d,w,t);continue}if(k+a[_]>t&&k>0&&a[_]>0){if(n.wordWrap===!1&&k<t){Ls(d,w,t);continue}d.push("")}if(k+a[_]>t&&n.wordWrap===!1){Ls(d,w,t);continue}d[d.length-1]+=w}n.trim!==!1&&(d=d.map(_=>cc(_)));let m=d.join(`
49
+ `),f=m[Symbol.iterator](),p=f.next(),g=f.next(),$=0;for(;!p.done;){let _=p.value,w=g.value;if(i+=_,_===Ei||_===Lo){So.lastIndex=$+1;let S=So.exec(m)?.groups;if(S?.code!==void 0){let O=Number.parseFloat(S.code);s=O===oc?void 0:O}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let k=s?dc(s):void 0;w===`
50
+ `?(r&&(i+=Oo("")),s&&k&&(i+=Co(k))):_===`
51
+ `&&(s&&k&&(i+=Co(s)),r&&(i+=Oo(r))),$+=_.length,p=g,g=f.next()}return i};mc=(e,t,n,i,s)=>{let r=t,o=0;for(let a=n;a<i;a++){let d=e[a];if(r=r-d.length,o++,r<=s)break}return{lineCount:r,removals:o}},vn=e=>{let{cursor:t,options:n,style:i}=e,s=e.output??process.stdout,r=zt(s),o=e.columnPadding??0,a=e.rowPadding??4,d=r-o,m=Us(s),f=h.default.dim("..."),p=e.maxItems??Number.POSITIVE_INFINITY,g=Math.max(m-a,0),$=Math.max(Math.min(p,g),5),_=0;t>=$-3&&(_=Math.max(Math.min(t-$+3,n.length-$),0));let w=$<n.length&&_>0,k=$<n.length&&_+$<n.length,S=Math.min(_+$,n.length),O=[],R=0;w&&R++,k&&R++;let M=_+(w?1:0),H=S-(k?1:0);for(let q=M;q<H;q++){let U=wn(i(n[q],q===t),d,{hard:!0,trim:!1}).split(`
52
+ `);O.push(U),R+=U.length}if(R>g){let q=0,U=0,ce=R,le=t-M,P=(ge,ie)=>mc(O,ce,ge,ie,g);w?({lineCount:ce,removals:q}=P(0,le),ce>g&&({lineCount:ce,removals:U}=P(le+1,O.length))):({lineCount:ce,removals:U}=P(le+1,O.length),ce>g&&({lineCount:ce,removals:q}=P(0,le))),q>0&&(w=!0,O.splice(0,q)),U>0&&(k=!0,O.splice(O.length-U,U))}let ee=[];w&&ee.push(f);for(let q of O)for(let U of q)ee.push(U);return k&&ee.push(f),ee};Jo=e=>new Dn({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,n)=>Ho(t,n)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??fe.withGuide,n=t?[`${h.default.gray(D)}`,`${dt(this.state)} ${e.message}`]:[`${dt(this.state)} ${e.message}`],i=this.userInput,s=this.options,r=e.placeholder,o=i===""&&r!==void 0,a=(d,m)=>{let f=Io(d),p=d.hint&&d.value===this.focusedValue?h.default.dim(` (${d.hint})`):"";switch(m){case"active":return`${h.default.green(qn)} ${f}${p}`;case"inactive":return`${h.default.dim(Qt)} ${h.default.dim(f)}`;case"disabled":return`${h.default.gray(Qt)} ${h.default.strikethrough(h.default.gray(f))}`}};switch(this.state){case"submit":{let d=fc(this.selectedValues,s),m=d.length>0?` ${h.default.dim(d.map(Io).join(", "))}`:"",f=t?h.default.gray(D):"";return`${n.join(`
53
53
  `)}
54
54
  ${f}${m}`}case"cancel":{let d=i?` ${h.default.strikethrough(h.default.dim(i))}`:"",m=t?h.default.gray(D):"";return`${n.join(`
55
55
  `)}
56
- ${m}${d}`}default:{let d=this.state==="error"?h.default.yellow:h.default.cyan,m=t?`${d(D)} `:"",f=t?d(Re):"",p="";if(this.isNavigating||o){let C=o?r:i;p=C!==""?` ${h.default.dim(C)}`:""}else p=` ${this.userInputWithCursor}`;let g=this.filteredOptions.length!==s.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",$=this.filteredOptions.length===0&&i?[`${m}${h.default.yellow("No matches found")}`]:[],k=this.state==="error"?[`${m}${h.default.yellow(this.error)}`]:[];t&&n.push(`${m.trimEnd()}`),n.push(`${m}${h.default.dim("Search:")}${p}${g}`,...$,...k);let w=[`${h.default.dim("\u2191/\u2193")} to select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],_=[`${m}${w.join(" \u2022 ")}`,f],S=this.filteredOptions.length===0?[]:wn({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:n.length+_.length,style:(C,R)=>a(C,C.disabled?"disabled":R?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...n,...S.map(C=>`${m}${C}`),..._].join(`
57
- `)}}}}).prompt(),ec=e=>{let t=(i,s,r,o)=>{let a=r.includes(i.value),d=i.label??String(i.value??""),m=i.hint&&o!==void 0&&i.value===o?h.default.dim(` (${i.hint})`):"",f=a?h.default.green(Yt):h.default.dim(yn);return i.disabled?`${h.default.gray(yn)} ${h.default.strikethrough(h.default.gray(d))}`:s?`${f} ${d}${m}`:`${f} ${h.default.dim(d)}`},n=new Pn({options:e.options,multiple:!0,filter:e.filter??((i,s)=>Mo(i,s)),validate:()=>{if(e.required&&n.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let i=`${h.default.gray(D)}
58
- ${at(this.state)} ${e.message}
59
- `,s=this.userInput,r=e.placeholder,o=s===""&&r!==void 0,a=this.isNavigating||o?h.default.dim(o?r:s):this.userInputWithCursor,d=this.options,m=this.filteredOptions.length!==d.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${i}${h.default.gray(D)} ${h.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${i}${h.default.gray(D)} ${h.default.strikethrough(h.default.dim(s))}`;default:{let f=this.state==="error"?h.default.yellow:h.default.cyan,p=[`${h.default.dim("\u2191/\u2193")} to navigate`,`${h.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],g=this.filteredOptions.length===0&&s?[`${f(D)} ${h.default.yellow("No matches found")}`]:[],$=this.state==="error"?[`${f(D)} ${h.default.yellow(this.error)}`]:[],k=[...`${i}${f(D)}`.split(`
60
- `),`${f(D)} ${h.default.dim("Search:")} ${a}${m}`,...g,...$],w=[`${f(D)} ${p.join(" \u2022 ")}`,`${f(Re)}`],_=wn({cursor:this.cursor,options:this.filteredOptions,style:(S,C)=>t(S,C,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:k.length+w.length});return[...k,..._.map(S=>`${f(D)} ${S}`),...w].join(`
61
- `)}}}});return n.prompt()},tc=[Po,Ws,Js,Hs],nc=[Vs,Io,Re,Ro];ic=e=>e,sc=(e="",t="",n)=>{let i=n?.output??process.stdout,s=Kt(i),r=2,o=n?.titlePadding??1,a=n?.contentPadding??2,d=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),m=n?.withGuide??me.withGuide?`${D} `:"",f=n?.formatBorder??ic,p=(n?.rounded?tc:nc).map(f),g=f(Ii),$=f(D),k=Fe(m),w=Fe(t),_=s-k,S=Math.floor(s*d)-k;if(n?.width==="auto"){let ce=e.split(`
62
- `),le=w+o*2;for(let he of ce){let ie=Fe(he)+a*2;ie>le&&(le=ie)}let P=le+r;P<S&&(S=P)}S%2!==0&&(S<_?S++:S--);let C=S-r,R=C-o*2,M=w>R?`${t.slice(0,R-3)}...`:t,[H,ee]=jo(Fe(M),C,o,n?.titleAlign),q=bn(e,C-a*2,{hard:!0,trim:!1});i.write(`${m}${p[0]}${g.repeat(H)}${M}${g.repeat(ee)}${p[1]}
56
+ ${m}${d}`}default:{let d=this.state==="error"?h.default.yellow:h.default.cyan,m=t?`${d(D)} `:"",f=t?d(Re):"",p="";if(this.isNavigating||o){let O=o?r:i;p=O!==""?` ${h.default.dim(O)}`:""}else p=` ${this.userInputWithCursor}`;let g=this.filteredOptions.length!==s.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",$=this.filteredOptions.length===0&&i?[`${m}${h.default.yellow("No matches found")}`]:[],_=this.state==="error"?[`${m}${h.default.yellow(this.error)}`]:[];t&&n.push(`${m.trimEnd()}`),n.push(`${m}${h.default.dim("Search:")}${p}${g}`,...$,..._);let w=[`${h.default.dim("\u2191/\u2193")} to select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],k=[`${m}${w.join(" \u2022 ")}`,f],S=this.filteredOptions.length===0?[]:vn({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:n.length+k.length,style:(O,R)=>a(O,O.disabled?"disabled":R?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...n,...S.map(O=>`${m}${O}`),...k].join(`
57
+ `)}}}}).prompt(),pc=e=>{let t=(i,s,r,o)=>{let a=r.includes(i.value),d=i.label??String(i.value??""),m=i.hint&&o!==void 0&&i.value===o?h.default.dim(` (${i.hint})`):"",f=a?h.default.green(Xt):h.default.dim(bn);return i.disabled?`${h.default.gray(bn)} ${h.default.strikethrough(h.default.gray(d))}`:s?`${f} ${d}${m}`:`${f} ${h.default.dim(d)}`},n=new Dn({options:e.options,multiple:!0,filter:e.filter??((i,s)=>Ho(i,s)),validate:()=>{if(e.required&&n.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let i=`${h.default.gray(D)}
58
+ ${dt(this.state)} ${e.message}
59
+ `,s=this.userInput,r=e.placeholder,o=s===""&&r!==void 0,a=this.isNavigating||o?h.default.dim(o?r:s):this.userInputWithCursor,d=this.options,m=this.filteredOptions.length!==d.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${i}${h.default.gray(D)} ${h.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${i}${h.default.gray(D)} ${h.default.strikethrough(h.default.dim(s))}`;default:{let f=this.state==="error"?h.default.yellow:h.default.cyan,p=[`${h.default.dim("\u2191/\u2193")} to navigate`,`${h.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],g=this.filteredOptions.length===0&&s?[`${f(D)} ${h.default.yellow("No matches found")}`]:[],$=this.state==="error"?[`${f(D)} ${h.default.yellow(this.error)}`]:[],_=[...`${i}${f(D)}`.split(`
60
+ `),`${f(D)} ${h.default.dim("Search:")} ${a}${m}`,...g,...$],w=[`${f(D)} ${p.join(" \u2022 ")}`,`${f(Re)}`],k=vn({cursor:this.cursor,options:this.filteredOptions,style:(S,O)=>t(S,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:_.length+w.length});return[..._,...k.map(S=>`${f(D)} ${S}`),...w].join(`
61
+ `)}}}});return n.prompt()},hc=[Mo,Bs,Ks,Gs],gc=[Js,Do,Re,No];yc=e=>e,bc=(e="",t="",n)=>{let i=n?.output??process.stdout,s=zt(i),r=2,o=n?.titlePadding??1,a=n?.contentPadding??2,d=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),m=n?.withGuide??fe.withGuide?`${D} `:"",f=n?.formatBorder??yc,p=(n?.rounded?hc:gc).map(f),g=f(Ti),$=f(D),_=Le(m),w=Le(t),k=s-_,S=Math.floor(s*d)-_;if(n?.width==="auto"){let ce=e.split(`
62
+ `),le=w+o*2;for(let ge of ce){let ie=Le(ge)+a*2;ie>le&&(le=ie)}let P=le+r;P<S&&(S=P)}S%2!==0&&(S<k?S++:S--);let O=S-r,R=O-o*2,M=w>R?`${t.slice(0,R-3)}...`:t,[H,ee]=Ao(Le(M),O,o,n?.titleAlign),q=wn(e,O-a*2,{hard:!0,trim:!1});i.write(`${m}${p[0]}${g.repeat(H)}${M}${g.repeat(ee)}${p[1]}
63
63
  `);let U=q.split(`
64
- `);for(let ce of U){let[le,P]=jo(Fe(ce),C,a,n?.contentAlign);i.write(`${m}${$}${" ".repeat(le)}${ce}${" ".repeat(P)}${$}
65
- `)}i.write(`${m}${p[2]}${g.repeat(C)}${p[3]}
66
- `)},We=e=>{let t=e.active??"Yes",n=e.inactive??"No";return new gi({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??me.withGuide,s=`${i?`${h.default.gray(D)}
67
- `:""}${at(this.state)} ${e.message}
64
+ `);for(let ce of U){let[le,P]=Ao(Le(ce),O,a,n?.contentAlign);i.write(`${m}${$}${" ".repeat(le)}${ce}${" ".repeat(P)}${$}
65
+ `)}i.write(`${m}${p[2]}${g.repeat(O)}${p[3]}
66
+ `)},He=e=>{let t=e.active??"Yes",n=e.inactive??"No";return new bi({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??fe.withGuide,s=`${i?`${h.default.gray(D)}
67
+ `:""}${dt(this.state)} ${e.message}
68
68
  `,r=this.value?t:n;switch(this.state){case"submit":{let o=i?`${h.default.gray(D)} `:"";return`${s}${o}${h.default.dim(r)}`}case"cancel":{let o=i?`${h.default.gray(D)} `:"";return`${s}${o}${h.default.strikethrough(h.default.dim(r))}${i?`
69
- ${h.default.gray(D)}`:""}`}default:{let o=i?`${h.default.cyan(D)} `:"",a=i?h.default.cyan(Re):"";return`${s}${o}${this.value?`${h.default.green(Un)} ${t}`:`${h.default.dim(Zt)} ${h.default.dim(t)}`}${e.vertical?i?`
69
+ ${h.default.gray(D)}`:""}`}default:{let o=i?`${h.default.cyan(D)} `:"",a=i?h.default.cyan(Re):"";return`${s}${o}${this.value?`${h.default.green(qn)} ${t}`:`${h.default.dim(Qt)} ${h.default.dim(t)}`}${e.vertical?i?`
70
70
  ${h.default.cyan(D)} `:`
71
- `:` ${h.default.dim("/")} `}${this.value?`${h.default.dim(Zt)} ${h.default.dim(n)}`:`${h.default.green(Un)} ${n}`}
71
+ `:` ${h.default.dim("/")} `}${this.value?`${h.default.dim(Qt)} ${h.default.dim(n)}`:`${h.default.green(qn)} ${n}`}
72
72
  ${a}
73
- `}}}}).prompt()},rc=async(e,t)=>{let n={},i=Object.keys(e);for(let s of i){let r=e[s],o=await r({results:n})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&de(o)){n[s]="canceled",t.onCancel({results:n});continue}n[s]=o}return n},oc=e=>{let{selectableGroups:t=!0,groupSpacing:n=0}=e,i=(r,o,a=[])=>{let d=r.label??String(r.value),m=typeof r.group=="string",f=m&&(a[a.indexOf(r)+1]??{group:!0}),p=m&&f&&f.group===!0,g=m?t?`${p?Re:D} `:" ":"",$="";if(n>0&&!m){let w=`
74
- ${h.default.cyan(D)}`;$=`${w.repeat(n-1)}${w} `}if(o==="active")return`${$}${h.default.dim(g)}${h.default.cyan(Ai)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${$}${g}${h.default.cyan(Ai)} ${h.default.dim(d)}`;if(o==="group-active-selected")return`${$}${g}${h.default.green(Yt)} ${h.default.dim(d)}`;if(o==="selected"){let w=m||t?h.default.green(Yt):"";return`${$}${h.default.dim(g)}${w} ${h.default.dim(d)}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${h.default.strikethrough(h.default.dim(d))}`;if(o==="active-selected")return`${$}${h.default.dim(g)}${h.default.green(Yt)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${h.default.dim(d)}`;let k=m||t?h.default.dim(yn):"";return`${$}${h.default.dim(g)}${k} ${h.default.dim(d)}`},s=e.required??!0;return new yi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:s,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(s&&(r===void 0||r.length===0))return`Please select at least one option.
73
+ `}}}}).prompt()},wc=async(e,t)=>{let n={},i=Object.keys(e);for(let s of i){let r=e[s],o=await r({results:n})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&de(o)){n[s]="canceled",t.onCancel({results:n});continue}n[s]=o}return n},vc=e=>{let{selectableGroups:t=!0,groupSpacing:n=0}=e,i=(r,o,a=[])=>{let d=r.label??String(r.value),m=typeof r.group=="string",f=m&&(a[a.indexOf(r)+1]??{group:!0}),p=m&&f&&f.group===!0,g=m?t?`${p?Re:D} `:" ":"",$="";if(n>0&&!m){let w=`
74
+ ${h.default.cyan(D)}`;$=`${w.repeat(n-1)}${w} `}if(o==="active")return`${$}${h.default.dim(g)}${h.default.cyan(Ri)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${$}${g}${h.default.cyan(Ri)} ${h.default.dim(d)}`;if(o==="group-active-selected")return`${$}${g}${h.default.green(Xt)} ${h.default.dim(d)}`;if(o==="selected"){let w=m||t?h.default.green(Xt):"";return`${$}${h.default.dim(g)}${w} ${h.default.dim(d)}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${h.default.strikethrough(h.default.dim(d))}`;if(o==="active-selected")return`${$}${h.default.dim(g)}${h.default.green(Xt)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${h.default.dim(d)}`;let _=m||t?h.default.dim(bn):"";return`${$}${h.default.dim(g)}${_} ${h.default.dim(d)}`},s=e.required??!0;return new wi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:s,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(s&&(r===void 0||r.length===0))return`Please select at least one option.
75
75
  ${h.default.reset(h.default.dim(`Press ${h.default.gray(h.default.bgWhite(h.default.inverse(" space ")))} to select, ${h.default.gray(h.default.bgWhite(h.default.inverse(" enter ")))} to submit`))}`},render(){let r=`${h.default.gray(D)}
76
- ${at(this.state)} ${e.message}
76
+ ${dt(this.state)} ${e.message}
77
77
  `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:m})=>o.includes(m)).map(m=>i(m,"submitted")),d=a.length===0?"":` ${a.join(h.default.dim(", "))}`;return`${r}${h.default.gray(D)}${d}`}case"cancel":{let a=this.options.filter(({value:d})=>o.includes(d)).map(d=>i(d,"cancelled")).join(h.default.dim(", "));return`${r}${h.default.gray(D)} ${a.trim()?`${a}
78
78
  ${h.default.gray(D)}`:""}`}case"error":{let a=this.error.split(`
79
79
  `).map((d,m)=>m===0?`${h.default.yellow(Re)} ${h.default.yellow(d)}`:` ${d}`).join(`
80
80
  `);return`${r}${h.default.yellow(D)} ${this.options.map((d,m,f)=>{let p=o.includes(d.value)||d.group===!0&&this.isGroupSelected(`${d.value}`),g=m===this.cursor;return!g&&typeof d.group=="string"&&this.options[this.cursor].value===d.group?i(d,p?"group-active-selected":"group-active",f):g&&p?i(d,"active-selected",f):p?i(d,"selected",f):i(d,g?"active":"inactive",f)}).join(`
81
81
  ${h.default.yellow(D)} `)}
82
82
  ${a}
83
- `}default:{let a=this.options.map((m,f,p)=>{let g=o.includes(m.value)||m.group===!0&&this.isGroupSelected(`${m.value}`),$=f===this.cursor,k=!$&&typeof m.group=="string"&&this.options[this.cursor].value===m.group,w="";return k?w=i(m,g?"group-active-selected":"group-active",p):$&&g?w=i(m,"active-selected",p):g?w=i(m,"selected",p):w=i(m,$?"active":"inactive",p),`${f!==0&&!w.startsWith(`
83
+ `}default:{let a=this.options.map((m,f,p)=>{let g=o.includes(m.value)||m.group===!0&&this.isGroupSelected(`${m.value}`),$=f===this.cursor,_=!$&&typeof m.group=="string"&&this.options[this.cursor].value===m.group,w="";return _?w=i(m,g?"group-active-selected":"group-active",p):$&&g?w=i(m,"active-selected",p):g?w=i(m,"selected",p):w=i(m,$?"active":"inactive",p),`${f!==0&&!w.startsWith(`
84
84
  `)?" ":""}${w}`}).join(`
85
85
  ${h.default.cyan(D)}`),d=a.startsWith(`
86
86
  `)?"":" ";return`${r}${h.default.cyan(D)}${d}${a}
87
87
  ${h.default.cyan(Re)}
88
- `}}}}).prompt()},ze={message:(e=[],{symbol:t=h.default.gray(D),secondarySymbol:n=h.default.gray(D),output:i=process.stdout,spacing:s=1,withGuide:r}={})=>{let o=[],a=r??me.withGuide,d=a?n:"",m=a?`${t} `:"",f=a?`${n} `:"";for(let g=0;g<s;g++)o.push(d);let p=Array.isArray(e)?e:e.split(`
89
- `);if(p.length>0){let[g,...$]=p;g.length>0?o.push(`${m}${g}`):o.push(a?t:"");for(let k of $)k.length>0?o.push(`${f}${k}`):o.push(a?n:"")}i.write(`${o.join(`
88
+ `}}}}).prompt()},Ye={message:(e=[],{symbol:t=h.default.gray(D),secondarySymbol:n=h.default.gray(D),output:i=process.stdout,spacing:s=1,withGuide:r}={})=>{let o=[],a=r??fe.withGuide,d=a?n:"",m=a?`${t} `:"",f=a?`${n} `:"";for(let g=0;g<s;g++)o.push(d);let p=Array.isArray(e)?e:e.split(`
89
+ `);if(p.length>0){let[g,...$]=p;g.length>0?o.push(`${m}${g}`):o.push(a?t:"");for(let _ of $)_.length>0?o.push(`${f}${_}`):o.push(a?n:"")}i.write(`${o.join(`
90
90
  `)}
91
- `)},info:(e,t)=>{ze.message(e,{...t,symbol:h.default.blue(Bs)})},success:(e,t)=>{ze.message(e,{...t,symbol:h.default.green(Gs)})},step:(e,t)=>{ze.message(e,{...t,symbol:h.default.green(Qt)})},warn:(e,t)=>{ze.message(e,{...t,symbol:h.default.yellow(Ks)})},warning:(e,t)=>{ze.warn(e,t)},error:(e,t)=>{ze.message(e,{...t,symbol:h.default.red(zs)})}},ac=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(Re)} ${h.default.red(e)}
91
+ `)},info:(e,t)=>{Ye.message(e,{...t,symbol:h.default.blue(zs)})},success:(e,t)=>{Ye.message(e,{...t,symbol:h.default.green(Ys)})},step:(e,t)=>{Ye.message(e,{...t,symbol:h.default.green(en)})},warn:(e,t)=>{Ye.message(e,{...t,symbol:h.default.yellow(Xs)})},warning:(e,t)=>{Ye.warn(e,t)},error:(e,t)=>{Ye.message(e,{...t,symbol:h.default.red(Zs)})}},$c=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(Re)} ${h.default.red(e)}
92
92
 
93
- `)},dc=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(Vs)} ${e}
94
- `)},lc=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(D)}
93
+ `)},kc=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(Js)} ${e}
94
+ `)},_c=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(D)}
95
95
  ${h.default.gray(Re)} ${e}
96
96
 
97
- `)},Dn=(e,t)=>e.split(`
97
+ `)},Nn=(e,t)=>e.split(`
98
98
  `).map(n=>t(n)).join(`
99
- `),cc=e=>{let t=(i,s)=>{let r=i.label??String(i.value);return s==="disabled"?`${h.default.gray(yn)} ${Dn(r,o=>h.default.strikethrough(h.default.gray(o)))}${i.hint?` ${h.default.dim(`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${h.default.cyan(Ai)} ${r}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="selected"?`${h.default.green(Yt)} ${Dn(r,h.default.dim)}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="cancelled"?`${Dn(r,o=>h.default.strikethrough(h.default.dim(o)))}`:s==="active-selected"?`${h.default.green(Yt)} ${r}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="submitted"?`${Dn(r,h.default.dim)}`:`${h.default.dim(yn)} ${Dn(r,h.default.dim)}`},n=e.required??!0;return new bi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
100
- ${h.default.reset(h.default.dim(`Press ${h.default.gray(h.default.bgWhite(h.default.inverse(" space ")))} to select, ${h.default.gray(h.default.bgWhite(h.default.inverse(" enter ")))} to submit`))}`},render(){let i=ft(e.output,e.message,`${Ys(this.state)} `,`${at(this.state)} `),s=`${h.default.gray(D)}
99
+ `),xc=e=>{let t=(i,s)=>{let r=i.label??String(i.value);return s==="disabled"?`${h.default.gray(bn)} ${Nn(r,o=>h.default.strikethrough(h.default.gray(o)))}${i.hint?` ${h.default.dim(`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${h.default.cyan(Ri)} ${r}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="selected"?`${h.default.green(Xt)} ${Nn(r,h.default.dim)}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="cancelled"?`${Nn(r,o=>h.default.strikethrough(h.default.dim(o)))}`:s==="active-selected"?`${h.default.green(Xt)} ${r}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:s==="submitted"?`${Nn(r,h.default.dim)}`:`${h.default.dim(bn)} ${Nn(r,h.default.dim)}`},n=e.required??!0;return new vi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
100
+ ${h.default.reset(h.default.dim(`Press ${h.default.gray(h.default.bgWhite(h.default.inverse(" space ")))} to select, ${h.default.gray(h.default.bgWhite(h.default.inverse(" enter ")))} to submit`))}`},render(){let i=pt(e.output,e.message,`${Qs(this.state)} `,`${dt(this.state)} `),s=`${h.default.gray(D)}
101
101
  ${i}
102
- `,r=this.value??[],o=(a,d)=>{if(a.disabled)return t(a,"disabled");let m=r.includes(a.value);return d&&m?t(a,"active-selected"):m?t(a,"selected"):t(a,d?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"submitted")).join(h.default.dim(", "))||h.default.dim("none"),d=ft(e.output,a,`${h.default.gray(D)} `);return`${s}${d}`}case"cancel":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"cancelled")).join(h.default.dim(", "));if(a.trim()==="")return`${s}${h.default.gray(D)}`;let d=ft(e.output,a,`${h.default.gray(D)} `);return`${s}${d}
102
+ `,r=this.value??[],o=(a,d)=>{if(a.disabled)return t(a,"disabled");let m=r.includes(a.value);return d&&m?t(a,"active-selected"):m?t(a,"selected"):t(a,d?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"submitted")).join(h.default.dim(", "))||h.default.dim("none"),d=pt(e.output,a,`${h.default.gray(D)} `);return`${s}${d}`}case"cancel":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"cancelled")).join(h.default.dim(", "));if(a.trim()==="")return`${s}${h.default.gray(D)}`;let d=pt(e.output,a,`${h.default.gray(D)} `);return`${s}${d}
103
103
  ${h.default.gray(D)}`}case"error":{let a=`${h.default.yellow(D)} `,d=this.error.split(`
104
104
  `).map((p,g)=>g===0?`${h.default.yellow(Re)} ${h.default.yellow(p)}`:` ${p}`).join(`
105
105
  `),m=s.split(`
106
106
  `).length,f=d.split(`
107
- `).length+1;return`${s}${a}${wn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:o}).join(`
107
+ `).length+1;return`${s}${a}${vn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:o}).join(`
108
108
  ${a}`)}
109
109
  ${d}
110
110
  `}default:{let a=`${h.default.cyan(D)} `,d=s.split(`
111
- `).length;return`${s}${a}${wn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:d+2,style:o}).join(`
111
+ `).length;return`${s}${a}${vn({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:d+2,style:o}).join(`
112
112
  ${a}`)}
113
113
  ${h.default.cyan(Re)}
114
- `}}}}).prompt()},uc=e=>h.default.dim(e),mc=(e,t,n)=>{let i={hard:!0,trim:!1},s=bn(e,t,i).split(`
115
- `),r=s.reduce((d,m)=>Math.max(Fe(m),d),0),o=s.map(n).reduce((d,m)=>Math.max(Fe(m),d),0),a=t-(o-r);return bn(e,a,i)},fc=(e="",t="",n)=>{let i=n?.output??Ke.default.stdout,s=n?.withGuide??me.withGuide,r=n?.format??uc,o=["",...mc(e,Kt(i)-6,r).split(`
116
- `).map(r),""],a=Fe(t),d=Math.max(o.reduce((g,$)=>{let k=Fe($);return k>g?k:g},0),a)+2,m=o.map(g=>`${h.default.gray(D)} ${g}${" ".repeat(d-Fe(g))}${h.default.gray(D)}`).join(`
114
+ `}}}}).prompt()},jc=e=>h.default.dim(e),Sc=(e,t,n)=>{let i={hard:!0,trim:!1},s=wn(e,t,i).split(`
115
+ `),r=s.reduce((d,m)=>Math.max(Le(m),d),0),o=s.map(n).reduce((d,m)=>Math.max(Le(m),d),0),a=t-(o-r);return wn(e,a,i)},Cc=(e="",t="",n)=>{let i=n?.output??ze.default.stdout,s=n?.withGuide??fe.withGuide,r=n?.format??jc,o=["",...Sc(e,zt(i)-6,r).split(`
116
+ `).map(r),""],a=Le(t),d=Math.max(o.reduce((g,$)=>{let _=Le($);return _>g?_:g},0),a)+2,m=o.map(g=>`${h.default.gray(D)} ${g}${" ".repeat(d-Le(g))}${h.default.gray(D)}`).join(`
117
117
  `),f=s?`${h.default.gray(D)}
118
- `:"",p=s?Eo:Js;i.write(`${f}${h.default.green(Qt)} ${h.default.reset(t)} ${h.default.gray(Ii.repeat(Math.max(d-a-1,1))+Ws)}
118
+ `:"",p=s?qo:Ks;i.write(`${f}${h.default.green(en)} ${h.default.reset(t)} ${h.default.gray(Ti.repeat(Math.max(d-a-1,1))+Bs)}
119
119
  ${m}
120
- ${h.default.gray(p+Ii.repeat(d+2)+Hs)}
121
- `)},pc=e=>new vo({validate:e.validate,mask:e.mask??To,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??me.withGuide,n=`${t?`${h.default.gray(D)}
122
- `:""}${at(this.state)} ${e.message}
120
+ ${h.default.gray(p+Ti.repeat(d+2)+Gs)}
121
+ `)},Oc=e=>new jo({validate:e.validate,mask:e.mask??Uo,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??fe.withGuide,n=`${t?`${h.default.gray(D)}
122
+ `:""}${dt(this.state)} ${e.message}
123
123
  `,i=this.userInputWithCursor,s=this.masked;switch(this.state){case"error":{let r=t?`${h.default.yellow(D)} `:"",o=t?`${h.default.yellow(Re)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${n.trim()}
124
124
  ${r}${a}
125
125
  ${o}${h.default.yellow(this.error)}
126
126
  `}case"submit":{let r=t?`${h.default.gray(D)} `:"",o=s?h.default.dim(s):"";return`${n}${r}${o}`}case"cancel":{let r=t?`${h.default.gray(D)} `:"",o=s?h.default.strikethrough(h.default.dim(s)):"";return`${n}${r}${o}${s&&t?`
127
127
  ${h.default.gray(D)}`:""}`}default:{let r=t?`${h.default.cyan(D)} `:"",o=t?h.default.cyan(Re):"";return`${n}${r}${i}
128
128
  ${o}
129
- `}}}}).prompt(),hc=e=>{let t=e.validate;return Fo({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(n){if(!Array.isArray(n)){if(!n)return"Please select a path";if(t)return t(n)}},options(){let n=this.userInput;if(n==="")return[];try{let i;return(0,Xt.existsSync)(n)?(0,Xt.lstatSync)(n).isDirectory()?i=n:i=(0,Nn.dirname)(n):i=(0,Nn.dirname)(n),(0,Xt.readdirSync)(i).map(s=>{let r=(0,Nn.join)(i,s),o=(0,Xt.lstatSync)(r);return{name:s,path:r,isDirectory:o.isDirectory()}}).filter(({path:s,isDirectory:r})=>s.startsWith(n)&&(e.directory||!r)).map(s=>({value:s.path}))}catch{return[]}}})},gc=h.default.magenta,qn=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:s,frames:r=Ci?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ci?80:120,signal:a,...d}={})=>{let m=Ms(),f,p,g=!1,$=!1,k="",w,_=performance.now(),S=Kt(n),C=d?.styleFrame??gc,R=A=>{let W=A>1?s??me.messages.error:i??me.messages.cancel;$=A===1,g&&(ie(W,A),$&&typeof t=="function"&&t())},M=()=>R(2),H=()=>R(1),ee=()=>{process.on("uncaughtExceptionMonitor",M),process.on("unhandledRejection",M),process.on("SIGINT",H),process.on("SIGTERM",H),process.on("exit",R),a&&a.addEventListener("abort",H)},q=()=>{process.removeListener("uncaughtExceptionMonitor",M),process.removeListener("unhandledRejection",M),process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H),process.removeListener("exit",R),a&&a.removeEventListener("abort",H)},U=()=>{if(w===void 0)return;m&&n.write(`
130
- `);let A=bn(w,S,{hard:!0,trim:!1}).split(`
131
- `);A.length>1&&n.write(gn.cursor.up(A.length-1)),n.write(gn.cursor.to(0)),n.write(gn.erase.down())},ce=A=>A.replace(/\.+$/,""),le=A=>{let W=(performance.now()-A)/1e3,ne=Math.floor(W/60),X=Math.floor(W%60);return ne>0?`[${ne}m ${X}s]`:`[${X}s]`},P=d.withGuide??me.withGuide,he=(A="")=>{g=!0,f=wo({output:n}),k=ce(A),_=performance.now(),P&&n.write(`${h.default.gray(D)}
132
- `);let W=0,ne=0;ee(),p=setInterval(()=>{if(m&&k===w)return;U(),w=k;let X=C(r[W]),ae;if(m)ae=`${X} ${k}...`;else if(e==="timer")ae=`${X} ${k} ${le(_)}`;else{let ge=".".repeat(Math.floor(ne)).slice(0,3);ae=`${X} ${k}${ge}`}let $e=bn(ae,S,{hard:!0,trim:!1});n.write($e),W=W+1<r.length?W+1:0,ne=ne<4?ne+.125:0},o)},ie=(A="",W=0,ne=!1)=>{if(!g)return;g=!1,clearInterval(p),U();let X=W===0?h.default.green(Qt):W===1?h.default.red(Fs):h.default.red(Ls);k=A??k,ne||(e==="timer"?n.write(`${X} ${k} ${le(_)}
133
- `):n.write(`${X} ${k}
134
- `)),q(),f()};return{start:he,stop:(A="")=>ie(A,0),message:(A="")=>{k=ce(A??k)},cancel:(A="")=>ie(A,1),error:(A="")=>ie(A,2),clear:()=>ie("",0,!0),get isCancelled(){return $}}},So={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Si=(e,t)=>e.includes(`
129
+ `}}}}).prompt(),Ic=e=>{let t=e.validate;return Jo({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(n){if(!Array.isArray(n)){if(!n)return"Please select a path";if(t)return t(n)}},options(){let n=this.userInput;if(n==="")return[];try{let i;return(0,Zt.existsSync)(n)?(0,Zt.lstatSync)(n).isDirectory()?i=n:i=(0,Un.dirname)(n):i=(0,Un.dirname)(n),(0,Zt.readdirSync)(i).map(s=>{let r=(0,Un.join)(i,s),o=(0,Zt.lstatSync)(r);return{name:s,path:r,isDirectory:o.isDirectory()}}).filter(({path:s,isDirectory:r})=>s.startsWith(n)&&(e.directory||!r)).map(s=>({value:s.path}))}catch{return[]}}})},Ac=h.default.magenta,Mn=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:s,frames:r=Ai?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ai?80:120,signal:a,...d}={})=>{let m=Vs(),f,p,g=!1,$=!1,_="",w,k=performance.now(),S=zt(n),O=d?.styleFrame??Ac,R=A=>{let W=A>1?s??fe.messages.error:i??fe.messages.cancel;$=A===1,g&&(ie(W,A),$&&typeof t=="function"&&t())},M=()=>R(2),H=()=>R(1),ee=()=>{process.on("uncaughtExceptionMonitor",M),process.on("unhandledRejection",M),process.on("SIGINT",H),process.on("SIGTERM",H),process.on("exit",R),a&&a.addEventListener("abort",H)},q=()=>{process.removeListener("uncaughtExceptionMonitor",M),process.removeListener("unhandledRejection",M),process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H),process.removeListener("exit",R),a&&a.removeEventListener("abort",H)},U=()=>{if(w===void 0)return;m&&n.write(`
130
+ `);let A=wn(w,S,{hard:!0,trim:!1}).split(`
131
+ `);A.length>1&&n.write(yn.cursor.up(A.length-1)),n.write(yn.cursor.to(0)),n.write(yn.erase.down())},ce=A=>A.replace(/\.+$/,""),le=A=>{let W=(performance.now()-A)/1e3,ne=Math.floor(W/60),X=Math.floor(W%60);return ne>0?`[${ne}m ${X}s]`:`[${X}s]`},P=d.withGuide??fe.withGuide,ge=(A="")=>{g=!0,f=xo({output:n}),_=ce(A),k=performance.now(),P&&n.write(`${h.default.gray(D)}
132
+ `);let W=0,ne=0;ee(),p=setInterval(()=>{if(m&&_===w)return;U(),w=_;let X=O(r[W]),ae;if(m)ae=`${X} ${_}...`;else if(e==="timer")ae=`${X} ${_} ${le(k)}`;else{let ye=".".repeat(Math.floor(ne)).slice(0,3);ae=`${X} ${_}${ye}`}let ke=wn(ae,S,{hard:!0,trim:!1});n.write(ke),W=W+1<r.length?W+1:0,ne=ne<4?ne+.125:0},o)},ie=(A="",W=0,ne=!1)=>{if(!g)return;g=!1,clearInterval(p),U();let X=W===0?h.default.green(en):W===1?h.default.red(Ws):h.default.red(Hs);_=A??_,ne||(e==="timer"?n.write(`${X} ${_} ${le(k)}
133
+ `):n.write(`${X} ${_}
134
+ `)),q(),f()};return{start:ge,stop:(A="")=>ie(A,0),message:(A="")=>{_=ce(A??_)},cancel:(A="")=>ie(A,1),error:(A="")=>ie(A,2),clear:()=>ie("",0,!0),get isCancelled(){return $}}},Ro={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Oi=(e,t)=>e.includes(`
135
135
  `)?e.split(`
136
136
  `).map(n=>t(n)).join(`
137
- `):t(e),dt=e=>{let t=(n,i)=>{let s=n.label??String(n.value);switch(i){case"disabled":return`${h.default.gray(Zt)} ${Si(s,h.default.gray)}${n.hint?` ${h.default.dim(`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Si(s,h.default.dim)}`;case"active":return`${h.default.green(Un)} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`;case"cancelled":return`${Si(s,r=>h.default.strikethrough(h.default.dim(r)))}`;default:return`${h.default.dim(Zt)} ${Si(s,h.default.dim)}`}};return new wi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??me.withGuide,i=`${at(this.state)} `,s=`${Ys(this.state)} `,r=ft(e.output,e.message,s,i),o=`${n?`${h.default.gray(D)}
137
+ `):t(e),lt=e=>{let t=(n,i)=>{let s=n.label??String(n.value);switch(i){case"disabled":return`${h.default.gray(Qt)} ${Oi(s,h.default.gray)}${n.hint?` ${h.default.dim(`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Oi(s,h.default.dim)}`;case"active":return`${h.default.green(qn)} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`;case"cancelled":return`${Oi(s,r=>h.default.strikethrough(h.default.dim(r)))}`;default:return`${h.default.dim(Qt)} ${Oi(s,h.default.dim)}`}};return new $i({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??fe.withGuide,i=`${dt(this.state)} `,s=`${Qs(this.state)} `,r=pt(e.output,e.message,s,i),o=`${n?`${h.default.gray(D)}
138
138
  `:""}${r}
139
- `;switch(this.state){case"submit":{let a=n?`${h.default.gray(D)} `:"",d=ft(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${d}`}case"cancel":{let a=n?`${h.default.gray(D)} `:"",d=ft(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${d}${n?`
139
+ `;switch(this.state){case"submit":{let a=n?`${h.default.gray(D)} `:"",d=pt(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${d}`}case"cancel":{let a=n?`${h.default.gray(D)} `:"",d=pt(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${d}${n?`
140
140
  ${h.default.gray(D)}`:""}`}default:{let a=n?`${h.default.cyan(D)} `:"",d=n?h.default.cyan(Re):"",m=o.split(`
141
- `).length,f=n?2:1;return`${o}${a}${wn({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:(p,g)=>t(p,p.disabled?"disabled":g?"active":"inactive")}).join(`
141
+ `).length,f=n?2:1;return`${o}${a}${vn({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:(p,g)=>t(p,p.disabled?"disabled":g?"active":"inactive")}).join(`
142
142
  ${a}`)}
143
143
  ${d}
144
- `}}}}).prompt()},bc=e=>{let t=(n,i="inactive")=>{let s=n.label??String(n.value);return i==="selected"?`${h.default.dim(s)}`:i==="cancelled"?`${h.default.strikethrough(h.default.dim(s))}`:i==="active"?`${h.default.bgCyan(h.default.gray(` ${n.value} `))} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`:`${h.default.gray(h.default.bgWhite(h.default.inverse(` ${n.value} `)))} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`};return new vi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let n=e.withGuide??me.withGuide,i=`${n?`${h.default.gray(D)}
145
- `:""}${at(this.state)} ${e.message}
146
- `;switch(this.state){case"submit":{let s=n?`${h.default.gray(D)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=ft(e.output,t(r,"selected"),s);return`${i}${o}`}case"cancel":{let s=n?`${h.default.gray(D)} `:"",r=ft(e.output,t(this.options[0],"cancelled"),s);return`${i}${r}${n?`
147
- ${h.default.gray(D)}`:""}`}default:{let s=n?`${h.default.cyan(D)} `:"",r=n?h.default.cyan(Re):"",o=this.options.map((a,d)=>ft(e.output,t(a,d===this.cursor?"active":"inactive"),s)).join(`
144
+ `}}}}).prompt()},Tc=e=>{let t=(n,i="inactive")=>{let s=n.label??String(n.value);return i==="selected"?`${h.default.dim(s)}`:i==="cancelled"?`${h.default.strikethrough(h.default.dim(s))}`:i==="active"?`${h.default.bgCyan(h.default.gray(` ${n.value} `))} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`:`${h.default.gray(h.default.bgWhite(h.default.inverse(` ${n.value} `)))} ${s}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`};return new ki({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let n=e.withGuide??fe.withGuide,i=`${n?`${h.default.gray(D)}
145
+ `:""}${dt(this.state)} ${e.message}
146
+ `;switch(this.state){case"submit":{let s=n?`${h.default.gray(D)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=pt(e.output,t(r,"selected"),s);return`${i}${o}`}case"cancel":{let s=n?`${h.default.gray(D)} `:"",r=pt(e.output,t(this.options[0],"cancelled"),s);return`${i}${r}${n?`
147
+ ${h.default.gray(D)}`:""}`}default:{let s=n?`${h.default.cyan(D)} `:"",r=n?h.default.cyan(Re):"",o=this.options.map((a,d)=>pt(e.output,t(a,d===this.cursor?"active":"inactive"),s)).join(`
148
148
  `);return`${i}${o}
149
149
  ${r}
150
- `}}}}).prompt()},Oo=`${h.default.gray(D)} `,zt={message:async(e,{symbol:t=h.default.gray(D)}={})=>{process.stdout.write(`${h.default.gray(D)}
150
+ `}}}}).prompt()},To=`${h.default.gray(D)} `,Yt={message:async(e,{symbol:t=h.default.gray(D)}={})=>{process.stdout.write(`${h.default.gray(D)}
151
151
  ${t} `);let n=3;for await(let i of e){i=i.replace(/\n/g,`
152
- ${Oo}`),i.includes(`
153
- `)&&(n=3+(0,Oi.stripVTControlCharacters)(i.slice(i.lastIndexOf(`
154
- `))).length);let s=(0,Oi.stripVTControlCharacters)(i).length;n+s<process.stdout.columns?(n+=s,process.stdout.write(i)):(process.stdout.write(`
155
- ${Oo}${i.trimStart()}`),n=3+(0,Oi.stripVTControlCharacters)(i.trimStart()).length)}process.stdout.write(`
156
- `)},info:e=>zt.message(e,{symbol:h.default.blue(Bs)}),success:e=>zt.message(e,{symbol:h.default.green(Gs)}),step:e=>zt.message(e,{symbol:h.default.green(Qt)}),warn:e=>zt.message(e,{symbol:h.default.yellow(Ks)}),warning:e=>zt.warn(e),error:e=>zt.message(e,{symbol:h.default.red(zs)})},wc=async(e,t)=>{for(let n of e){if(n.enabled===!1)continue;let i=qn(t);i.start(n.title);let s=await n.task(i.message);i.stop(s||n.title)}},vc=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),$c=e=>{let t=e.output??process.stdout,n=Kt(t),i=h.default.gray(D),s=e.spacing??1,r=3,o=e.retainLog===!0,a=!Ms()&&Co(t);t.write(`${i}
157
- `),t.write(`${h.default.green(Qt)} ${e.title}
158
- `);for(let _=0;_<s;_++)t.write(`${i}
159
- `);let d=[{value:"",full:""}],m=!1,f=_=>{if(d.length===0)return;let S=0;_&&(S+=s+2);for(let C of d){let{value:R,result:M}=C,H=M?.message??R;if(H.length===0)continue;M===void 0&&C.header!==void 0&&C.header!==""&&(H+=`
160
- ${C.header}`);let ee=H.split(`
161
- `).reduce((q,U)=>U===""?q+1:q+Math.ceil((U.length+r)/n),0);S+=ee}S>0&&(S+=1,t.write(gn.erase.lines(S)))},p=(_,S,C)=>{let R=C?`${_.full}
162
- ${_.value}`:_.value;_.header!==void 0&&_.header!==""&&ze.message(_.header.split(`
163
- `).map(h.default.bold),{output:t,secondarySymbol:i,symbol:i,spacing:0}),ze.message(R.split(`
164
- `).map(h.default.dim),{output:t,secondarySymbol:i,symbol:i,spacing:S??s})},g=()=>{for(let _ of d){let{header:S,value:C,full:R}=_;(S===void 0||S.length===0)&&C.length===0||p(_,void 0,o===!0&&R.length>0)}},$=(_,S,C)=>{if(f(!1),(C?.raw!==!0||!m)&&_.value!==""&&(_.value+=`
165
- `),_.value+=vc(S),m=C?.raw===!0,e.limit!==void 0){let R=_.value.split(`
166
- `),M=R.length-e.limit;if(M>0){let H=R.splice(0,M);o&&(_.full+=(_.full===""?"":`
152
+ ${To}`),i.includes(`
153
+ `)&&(n=3+(0,Ii.stripVTControlCharacters)(i.slice(i.lastIndexOf(`
154
+ `))).length);let s=(0,Ii.stripVTControlCharacters)(i).length;n+s<process.stdout.columns?(n+=s,process.stdout.write(i)):(process.stdout.write(`
155
+ ${To}${i.trimStart()}`),n=3+(0,Ii.stripVTControlCharacters)(i.trimStart()).length)}process.stdout.write(`
156
+ `)},info:e=>Yt.message(e,{symbol:h.default.blue(zs)}),success:e=>Yt.message(e,{symbol:h.default.green(Ys)}),step:e=>Yt.message(e,{symbol:h.default.green(en)}),warn:e=>Yt.message(e,{symbol:h.default.yellow(Xs)}),warning:e=>Yt.warn(e),error:e=>Yt.message(e,{symbol:h.default.red(Zs)})},Ec=async(e,t)=>{for(let n of e){if(n.enabled===!1)continue;let i=Mn(t);i.start(n.title);let s=await n.task(i.message);i.stop(s||n.title)}},Pc=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Dc=e=>{let t=e.output??process.stdout,n=zt(t),i=h.default.gray(D),s=e.spacing??1,r=3,o=e.retainLog===!0,a=!Vs()&&Eo(t);t.write(`${i}
157
+ `),t.write(`${h.default.green(en)} ${e.title}
158
+ `);for(let k=0;k<s;k++)t.write(`${i}
159
+ `);let d=[{value:"",full:""}],m=!1,f=k=>{if(d.length===0)return;let S=0;k&&(S+=s+2);for(let O of d){let{value:R,result:M}=O,H=M?.message??R;if(H.length===0)continue;M===void 0&&O.header!==void 0&&O.header!==""&&(H+=`
160
+ ${O.header}`);let ee=H.split(`
161
+ `).reduce((q,U)=>U===""?q+1:q+Math.ceil((U.length+r)/n),0);S+=ee}S>0&&(S+=1,t.write(yn.erase.lines(S)))},p=(k,S,O)=>{let R=O?`${k.full}
162
+ ${k.value}`:k.value;k.header!==void 0&&k.header!==""&&Ye.message(k.header.split(`
163
+ `).map(h.default.bold),{output:t,secondarySymbol:i,symbol:i,spacing:0}),Ye.message(R.split(`
164
+ `).map(h.default.dim),{output:t,secondarySymbol:i,symbol:i,spacing:S??s})},g=()=>{for(let k of d){let{header:S,value:O,full:R}=k;(S===void 0||S.length===0)&&O.length===0||p(k,void 0,o===!0&&R.length>0)}},$=(k,S,O)=>{if(f(!1),(O?.raw!==!0||!m)&&k.value!==""&&(k.value+=`
165
+ `),k.value+=Pc(S),m=O?.raw===!0,e.limit!==void 0){let R=k.value.split(`
166
+ `),M=R.length-e.limit;if(M>0){let H=R.splice(0,M);o&&(k.full+=(k.full===""?"":`
167
167
  `)+H.join(`
168
- `))}_.value=R.join(`
169
- `)}a&&k()},k=()=>{for(let _ of d)_.result?_.result.status==="error"?ze.error(_.result.message,{output:t,secondarySymbol:i,spacing:0}):ze.success(_.result.message,{output:t,secondarySymbol:i,spacing:0}):_.value!==""&&p(_,0)},w=(_,S)=>{f(!1),_.result=S,a&&k()};return{message(_,S){$(d[0],_,S)},group(_){let S={header:_,value:"",full:""};return d.push(S),{message(C,R){$(S,C,R)},error(C){w(S,{status:"error",message:C})},success(C){w(S,{status:"success",message:C})}}},error(_,S){f(!0),ze.error(_,{output:t,secondarySymbol:i,spacing:1}),S?.showLog!==!1&&g(),d.splice(1,d.length-1),d[0].value="",d[0].full=""},success(_,S){f(!0),ze.success(_,{output:t,secondarySymbol:i,spacing:1}),S?.showLog===!0&&g(),d.splice(1,d.length-1),d[0].value="",d[0].full=""}}},Ue=e=>new $i({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??me.withGuide,n=`${`${t?`${h.default.gray(D)}
170
- `:""}${at(this.state)} `}${e.message}
168
+ `))}k.value=R.join(`
169
+ `)}a&&_()},_=()=>{for(let k of d)k.result?k.result.status==="error"?Ye.error(k.result.message,{output:t,secondarySymbol:i,spacing:0}):Ye.success(k.result.message,{output:t,secondarySymbol:i,spacing:0}):k.value!==""&&p(k,0)},w=(k,S)=>{f(!1),k.result=S,a&&_()};return{message(k,S){$(d[0],k,S)},group(k){let S={header:k,value:"",full:""};return d.push(S),{message(O,R){$(S,O,R)},error(O){w(S,{status:"error",message:O})},success(O){w(S,{status:"success",message:O})}}},error(k,S){f(!0),Ye.error(k,{output:t,secondarySymbol:i,spacing:1}),S?.showLog!==!1&&g(),d.splice(1,d.length-1),d[0].value="",d[0].full=""},success(k,S){f(!0),Ye.success(k,{output:t,secondarySymbol:i,spacing:1}),S?.showLog===!0&&g(),d.splice(1,d.length-1),d[0].value="",d[0].full=""}}},Ue=e=>new _i({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??fe.withGuide,n=`${`${t?`${h.default.gray(D)}
170
+ `:""}${dt(this.state)} `}${e.message}
171
171
  `,i=e.placeholder?h.default.inverse(e.placeholder[0])+h.default.dim(e.placeholder.slice(1)):h.default.inverse(h.default.hidden("_")),s=this.userInput?this.userInputWithCursor:i,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${h.default.yellow(this.error)}`:"",a=t?`${h.default.yellow(D)} `:"",d=t?h.default.yellow(Re):"";return`${n.trim()}
172
172
  ${a}${s}
173
173
  ${d}${o}
174
174
  `}case"submit":{let o=r?` ${h.default.dim(r)}`:"",a=t?h.default.gray(D):"";return`${n}${a}${o}`}case"cancel":{let o=r?` ${h.default.strikethrough(h.default.dim(r))}`:"",a=t?h.default.gray(D):"";return`${n}${a}${o}${r.trim()?`
175
175
  ${a}`:""}`}default:{let o=t?`${h.default.cyan(D)} `:"",a=t?h.default.cyan(Re):"";return`${n}${o}${s}
176
176
  ${a}
177
- `}}}}).prompt()});function _c(e){return!!(e.json||!Te)}function j(e,t=50){console.log(),console.log(` ${B.default.bold(e)}`),console.log(` ${B.default.dim("\u2500".repeat(t))}`)}function c(e,t,n=2){let i=" ".repeat(n);console.log(`${i}${B.default.dim(e.padEnd(16))} ${t}`)}function l(){console.log()}function _e(e){console.log(` ${B.default.dim(e)}`)}function I(e,t){console.log(` ${B.default.dim(e)} ${B.default.cyan(t)}`)}function Ho(e){return e.split(/(https?:\/\/[^\s]+)/g).map(n=>/^https?:\/\//.test(n)?`\x1B]8;;${n}\x1B\\${B.default.underline(B.default.cyan(n))}\x1B]8;;\x1B\\`:B.default.dim(n)).join("")}function tr(e,t){console.error(` ${y.error} ${B.default.red(e)}`),t&&console.error(` ${Ho(t)}`)}function O(e=!0){return e?qn():kc}function Jo(e){return e.replace(xc,"")}function Ti(e,t){let n=Jo(e).length,i=Math.max(0,t-n);return e+" ".repeat(i)}function G(e,t,n){let i=n||e.map((o,a)=>{let d=t.reduce((m,f)=>Math.max(m,Jo(f[a]||"").length),0);return Math.max(o.length,d)+2}),s=e.map((o,a)=>B.default.dim(o.padEnd(i[a]))).join(" "),r=i.map(o=>B.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${s}`),console.log(` ${r}`);for(let o of t){let a=o.map((d,m)=>Ti(d,i[m])).join(" ");console.log(` ${a}`)}}function jc(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function er(e){if(Array.isArray(e))return e.map(er);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[n,i]of Object.entries(e))t[jc(n)]=er(i);return t}return e}function b(e,t){let n=er(e);if(!t){console.log(JSON.stringify(n,null,2));return}let i=t.split(",").map(s=>s.trim()).filter(Boolean);if(Array.isArray(n)){let s=n.map(r=>Lo(r,i));console.log(JSON.stringify(s,null,2))}else console.log(JSON.stringify(n&&typeof n=="object"?Lo(n,i):n,null,2))}function Lo(e,t){let n={};for(let i of t)i in e&&(n[i]=e[i]);if(Object.keys(n).length===0){for(let[i,s]of Object.entries(e))if(Array.isArray(s)&&s.length>0&&typeof s[0]=="object"){let r=s.map(o=>{let a={};for(let d of t)d in o&&(a[d]=o[d]);return a});Object.keys(r[0]).length>0&&(n[i]=r)}}return n}function St(e){return!!(e.yes||_c(e))}function Ut(){let e=xt();return e?` as ${B.default.bold(e)}`:""}function K(e,t,n,i){if(n){b({dry_run:!0,action:e,...t},i);return}console.log(),console.log(` ${B.default.yellow("\u25B8 DRY RUN")} ${B.default.dim("- no changes made")}`),console.log(` ${B.default.dim("Action:")} ${B.default.bold(e)}`);for(let[s,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${B.default.dim(s+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${B.default.dim(s+":")} ${JSON.stringify(r)}`:` ${B.default.dim(s+":")} ${String(r)}`));console.log()}function Oc(e,t,n){return t===401||t===403?"auth_required":t===402||n?"payment_required":t===404?"not_found":t===409?"conflict":t===422?"validation_error":t===429?"rate_limited":/contact/i.test(e)?"contact_required":"error"}function u(e,t){let n=e||`Request failed${t?.status?` (${t.status})`:""}`,i=t?.code||Oc(n,t?.status,t?.fixUrl),s=t?.fixCommand||Sc[i];if(t?.json){let r={error:n,code:i,...t.data};t.hint&&(r.hint=t.hint),s&&(r.fix_command=s),t.fixUrl&&(r.fix_url=t.fixUrl),b(r,t.fields)}else tr(n,t?.hint),s?console.error(` ${B.default.dim("Or run:")} ${B.default.cyan(s)}`):t?.fixUrl&&console.error(` ${Ho(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function Le(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Wo.execFile)(t,[e])}function Ot(e){return new Promise(t=>setTimeout(t,e))}function en(e,t,n,i=!0){let s=process.stdout.isTTY??!1;if(!i)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function d(){let g=" "+e.map((w,_)=>B.default.dim(w.padEnd(n[_]))).join(" "),$=" "+n.map(w=>B.default.dim("\u2500".repeat(w))).join(" "),k=[g,$];for(let w of t){let _=w.status==="done"?w.icon??y.success:B.default.cyan(Vo[r%Vo.length]),S=w.cells.map((C,R)=>Ti(C,n[R])).join(" ");k.push(` ${_} ${S}`)}return k}let m=!1,f=()=>process.stdout.write("\x1B[?25h");function p(){let g=d();if(m&&s){process.stdout.write(`\x1B[${a}A`);for(let $ of g)process.stdout.write(`\x1B[2K${$}
178
- `)}else{for(let $ of g)console.log($);m=!0}}return{start(){s&&(process.stdout.write("\x1B[?25l"),process.on("exit",f)),p(),s&&(o=setInterval(()=>{r++,p()},80))},markDone(g,$){t[g].status="done",$!==void 0&&(t[g].icon=$),s&&p()},stop(){o&&clearInterval(o);for(let g of t)g.status="done";p(),s&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",f))}}}var B,Wo,Te,y,v,kc,xc,Sc,Vo,V=je(()=>{"use strict";B=N(F(),1),Wo=require("child_process");De();qe();Te=process.stdout.isTTY??!1;y={success:B.default.green("\u2713"),error:B.default.red("\u2717"),warning:B.default.yellow("!"),info:B.default.cyan("\u25CF"),arrow:B.default.dim("\u2192"),dot:B.default.dim("\xB7"),dash:B.default.dim("\u2500")},v={domain:e=>B.default.bold(B.default.white(e)),price:e=>B.default.green(`$${e}`),label:e=>B.default.dim(e),value:e=>B.default.white(e),dim:e=>B.default.dim(e),bold:e=>B.default.bold(e),success:e=>B.default.green(e),error:e=>B.default.red(e),warn:e=>B.default.yellow(e),cyan:e=>B.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${B.default.underline(B.default.cyan(e))}\x1B]8;;\x1B\\`};kc={start:()=>{},stop:()=>{},message:()=>{}};xc=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Sc={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Vo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function Bo(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function Go(e){return Bo(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(Bo)}async function Ko(){if(ir)return;let e=process.argv.includes("--json")||!_s,t=Ge(),n=ot();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${n}`}})).json();if(Go(r)){ir=!0;return}}catch{}e&&(console.log(JSON.stringify({error:"Paid plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),l(),console.log(` ${Se.default.dim("This feature requires a")} ${Se.default.bold("paid plan")} ${Se.default.dim(`(including an active ${Et.mailProductName} workspace plan or legacy Pro subscription).`)}`),console.log(` ${Se.default.dim("Opening pricing page")} ${y.arrow} ${Se.default.cyan("domani.run/pricing")}`),Le(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),l();let i=O(!0);i.start("Waiting for upgrade...");for(let s=0;s<120;s++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${n}`}})).json();if(Go(o)){ir=!0,i.stop(`${y.success} Paid plan active! Continuing...`),l();return}}catch{}}i.stop("Timed out"),console.error(` ${Se.default.red("\u2717")} No upgrade detected. Visit ${Se.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function zo(){if(nr||ot()){nr=!0;return}let e=process.argv.includes("--json")||!_s,{source:t}=Pt(),n=hn(),i=t==="flag"||t==="env"?`domani login --account ${n}`:"domani login";e&&(console.log(JSON.stringify({error:t==="flag"||t==="env"?`Not logged in to the CLI account "${n}"`:"Not logged in",code:"auth_required",hint:`Run '${i}' or set DOMANI_API_KEY environment variable`,fix_command:i},null,2)),process.exit(1)),l(),console.log(` ${Se.default.dim("You're not logged in.")} Starting authentication...`),l();let s=Ge(),r=O(!0);r.start("Requesting auth code");let o;try{o=await fetch(`${s}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{r.stop("Failed"),console.error(` ${Se.default.red("\u2717")} Could not reach ${s}. Check your connection.`),process.exit(1)}if(!o.ok){r.stop("Failed");let m=`Server error (${o.status})`;try{let f=await o.json();m=f.error||f.message||m}catch{}console.error(` ${Se.default.red("\u2717")} ${m}`),process.exit(1)}let a,d;try{({code:a,auth_url:d}=await o.json())}catch{r.stop("Failed"),console.error(` ${Se.default.red("\u2717")} Invalid response from server.`),process.exit(1)}r.stop(`${y.success} Auth code ready`),l(),console.log(` ${Se.default.dim("Verification code:")} ${Se.default.bold(Se.default.cyan(a))}`),console.log(` ${Se.default.dim("Opening browser")} ${y.arrow} ${v.url(d)}`),Le(d),l(),r.start("Waiting for browser approval");for(let m=0;m<120;m++){await new Promise(g=>setTimeout(g,5e3));let f=await fetch(`${s}/api/auth/cli/poll?code=${a}`).catch(()=>null);if(!f||!f.ok&&f.status!==202)continue;let p=await f.json().catch(()=>({}));if(p.status==="complete"){ui(n,{token:p.token,email:p.email,api_url:s}),nr=!0,r.stop(`${y.success} Logged in as ${Se.default.bold(p.email)}`),l();return}}r.stop("Timed out"),console.error(` ${Se.default.red("\u2717")} No approval received. Run ${Se.default.cyan("domani login")} to try again.`),process.exit(1)}var Se,nr,ir,sr=je(()=>{"use strict";Se=N(F(),1);si();De();V();nr=!1,ir=!1});function Qo(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let n=t.trim().slice(0,120);return e.ok?(Object.defineProperty(e,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${e.status})`,hint:`The server replied but not with JSON${n?` (got: "${n}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${e.status})`,hint:"The server returned an unexpected response. Try again later."}}},e}async function x(e,t={},n=!1){let i=ot(),s=`${Ge()}${e}`,r=await fetch(s,{...t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","User-Agent":`domani-cli/${Ie}`,...t.headers}});if(!n){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await Ko(),x(e,t,!0)}catch{}}return Qo(r)}async function ke(e,t={}){let n=`${Ge()}${e}`,i=ot(),s=await fetch(n,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${Ie}`,...i?{Authorization:`Bearer ${i}`}:{},...t.headers}});return Qo(s)}var z=je(()=>{"use strict";De();sr()});function Mt(){return{ok:!0}}function Ct(e,t,n){return{ok:!1,error:{message:e,code:t,hint:n}}}function sa(e){return Rc.test(e)?Ct("Input contains control characters","invalid_input","Remove non-printable characters from the input"):Mt()}function Uc(e){return Tc.test(e)?Ct("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):Mt()}function qc(e){return Ec.test(e)?Ct("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):Mt()}function Mc(e){return Pc.test(e)?Ct("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):Mt()}function ra(e){if(!e)return Ct("Domain name is required","validation_error");if(e.length>ia)return Ct(`Domain name too long (${e.length} chars, max ${ia})`,"validation_error");for(let t of[sa,Uc,qc,Mc]){let n=t(e);if(!n.ok)return n}return Dc.test(e)?Mt():Ct(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Fc(e){if(!e)return Ct("TLD is required","validation_error");let t=sa(e);return t.ok?Nc.test(e)?Mt():Ct(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function Lc(e){for(let t of e){let n=ra(t);if(!n.ok)return n}return Mt()}function Vc(e){for(let t of e){let n=Fc(t);if(!n.ok)return n}return Mt()}function Y(e,t){let n=ra(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}function oa(e,t){let n=Lc(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}function Ei(e,t){let n=Vc(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}var Rc,Tc,Ec,Pc,Dc,Nc,ia,we=je(()=>{"use strict";V();Rc=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Tc=/\.\.[/\\]/,Ec=/[?#]/,Pc=/%[0-9a-fA-F]{2}/,Dc=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Nc=/^\.?[a-zA-Z]{2,63}$/,ia=253});function or(e,t){return t!==void 0&&Math.round(t*100)!==Math.round(e*100)}function nt(e,t){return or(e,t)?`$${e.toFixed(2)} first year, then $${t.toFixed(2)}/yr`:`$${e.toFixed(2)}/yr`}var Pi=je(()=>{"use strict"});function Mn(e){return Math.round(e*100)/100}function Ft(e){return e.code==="PRICE_ABOVE_MAX"&&typeof e.price=="number"?e.price:void 0}function ar(e){return`Nothing was charged. Re-run with --max-price ${e.toFixed(2)} to accept the new price.`}function Wc(e){return typeof e.renewal_price=="number"&&e.renewal_price>0?e.renewal_price:void 0}async function Fn(e,t,n,i,s){let r=Wc(n);St(s)&&u(n.error??`The price is now $${e.toFixed(2)}, above $${t.toFixed(2)}. Nothing was charged.`,{code:"price_above_max",hint:ar(e),data:{price:e,...typeof n.listed_price=="number"?{listed_price:n.listed_price}:{},...r!==void 0?{renewal_price:r}:{}},json:s.json,fields:s.fields});let o=r!==void 0?`, then ${v.price(r.toFixed(2))}/year to renew`:"",a=await We({message:`The price changed: ${v.price(e.toFixed(2))} instead of ${v.price(t.toFixed(2))}${o}. Nothing was charged. ${i} for ${v.price(e.toFixed(2))}?`});if(!a||typeof a=="symbol"){console.log(` ${aa.default.dim("Cancelled.")}`);return}return e}function tn(e,t){if(e===void 0)return;let n=Number(e);return(!Number.isFinite(n)||n<=0)&&u(`--max-price must be a positive amount in USD, got "${e}"`,{code:"validation_error",json:t.json,fields:t.fields}),n}var aa,Di=je(()=>{"use strict";qe();aa=N(F(),1);V()});async function ye(){Te||u("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let e=O(!0);e.start("Loading your domains");let t=await x("/api/domains"),n=await t.json();t.ok||(e.stop("Failed"),tr(n.error,n.hint),process.exit(1));let i=n.domains||[];i.length===0&&(e.stop("No domains"),l(),console.log(` ${dr.default.dim("No domains yet.")} Use: ${dr.default.cyan("domani buy <domain>")}`),l(),process.exit(0)),e.stop(`${i.length} domain(s)`);let s=await dt({message:"Which domain?",options:i.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return de(s)&&process.exit(0),s}var dr,it=je(()=>{"use strict";z();qe();dr=N(F(),1);V()});var la={};mn(la,{connect:()=>lr});async function lr(e,t,n){e||(e=await ye()),Y(e,n);let i;if(t&&!n.provider?t.includes(".")?i=t:n.provider=t:i=t,!i&&!n.provider&&!n.list&&n.dryRun)return K("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},n.json,n.fields);if(!i&&!n.provider&&!n.list){let s=O(!n.json);s.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop("Providers loaded"),n.json){b(o,n.fields);return}let a=[];for(let w of["hosting","email"]){let _=o.providers?.[w]||[];for(let S of _)a.push({value:`${w}:${S.name}`,label:S.name,hint:w})}a.length===0&&u("No providers available",{code:"not_found",json:n.json,fields:n.fields});let d=await dt({message:"Choose a provider",options:a});de(d)&&process.exit(0);let[m,f]=d.split(":"),g=(o.providers?.[m]||[]).find(w=>w.name===f),$;if(g&&g.methods.length>1){let w=await dt({message:"Choose a method",options:g.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});de(w)&&process.exit(0),$=w}let k;if(m==="hosting"&&g?.requires_target){g.notes?.setup&&_e(g.notes.setup);let w=await Ue({message:"Target hostname or IP"});de(w)&&process.exit(0),k=w.trim()}return da(e,{target:k,provider:f,method:$,dryRun:n.dryRun,json:!1})}if(n.list){let s=O(!n.json);s.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop("Providers loaded"),n.json){b(o,n.fields);return}j(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let d=o.providers?.[a];if(d?.length){l(),console.log(` ${fe.default.bold(a.toUpperCase())}`);for(let m of d){let f=m.methods.map(p=>p.default?fe.default.green(`${p.name} (default)`):fe.default.dim(p.name)).join(fe.default.dim(", "));console.log(` ${fe.default.cyan(m.name.padEnd(20))} ${f}`)}}}l();return}return da(e,n)}async function da(e,t){let n={};if(t.target&&(n.target=t.target),t.provider&&(n.provider=t.provider),t.method&&(n.method=t.method),t.dryRun)return K("connect",{domain:e,...n},t.json,t.fields);let i=O(!t.json);i.start(`Connecting ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(n)}),r=await s.json();s.ok||(i.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(i.stop(o?`${y.success} DNS instructions for ${fe.default.cyan(r.provider)}`:`${y.success} Connected to ${fe.default.cyan(r.provider)}`),t.json){b(r,t.fields);return}if(j(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),c("Provider",fe.default.cyan(r.provider)),c("Method",r.method),r.records?.length){let a=[8,22,40];l(),console.log(` ${fe.default.bold("DNS Records")}`);let d=["Type","Name","Value"].map((f,p)=>fe.default.dim(f.padEnd(a[p]))).join(" "),m=a.map(f=>fe.default.dim("\u2500".repeat(f))).join(" ");console.log(` ${d}`),console.log(` ${m}`);for(let f of r.records){let p=f.record,g=f.status!=="already_set";process.stdout.isTTY&&g&&await Ot(50);let k=[fe.default.yellow(p.type),p.name,fe.default.cyan(p.value)+(p.priority?fe.default.dim(` pri=${p.priority}`):"")].map((S,C)=>Ti(S,a[C])).join(" "),w=f.status==="already_set"?fe.default.dim("\u2713"):f.status==="updated"?fe.default.yellow("\u21BA"):f.status==="pending"?fe.default.yellow("\u2192"):y.success,_=f.status==="already_set"?fe.default.dim(" already set"):f.status==="updated"?fe.default.dim(" updated"):f.status==="pending"?fe.default.dim(" add this"):"";console.log(` ${w} ${k}${_}`)}}l(),r.next_steps?.length?(console.log(` ${fe.default.bold("Next steps")}`),r.next_steps.forEach((a,d)=>{console.log(` ${fe.default.dim(`${d+1}.`)} ${a}`)})):r.hint&&console.log(` ${fe.default.dim(r.hint)}`),r.docs&&console.log(` ${fe.default.dim("Docs:")} ${v.url(r.docs)}`),l()}var fe,cr=je(()=>{"use strict";z();fe=N(F(),1);qe();V();we();it()});function nn(e,t=process.env){if(e.clearHeaders&&(e.authorizationEnv||e.apiKeyEnv))throw new Error("--clear-headers cannot be combined with header environment options");if(e.clearHeaders)return{};let n={},i=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[s,r]of i){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);n[s]=o}return Object.keys(n).length>0?n:void 0}function sn(e){return e?Object.keys(e):[]}var Ni=je(()=>{"use strict"});var ka={};mn(ka,{buildSendBody:()=>ga,contactsQuery:()=>ba,email:()=>Ln,inboxQuery:()=>va,parseRecipients:()=>qi,recipientField:()=>Mi,resolveDomainArg:()=>ur,resolveDraftIdArg:()=>pa,systemLocale:()=>ha});function Bc(e){return[T.default.yellow(e.type),e.name,T.default.cyan(e.value)+(e.priority?T.default.dim(` pri=${e.priority}`):"")]}function fr(e){return Jc[e]||e}function qi(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Mi(e){if(e.length!==0)return e.length===1?e[0]:e}function Gc(e,t){if(e&&e.includes("@")){let[n,i]=e.split("@",2);!t.slug&&n&&(t.slug=n),!t.domain&&i&&(t.domain=i)}}function ur(e,t){if(t.domain)return t.domain;if(e&&!e.includes("@"))return e}async function Ye(e){return e.domain?(Y(e.domain,e),e.domain):ye()}async function Ln(e,t,n){if(e&&e.includes(".")&&!Hc.includes(e))return n.check?ua(e,!!n.json,n.fields):t?ma(e,t,!!n.json,n.fields):$a(e,!!n.json,n.fields);if(Gc(t,n),n.body&&!n.text&&(n.text=n.body),n.title&&!n.subject&&(n.subject=n.title),n.from&&n.from.includes("@")){let[i,s]=n.from.split("@",2);!n.slug&&i&&(n.slug=i),!n.domain&&s&&(n.domain=s)}switch(e){case void 0:return ca(n);case"list":return ca(n);case"inbox":return _u(n);case"folders":return ku(n);case"drafts":return xu(n);case"draft":return tu(t,n);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return ju(e,n);case"setup":return n.domain=ur(t,n),cu(n);case"status":return n.domain=ur(t,n),uu(n);case"remove":return mu(n);case"create":return fu(n);case"delete":return pu(n);case"send":return hu(n);case"webhook":return Su(n);case"webhook-test":return Ou(n);case"forward":return Cu(n);case"work":return ru(n);case"triage":return ou(n);case"note":return au(n);case"notes":return du(n);case"activity":return lu(n);case"changes":return Xc(n);case"search":return Zc(t,n);case"threads":return Qc(n);case"thread":return eu(t,n);case"label":return nu(n);case"facts":return iu(t,n);case"extract":return su(t,n);case"coordination":return Kc(n);case"presence":return zc(n);case"release-presence":return Yc(n);case"escalate":return gu(n);case"remind":return yu(n);case"contacts":return bu(n);case"contact-add":return wu(n);case"contact-remove":return vu(n);case"tone":return $u(n);case"check":return ua(n.domain||await ye(),!!n.json,n.fields);case"connect":return ma(n.domain||await ye(),t||void 0,!!n.json,n.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:n.json,fields:n.fields})}}function pr(e){let t=e.mailboxIds?.split(",").map(n=>n.trim()).filter(Boolean)[0];return(!t||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Pass --mailbox-ids mb_1 --thread-key 'jmap:thread_1'",code:"validation_error",json:e.json,fields:e.fields}),{mailboxId:t,threadKey:e.threadKey}}async function Kc(e){let{mailboxId:t,threadKey:n}=pr(e),i=new URLSearchParams({mailbox_id:t,thread_key:n}),s=await x(`/api/email/collaboration/coordination?${i}`),r=await s.json();if(s.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(r,e.fields);j("Conversation Coordination"),c("Conversation",r.conversation_id),c("Reply version",String(r.reply_version)),c("Presence",String(r.presence?.length||0)),c("Compose lease",r.compose_lease?.holder?.label||"none")}async function zc(e){let{mailboxId:t,threadKey:n}=pr(e);e.clientId||u("Client ID required",{hint:"Pass a stable --client-id for this agent process or app installation",code:"validation_error",json:e.json,fields:e.fields});let i=e.mode||"viewing";["viewing","composing"].includes(i)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let s=await x("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:n,client_id:e.clientId,mode:i,acquire_lease:e.acquireLease!==!1})}),r=await s.json();if(s.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(r,e.fields);j("Conversation Presence"),c("Mode",i),c("Reply version",String(r.reply_version)),c("Lease ID",r.compose_lease?.lease_id||"none"),c("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function Yc(e){let{mailboxId:t,threadKey:n}=pr(e);e.clientId||u("Client ID required",{hint:"Pass the same --client-id used for presence",code:"validation_error",json:e.json,fields:e.fields});let i=await x("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:n,client_id:e.clientId,lease_id:e.leaseId})}),s=await i.json();if(i.ok||u(s.error||"Could not release presence",{code:s.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j("Conversation Presence"),c("Released",e.clientId),c("Remaining presence",String(s.presence?.length||0))}async function Xc(e){let t=e.mailboxIds?.split(",").map(r=>r.trim()).filter(Boolean)[0];t||u("Mailbox ID required",{hint:"Usage: domani email changes --mailbox-ids mb_1 [--cursor <opaque>]",code:"validation_error",json:e.json,fields:e.fields});let n=new URLSearchParams({mailbox_id:t});e.cursor&&n.set("cursor",e.cursor),e.limit&&n.set("limit",e.limit);let i=await x(`/api/email/changes?${n}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);if(j("Mailbox Changes"),s.requires_full_sync){c("Full sync","Required"),c("Baseline cursor",s.next_cursor),_e("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}s.changes.length?G(["Sequence","Type","Resource","Created"],s.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${T.default.dim("No changes since this cursor.")}`),c("Next cursor",s.next_cursor),s.has_more&&_e("More changes are available; call again with the next cursor.")}function Ui(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}async function Zc(e,t){let n=(t.query||(e&&!e.includes("@")?e:void 0)||"").trim();n||u("Query required",{hint:'Usage: domani email search "the invoice from tucows" [--from hi@myapp.dev] [--mode hybrid|semantic|keyword] [--limit 10] [--label billing]',code:"validation_error",json:t.json,fields:t.fields});let i=new URLSearchParams({q:n});t.mode&&i.set("mode",t.mode),t.limit&&i.set("limit",t.limit),t.slug&&t.domain&&i.set("mailbox",`${t.slug}@${t.domain}`),t.folder&&i.set("folder",t.folder),t.since&&i.set("since",t.since),t.until&&i.set("until",t.until),t.label&&i.set("label",t.label);let s=await x(`/api/emails/search?${i}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);if(j(`Search: ${n}`),!r.results.length){console.log(` ${T.default.dim(r.hint||"No mail matches this search.")}`);return}G(["Why","From","Subject","Mailbox","Message"],r.results.map(o=>[o.why,o.message.from.slice(0,28),(o.message.subject||"").slice(0,44),o.message.mailbox.slice(0,28),o.message.id]),[8,30,46,30,28]),_e(`${r.results.length} result${r.results.length===1?"":"s"} in ${r.took_ms} ms, mode ${r.mode}. Open one with: domani email thread <thread_id> --from <mailbox>`)}async function Qc(e){let{address:t}=At(e,"Usage: domani email threads --from hi@myapp.dev [--folder inbox] [--since <iso>] [--limit 25] [--cursor <cursor>] [--label billing]"),n=new URLSearchParams;e.folder&&n.set("folder",e.folder),e.since&&n.set("since",e.since),e.limit&&n.set("limit",e.limit),e.cursor&&n.set("cursor",e.cursor),e.label&&n.set("label",e.label);let i=n.toString(),s=await x(`/api/emails/${encodeURIComponent(t)}/threads${i?`?${i}`:""}`),r=await s.json();if(s.ok||u(r.error||r.message,{code:r.code,hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return b(r,e.fields);if(j(`Threads in ${t}`),!r.threads.length){console.log(` ${T.default.dim("No conversations here.")}`);return}G(["Messages","Unread","Subject","With","Last","Thread"],r.threads.map(o=>[String(o.message_count),String(o.unread_count),(o.subject||"").slice(0,40),o.participants.filter(a=>a!==t).join(", ").slice(0,30),o.last_message_at.slice(0,16),o.id]),[9,7,42,32,17,28]),r.next_cursor&&c("Next cursor",r.next_cursor)}async function eu(e,t){let n=t.threadId||(e&&!e.includes("@")?e:void 0),{address:i}=At(t,"Usage: domani email thread <thread_id> --from hi@myapp.dev");n||u("Thread ID required",{hint:"Usage: domani email thread <thread_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/threads/${encodeURIComponent(n)}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);j(r.subject||"Conversation"),c("Messages",String(r.message_count)),c("Unread",String(r.unread_count)),c("With",r.participants.join(", "));for(let o of r.messages)console.log(`
179
- ${T.default.bold(o.direction==="out"?"\u2192":"\u2190")} ${o.from} ${T.default.dim(o.created_at.slice(0,16))}${o.labels?.length?` ${T.default.dim(`[${o.labels.join(", ")}]`)}`:""} ${T.default.dim(o.id)}`),o.text&&console.log(` ${o.text.replace(/\s+/g," ").trim().slice(0,300)}`)}function pa(e){return e&&!e.includes("@")?e:void 0}async function tu(e,t){let n=pa(e),{address:i}=At(t,"Usage: domani email draft <draft_id> --from hi@myapp.dev");n||u("Draft ID required",{hint:"Usage: domani email draft <draft_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/drafts/${encodeURIComponent(n)}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);j(r.subject||"(no subject)"),c("From",r.from||"-"),c("To",(r.to||[]).map(o=>o.address).join(", ")||"-"),r.cc?.length&&c("Cc",r.cc.map(o=>o.address).join(", ")),c("Updated",r.updated_at.slice(0,16)),r.text&&console.log(`
180
- ${r.text.replace(/\s+/g," ").trim().slice(0,500)}`)}async function nu(e){let{address:t}=At(e,"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b"),n=Ui(e.messageIds),i=Ui(e.add),s=Ui(e.remove),r=e.set===void 0?void 0:Ui(e.set);(!n.length||!i.length&&!s.length&&r===void 0)&&u("Message IDs and labels required",{hint:"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b",code:"validation_error",json:e.json,fields:e.fields});let o={message_ids:n,action:"label",idempotency_key:e.idempotencyKey||(0,mr.randomUUID)()};i.length&&(o.add=i),s.length&&(o.remove=s),r!==void 0&&(o.set=r);let a=await x(`/api/emails/${encodeURIComponent(t)}/messages/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await a.json();if(a.ok||u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields}),e.json)return b(d,e.fields);let m=d.results||[];j("Labels"),G(["Message","Result"],m.map(f=>[f.message_id,f.ok?f.changed?"updated":"unchanged":f.error?.message||"failed"]),[30,40])}async function iu(e,t){let n=t.messageIds||(e&&!e.includes("@")?e:void 0),{address:i}=At(t,"Usage: domani email facts <message_id> --from hi@myapp.dev");n||u("Message ID required",{hint:"Usage: domani email facts <message_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(n)}/facts`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);if(j("Facts"),!r.analysed){c("Analysed","no"),c("Reason",r.reason),_e(r.reason==="not_enabled"?"Enable the mailbox in the assistant: domani assistant set --enable --mailboxes <id>":"The analysis has not happened yet; try again in a minute.");return}c("Analysis",`${r.analysis.id} (${r.analysis.generated_at.slice(0,16)}, ${r.analysis.coverage})`),r.facts.length?G(["Subject","Predicate","Value","Basis"],r.facts.map(o=>[(o.subject||"").slice(0,28),(o.predicate||"").slice(0,28),`${o.value?.value??o.object??""}${o.value?.currency?` ${o.value.currency}`:""}`.slice(0,32),o.basis||""]),[30,30,34,18]):console.log(` ${T.default.dim("No claim recorded.")}`);for(let o of r.commitments)c("Promised",`${o.who}: ${o.what}`);for(let o of r.expectations)c("Awaited",`${o.who}: ${o.what}`)}async function su(e,t){let n=t.messageIds||(e&&!e.includes("@")?e:void 0),i=`Usage: domani email extract <message_id> --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}' [--instructions "amounts in EUR"] (or --schema @fields.json)`,{address:s}=At(t,i);(!n||!t.schema)&&u("Message ID and --schema required",{hint:i,code:"validation_error",json:t.json,fields:t.fields});let r;try{let d=t.schema.startsWith("@")?(0,fa.readFileSync)(t.schema.slice(1),"utf8"):t.schema;r=JSON.parse(d)}catch(d){u("Schema must be JSON (inline or @file)",{hint:d instanceof Error?d.message:String(d),code:"validation_error",json:t.json,fields:t.fields})}let o=await x(`/api/emails/${encodeURIComponent(s)}/messages/${encodeURIComponent(n)}/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schema:r,...t.instructions?{instructions:t.instructions}:{}})}),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return b(a,t.fields);j("Extraction"),c("Confidence",String(a.confidence)),c("Cached",a.cached?"yes":"no"),c("Model",a.model);for(let[d,m]of Object.entries(a.data))c(d,m===null?T.default.dim("null"):typeof m=="object"?JSON.stringify(m):String(m));for(let d of a.evidence_quotes)console.log(` ${T.default.dim(`"${d.slice(0,120)}"`)}`)}async function ru(e){let t=(e.mailboxIds||"").split(",").map(r=>r.trim()).filter(Boolean);t.length||u("Mailbox IDs required",{hint:"Usage: domani email work --mailbox-ids mb_1,mb_2",code:"validation_error",json:e.json,fields:e.fields});let n=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&n.set("status",e.status),e.assigned&&n.set("assigned",e.assigned),e.limit&&n.set("limit",e.limit);let i=await x(`/api/email/work-queue?${n}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);if(j("Shared Inbox Work"),!s.items.length)return console.log(` ${T.default.dim("No conversations match this queue.")}`);G(["Thread","Status","Assignee","Subject"],s.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),s.partial&&_e("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function ou(e){(!e.mailboxIds||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Usage: domani email triage --mailbox-ids mb_1 --thread-key <key> --status closed",code:"validation_error",json:e.json,fields:e.fields});let t=e.assigneeId&&e.assigneeType?{type:e.assigneeType,id:e.assigneeId}:void 0,n=await x("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(s=>s.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),i=await n.json();if(n.ok||u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return b(i,e.fields);j("Conversation Updated"),c("Status",i.status),c("Assignee",i.assignee?.label||"Unassigned"),c("Version",i.version)}async function au(e){(!e.conversationId||!e.note)&&u("Conversation ID and note required",{hint:'Usage: domani email note --conversation-id conv_1 --note "Waiting for finance"',code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`,{method:"POST",body:JSON.stringify({body:e.note})}),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);console.log(`${y.success} Private note added`)}async function du(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email notes --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);if(j("Private Notes"),!n.notes.length)return console.log(` ${T.default.dim("No private notes yet.")}`);G(["Author","Created","Note"],n.notes.map(i=>[i.author.label,i.created_at,i.body]),[28,24,64])}async function lu(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email activity --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/activity`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);if(j("Conversation Activity"),!n.activity.length)return console.log(` ${T.default.dim("No activity yet.")}`);G(["Type","Actor","Created"],n.activity.map(i=>[i.type,i.actor.label,i.created_at]),[36,32,24])}async function cu(e){let t=await Ye(e);if(e.dryRun)return K("email_setup",{domain:t},e.json,e.fields);let n=O(!e.json);n.start(`Setting up email on ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Email ${s.status==="already_configured"?"already configured":"configured"}`),e.json){b(s,e.fields);return}if(s.records?.length){l(),j(`Email DNS Records ${v.domain(t)}`);let r=s.records.map(o=>[T.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?T.default.green(o.status):T.default.yellow(o.status)]);G(["Type","Name","Value","Status"],r,[8,28,44,12])}l(),s.hint&&_e(s.hint),I("Check status:",`domani email status --domain ${t}`),l()}async function uu(e){let t=await Ye(e),n=O(!e.json);n.start(`Checking email status for ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Status loaded`),e.json){b(s,e.fields);return}if(j(`Email ${v.domain(t)}`),c("Enabled",s.enabled?T.default.green("yes"):T.default.dim("no")),s.enabled&&(c("Verified",s.verified?T.default.green("yes"):T.default.yellow("pending")),c("Mailboxes",String(s.mailbox_count))),l(),!s.enabled)I("Set up email:",`domani email setup --domain ${t}`),l();else if(!s.verified&&s.records?.length){console.log(` ${T.default.yellow("!")} Add these DNS records to verify:`);for(let r of s.records)console.log(` ${T.default.yellow(r.type)} ${r.name} ${T.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);l()}}async function mu(e){let t=await Ye(e);if(e.dryRun)return K("email_remove",{domain:t},e.json,e.fields);let n=O(!e.json);n.start(`Removing email from ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Email disabled`),e.json){b(s,e.fields);return}s.mailboxes_deleted>0&&console.log(` ${T.default.dim(`${s.mailboxes_deleted} mailbox(es) deleted.`)}`),l()}async function ca(e){let t=O(!e.json);t.start("Loading mailboxes");let n=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",i=await x(`/api/emails${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.mailboxes||[];if(t.stop(`${y.success} ${r.length} mailbox(es)`),e.json){b(s,e.fields);return}if(r.length===0){l(),console.log(` ${T.default.dim("No mailboxes.")}`),l(),I("Create one:","domani email create hello@example.com"),l();return}l(),j("Mailboxes");let o=r.map(a=>[T.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):T.default.dim("-"),T.default.dim(new Date(a.created_at).toLocaleDateString())]);G(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),l()}async function fu(e){let t=await Ye(e);if(e.dryRun)return K("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let n=e.slug;if(!n&&!e.json){let m=await Ue({message:`Email handle for @${t}:`,placeholder:"hello"});de(m)&&process.exit(0),n=m}n||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let i=`${n}@${t}`,s=O(!e.json);s.start("Creating mailbox");let r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:i,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){s.stop("");let m=o.txt_record,f=o.email_records||[],p=[{type:"TXT",name:m?.name||"@",value:m?.value||"",note:"ownership proof"},...f];l(),console.log(" Add these records at your DNS provider:"),l();for(let S of p){let C=S.priority!==void 0?` ${T.default.dim(`priority: ${S.priority}`)}`:"",R=S.note?` ${T.default.dim(`(${S.note})`)}`:"";console.log(` ${T.default.yellow(S.type)} ${T.default.bold(S.name)}${C}${R}`),console.log(` ${T.default.dim("\u2192")} ${T.default.cyan(S.value)}`),l()}_e("DNS propagation typically takes 5-30 minutes. Checking automatically..."),l();let g=p.map(S=>({cells:[T.default.yellow(S.type),S.name,S.note?T.default.dim(`(${S.note})`):""],status:"pending"})),$=en(["Type","Name",""],g,[6,24,16]);$.start();let k=0;for(;r.status===202&&k<60;)await Ot(15e3),k++,r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:i,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&($.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&($.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${i}`,code:"timeout",json:e.json,fields:e.fields})),$.markDone(0);let w=S=>`${S.type}:${S.name}`,_=new Map;p.slice(1).forEach((S,C)=>_.set(w(S),C+1));for(let S=0;S<60;S++){await Ot(15e3);let C=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),R=await C.json();if(C.ok&&R.records){for(let M of R.records)if(M.status==="verified"||M.status==="created"){let H=_.get(w(M));H!==void 0&&$.markDone(H)}}if(C.ok&&R.verified)break}$.stop(),l()}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),s.stop(`${y.success} ${T.default.cyan(o.address)} created`),e.json){b(o,e.fields);return}let a=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),d=await a.json();l(),a.ok&&d.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${On}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${On}/inbox?address=${encodeURIComponent(o.address)}`)),l()}async function pu(e){let t=await Ye(e);if(e.slug||u("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let n=O(!e.json);n.start(`Deleting ${e.slug}@${t}`);let i=encodeURIComponent(`${e.slug}@${t}`),s=await x(`/api/emails/${i}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Mailbox deleted`),e.json){b(r,e.fields);return}console.log(` ${T.default.dim(`${r.address} and all messages deleted.`)}`),l()}function ha(){let e=Intl.DateTimeFormat().resolvedOptions();return{locale:e.locale,timeZone:e.timeZone}}function ga(e){let t={to:Mi(qi(e.to))},n=Mi(qi(e.cc)),i=Mi(qi(e.bcc));if(n&&(t.cc=n),i&&(t.bcc=i),e.subject&&(t.subject=e.subject),e.text&&(t.text=e.text),e.inReplyTo)if(t.in_reply_to=e.inReplyTo,e.quote!==!1){let{locale:s,timeZone:r}=ha();t.quote_original={locale:s,time_zone:r}}else t.quote_original=!1;return e.references&&(t.references=e.references),e.sendAt&&(t.send_at=e.sendAt),t}async function hu(e){let t=await Ye(e);if(e.slug||u("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:e.json,fields:e.fields}),e.to||u("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let n=O(!e.json);n.start(`Sending from ${e.slug}@${t}`);let i=ga(e),s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}/send`,{method:"POST",body:JSON.stringify(i)}),o=await r.json();if(!r.ok){n.stop("Failed");let d=o.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${T.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:o.hint;u(o.error||o.message,{hint:d,status:r.status,json:e.json,fields:e.fields})}let a=Array.isArray(o.to)?o.to.join(", "):o.to;if(n.stop(o.status==="scheduled"?`${y.success} Scheduled for ${T.default.cyan(e.sendAt||"")} to ${T.default.cyan(a)} ${T.default.dim("(trash the message before then to cancel)")}`:`${y.success} Sent to ${T.default.cyan(a)}`),e.json){b(o,e.fields);return}}function At(e,t){return(!e.slug||!e.domain)&&u("Mailbox address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),{domain:e.domain,slug:e.slug,address:`${e.slug}@${e.domain}`}}async function ya(e,t,n,i,s){let r=O(!n.json);r.start(i);let o=await x(e,{method:"POST",body:JSON.stringify(t)}),a=await o.json();o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:n.json,fields:n.fields})),r.stop(s(a)),n.json&&b(a,n.fields)}async function gu(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:n}=At(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let i={};e.reason&&(i.reason=e.reason),e.clear&&(i.clear=!0),await ya(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(e.messageId)}/escalate`,i,e,e.clear?"Clearing escalation":"Flagging for a human",s=>s.needs_human?`${y.success} Flagged for a human ${T.default.dim("(conversation held, email.escalated fired)")}`:`${y.success} Escalation cleared`)}async function yu(e){let t='Usage: domani email remind hello@example.com --message-id MSG_ID --at 2026-09-03T09:00:00Z [--note "chase the invoice"] [--clear]',{address:n}=At(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),!e.at&&!e.clear&&u("Reminder time required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let i={};e.at&&(i.remind_at=e.at),e.note&&(i.note=e.note),e.clear&&(i.clear=!0),await ya(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(e.messageId)}/remind`,i,e,e.clear?"Clearing reminder":"Setting follow-up reminder",s=>s.remind_at?`${y.success} Reminder set for ${T.default.cyan(String(s.remind_at))} ${T.default.dim("(fires only if still unanswered)")}`:`${y.success} Reminder cleared`)}function ba(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.order&&t.set("order",e.order),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function bu(e){let t=await x(`/api/contacts${ba(e)}`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json){b(n,e.fields);return}let i=n.contacts||[];if(i.length===0){console.log(T.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let s of i){let r=s.name?` ${T.default.dim(s.name)}`:"",o=s.notes?` ${T.default.dim("-")} ${s.notes}`:"";console.log(`${T.default.cyan(s.address)}${r} ${T.default.dim(`(${s.message_count} msg${s.message_count!==1?"s":""}, last ${s.last_direction||"-"})`)}${o}`)}n.next_cursor&&console.log(T.default.dim(`More: --cursor ${n.next_cursor}`))}function wa(e,t){return e.slug&&e.domain?`${e.slug}@${e.domain}`:(u("Contact address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),"")}async function wu(e){let n=wa(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),i={address:n};e.name!==void 0&&(i.name=e.name),e.notes!==void 0&&(i.notes=e.notes);let s=await x("/api/contacts",{method:"POST",body:JSON.stringify(i)}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){b(r,e.fields);return}console.log(`${y.success} Contact ${T.default.cyan(n)} saved.`)}async function vu(e){let n=wa(e,"Usage: domani email contact-remove ada@example.com"),i=await x(`/api/contacts/${encodeURIComponent(n)}`,{method:"DELETE"}),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json){b(s,e.fields);return}console.log(s.deleted?`${y.success} Contact ${T.default.cyan(n)} deleted.`:T.default.dim(`No contact ${n}.`))}async function $u(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:n}=At(e,t),i=encodeURIComponent(n);if(e.set===void 0&&!e.clear){let o=await x(`/api/emails/${i}`),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}),e.json){b({address:n,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:T.default.dim(`No tone notes on ${n}. Set them with --set.`));return}let s=await x(`/api/emails/${i}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){b(r,e.fields);return}console.log(e.clear?`${y.success} Tone notes cleared on ${T.default.cyan(n)}.`:`${y.success} Tone notes set on ${T.default.cyan(n)}.`)}function va(e){let t=new URLSearchParams;e.direction&&t.set("direction",e.direction),e.folder&&t.set("folder",e.folder),e.view&&t.set("view",e.view),e.limit&&t.set("limit",e.limit),e.since&&t.set("since",e.since),e.until&&t.set("until",e.until),e.label&&t.set("label",e.label),e.kind&&t.set("kind",e.kind),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function _u(e){let t=await Ye(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--kind person,update] [--limit 20] [--cursor <next_cursor>]",code:"validation_error",json:e.json,fields:e.fields});let n=va(e),i=O(!e.json);i.start(`Loading messages for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}/messages${n}`),o=await r.json();r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));let a=o.messages||[];if(e.json){i.stop(`${y.success} ${a.length} message(s)`),b(o,e.fields);return}if(a.length===0){i.stop(`${T.default.dim("No messages")}`);return}let d=a.length>1?"s":"";i.stop(`${y.success} ${T.default.cyan(`${e.slug}@${t}`)} ${T.default.dim("\xB7 "+a.length+" message"+d)}`);for(let m of a){let f=m.direction==="in"?`${T.default.green("in ")}${m.kind?` ${T.default.dim(m.kind.padEnd(10))}`:""}`:T.default.dim("out"),p=m.direction==="in"?m.from:m.to,g=m.subject||"(no subject)",$=T.default.dim(new Date(m.created_at).toLocaleString()),k=g;if(m.text){let w=m.text.replace(/\s+/g," ").trim(),_=w.length>60?w.slice(0,60)+"\u2026":w;k=`${g} ${T.default.dim("- "+_)}`}console.log(` ${f} ${p.padEnd(30)} ${k} ${$}`)}o.next_cursor&&console.log(T.default.dim(`More: --cursor ${o.next_cursor}`))}async function ku(e){let t=await Ye(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=encodeURIComponent(`${e.slug}@${t}`),i=await x(`/api/emails/${n}/folders`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j(`Folders for ${e.slug}@${t}`);for(let r of s.folders||[])c(r.id,`${r.total} total, ${r.unread} unread`);for(let r of s.views||[])c(r.id,`${r.total} total, ${r.unread} unread`)}async function xu(e){let t=await Ye(e);e.slug||u("Slug required",{hint:"Usage: domani email drafts hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=encodeURIComponent(`${e.slug}@${t}`),i=await x(`/api/emails/${n}/drafts`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j(`Drafts from ${e.slug}@${t}`);let r=s.drafts||[];if(!r.length){console.log(` ${T.default.dim("No drafts.")}`);return}for(let o of r){let a=o.to.map(p=>p.address).join(", "),d=o.subject||"(no subject)",m=(o.text||"").replace(/\s+/g," ").trim(),f=m.length>60?m.slice(0,60)+"\u2026":m;console.log(` ${T.default.dim(o.updated_at.slice(0,16))} ${a.padEnd(30)} ${d}${f?T.default.dim(" - "+f):""} ${T.default.dim(o.id)}`)}}async function ju(e,t){let n=await Ye(t);t.slug||u("Slug required",{hint:`Usage: domani email ${e} hello@example.com --message-ids id1,id2`,code:"validation_error",json:t.json,fields:t.fields});let i=(t.messageIds||"").split(",").map(f=>f.trim()).filter(Boolean);i.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let s={message_ids:i,idempotency_key:t.idempotencyKey||(0,mr.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(s,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(s.action="restore"),(e==="read"||e==="unread")&&Object.assign(s,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(s,{action:"star",starred:e==="star"}),t.dryRun)return K("email_messages_action",{address:`${t.slug}@${n}`,...s},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${n}`),o=await x(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(s)}),a=await o.json();if(!o.ok&&o.status!==207&&u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return b(a,t.fields);let d=(a.results||[]).filter(f=>f.ok).length,m=(a.results||[]).length-d;console.log(`${y.success} ${d} updated${m?T.default.yellow(`, ${m} failed`):""}`),a.operation_id&&(c("Operation",a.operation_id),c("Idempotency key",a.idempotency_key),a.idempotent_replay&&c("Receipt","replayed (no duplicate mutation)"))}async function Su(e){let t=await Ye(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:e.json,fields:e.fields});let n=`${e.slug}@${t}`,i=encodeURIComponent(n),s;try{s=nn(e)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}let r;if(e.events!==void 0&&(r=e.events.split(",").map(a=>a.trim()).filter(Boolean),r.length===0&&u("--events needs at least one event",{hint:"Example: --events email.received,email.bounced,email.delivered",code:"validation_error",json:e.json,fields:e.fields}),e.url||u("--url is required when changing webhook events",{hint:"Pass the existing webhook URL together with --events.",code:"validation_error",json:e.json,fields:e.fields})),!e.url&&s!==void 0&&u("--url is required when changing webhook auth headers",{hint:"Pass the existing webhook URL with --authorization-env, --api-key-env, or --clear-headers.",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_webhook",{address:n,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...s!==void 0?{header_names:sn(s)}:{}},e.json,e.fields);let o=O(!e.json);if(e.url){o.start(`Setting webhook for ${n}`);let a=await x(`/api/emails/${i}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...s!==void 0?{headers:s}:{},...r!==void 0?{events:r}:{}})}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${y.success} Webhook set`),e.json){b(d,e.fields);return}j(`Mailbox ${d.address}`),c("Webhook",v.url(d.webhook_url)),c("Events",d.events?.join(", ")||T.default.dim("email.received")),c("Auth headers",d.header_names?.join(", ")||T.default.dim("none")),c("Signing secret",T.default.dim(d.signing_secret)),l()}else{o.start(`Removing webhook for ${n}`);let a=await x(`/api/emails/${i}/webhook`,{method:"DELETE"}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${y.success} Webhook removed`),e.json){b(d,e.fields);return}j(`Mailbox ${d.address}`),c("Webhook",T.default.dim("none")),l()}}async function Ou(e){let t=await Ye(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=`${e.slug}@${t}`;if(e.dryRun)return K("email_webhook_test",{address:n},e.json,e.fields);let i=O(!e.json);i.start(`Testing webhook for ${n}`);let s=await x(`/api/emails/${encodeURIComponent(n)}/webhook/test`,{method:"POST"}),r=await s.json();if((!s.ok||!r.success)&&(i.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Test delivered`),e.json)return b(r,e.fields);j(`Mailbox ${n}`),c("Delivery",T.default.green("successful")),typeof r.status=="number"&&c("Endpoint",`HTTP ${r.status}`),l()}async function Cu(e){let t=await Ye(e);if(e.slug||u("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let n=O(!e.json),i=e.forwardTo||null;n.start(`Updating forward for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({forward_to:i})}),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Forward ${i?"set":"removed"}`),e.json){b(o,e.fields);return}j(`Mailbox ${o.address}`),c("Forward to",o.forward_to?T.default.cyan(o.forward_to):T.default.dim("none")),l()}async function ua(e,t,n){let i=O(!t);i.start(`Checking email health for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop("Email health checked"),t){b(r,n);return}if(j(`Email Health ${v.domain(r.domain)}`),r.provider?c("Provider",T.default.cyan(fr(r.provider))):c("Provider",T.default.dim("unknown")),r.mx.configured?c("MX",`${y.success} ${T.default.green("propagated")} ${T.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${y.error} ${T.default.red("not configured")}`),r.spf.configured?c("SPF",`${y.success} ${T.default.green(r.spf.value)}`):c("SPF",`${y.error} ${T.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${y.success} ${T.default.green(o)}`)}else c("DMARC",`${y.error} ${T.default.red("missing")}`);r.dkim.configured?c("DKIM",`${y.success} ${T.default.green("found")} ${T.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${y.warning} ${T.default.yellow("not found")}`),l(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(_e("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),l()):(I("Set up email:",`domani email ${e} google`),l())}async function ma(e,t,n,i){return t?_a(e,t,n,i):$a(e,n,i)}async function $a(e,t,n){let i=O(!t);i.start("Loading email providers");let s=await x(`/api/domains/${encodeURIComponent(e)}/connect`),r=await s.json();s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:n});let a=await dt({message:"Choose an email provider",options:o.map(d=>({value:d.name,label:fr(d.name)}))});return de(a)&&process.exit(0),_a(e,a,t,n)}async function _a(e,t,n,i){if(n){let m=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),f=await m.json();m.ok||u(f.error||f.message,{hint:f.hint,status:m.status,json:n,fields:i}),b(f,i);return}let s=await x(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!s.ok){let m=await s.json();u(m.error||m.message,{hint:m.hint,status:s.status,json:n,fields:i})}let r=await s.json(),o=r.preview?.records??[],a=r.preview?.provider??t,d=fr(a);if(j(`Email ${v.domain(e)}`),c("Provider",T.default.cyan(d)),o.length){l(),console.log(` ${T.default.bold("DNS Records")}`);let m=[8,24,40],f=en(["Type","Name","Value"],o.map(S=>({cells:Bc(S),status:"pending"})),m);f.start();let p=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await p.json();p.ok||(f.stop(),l(),u(g.error||g.message,{hint:g.hint,status:p.status,json:n,fields:i}));let $=g.records||[];for(let S=0;S<o.length;S++)$.find(R=>R.record.type===o[S].type&&R.record.name===o[S].name&&R.record.value===o[S].value)?.status==="already_set"||await Ot(60),f.markDone(S);await Ot(80),f.stop();let k=$.filter(S=>S.status==="created"||S.status==="updated").length,w=$.filter(S=>S.status==="already_set").length,_;w===$.length?_=`All ${w} records already set`:w>0?_=`${k} created, ${w} already set`:_=`${k} DNS records set`,l(),console.log(` ${y.success} ${T.default.green(`Email configured - ${_}`)}`)}else{let m=O(!0);m.start("Setting DNS records");let f=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),p=await f.json();f.ok||(m.stop("Failed"),u(p.error||p.message,{hint:p.hint,status:f.status,json:n,fields:i})),m.stop(`${y.success} Email configured via ${T.default.cyan(d)}`)}l(),I("Verify propagation:",`domani email ${e} --check`),l()}var T,mr,fa,Hc,Jc,hr=je(()=>{"use strict";z();Cn();T=N(F(),1);qe();V();we();it();mr=require("node:crypto"),fa=require("node:fs");Ni();Hc=["setup","status","remove","list","create","delete","send","inbox","folders","drafts","draft","archive","trash","restore","read","unread","star","unstar","webhook","forward","check","connect","work","triage","notes","note","activity","changes","coordination","presence","release-presence","escalate","remind","contacts","contact-add","contact-remove","tone","search","threads","thread","label","facts","extract"],Jc={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var ja={};mn(ja,{dns:()=>yr,nextDnsRecords:()=>xa});function xa(e,t,n){let i=r=>r.type===t.type&&r.name===t.name;return n==="add"&&e.some(r=>i(r)&&r.value===t.value)?{kind:"unchanged"}:n==="add"&&t.type==="CNAME"&&e.some(i)?{kind:"cname_taken"}:{kind:"write",records:[...n==="add"?e:e.filter(r=>!i(r)),{...t,ttl:3600}]}}async function yr(e,t,n,i,s,r){e||(e=await ye()),Y(e,r);let o=r?.json??!1,a=r?.type||n,d=r?.name||i,m=r?.value||s;if(!t||t==="get"){let f=O(!o);f.start(`Loading DNS for ${v.domain(e)}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns`),g=await p.json();if(p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields})),f.stop(`${g.records.length} record(s)`),o){b(g,r?.fields);return}if(g.records.length===0){l(),console.log(` ${Oe.default.dim(`No DNS records for ${e}`)}`),l(),I("Auto-configure DNS:",`domani connect ${e}`),l();return}let $=[8,24,40,8];j(`DNS ${v.domain(e)}`,$.reduce((w,_)=>w+_,0)+$.length-1);let k=g.records.map(w=>{let _=w.priority?Oe.default.dim(` pri=${w.priority}`):"";return[Oe.default.yellow(w.type),w.name,Oe.default.cyan(w.value)+_,Oe.default.dim(String(w.ttl))]});G(["Type","Name","Value","TTL"],k,$),l();return}if(t==="set"||t==="add"){let f=t==="add";if((!a||!d||!m)&&u(`Missing arguments for dns ${t}`,{hint:`Usage: domani dns <domain> ${t} --type A --name www --value 1.2.3.4`,code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return K(f?"dns_add":"dns_set",{domain:e,record:{type:a.toUpperCase(),name:d,value:m,ttl:3600}},o,r?.fields);let p=O(!o);p.start(`${f?"Adding":"Setting"} ${Oe.default.yellow(a.toUpperCase())} record`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),$=await g.json();g.ok||(p.stop("Failed"),u($.error||$.message||"Could not read the current DNS records; nothing was changed.",{hint:$.hint,status:g.status,json:o,fields:r?.fields}));let k=$.records??[],w=a.toUpperCase(),_=xa(k,{type:w,name:d,value:m},f?"add":"set");if(_.kind==="unchanged"){p.stop(`${y.success} ${Oe.default.yellow(w)} ${d} ${y.arrow} ${Oe.default.cyan(m)} already exists`),o&&b({records:k,unchanged:!0},r?.fields);return}_.kind==="cname_taken"&&(p.stop("Failed"),u(`${d} already has a CNAME record; a name can hold only one.`,{hint:`Replace it with: domani dns ${e} set --type CNAME --name ${d} --value ${m}`,code:"validation_error",json:o,fields:r?.fields}));let S=_.records,C=await x(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:S})}),R=await C.json();C.ok||(p.stop("Failed"),u(R.error||R.message,{hint:R.hint,status:C.status,json:o,fields:r?.fields})),p.stop(`${y.success} ${Oe.default.yellow(a.toUpperCase())} ${d} ${y.arrow} ${Oe.default.cyan(m)}`),o?b(R,r?.fields):(l(),I("Check propagation:",`domani status ${e}`),l());return}if(t==="delete"){if((!a||!d)&&u("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 K("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:d}},o,r?.fields);let f=O(!o);f.start(`Deleting ${Oe.default.yellow(a.toUpperCase())} ${d}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(d)}`,{method:"DELETE"}),g=await p.json();p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields})),f.stop(`${y.success} Deleted ${Oe.default.yellow(a.toUpperCase())} ${d}`),o?b(g,r?.fields):(l(),I("Check propagation:",`domani status ${e}`),l());return}if(t==="snapshot"){if(r?.dryRun)return K("dns_snapshot",{domain:e},o,r?.fields);let f=O(!o);f.start(`Capturing DNS snapshot for ${v.domain(e)}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),g=await p.json();p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields}));let $=g.records?.length??0;if(f.stop(`${y.success} Captured ${$} record(s)`),o){b(g,r?.fields);return}let k=`${e}.dns.json`,w=(0,gr.resolve)(process.cwd(),k);(0,Fi.writeFileSync)(w,JSON.stringify(g,null,2)+`
181
- `),j("DNS Snapshot"),c("Domain",v.domain(g.domain)),c("Records",String($)),c("Subdomains",String(g.subdomains?.length??0)),c("Sources",(g.sources||[]).join(", ")||"none"),c("Captured",g.capturedAt||g.captured_at||"now"),c("Saved to",Oe.default.cyan(k)),l(),I("Restore from this snapshot:",`domani dns ${e} restore --file ${k}`),l();return}if(t==="restore"){if(r?.dryRun)return K("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let f=O(!o),p;if(r?.file){let k=(0,gr.resolve)(process.cwd(),r.file);k.startsWith(process.cwd())||u("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let w=(0,Fi.readFileSync)(k,"utf-8"),_=JSON.parse(w);p=JSON.stringify({snapshot:_}),f.start(`Restoring DNS for ${v.domain(e)} from ${Oe.default.cyan(r.file)}`)}catch(w){u(`Failed to read snapshot file: ${w instanceof Error?w.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else f.start(`Restoring DNS for ${v.domain(e)} from server backup`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...p?{body:p}:{}}),$=await g.json();if(g.ok||(f.stop("Failed"),u($.error||$.message,{hint:$.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${y.success} Restored DNS`),o){b($,r?.fields);return}if(j("DNS Restored"),c("Domain",v.domain($.domain)),c("Applied",Oe.default.green(String($.applied??0))),c("Skipped",Oe.default.dim(String($.skipped??0))),$.errors?.length>0){c("Errors",Oe.default.red(String($.errors.length)));for(let k of $.errors)console.log(` ${Oe.default.red("\u2022")} ${k}`)}l(),I("Verify DNS records:",`domani dns ${e}`),l();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'add', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Oe,Fi,gr,br=je(()=>{"use strict";z();Oe=N(F(),1);V();we();it();Fi=require("node:fs"),gr=require("node:path")});var Sa={};mn(Sa,{status:()=>wr});function Au(e){return[lt.default.yellow(e.type),e.name,lt.default.cyan(e.value)+(e.priority?lt.default.dim(` pri=${e.priority}`):"")]}function Iu(e){if(j(`Status ${v.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),n=e.days_until_expiry,i=n!=null&&n<30?lt.default.red:n!=null&&n<90?lt.default.yellow:lt.default.green;c("Expires",`${t} ${lt.default.dim("(")}${i(`${n} days`)}${lt.default.dim(")")}`)}}async function wr(e,t){if(e||(e=await ye()),Y(e,t),t.json){let p=await x(`/api/domains/${encodeURIComponent(e)}/status`),g=await p.json();p.ok||u(g.error||g.message,{hint:g.hint,status:p.status,json:t.json,fields:t.fields}),b(g,t.fields);return}let n=O(!0);n.start(`Checking ${v.domain(e)}`);let i;try{i=await x(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{n.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!i.ok){n.stop("Failed");try{let p=await i.json();u(p.error||p.message,{hint:p.hint,status:i.status,json:t.json,fields:t.fields})}catch{u(`Server error (${i.status})`,{status:i.status,json:t.json,fields:t.fields})}}let s=i.body;s||(n.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,d=[],m=!1,f="";try{for await(let p of s){o+=r.decode(p,{stream:!0});let g=o.split(`
182
- `);o=g.pop()??"";for(let $ of g)if($.startsWith("event: "))f=$.slice(7);else if($.startsWith("data: ")){let k=JSON.parse($.slice(6));if(f==="info"&&(n.stop("Status retrieved"),m=!0,Iu(k)),f==="records")if(d=k,d.length>0){l(),console.log(` ${lt.default.bold("DNS Records")}`);let w=[8,10,34];a=en(["Type","Name","Value"],d.map(_=>({cells:Au(_),status:"pending"})),w),a.start()}else l(),c("DNS",lt.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${e}`);if(f==="propagation"&&a){let{index:w,propagated:_}=k,S=_?y.success:`${y.warning}`;a.markDone(w,S)}f==="done"&&a&&a.stop(),f==="error"&&(m||n.stop("Failed"),a&&a.stop(),u(k.message||"Status check failed"))}}}catch{m||n.stop("Failed"),a&&a.stop(),u("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:t.json,fields:t.fields})}m||n.stop("Done"),l()}var lt,vr=je(()=>{"use strict";z();lt=N(F(),1);V();we();it()});var Vn={};mn(Vn,{buy:()=>_r});async function $r(e){let t=await dt({message:`What's next for ${Ce.default.cyan(e)}?`,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(de(t)||t==="done"){l();return}if(l(),t==="connect"){let{connect:n}=await Promise.resolve().then(()=>(cr(),la));await n(e,void 0,{})}else if(t==="email"){let n=await Ue({message:`Mailbox name for ${Ce.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(de(n)||!n){l();return}l();let{email:i}=await Promise.resolve().then(()=>(hr(),ka));await i("create",void 0,{domain:e,slug:n})}else if(t==="dns"){let{dns:n}=await Promise.resolve().then(()=>(br(),ja));await n(e)}else if(t==="status"){let{status:n}=await Promise.resolve().then(()=>(vr(),Sa));await n(e,{})}}async function Oa(e,t,n){let i=O(!n.json);i.start("Purchasing");let s=await x("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e,...t!==void 0?{max_price:t}:{}})});if(!s.ok||!s.body){let f=await s.json().catch(()=>({})),p=Ft(f);if(p!==void 0)return i.stop("Price changed - nothing was charged"),{refused:{price:p,error:f.error,renewal_price:f.renewal_price,listed_price:f.listed_price}};i.stop("Purchase failed"),u(f.error||f.message,{hint:f.hint,fixUrl:f.setup_url||f.payment_options?.card?.setup_url,status:s.status,json:n.json,fields:n.fields})}let r={},o=new TextDecoder,a="",d="";for await(let f of s.body){a+=o.decode(f,{stream:!0});let p=a.split(`
183
- `);a=p.pop()??"";for(let g of p)if(g.startsWith("event: "))d=g.slice(7).trim();else if(g.startsWith("data: ")){let $=JSON.parse(g.slice(6));if(d==="checking")i.message(`Checking ${v.domain($.domain)}`);else if(d==="payment")i.message(`Charging ${v.price($.total)}`);else if(d==="registering")i.message(`Registering ${v.domain($.domain)}`);else if(d==="registered")r=$;else if(d==="error"){let k=Ft($);if(k!==void 0)return i.stop("Price changed - nothing was charged"),{refused:{price:k,error:$.error,renewal_price:$.renewal_price,listed_price:$.listed_price}};i.stop("Purchase failed"),u($.error,{hint:$.hint,fixUrl:$.setup_url,status:s.status,json:n.json,fields:n.fields})}}}let m=r.expires?Ce.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";return i.stop(`${y.success} ${v.domain(r.domain)} is yours!${m}`),{registered:r}}async function Ru(e,t){Y(e,t);let n=tn(t.maxPrice,t),i;if(t.preChecked)i={available:!0,...t.preChecked};else{let a=O(!t.json);a.start(`Checking ${v.domain(e)}`);let d=await x(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await d.json(),d.ok||(a.stop("Search failed"),u(i.error,{hint:i.hint,status:d.status,json:t.json,fields:t.fields})),i.available||(a.stop(`${y.error} ${v.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),a.stop(`${y.success} ${v.domain(e)} ${y.dot} available ${y.dot} ${Ce.default.green(nt(i.price,i.renewal_price))}`)}let s=n??(typeof i.price=="number"?Mn(i.price):void 0);if(t.dryRun)return K("buy",{domain:e,available:!0,price:i.price,...i.renewal_price!==void 0?{renewal_price:i.renewal_price}:{},currency:i.currency||"USD",max_price:s,acting_as:xt()},t.json,t.fields);if(!St(t)){let a=await We({message:`Purchase ${Ce.default.bold(e)} for ${Ce.default.green(nt(i.price,i.renewal_price))}${Ut()}?`});if(!a||typeof a=="symbol"){console.log(` ${Ce.default.dim("Cancelled.")}`);return}}let r=await Oa(e,s,t);for(;"refused"in r;){let a=await Fn(r.refused.price,s??i.price,r.refused,"Buy",t);if(a===void 0)return;s=a,r=await Oa(e,s,t)}let o=r.registered;if(t.json){b(o,t.fields);return}Te?await $r(o.domain):(I("Connect to a service:",`domani connect ${o.domain}`),I("Set up email:",`domani email setup ${o.domain}`),I("Configure DNS:",`domani dns ${o.domain}`),l())}async function Tu(e,t){oa(e,t);let n=tn(t.maxPrice,t),i=!!t.json,s=O(!i);s.start(`Checking ${e.length} domains`);let r=await Promise.all(e.map(async _=>{try{let S=await x(`/api/domains/search?q=${encodeURIComponent(_)}`),C=await S.json();return{domain:_,available:S.ok&&C.available,price:C.price,renewal_price:C.renewal_price}}catch{return{domain:_,available:!1,price:void 0,renewal_price:void 0}}})),o=r.filter(_=>_.available),a=r.filter(_=>!_.available);o.length===0&&(s.stop(`${y.error} None of the ${e.length} domains are available`),process.exit(1));let d=o.reduce((_,S)=>_+(S.price||0),0),m=o.reduce((_,S)=>_+(S.renewal_price??S.price??0),0),f=or(d,m)?`, then ${v.price(m.toFixed(2))}/yr`:"";if(s.stop(`${y.success} ${o.length}/${e.length} available ${y.dot} ${v.price(d.toFixed(2))} total`),a.length>0)for(let _ of a)console.log(` ${y.error} ${v.domain(_.domain)} ${Ce.default.dim("not available")}`);let p=n??(o.every(_=>typeof _.price=="number")?Mn(d):void 0);if(t.dryRun)return K("buy_bulk",{domains:o.map(_=>({domain:_.domain,price:_.price,..._.renewal_price!==void 0?{renewal_price:_.renewal_price}:{}})),unavailable:a.map(_=>_.domain),total_price:parseFloat(d.toFixed(2)),max_price:p,acting_as:xt()},t.json,t.fields);if(!St(t)){let _=await We({message:`Purchase ${Ce.default.bold(String(o.length))} domain${o.length>1?"s":""} for ${v.price(d.toFixed(2))}${f}${Ut()}?`});if(!_||typeof _=="symbol"){console.log(` ${Ce.default.dim("Cancelled.")}`);return}}l();let g,$;for(;;){let _=en(["Domain","Price"],o.map(R=>({cells:[v.domain(R.domain),R.price?Ce.default.green(nt(R.price,R.renewal_price)):""],status:"pending"})),[30,12],!i);_.start(),g=await x("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:o.map(R=>R.domain),...p!==void 0?{max_price:p}:{}})}),$=await g.json();let S=g.ok?void 0:Ft($);if(S===void 0){let R=new Set(($.results||[]).map(M=>M.domain));for(let M=0;M<o.length;M++){let H=o[M].domain.toLowerCase().trim();_.markDone(M,R.has(H)?y.success:y.error)}_.stop();break}for(let R=0;R<o.length;R++)_.markDone(R,Ce.default.dim("\xB7"));_.stop(),l();let C=await Fn(S,p??d,$,"Buy",t);if(C===void 0)return;p=C,l()}if(g.ok||u($.error,{hint:$.hint,fixUrl:$.setup_url,status:g.status,json:t.json,fields:t.fields}),i){b($,t.fields);return}l();let k=$.summary?.succeeded??0,w=$.summary?.failed??0;if(k>0&&console.log(` ${y.success} ${Ce.default.green(`${k} domain${k>1?"s":""} registered`)}`),w>0){console.log(` ${y.error} ${Ce.default.red(`${w} failed`)}`);for(let _ of $.errors||[])console.log(` ${Ce.default.dim("\u2500")} ${v.domain(_.domain)}: ${Ce.default.dim(_.error)}${_.hint?` ${Ce.default.dim(`(${_.hint})`)}`:""}`)}if(l(),k>0&&Te){let _=($.results||[]).filter(S=>S.success).map(S=>S.domain);if(_.length===1)await $r(_[0]);else{let S=await dt({message:"Set up one of your new domains?",options:[..._.map(C=>({value:C,label:Ce.default.cyan(C)})),{value:"done",label:"Done"}]});!de(S)&&S!=="done"?(l(),await $r(S)):l()}}else k>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),l())}async function _r(e,t){let n=e.filter(Boolean);if(n.length===0){Te||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let i=await Ue({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(de(i)||!i)&&process.exit(0),n=i.split(/\s+/).filter(Boolean)}return n.length===1?Ru(n[0],t):Tu(n,t)}var Ce,vn=je(()=>{"use strict";z();qe();Ce=N(F(),1);V();De();we();Di();Pi()});var Br=N(Jr(),1),{program:tf,createCommand:nf,createArgument:sf,createOption:rf,CommanderError:of,InvalidArgumentError:af,InvalidOptionArgumentError:df,Command:Gr,Argument:lf,Option:cf,Help:uf}=Br.default;si();var $t=N(F(),1);De();sr();V();Cn();De();var tt=N(F(),1);V();var Cc=new Set(["cli","mcp","plugin","skill","api"]);function Ac(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),n=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),i=!!(t?.length||n?.length||e.label||e.expiresIn),s=e.surface||"cli";if(!Cc.has(s))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let r=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(r!==void 0&&(!Number.isInteger(r)||r<3600||r>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:i,body:{...t?.length?{scopes:t}:{},...n?.length?{mailboxes:n}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:s,intent:"programmatic_access"}}}function Yo(e){return e!=="default"||rt().some(n=>n.name!==e)?` ${tt.default.dim(`(account ${e})`)}`:""}async function Xo(e){let t=Ge(),n=O(!e.json),i;try{i=Ac(e)}catch($){u($ instanceof Error?$.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:s,delegated:r}=i,o=hn(),a=$s(o);if(a&&!r){n.start("Checking session");try{let $=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if($.ok){let k=await $.json();n.stop(`Already logged in as ${tt.default.bold(k.email)}${Yo(o)}`),e.json&&b({status:"already_logged_in",email:k.email,account:o});return}}catch{}n.stop("Session expired, re-authenticating"),l()}n.start("Requesting auth code");let d=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!d.ok){n.stop("Failed to initiate login");try{let $=await d.json();u($.error||$.message||`Server error (${d.status})`,{hint:$.hint,code:"login_failed",json:e.json})}catch{u(`Could not reach ${t}. Check your connection and try again.`,{code:"network_error",json:e.json})}}let{code:m,auth_url:f,expires_in:p}=await d.json();if(n.stop("Auth code received"),e.json){b({status:"awaiting_approval",code:m,auth_url:f,expires_in:p,account:o});return}l(),console.log(` ${tt.default.dim("Verification code:")} ${tt.default.bold(tt.default.cyan(m))}`),e.open!==!1?(console.log(` ${tt.default.dim("Opening browser")} ${y.arrow} ${v.url(f)}`),Le(f)):console.log(` ${tt.default.dim("Open this URL to approve:")} ${v.url(f)}`),l(),n.start("Waiting for approval");let g=120;for(let $=0;$<g;$++){await new Promise(_=>setTimeout(_,5e3));let k=await fetch(`${t}/api/auth/cli/poll?code=${m}`);!k.ok&&k.status!==202&&(n.stop("Login failed"),u(`Server error (${k.status})`,{code:"login_failed"}));let w=await k.json();if(w.status==="complete"){ui(o,{token:w.token,email:w.email,api_url:t}),n.stop(`Logged in as ${tt.default.bold(w.email)}${Yo(o)}`),l();let _=Be().active_account;if(_&&_!==o){console.log(` ${tt.default.dim(`Commands still act as the active account "${_}".`)}`),I("Switch to this one:",`domani use ${o}`),I("Or use it once:",`domani --account ${o} me`),l();return}console.log(` ${tt.default.bold("Get one real result:")}`),I("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),I("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),I("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${tt.default.dim("A custom domain can wait until this loop works.")}`),l();return}w.error&&(n.stop("Login failed"),u(w.error||w.message,{hint:w.hint,code:"login_failed"}))}n.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}De();var rr=N(F(),1);V();async function Zo(e){let t=hn(),n=ro(t);if(!n){e.json?b({status:"not_logged_in",account:t}):console.log(` ${rr.default.dim(`Not logged in${t==="default"?"":` to the account "${t}"`}.`)}`);return}let i=rt().map(r=>r.name);if(e.json){b({status:"logged_out",account:t,email:n.email||null,remaining_accounts:i});return}let s=[n.email,i.length>0||t!=="default"?`account ${t}`:void 0].filter(Boolean).join(", ");console.log(` ${y.success} Logged out${s?` ${rr.default.dim(`(${s})`)}`:""}`),i.length>0&&!Be().active_account&&I("Pick the account to use next:",`domani use ${i[0]}`)}z();De();var qt=N(F(),1);V();async function ea(e){let[t,n]=await Promise.all([x("/api/me"),x("/api/me/activation")]),i=await t.json();t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields});let s=n.ok?await n.json():null,r=Tn(),o={name:r.name??null,source:r.source};if(e.json){b({...i,activation:s,cli_account:o},e.fields);return}if(j("Account"),c("Email",qt.default.bold(i.email)),c("CLI account",r.source==="api_key_env"?qt.default.dim("DOMANI_API_KEY"):`${r.name??"-"}${r.source==="flag"?qt.default.dim(" (--account)"):r.source==="env"?qt.default.dim(" (DOMANI_ACCOUNT)"):""}`),c("Payment",i.has_payment_method?`${y.success} ${qt.default.green("active")}`:`${y.error} ${qt.default.dim("none")}`),c("Domains",String(i.domain_count)),c("API tokens",String(i.token_count)),c("Referral code",i.referral_code||qt.default.dim("-")),c("Created",new Date(i.created_at).toLocaleDateString()),s){c("Activation",s.status);let a=s.recommended_actions?.[0];a&&c("Next action",a.label)}l()}var pt=N(F(),1);De();V();var Ic={api_key_env:"DOMANI_API_KEY",flag:"--account",env:"DOMANI_ACCOUNT",active:"domani use",none:"none"};async function ta(e){let t=rt(),n=Be().active_account??null,i=Tn();if(e.json){b({active:n,current:i.name??null,source:i.source,accounts:t.map(r=>({name:r.name,email:r.email??null,api_url:r.api_url??null,active:r.name===n,current:r.name===i.name}))});return}if(t.length===0){console.log(` ${pt.default.dim("No saved accounts.")}`),I("Log in:","domani login");return}j("Accounts");let s=Math.max(...t.map(r=>r.name.length));for(let r of t){let o=r.name===i.name?pt.default.green("*"):" ",a=[r.name===n?"active":void 0,r.name===i.name&&i.source!=="active"?`selected by ${Ic[i.source]}`:void 0].filter(Boolean);console.log(` ${o} ${pt.default.bold(r.name.padEnd(s))} ${r.email??pt.default.dim("unknown email")}${a.length?` ${pt.default.dim(a.join(", "))}`:""}`)}i.source==="api_key_env"&&(l(),console.log(` ${y.warning} ${pt.default.dim("DOMANI_API_KEY is set: every command uses that key, not these accounts.")}`)),l(),I("Switch:","domani use <name>"),I("Add one:","domani login --account <name>"),l()}async function na(e,t){if(ci(e)||u(`Invalid account name: ${e}`,{code:"validation_error",hint:"Use letters, digits, dot, dash or underscore",json:t.json}),!oo(e)){let i=rt().map(s=>s.name);u(`No saved account named "${e}"`,{code:"account_not_found",hint:i.length?`Saved accounts: ${i.join(", ")}. Add one with 'domani login --account ${e}'`:`Log in with 'domani login --account ${e}'`,json:t.json})}let n=rt().find(i=>i.name===e)?.email??null;if(t.json){b({status:"switched",active:e,email:n});return}console.log(` ${y.success} Now using ${pt.default.bold(e)}${n?` ${pt.default.dim(`(${n})`)}`:""}`),process.env.DOMANI_ACCOUNT&&process.env.DOMANI_ACCOUNT!==e&&console.log(` ${y.warning} ${pt.default.dim(`DOMANI_ACCOUNT=${process.env.DOMANI_ACCOUNT} still overrides it in this shell.`)}`)}z();qe();var E=N(F(),1);V();we();Pi();function Lt(e){return!e.available&&!e.error&&!e.registry_status&&e.price===0&&!!e.reason&&!rn(e)}var Wi="not sold on Domani";function rn(e){return e.tld_kind==="alt_root"}function kr(e){return e.reason||`${e.domain} does not resolve in public DNS: its TLD is not in the DNS root zone (IANA). Domani does not offer it.`}function ht(e){return e.registry_status==="premium"||e.registry_status==="reserved"}function _n(e){return e.registry_status==="reserved"?"reserved":e.registry_price!==void 0?`premium $${e.registry_price.toFixed(2)}`:"premium"}function xr(e){if(e.reason)return e.reason;if(e.registry_status==="reserved")return`${e.domain} is reserved by the registry and cannot be registered.`;let t=e.registry_price!==void 0?`: the registry prices it at $${e.registry_price.toFixed(2)}`:" priced by the registry";return`${e.domain} is a premium name${t}. Premium names cannot be bought at the standard price.`}function on(e,t){let n=e.findIndex(i=>i.domain===t);return n!==-1&&e.splice(n,1),n}var Xe=10,$n=200,Li=["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"],Vi=null;async function Ca(){if(Vi)return Vi;try{let e=await ke("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let n=(await e.json()).tlds.map(i=>i.tld);if(n.length>0){let i=new Set(Li),s=new Set(n),r=[...Li.filter(o=>s.has(o)),...n.filter(o=>!i.has(o))];return Vi=r,r}}}catch{}return Vi=Li,Li}async function Eu(e,t,n,i,s){let r=[],o=[],a=Xe,d=0,m=!0,f=0,p=0,g=!1,$=!1,k=null,w="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=0,C=setInterval(()=>{$||!m||(S=(S+1)%_.length,U())},80);function R(){f>0&&(process.stdout.write(`\x1B[${f}A\x1B[0J`),f=0)}function M(){if(m)return[];let A=Xe+p*Xe;return r.length>a||i&&A<s.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function ee(){let A=M();return Math.max(0,H().length+A.length-1)}let q=6;function U(){R();let A=[],W=H(),ne=!m&&W.length===0&&o.length>0,X=ne?o.slice(0,q):W,ae=X.reduce((ge,te)=>Math.max(ge,te.domain.length),0),$e=M();for(let ge=0;ge<X.length;ge++){let te=X[ge];if(ne)A.push(`${E.default.dim("\u2502")} ${E.default.dim("\u2715")} ${E.default.dim(te.domain.padEnd(ae))} ${E.default.dim(ht(te)?_n(te):Lt(te)?Wi:"taken")}`);else{let ue=ge===d,ut=ue?E.default.green("\u25CF"):E.default.dim("\u25CB"),Ht=te.domain.padEnd(ae),cn=ue?E.default.bold(E.default.cyan(Ht)):Ht,jn=te.for_sale?E.default.cyan(`$${te.for_sale.price} (for sale)`):E.default.dim(nt(te.price,te.renewal_price));A.push(`${E.default.dim("\u2502")} ${ut} ${cn} ${jn}`)}}if(ne&&o.length>q&&A.push(`${E.default.dim("\u2502")} ${E.default.dim(`\u2026 and ${o.length-q} more taken`)}`),m){let ge=w?E.default.dim(`checking ${w}\u2026`):E.default.dim("searching\u2026");A.push(`${E.default.dim("\u2502")} ${E.default.cyan(_[S])} ${ge}`)}else{let ge=Xe+p*Xe;i&&ge>=s.length&&A.push(`${E.default.dim("\u2502")} ${E.default.dim(`All ${Math.min(ge,s.length)} TLDs searched`)}`);for(let ue=0;ue<$e.length;ue++){let cn=H().length+ue===d?E.default.green("\u25CF"):E.default.dim("\u25CB"),jn=$e[ue]==="more"?E.default.dim("More \u2192"):$e[ue]==="new"?E.default.dim("New search \u2192"):E.default.dim("Skip");A.push(`${E.default.dim("\u2502")} ${cn} ${jn}`)}A.push(E.default.dim("\u2514"))}process.stdout.write(A.join(`
177
+ `}}}}).prompt()});function Nc(e){return!!(e.json||!Te)}function j(e,t=50){console.log(),console.log(` ${G.default.bold(e)}`),console.log(` ${G.default.dim("\u2500".repeat(t))}`)}function l(e,t,n=2){let i=" ".repeat(n);console.log(`${i}${G.default.dim(e.padEnd(16))} ${t}`)}function c(){console.log()}function ue(e){console.log(` ${G.default.dim(e)}`)}function I(e,t){console.log(` ${G.default.dim(e)} ${G.default.cyan(t)}`)}function zo(e){return e.split(/(https?:\/\/[^\s]+)/g).map(n=>/^https?:\/\//.test(n)?`\x1B]8;;${n}\x1B\\${G.default.underline(G.default.cyan(n))}\x1B]8;;\x1B\\`:G.default.dim(n)).join("")}function sr(e,t){console.error(` ${y.error} ${G.default.red(e)}`),t&&console.error(` ${zo(t)}`)}function C(e=!0){return e?Mn():Uc}function Yo(e){return e.replace(qc,"")}function Pi(e,t){let n=Yo(e).length,i=Math.max(0,t-n);return e+" ".repeat(i)}function B(e,t,n){let i=n||e.map((o,a)=>{let d=t.reduce((m,f)=>Math.max(m,Yo(f[a]||"").length),0);return Math.max(o.length,d)+2}),s=e.map((o,a)=>G.default.dim(o.padEnd(i[a]))).join(" "),r=i.map(o=>G.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${s}`),console.log(` ${r}`);for(let o of t){let a=o.map((d,m)=>Pi(d,i[m])).join(" ");console.log(` ${a}`)}}function Mc(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ir(e){if(Array.isArray(e))return e.map(ir);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[n,i]of Object.entries(e))t[Mc(n)]=ir(i);return t}return e}function b(e,t){let n=ir(e);if(!t){console.log(JSON.stringify(n,null,2));return}let i=t.split(",").map(s=>s.trim()).filter(Boolean);if(Array.isArray(n)){let s=n.map(r=>Bo(r,i));console.log(JSON.stringify(s,null,2))}else console.log(JSON.stringify(n&&typeof n=="object"?Bo(n,i):n,null,2))}function Bo(e,t){let n={};for(let i of t)i in e&&(n[i]=e[i]);if(Object.keys(n).length===0){for(let[i,s]of Object.entries(e))if(Array.isArray(s)&&s.length>0&&typeof s[0]=="object"){let r=s.map(o=>{let a={};for(let d of t)d in o&&(a[d]=o[d]);return a});Object.keys(r[0]).length>0&&(n[i]=r)}}return n}function Ct(e){return!!(e.yes||Nc(e))}function qt(){let e=jt();return e?` as ${G.default.bold(e)}`:""}function K(e,t,n,i){if(n){b({dry_run:!0,action:e,...t},i);return}console.log(),console.log(` ${G.default.yellow("\u25B8 DRY RUN")} ${G.default.dim("- no changes made")}`),console.log(` ${G.default.dim("Action:")} ${G.default.bold(e)}`);for(let[s,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${G.default.dim(s+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${G.default.dim(s+":")} ${JSON.stringify(r)}`:` ${G.default.dim(s+":")} ${String(r)}`));console.log()}function Lc(e,t,n){return t===401||t===403?"auth_required":t===402||n?"payment_required":t===404?"not_found":t===409?"conflict":t===422?"validation_error":t===429?"rate_limited":/contact/i.test(e)?"contact_required":"error"}function u(e,t){let n=e||`Request failed${t?.status?` (${t.status})`:""}`,i=t?.code||Lc(n,t?.status,t?.fixUrl),s=t?.fixCommand||Fc[i];if(t?.json){let r={error:n,code:i,...t.data};t.hint&&(r.hint=t.hint),s&&(r.fix_command=s),t.fixUrl&&(r.fix_url=t.fixUrl),b(r,t.fields)}else sr(n,t?.hint),s?console.error(` ${G.default.dim("Or run:")} ${G.default.cyan(s)}`):t?.fixUrl&&console.error(` ${zo(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function Ve(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Ko.execFile)(t,[e])}function Ot(e){return new Promise(t=>setTimeout(t,e))}function tn(e,t,n,i=!0){let s=process.stdout.isTTY??!1;if(!i)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function d(){let g=" "+e.map((w,k)=>G.default.dim(w.padEnd(n[k]))).join(" "),$=" "+n.map(w=>G.default.dim("\u2500".repeat(w))).join(" "),_=[g,$];for(let w of t){let k=w.status==="done"?w.icon??y.success:G.default.cyan(Go[r%Go.length]),S=w.cells.map((O,R)=>Pi(O,n[R])).join(" ");_.push(` ${k} ${S}`)}return _}let m=!1,f=()=>process.stdout.write("\x1B[?25h");function p(){let g=d();if(m&&s){process.stdout.write(`\x1B[${a}A`);for(let $ of g)process.stdout.write(`\x1B[2K${$}
178
+ `)}else{for(let $ of g)console.log($);m=!0}}return{start(){s&&(process.stdout.write("\x1B[?25l"),process.on("exit",f)),p(),s&&(o=setInterval(()=>{r++,p()},80))},markDone(g,$){t[g].status="done",$!==void 0&&(t[g].icon=$),s&&p()},stop(){o&&clearInterval(o);for(let g of t)g.status="done";p(),s&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",f))}}}var G,Ko,Te,y,v,Uc,qc,Fc,Go,L=_e(()=>{"use strict";G=N(F(),1),Ko=require("child_process");De();qe();Te=process.stdout.isTTY??!1;y={success:G.default.green("\u2713"),error:G.default.red("\u2717"),warning:G.default.yellow("!"),info:G.default.cyan("\u25CF"),arrow:G.default.dim("\u2192"),dot:G.default.dim("\xB7"),dash:G.default.dim("\u2500")},v={domain:e=>G.default.bold(G.default.white(e)),price:e=>G.default.green(`$${e}`),label:e=>G.default.dim(e),value:e=>G.default.white(e),dim:e=>G.default.dim(e),bold:e=>G.default.bold(e),success:e=>G.default.green(e),error:e=>G.default.red(e),warn:e=>G.default.yellow(e),cyan:e=>G.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${G.default.underline(G.default.cyan(e))}\x1B]8;;\x1B\\`};Uc={start:()=>{},stop:()=>{},message:()=>{}};qc=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Fc={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Go=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function Xo(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function Zo(e){return Xo(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(Xo)}async function Qo(){if(or)return;let e=process.argv.includes("--json")||!js,t=Ke(),n=at();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${n}`}})).json();if(Zo(r)){or=!0;return}}catch{}e&&(console.log(JSON.stringify({error:"Paid plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),c(),console.log(` ${Se.default.dim("This feature requires a")} ${Se.default.bold("paid plan")} ${Se.default.dim(`(including an active ${Pt.mailProductName} workspace plan or legacy Pro subscription).`)}`),console.log(` ${Se.default.dim("Opening pricing page")} ${y.arrow} ${Se.default.cyan("domani.run/pricing")}`),Ve(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),c();let i=C(!0);i.start("Waiting for upgrade...");for(let s=0;s<120;s++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${n}`}})).json();if(Zo(o)){or=!0,i.stop(`${y.success} Paid plan active! Continuing...`),c();return}}catch{}}i.stop("Timed out"),console.error(` ${Se.default.red("\u2717")} No upgrade detected. Visit ${Se.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function ea(){if(rr||at()){rr=!0;return}let e=process.argv.includes("--json")||!js,{source:t}=Dt(),n=gn(),i=t==="flag"||t==="env"?`domani login --account ${n}`:"domani login";e&&(console.log(JSON.stringify({error:t==="flag"||t==="env"?`Not logged in to the CLI account "${n}"`:"Not logged in",code:"auth_required",hint:`Run '${i}' or set DOMANI_API_KEY environment variable`,fix_command:i},null,2)),process.exit(1)),c(),console.log(` ${Se.default.dim("You're not logged in.")} Starting authentication...`),c();let s=Ke(),r=C(!0);r.start("Requesting auth code");let o;try{o=await fetch(`${s}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{r.stop("Failed"),console.error(` ${Se.default.red("\u2717")} Could not reach ${s}. Check your connection.`),process.exit(1)}if(!o.ok){r.stop("Failed");let m=`Server error (${o.status})`;try{let f=await o.json();m=f.error||f.message||m}catch{}console.error(` ${Se.default.red("\u2717")} ${m}`),process.exit(1)}let a,d;try{({code:a,auth_url:d}=await o.json())}catch{r.stop("Failed"),console.error(` ${Se.default.red("\u2717")} Invalid response from server.`),process.exit(1)}r.stop(`${y.success} Auth code ready`),c(),console.log(` ${Se.default.dim("Verification code:")} ${Se.default.bold(Se.default.cyan(a))}`),console.log(` ${Se.default.dim("Opening browser")} ${y.arrow} ${v.url(d)}`),Ve(d),c(),r.start("Waiting for browser approval");for(let m=0;m<120;m++){await new Promise(g=>setTimeout(g,5e3));let f=await fetch(`${s}/api/auth/cli/poll?code=${a}`).catch(()=>null);if(!f||!f.ok&&f.status!==202)continue;let p=await f.json().catch(()=>({}));if(p.status==="complete"){fi(n,{token:p.token,email:p.email,api_url:s}),rr=!0,r.stop(`${y.success} Logged in as ${Se.default.bold(p.email)}`),c();return}}r.stop("Timed out"),console.error(` ${Se.default.red("\u2717")} No approval received. Run ${Se.default.cyan("domani login")} to try again.`),process.exit(1)}var Se,rr,or,ar=_e(()=>{"use strict";Se=N(F(),1);oi();De();L();rr=!1,or=!1});function sa(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let n=t.trim().slice(0,120);return e.ok?(Object.defineProperty(e,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${e.status})`,hint:`The server replied but not with JSON${n?` (got: "${n}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${e.status})`,hint:"The server returned an unexpected response. Try again later."}}},e}async function x(e,t={},n=!1){let i=at(),s=`${Ke()}${e}`,r=await fetch(s,{...t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","User-Agent":`domani-cli/${Ae}`,...t.headers}});if(!n){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await Qo(),x(e,t,!0)}catch{}}return sa(r)}async function xe(e,t={}){let n=`${Ke()}${e}`,i=at(),s=await fetch(n,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${Ae}`,...i?{Authorization:`Bearer ${i}`}:{},...t.headers}});return sa(s)}var z=_e(()=>{"use strict";De();ar()});function Ft(){return{ok:!0}}function It(e,t,n){return{ok:!1,error:{message:e,code:t,hint:n}}}function la(e){return Jc.test(e)?It("Input contains control characters","invalid_input","Remove non-printable characters from the input"):Ft()}function Xc(e){return Bc.test(e)?It("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):Ft()}function Zc(e){return Gc.test(e)?It("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):Ft()}function Qc(e){return Kc.test(e)?It("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):Ft()}function ca(e){if(!e)return It("Domain name is required","validation_error");if(e.length>da)return It(`Domain name too long (${e.length} chars, max ${da})`,"validation_error");for(let t of[la,Xc,Zc,Qc]){let n=t(e);if(!n.ok)return n}return zc.test(e)?Ft():It(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function eu(e){if(!e)return It("TLD is required","validation_error");let t=la(e);return t.ok?Yc.test(e)?Ft():It(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function tu(e){for(let t of e){let n=ca(t);if(!n.ok)return n}return Ft()}function nu(e){for(let t of e){let n=eu(t);if(!n.ok)return n}return Ft()}function Y(e,t){let n=ca(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}function ua(e,t){let n=tu(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}function Di(e,t){let n=nu(e);n.ok||u(n.error.message,{code:n.error.code,hint:n.error.hint,json:t?.json,fields:t?.fields})}var Jc,Bc,Gc,Kc,zc,Yc,da,ve=_e(()=>{"use strict";L();Jc=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Bc=/\.\.[/\\]/,Gc=/[?#]/,Kc=/%[0-9a-fA-F]{2}/,zc=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Yc=/^\.?[a-zA-Z]{2,63}$/,da=253});function lr(e,t){return t!==void 0&&Math.round(t*100)!==Math.round(e*100)}function it(e,t){return lr(e,t)?`$${e.toFixed(2)} first year, then $${t.toFixed(2)}/yr`:`$${e.toFixed(2)}/yr`}var Ni=_e(()=>{"use strict"});function Fn(e){return Math.round(e*100)/100}function Lt(e){return e.code==="PRICE_ABOVE_MAX"&&typeof e.price=="number"?e.price:void 0}function cr(e){return`Nothing was charged. Re-run with --max-price ${e.toFixed(2)} to accept the new price.`}function iu(e){return typeof e.renewal_price=="number"&&e.renewal_price>0?e.renewal_price:void 0}async function Ln(e,t,n,i,s){let r=iu(n);Ct(s)&&u(n.error??`The price is now $${e.toFixed(2)}, above $${t.toFixed(2)}. Nothing was charged.`,{code:"price_above_max",hint:cr(e),data:{price:e,...typeof n.listed_price=="number"?{listed_price:n.listed_price}:{},...r!==void 0?{renewal_price:r}:{}},json:s.json,fields:s.fields});let o=r!==void 0?`, then ${v.price(r.toFixed(2))}/year to renew`:"",a=await He({message:`The price changed: ${v.price(e.toFixed(2))} instead of ${v.price(t.toFixed(2))}${o}. Nothing was charged. ${i} for ${v.price(e.toFixed(2))}?`});if(!a||typeof a=="symbol"){console.log(` ${ma.default.dim("Cancelled.")}`);return}return e}function nn(e,t){if(e===void 0)return;let n=Number(e);return(!Number.isFinite(n)||n<=0)&&u(`--max-price must be a positive amount in USD, got "${e}"`,{code:"validation_error",json:t.json,fields:t.fields}),n}var ma,Ui=_e(()=>{"use strict";qe();ma=N(F(),1);L()});async function be(){Te||u("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let e=C(!0);e.start("Loading your domains");let t=await x("/api/domains"),n=await t.json();t.ok||(e.stop("Failed"),sr(n.error,n.hint),process.exit(1));let i=n.domains||[];i.length===0&&(e.stop("No domains"),c(),console.log(` ${ur.default.dim("No domains yet.")} Use: ${ur.default.cyan("domani buy <domain>")}`),c(),process.exit(0)),e.stop(`${i.length} domain(s)`);let s=await lt({message:"Which domain?",options:i.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return de(s)&&process.exit(0),s}var ur,st=_e(()=>{"use strict";z();qe();ur=N(F(),1);L()});var pa={};fn(pa,{connect:()=>mr});async function mr(e,t,n){e||(e=await be()),Y(e,n);let i;if(t&&!n.provider?t.includes(".")?i=t:n.provider=t:i=t,!i&&!n.provider&&!n.list&&n.dryRun)return K("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},n.json,n.fields);if(!i&&!n.provider&&!n.list){let s=C(!n.json);s.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop("Providers loaded"),n.json){b(o,n.fields);return}let a=[];for(let w of["hosting","email"]){let k=o.providers?.[w]||[];for(let S of k)a.push({value:`${w}:${S.name}`,label:S.name,hint:w})}a.length===0&&u("No providers available",{code:"not_found",json:n.json,fields:n.fields});let d=await lt({message:"Choose a provider",options:a});de(d)&&process.exit(0);let[m,f]=d.split(":"),g=(o.providers?.[m]||[]).find(w=>w.name===f),$;if(g&&g.methods.length>1){let w=await lt({message:"Choose a method",options:g.methods.map(k=>({value:k.name,label:k.name,hint:k.default?"default":void 0}))});de(w)&&process.exit(0),$=w}let _;if(m==="hosting"&&g?.requires_target){g.notes?.setup&&ue(g.notes.setup);let w=await Ue({message:"Target hostname or IP"});de(w)&&process.exit(0),_=w.trim()}return fa(e,{target:_,provider:f,method:$,dryRun:n.dryRun,json:!1})}if(n.list){let s=C(!n.json);s.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop("Providers loaded"),n.json){b(o,n.fields);return}j(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let d=o.providers?.[a];if(d?.length){c(),console.log(` ${pe.default.bold(a.toUpperCase())}`);for(let m of d){let f=m.methods.map(p=>p.default?pe.default.green(`${p.name} (default)`):pe.default.dim(p.name)).join(pe.default.dim(", "));console.log(` ${pe.default.cyan(m.name.padEnd(20))} ${f}`)}}}c();return}return fa(e,n)}async function fa(e,t){let n={};if(t.target&&(n.target=t.target),t.provider&&(n.provider=t.provider),t.method&&(n.method=t.method),t.dryRun)return K("connect",{domain:e,...n},t.json,t.fields);let i=C(!t.json);i.start(`Connecting ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(n)}),r=await s.json();s.ok||(i.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(i.stop(o?`${y.success} DNS instructions for ${pe.default.cyan(r.provider)}`:`${y.success} Connected to ${pe.default.cyan(r.provider)}`),t.json){b(r,t.fields);return}if(j(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),l("Provider",pe.default.cyan(r.provider)),l("Method",r.method),r.records?.length){let a=[8,22,40];c(),console.log(` ${pe.default.bold("DNS Records")}`);let d=["Type","Name","Value"].map((f,p)=>pe.default.dim(f.padEnd(a[p]))).join(" "),m=a.map(f=>pe.default.dim("\u2500".repeat(f))).join(" ");console.log(` ${d}`),console.log(` ${m}`);for(let f of r.records){let p=f.record,g=f.status!=="already_set";process.stdout.isTTY&&g&&await Ot(50);let _=[pe.default.yellow(p.type),p.name,pe.default.cyan(p.value)+(p.priority?pe.default.dim(` pri=${p.priority}`):"")].map((S,O)=>Pi(S,a[O])).join(" "),w=f.status==="already_set"?pe.default.dim("\u2713"):f.status==="updated"?pe.default.yellow("\u21BA"):f.status==="pending"?pe.default.yellow("\u2192"):y.success,k=f.status==="already_set"?pe.default.dim(" already set"):f.status==="updated"?pe.default.dim(" updated"):f.status==="pending"?pe.default.dim(" add this"):"";console.log(` ${w} ${_}${k}`)}}c(),r.next_steps?.length?(console.log(` ${pe.default.bold("Next steps")}`),r.next_steps.forEach((a,d)=>{console.log(` ${pe.default.dim(`${d+1}.`)} ${a}`)})):r.hint&&console.log(` ${pe.default.dim(r.hint)}`),r.docs&&console.log(` ${pe.default.dim("Docs:")} ${v.url(r.docs)}`),c()}var pe,fr=_e(()=>{"use strict";z();pe=N(F(),1);qe();L();ve();st()});function sn(e,t=process.env){if(e.clearHeaders&&(e.authorizationEnv||e.apiKeyEnv))throw new Error("--clear-headers cannot be combined with header environment options");if(e.clearHeaders)return{};let n={},i=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[s,r]of i){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);n[s]=o}return Object.keys(n).length>0?n:void 0}function rn(e){return e?Object.keys(e):[]}var qi=_e(()=>{"use strict"});function Vn(e,t,n){return u(e,{hint:t,code:"validation_error",json:n.json,fields:n.fields})}function pr(e){return e.slug&&e.domain?`${e.slug}@${e.domain}`:null}function ga(e,t){return t.messageId||t.messageIds||(e&&!e.includes("@")?e:void 0)}function ya(e,t,n){return`/api/emails/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/${n}`}function ru(e,t,n){return e.match==="domain"?`domani email sender-rule-add --action block --match domain --value ${e.value}`:`domani email sender-rule-add --action block --match campaign --from ${t} --message-id ${n}`}function ou(e){let t=new URLSearchParams;e.action&&t.set("action",e.action),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function au(e){if(!e.action||!ha.includes(e.action))return{error:"--action must be block or allow"};if(!e.match||!su.includes(e.match))return{error:"--match must be address, domain or campaign"};let t=pr(e),n={action:e.action,match:e.match};if(e.messageId){if(!t)return{error:"--message-id needs --from, the mailbox the message is in"};n.mailbox=t,n.message_id=e.messageId}else if(e.value){if(e.match==="campaign")return{error:"A campaign rule is taken from a message: pass --from and --message-id"};n.value=e.value}else return{error:"Pass --value, or --from and --message-id"};return e.confirm&&(n.confirm=!0),{body:n}}function du(e,t){return`/api/sender-rules/${encodeURIComponent(e)}${t?"?restore=false":""}`}function hr(e){return e.match==="campaign"?e.label?`campaign "${e.label.slice(0,48)}"`:`campaign ${e.value.slice(0,8)}`:e.match==="domain"?`everything from ${e.value}`:e.value}async function Mi(e,t,n,i){let s=C(!n.json);s.start(i);let r=await x(e,t),o=await r.json();return r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop("Done"),o}async function ba(e,t){let n="Usage: domani email spam <message_id> --from hi@myapp.dev [--confirm]",i=pr(t),s=ga(e,t);(!i||!s)&&Vn("Mailbox and message ID required",n,t);let r=await Mi(ya(i,s,"spam"),{method:"POST",body:JSON.stringify(t.confirm?{confirm:!0}:{})},t,"Marking as spam");if(t.json)return b(r,t.fields);j("Spam"),l("Message",`${r.message_id} ${Me.default.dim("moved to Spam")}`),r.rule&&l("Blocked",`${Me.default.cyan(r.sender)} ${Me.default.dim("for every mailbox of the account")}`),l("Moved",`${r.moved} other message${r.moved===1?"":"s"} from the sender`),r.confirmation_required&&(console.log(` ${y.warning} ${r.confirmation_required.message}`),I("Block them anyway:",`domani email spam ${s} --from ${i} --confirm`));let o=r.suggestions||[];if(o.length){console.log(),console.log(` ${Me.default.bold("One step further")}`);for(let a of o){let d=a.match==="domain"?`Everything from ${a.value}`:`The same campaign${a.label?` ("${a.label.slice(0,48)}")`:""}`;console.log(` ${d}: ${a.count} message${a.count===1?"":"s"} in ${a.mailboxes} mailbox${a.mailboxes===1?"":"es"}`),I(" Apply:",ru(a,i,s))}}else r.hint&&ue(r.hint)}async function wa(e,t){let n="Usage: domani email not-spam <message_id> --from hi@myapp.dev",i=pr(t),s=ga(e,t);(!i||!s)&&Vn("Mailbox and message ID required",n,t);let r=await Mi(ya(i,s,"not-spam"),{method:"POST",body:"{}"},t,"Marking as not spam");if(t.json)return b(r,t.fields);j("Not spam"),l("Message",`${r.message_id} ${Me.default.dim("back in the Inbox")}`),r.rule&&l("Allowed",`${Me.default.cyan(r.sender)} ${Me.default.dim("for every mailbox of the account")}`),l("Moved",`${r.moved} other message${r.moved===1?"":"s"} back from Spam`);let o=r.matching_rules||[];if(o.length){console.log(),console.log(` ${Me.default.bold("Wider rules that also matched it")}`);for(let a of o)console.log(` Block on ${hr(a)}`),I(" Remove:",`domani email sender-rule-remove ${a.id}`)}else r.hint&&ue(r.hint)}async function va(e){e.action&&!ha.includes(e.action)&&Vn("--action must be block or allow","Usage: domani email sender-rules [--action block|allow] [--limit 50] [--cursor C]",e);let t=await x(`/api/sender-rules${ou(e)}`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);let i=n.rules||[];if(!i.length){console.log(Me.default.dim("No learned rules yet. Mark a message as spam (domani email spam) to block its sender."));return}j("Learned sender rules"),B(["ID","Rule","Moved","By","When"],i.map(s=>[s.id,`${s.action==="block"?Me.default.red("block"):Me.default.green("allow")} ${hr(s)}`,String(s.moved+s.hits),s.created_by.label.slice(0,20),s.created_at.slice(0,10)]),[27,56,7,22,11]),n.next_cursor&&console.log(Me.default.dim(`More: --cursor ${n.next_cursor}`))}async function $a(e){let t="Usage: domani email sender-rule-add --action block|allow --match address|domain --value secure.net [--confirm] (or --match campaign --from hi@myapp.dev --message-id MSG)",n=au(e);if("error"in n)return Vn(n.error,t,e);let i=await Mi("/api/sender-rules",{method:"POST",body:JSON.stringify(n.body)},e,"Saving the rule");if(e.json)return b(i,e.fields);let s=i.rule;console.log(`${y.success} ${s.action==="block"?"Blocked":"Allowed"} ${Me.default.cyan(hr(s))} ${Me.default.dim(`(${s.id})`)}`),console.log(` ${i.moved} message${i.moved===1?"":"s"} already received moved ${s.action==="block"?"to Spam":"back to the Inbox"}.`),i.truncated&&ue("The scan stopped early: some older copies of the campaign may still be in place."),I("Undo:",`domani email sender-rule-remove ${s.id}`)}async function ka(e,t){let n=e&&!e.includes("@")?e:void 0;n||Vn("Rule ID required","Usage: domani email sender-rule-remove <rule_id> [--keep-moved]",t);let i=await Mi(du(n,t.keepMoved),{method:"DELETE"},t,"Removing the rule");if(t.json)return b(i,t.fields);console.log(`${y.success} Rule ${Me.default.cyan(n)} removed.${t.keepMoved?"":` ${i.restored} message${i.restored===1?"":"s"} went back where ${i.restored===1?"it was":"they were"}.`}`)}var Me,ha,su,_a=_e(()=>{"use strict";Me=N(F(),1);z();L();ha=["block","allow"],su=["address","domain","campaign"]});var Ua={};fn(Ua,{buildSendBody:()=>Aa,contactsQuery:()=>Ta,email:()=>Wn,inboxQuery:()=>Pa,parseRecipients:()=>Li,recipientField:()=>Vi,resolveDomainArg:()=>gr,resolveDraftIdArg:()=>Oa,systemLocale:()=>Ia});function uu(e){return[T.default.yellow(e.type),e.name,T.default.cyan(e.value)+(e.priority?T.default.dim(` pri=${e.priority}`):"")]}function br(e){return cu[e]||e}function Li(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Vi(e){if(e.length!==0)return e.length===1?e[0]:e}function mu(e,t){if(e&&e.includes("@")){let[n,i]=e.split("@",2);!t.slug&&n&&(t.slug=n),!t.domain&&i&&(t.domain=i)}}function gr(e,t){if(t.domain)return t.domain;if(e&&!e.includes("@"))return e}async function Xe(e){return e.domain?(Y(e.domain,e),e.domain):be()}async function Wn(e,t,n){if(e&&e.includes(".")&&!lu.includes(e))return n.check?ja(e,!!n.json,n.fields):t?Sa(e,t,!!n.json,n.fields):Da(e,!!n.json,n.fields);if(mu(t,n),n.body&&!n.text&&(n.text=n.body),n.title&&!n.subject&&(n.subject=n.title),n.from&&n.from.includes("@")){let[i,s]=n.from.split("@",2);!n.slug&&i&&(n.slug=i),!n.domain&&s&&(n.domain=s)}switch(e){case void 0:return xa(n);case"list":return xa(n);case"inbox":return Lu(n);case"folders":return Vu(n);case"drafts":return Wu(n);case"draft":return vu(t,n);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return Hu(e,n);case"setup":return n.domain=gr(t,n),Iu(n);case"status":return n.domain=gr(t,n),Au(n);case"remove":return Ru(n);case"create":return Tu(n);case"delete":return Eu(n);case"send":return Pu(n);case"webhook":return Ju(n);case"webhook-test":return Bu(n);case"forward":return Gu(n);case"work":return xu(n);case"triage":return ju(n);case"note":return Su(n);case"notes":return Cu(n);case"activity":return Ou(n);case"changes":return gu(n);case"search":return yu(t,n);case"threads":return bu(n);case"thread":return wu(t,n);case"label":return $u(n);case"facts":return ku(t,n);case"extract":return _u(t,n);case"spam":return ba(t,n);case"not-spam":return wa(t,n);case"sender-rules":return va(n);case"sender-rule-add":return $a(n);case"sender-rule-remove":return ka(t,n);case"coordination":return fu(n);case"presence":return pu(n);case"release-presence":return hu(n);case"escalate":return Du(n);case"remind":return Nu(n);case"contacts":return Uu(n);case"contact-add":return qu(n);case"contact-remove":return Mu(n);case"tone":return Fu(n);case"check":return ja(n.domain||await be(),!!n.json,n.fields);case"connect":return Sa(n.domain||await be(),t||void 0,!!n.json,n.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, spam, not-spam, sender-rules, sender-rule-add, sender-rule-remove, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:n.json,fields:n.fields})}}function wr(e){let t=e.mailboxIds?.split(",").map(n=>n.trim()).filter(Boolean)[0];return(!t||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Pass --mailbox-ids mb_1 --thread-key 'jmap:thread_1'",code:"validation_error",json:e.json,fields:e.fields}),{mailboxId:t,threadKey:e.threadKey}}async function fu(e){let{mailboxId:t,threadKey:n}=wr(e),i=new URLSearchParams({mailbox_id:t,thread_key:n}),s=await x(`/api/email/collaboration/coordination?${i}`),r=await s.json();if(s.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(r,e.fields);j("Conversation Coordination"),l("Conversation",r.conversation_id),l("Reply version",String(r.reply_version)),l("Presence",String(r.presence?.length||0)),l("Compose lease",r.compose_lease?.holder?.label||"none")}async function pu(e){let{mailboxId:t,threadKey:n}=wr(e);e.clientId||u("Client ID required",{hint:"Pass a stable --client-id for this agent process or app installation",code:"validation_error",json:e.json,fields:e.fields});let i=e.mode||"viewing";["viewing","composing"].includes(i)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let s=await x("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:n,client_id:e.clientId,mode:i,acquire_lease:e.acquireLease!==!1})}),r=await s.json();if(s.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(r,e.fields);j("Conversation Presence"),l("Mode",i),l("Reply version",String(r.reply_version)),l("Lease ID",r.compose_lease?.lease_id||"none"),l("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function hu(e){let{mailboxId:t,threadKey:n}=wr(e);e.clientId||u("Client ID required",{hint:"Pass the same --client-id used for presence",code:"validation_error",json:e.json,fields:e.fields});let i=await x("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:n,client_id:e.clientId,lease_id:e.leaseId})}),s=await i.json();if(i.ok||u(s.error||"Could not release presence",{code:s.code||"api_error",json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j("Conversation Presence"),l("Released",e.clientId),l("Remaining presence",String(s.presence?.length||0))}async function gu(e){let t=e.mailboxIds?.split(",").map(r=>r.trim()).filter(Boolean)[0];t||u("Mailbox ID required",{hint:"Usage: domani email changes --mailbox-ids mb_1 [--cursor <opaque>]",code:"validation_error",json:e.json,fields:e.fields});let n=new URLSearchParams({mailbox_id:t});e.cursor&&n.set("cursor",e.cursor),e.limit&&n.set("limit",e.limit);let i=await x(`/api/email/changes?${n}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);if(j("Mailbox Changes"),s.requires_full_sync){l("Full sync","Required"),l("Baseline cursor",s.next_cursor),ue("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}s.changes.length?B(["Sequence","Type","Resource","Created"],s.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${T.default.dim("No changes since this cursor.")}`),l("Next cursor",s.next_cursor),s.has_more&&ue("More changes are available; call again with the next cursor.")}function Fi(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}async function yu(e,t){let n=(t.query||(e&&!e.includes("@")?e:void 0)||"").trim();n||u("Query required",{hint:'Usage: domani email search "the invoice from tucows" [--from hi@myapp.dev] [--mode hybrid|semantic|keyword] [--limit 10] [--label billing]',code:"validation_error",json:t.json,fields:t.fields});let i=new URLSearchParams({q:n});t.mode&&i.set("mode",t.mode),t.limit&&i.set("limit",t.limit),t.slug&&t.domain&&i.set("mailbox",`${t.slug}@${t.domain}`),t.folder&&i.set("folder",t.folder),t.since&&i.set("since",t.since),t.until&&i.set("until",t.until),t.label&&i.set("label",t.label);let s=await x(`/api/emails/search?${i}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);if(j(`Search: ${n}`),!r.results.length){console.log(` ${T.default.dim(r.hint||"No mail matches this search.")}`);return}B(["Why","From","Subject","Mailbox","Message"],r.results.map(o=>[o.why,o.message.from.slice(0,28),(o.message.subject||"").slice(0,44),o.message.mailbox.slice(0,28),o.message.id]),[8,30,46,30,28]),ue(`${r.results.length} result${r.results.length===1?"":"s"} in ${r.took_ms} ms, mode ${r.mode}. Open one with: domani email thread <thread_id> --from <mailbox>`)}async function bu(e){let{address:t}=At(e,"Usage: domani email threads --from hi@myapp.dev [--folder inbox] [--since <iso>] [--limit 25] [--cursor <cursor>] [--label billing]"),n=new URLSearchParams;e.folder&&n.set("folder",e.folder),e.since&&n.set("since",e.since),e.limit&&n.set("limit",e.limit),e.cursor&&n.set("cursor",e.cursor),e.label&&n.set("label",e.label);let i=n.toString(),s=await x(`/api/emails/${encodeURIComponent(t)}/threads${i?`?${i}`:""}`),r=await s.json();if(s.ok||u(r.error||r.message,{code:r.code,hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return b(r,e.fields);if(j(`Threads in ${t}`),!r.threads.length){console.log(` ${T.default.dim("No conversations here.")}`);return}B(["Messages","Unread","Subject","With","Last","Thread"],r.threads.map(o=>[String(o.message_count),String(o.unread_count),(o.subject||"").slice(0,40),o.participants.filter(a=>a!==t).join(", ").slice(0,30),o.last_message_at.slice(0,16),o.id]),[9,7,42,32,17,28]),r.next_cursor&&l("Next cursor",r.next_cursor)}async function wu(e,t){let n=t.threadId||(e&&!e.includes("@")?e:void 0),{address:i}=At(t,"Usage: domani email thread <thread_id> --from hi@myapp.dev");n||u("Thread ID required",{hint:"Usage: domani email thread <thread_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/threads/${encodeURIComponent(n)}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);j(r.subject||"Conversation"),l("Messages",String(r.message_count)),l("Unread",String(r.unread_count)),l("With",r.participants.join(", "));for(let o of r.messages)console.log(`
179
+ ${T.default.bold(o.direction==="out"?"\u2192":"\u2190")} ${o.from} ${T.default.dim(o.created_at.slice(0,16))}${o.labels?.length?` ${T.default.dim(`[${o.labels.join(", ")}]`)}`:""} ${T.default.dim(o.id)}`),o.text&&console.log(` ${o.text.replace(/\s+/g," ").trim().slice(0,300)}`)}function Oa(e){return e&&!e.includes("@")?e:void 0}async function vu(e,t){let n=Oa(e),{address:i}=At(t,"Usage: domani email draft <draft_id> --from hi@myapp.dev");n||u("Draft ID required",{hint:"Usage: domani email draft <draft_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/drafts/${encodeURIComponent(n)}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);j(r.subject||"(no subject)"),l("From",r.from||"-"),l("To",(r.to||[]).map(o=>o.address).join(", ")||"-"),r.cc?.length&&l("Cc",r.cc.map(o=>o.address).join(", ")),l("Updated",r.updated_at.slice(0,16)),r.text&&console.log(`
180
+ ${r.text.replace(/\s+/g," ").trim().slice(0,500)}`)}async function $u(e){let{address:t}=At(e,"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b"),n=Fi(e.messageIds),i=Fi(e.add),s=Fi(e.remove),r=e.set===void 0?void 0:Fi(e.set);(!n.length||!i.length&&!s.length&&r===void 0)&&u("Message IDs and labels required",{hint:"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b",code:"validation_error",json:e.json,fields:e.fields});let o={message_ids:n,action:"label",idempotency_key:e.idempotencyKey||(0,yr.randomUUID)()};i.length&&(o.add=i),s.length&&(o.remove=s),r!==void 0&&(o.set=r);let a=await x(`/api/emails/${encodeURIComponent(t)}/messages/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await a.json();if(a.ok||u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields}),e.json)return b(d,e.fields);let m=d.results||[];j("Labels"),B(["Message","Result"],m.map(f=>[f.message_id,f.ok?f.changed?"updated":"unchanged":f.error?.message||"failed"]),[30,40])}async function ku(e,t){let n=t.messageIds||(e&&!e.includes("@")?e:void 0),{address:i}=At(t,"Usage: domani email facts <message_id> --from hi@myapp.dev");n||u("Message ID required",{hint:"Usage: domani email facts <message_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await x(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(n)}/facts`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return b(r,t.fields);if(j("Facts"),!r.analysed){l("Analysed","no"),l("Reason",r.reason),ue(r.reason==="not_enabled"?"Enable the mailbox in the assistant: domani assistant set --enable --mailboxes <id>":"The analysis has not happened yet; try again in a minute.");return}l("Analysis",`${r.analysis.id} (${r.analysis.generated_at.slice(0,16)}, ${r.analysis.coverage})`),r.facts.length?B(["Subject","Predicate","Value","Basis"],r.facts.map(o=>[(o.subject||"").slice(0,28),(o.predicate||"").slice(0,28),`${o.value?.value??o.object??""}${o.value?.currency?` ${o.value.currency}`:""}`.slice(0,32),o.basis||""]),[30,30,34,18]):console.log(` ${T.default.dim("No claim recorded.")}`);for(let o of r.commitments)l("Promised",`${o.who}: ${o.what}`);for(let o of r.expectations)l("Awaited",`${o.who}: ${o.what}`)}async function _u(e,t){let n=t.messageIds||(e&&!e.includes("@")?e:void 0),i=`Usage: domani email extract <message_id> --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}' [--instructions "amounts in EUR"] (or --schema @fields.json)`,{address:s}=At(t,i);(!n||!t.schema)&&u("Message ID and --schema required",{hint:i,code:"validation_error",json:t.json,fields:t.fields});let r;try{let d=t.schema.startsWith("@")?(0,Ca.readFileSync)(t.schema.slice(1),"utf8"):t.schema;r=JSON.parse(d)}catch(d){u("Schema must be JSON (inline or @file)",{hint:d instanceof Error?d.message:String(d),code:"validation_error",json:t.json,fields:t.fields})}let o=await x(`/api/emails/${encodeURIComponent(s)}/messages/${encodeURIComponent(n)}/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schema:r,...t.instructions?{instructions:t.instructions}:{}})}),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return b(a,t.fields);j("Extraction"),l("Confidence",String(a.confidence)),l("Cached",a.cached?"yes":"no"),l("Model",a.model);for(let[d,m]of Object.entries(a.data))l(d,m===null?T.default.dim("null"):typeof m=="object"?JSON.stringify(m):String(m));for(let d of a.evidence_quotes)console.log(` ${T.default.dim(`"${d.slice(0,120)}"`)}`)}async function xu(e){let t=(e.mailboxIds||"").split(",").map(r=>r.trim()).filter(Boolean);t.length||u("Mailbox IDs required",{hint:"Usage: domani email work --mailbox-ids mb_1,mb_2",code:"validation_error",json:e.json,fields:e.fields});let n=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&n.set("status",e.status),e.assigned&&n.set("assigned",e.assigned),e.limit&&n.set("limit",e.limit);let i=await x(`/api/email/work-queue?${n}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);if(j("Shared Inbox Work"),!s.items.length)return console.log(` ${T.default.dim("No conversations match this queue.")}`);B(["Thread","Status","Assignee","Subject"],s.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),s.partial&&ue("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function ju(e){(!e.mailboxIds||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Usage: domani email triage --mailbox-ids mb_1 --thread-key <key> --status closed",code:"validation_error",json:e.json,fields:e.fields});let t=e.assigneeId&&e.assigneeType?{type:e.assigneeType,id:e.assigneeId}:void 0,n=await x("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(s=>s.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),i=await n.json();if(n.ok||u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return b(i,e.fields);j("Conversation Updated"),l("Status",i.status),l("Assignee",i.assignee?.label||"Unassigned"),l("Version",i.version)}async function Su(e){(!e.conversationId||!e.note)&&u("Conversation ID and note required",{hint:'Usage: domani email note --conversation-id conv_1 --note "Waiting for finance"',code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`,{method:"POST",body:JSON.stringify({body:e.note})}),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);console.log(`${y.success} Private note added`)}async function Cu(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email notes --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);if(j("Private Notes"),!n.notes.length)return console.log(` ${T.default.dim("No private notes yet.")}`);B(["Author","Created","Note"],n.notes.map(i=>[i.author.label,i.created_at,i.body]),[28,24,64])}async function Ou(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email activity --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/activity`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return b(n,e.fields);if(j("Conversation Activity"),!n.activity.length)return console.log(` ${T.default.dim("No activity yet.")}`);B(["Type","Actor","Created"],n.activity.map(i=>[i.type,i.actor.label,i.created_at]),[36,32,24])}async function Iu(e){let t=await Xe(e);if(e.dryRun)return K("email_setup",{domain:t},e.json,e.fields);let n=C(!e.json);n.start(`Setting up email on ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Email ${s.status==="already_configured"?"already configured":"configured"}`),e.json){b(s,e.fields);return}if(s.records?.length){c(),j(`Email DNS Records ${v.domain(t)}`);let r=s.records.map(o=>[T.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?T.default.green(o.status):T.default.yellow(o.status)]);B(["Type","Name","Value","Status"],r,[8,28,44,12])}c(),s.hint&&ue(s.hint),I("Check status:",`domani email status --domain ${t}`),c()}async function Au(e){let t=await Xe(e),n=C(!e.json);n.start(`Checking email status for ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Status loaded`),e.json){b(s,e.fields);return}if(j(`Email ${v.domain(t)}`),l("Enabled",s.enabled?T.default.green("yes"):T.default.dim("no")),s.enabled&&(l("Verified",s.verified?T.default.green("yes"):T.default.yellow("pending")),l("Mailboxes",String(s.mailbox_count))),c(),!s.enabled)I("Set up email:",`domani email setup --domain ${t}`),c();else if(!s.verified&&s.records?.length){console.log(` ${T.default.yellow("!")} Add these DNS records to verify:`);for(let r of s.records)console.log(` ${T.default.yellow(r.type)} ${r.name} ${T.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);c()}}async function Ru(e){let t=await Xe(e);if(e.dryRun)return K("email_remove",{domain:t},e.json,e.fields);let n=C(!e.json);n.start(`Removing email from ${v.domain(t)}`);let i=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Email disabled`),e.json){b(s,e.fields);return}s.mailboxes_deleted>0&&console.log(` ${T.default.dim(`${s.mailboxes_deleted} mailbox(es) deleted.`)}`),c()}async function xa(e){let t=C(!e.json);t.start("Loading mailboxes");let n=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",i=await x(`/api/emails${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.mailboxes||[];if(t.stop(`${y.success} ${r.length} mailbox(es)`),e.json){b(s,e.fields);return}if(r.length===0){c(),console.log(` ${T.default.dim("No mailboxes.")}`),c(),I("Create one:","domani email create hello@example.com"),c();return}c(),j("Mailboxes");let o=r.map(a=>[T.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):T.default.dim("-"),T.default.dim(new Date(a.created_at).toLocaleDateString())]);B(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),c()}async function Tu(e){let t=await Xe(e);if(e.dryRun)return K("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let n=e.slug;if(!n&&!e.json){let m=await Ue({message:`Email handle for @${t}:`,placeholder:"hello"});de(m)&&process.exit(0),n=m}n||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let i=`${n}@${t}`,s=C(!e.json);s.start("Creating mailbox");let r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:i,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){s.stop("");let m=o.txt_record,f=o.email_records||[],p=[{type:"TXT",name:m?.name||"@",value:m?.value||"",note:"ownership proof"},...f];c(),console.log(" Add these records at your DNS provider:"),c();for(let S of p){let O=S.priority!==void 0?` ${T.default.dim(`priority: ${S.priority}`)}`:"",R=S.note?` ${T.default.dim(`(${S.note})`)}`:"";console.log(` ${T.default.yellow(S.type)} ${T.default.bold(S.name)}${O}${R}`),console.log(` ${T.default.dim("\u2192")} ${T.default.cyan(S.value)}`),c()}ue("DNS propagation typically takes 5-30 minutes. Checking automatically..."),c();let g=p.map(S=>({cells:[T.default.yellow(S.type),S.name,S.note?T.default.dim(`(${S.note})`):""],status:"pending"})),$=tn(["Type","Name",""],g,[6,24,16]);$.start();let _=0;for(;r.status===202&&_<60;)await Ot(15e3),_++,r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:i,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&($.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&($.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${i}`,code:"timeout",json:e.json,fields:e.fields})),$.markDone(0);let w=S=>`${S.type}:${S.name}`,k=new Map;p.slice(1).forEach((S,O)=>k.set(w(S),O+1));for(let S=0;S<60;S++){await Ot(15e3);let O=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),R=await O.json();if(O.ok&&R.records){for(let M of R.records)if(M.status==="verified"||M.status==="created"){let H=k.get(w(M));H!==void 0&&$.markDone(H)}}if(O.ok&&R.verified)break}$.stop(),c()}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),s.stop(`${y.success} ${T.default.cyan(o.address)} created`),e.json){b(o,e.fields);return}let a=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),d=await a.json();c(),a.ok&&d.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${On}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${On}/inbox?address=${encodeURIComponent(o.address)}`)),c()}async function Eu(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let n=C(!e.json);n.start(`Deleting ${e.slug}@${t}`);let i=encodeURIComponent(`${e.slug}@${t}`),s=await x(`/api/emails/${i}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Mailbox deleted`),e.json){b(r,e.fields);return}console.log(` ${T.default.dim(`${r.address} and all messages deleted.`)}`),c()}function Ia(){let e=Intl.DateTimeFormat().resolvedOptions();return{locale:e.locale,timeZone:e.timeZone}}function Aa(e){let t={to:Vi(Li(e.to))},n=Vi(Li(e.cc)),i=Vi(Li(e.bcc));if(n&&(t.cc=n),i&&(t.bcc=i),e.subject&&(t.subject=e.subject),e.text&&(t.text=e.text),e.inReplyTo)if(t.in_reply_to=e.inReplyTo,e.quote!==!1){let{locale:s,timeZone:r}=Ia();t.quote_original={locale:s,time_zone:r}}else t.quote_original=!1;return e.references&&(t.references=e.references),e.sendAt&&(t.send_at=e.sendAt),t}async function Pu(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:e.json,fields:e.fields}),e.to||u("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let n=C(!e.json);n.start(`Sending from ${e.slug}@${t}`);let i=Aa(e),s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}/send`,{method:"POST",body:JSON.stringify(i)}),o=await r.json();if(!r.ok){n.stop("Failed");let d=o.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${T.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:o.hint;u(o.error||o.message,{hint:d,status:r.status,json:e.json,fields:e.fields})}let a=Array.isArray(o.to)?o.to.join(", "):o.to;if(n.stop(o.status==="scheduled"?`${y.success} Scheduled for ${T.default.cyan(e.sendAt||"")} to ${T.default.cyan(a)} ${T.default.dim("(trash the message before then to cancel)")}`:`${y.success} Sent to ${T.default.cyan(a)}`),e.json){b(o,e.fields);return}}function At(e,t){return(!e.slug||!e.domain)&&u("Mailbox address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),{domain:e.domain,slug:e.slug,address:`${e.slug}@${e.domain}`}}async function Ra(e,t,n,i,s){let r=C(!n.json);r.start(i);let o=await x(e,{method:"POST",body:JSON.stringify(t)}),a=await o.json();o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:n.json,fields:n.fields})),r.stop(s(a)),n.json&&b(a,n.fields)}async function Du(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:n}=At(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let i={};e.reason&&(i.reason=e.reason),e.clear&&(i.clear=!0),await Ra(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(e.messageId)}/escalate`,i,e,e.clear?"Clearing escalation":"Flagging for a human",s=>s.needs_human?`${y.success} Flagged for a human ${T.default.dim("(conversation held, email.escalated fired)")}`:`${y.success} Escalation cleared`)}async function Nu(e){let t='Usage: domani email remind hello@example.com --message-id MSG_ID --at 2026-09-03T09:00:00Z [--note "chase the invoice"] [--clear]',{address:n}=At(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),!e.at&&!e.clear&&u("Reminder time required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let i={};e.at&&(i.remind_at=e.at),e.note&&(i.note=e.note),e.clear&&(i.clear=!0),await Ra(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(e.messageId)}/remind`,i,e,e.clear?"Clearing reminder":"Setting follow-up reminder",s=>s.remind_at?`${y.success} Reminder set for ${T.default.cyan(String(s.remind_at))} ${T.default.dim("(fires only if still unanswered)")}`:`${y.success} Reminder cleared`)}function Ta(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.order&&t.set("order",e.order),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Uu(e){let t=await x(`/api/contacts${Ta(e)}`),n=await t.json();if(t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields}),e.json){b(n,e.fields);return}let i=n.contacts||[];if(i.length===0){console.log(T.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let s of i){let r=s.name?` ${T.default.dim(s.name)}`:"",o=s.notes?` ${T.default.dim("-")} ${s.notes}`:"";console.log(`${T.default.cyan(s.address)}${r} ${T.default.dim(`(${s.message_count} msg${s.message_count!==1?"s":""}, last ${s.last_direction||"-"})`)}${o}`)}n.next_cursor&&console.log(T.default.dim(`More: --cursor ${n.next_cursor}`))}function Ea(e,t){return e.slug&&e.domain?`${e.slug}@${e.domain}`:(u("Contact address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),"")}async function qu(e){let n=Ea(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),i={address:n};e.name!==void 0&&(i.name=e.name),e.notes!==void 0&&(i.notes=e.notes);let s=await x("/api/contacts",{method:"POST",body:JSON.stringify(i)}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){b(r,e.fields);return}console.log(`${y.success} Contact ${T.default.cyan(n)} saved.`)}async function Mu(e){let n=Ea(e,"Usage: domani email contact-remove ada@example.com"),i=await x(`/api/contacts/${encodeURIComponent(n)}`,{method:"DELETE"}),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json){b(s,e.fields);return}console.log(s.deleted?`${y.success} Contact ${T.default.cyan(n)} deleted.`:T.default.dim(`No contact ${n}.`))}async function Fu(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:n}=At(e,t),i=encodeURIComponent(n);if(e.set===void 0&&!e.clear){let o=await x(`/api/emails/${i}`),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}),e.json){b({address:n,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:T.default.dim(`No tone notes on ${n}. Set them with --set.`));return}let s=await x(`/api/emails/${i}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){b(r,e.fields);return}console.log(e.clear?`${y.success} Tone notes cleared on ${T.default.cyan(n)}.`:`${y.success} Tone notes set on ${T.default.cyan(n)}.`)}function Pa(e){let t=new URLSearchParams;e.direction&&t.set("direction",e.direction),e.folder&&t.set("folder",e.folder),e.view&&t.set("view",e.view),e.limit&&t.set("limit",e.limit),e.since&&t.set("since",e.since),e.until&&t.set("until",e.until),e.label&&t.set("label",e.label),e.kind&&t.set("kind",e.kind),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Lu(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--kind person,update] [--limit 20] [--cursor <next_cursor>]",code:"validation_error",json:e.json,fields:e.fields});let n=Pa(e),i=C(!e.json);i.start(`Loading messages for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}/messages${n}`),o=await r.json();r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));let a=o.messages||[];if(e.json){i.stop(`${y.success} ${a.length} message(s)`),b(o,e.fields);return}if(a.length===0){i.stop(`${T.default.dim("No messages")}`);return}let d=a.length>1?"s":"";i.stop(`${y.success} ${T.default.cyan(`${e.slug}@${t}`)} ${T.default.dim("\xB7 "+a.length+" message"+d)}`);for(let m of a){let f=m.direction==="in"?`${T.default.green("in ")}${m.kind?` ${T.default.dim(m.kind.padEnd(10))}`:""}`:T.default.dim("out"),p=m.direction==="in"?m.from:m.to,g=m.subject||"(no subject)",$=T.default.dim(new Date(m.created_at).toLocaleString()),_=g;if(m.text){let w=m.text.replace(/\s+/g," ").trim(),k=w.length>60?w.slice(0,60)+"\u2026":w;_=`${g} ${T.default.dim("- "+k)}`}console.log(` ${f} ${p.padEnd(30)} ${_} ${$}`)}o.next_cursor&&console.log(T.default.dim(`More: --cursor ${o.next_cursor}`))}async function Vu(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=encodeURIComponent(`${e.slug}@${t}`),i=await x(`/api/emails/${n}/folders`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j(`Folders for ${e.slug}@${t}`);for(let r of s.folders||[])l(r.id,`${r.total} total, ${r.unread} unread`);for(let r of s.views||[])l(r.id,`${r.total} total, ${r.unread} unread`)}async function Wu(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email drafts hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=encodeURIComponent(`${e.slug}@${t}`),i=await x(`/api/emails/${n}/drafts`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return b(s,e.fields);j(`Drafts from ${e.slug}@${t}`);let r=s.drafts||[];if(!r.length){console.log(` ${T.default.dim("No drafts.")}`);return}for(let o of r){let a=o.to.map(p=>p.address).join(", "),d=o.subject||"(no subject)",m=(o.text||"").replace(/\s+/g," ").trim(),f=m.length>60?m.slice(0,60)+"\u2026":m;console.log(` ${T.default.dim(o.updated_at.slice(0,16))} ${a.padEnd(30)} ${d}${f?T.default.dim(" - "+f):""} ${T.default.dim(o.id)}`)}}async function Hu(e,t){let n=await Xe(t);t.slug||u("Slug required",{hint:`Usage: domani email ${e} hello@example.com --message-ids id1,id2`,code:"validation_error",json:t.json,fields:t.fields});let i=(t.messageIds||"").split(",").map(f=>f.trim()).filter(Boolean);i.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let s={message_ids:i,idempotency_key:t.idempotencyKey||(0,yr.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(s,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(s.action="restore"),(e==="read"||e==="unread")&&Object.assign(s,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(s,{action:"star",starred:e==="star"}),t.dryRun)return K("email_messages_action",{address:`${t.slug}@${n}`,...s},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${n}`),o=await x(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(s)}),a=await o.json();if(!o.ok&&o.status!==207&&u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return b(a,t.fields);let d=(a.results||[]).filter(f=>f.ok).length,m=(a.results||[]).length-d;console.log(`${y.success} ${d} updated${m?T.default.yellow(`, ${m} failed`):""}`),a.operation_id&&(l("Operation",a.operation_id),l("Idempotency key",a.idempotency_key),a.idempotent_replay&&l("Receipt","replayed (no duplicate mutation)"))}async function Ju(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:e.json,fields:e.fields});let n=`${e.slug}@${t}`,i=encodeURIComponent(n),s;try{s=sn(e)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}let r;if(e.events!==void 0&&(r=e.events.split(",").map(a=>a.trim()).filter(Boolean),r.length===0&&u("--events needs at least one event",{hint:"Example: --events email.received,email.bounced,email.delivered",code:"validation_error",json:e.json,fields:e.fields}),e.url||u("--url is required when changing webhook events",{hint:"Pass the existing webhook URL together with --events.",code:"validation_error",json:e.json,fields:e.fields})),!e.url&&s!==void 0&&u("--url is required when changing webhook auth headers",{hint:"Pass the existing webhook URL with --authorization-env, --api-key-env, or --clear-headers.",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_webhook",{address:n,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...s!==void 0?{header_names:rn(s)}:{}},e.json,e.fields);let o=C(!e.json);if(e.url){o.start(`Setting webhook for ${n}`);let a=await x(`/api/emails/${i}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...s!==void 0?{headers:s}:{},...r!==void 0?{events:r}:{}})}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${y.success} Webhook set`),e.json){b(d,e.fields);return}j(`Mailbox ${d.address}`),l("Webhook",v.url(d.webhook_url)),l("Events",d.events?.join(", ")||T.default.dim("email.received")),l("Auth headers",d.header_names?.join(", ")||T.default.dim("none")),l("Signing secret",T.default.dim(d.signing_secret)),c()}else{o.start(`Removing webhook for ${n}`);let a=await x(`/api/emails/${i}/webhook`,{method:"DELETE"}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${y.success} Webhook removed`),e.json){b(d,e.fields);return}j(`Mailbox ${d.address}`),l("Webhook",T.default.dim("none")),c()}}async function Bu(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let n=`${e.slug}@${t}`;if(e.dryRun)return K("email_webhook_test",{address:n},e.json,e.fields);let i=C(!e.json);i.start(`Testing webhook for ${n}`);let s=await x(`/api/emails/${encodeURIComponent(n)}/webhook/test`,{method:"POST"}),r=await s.json();if((!s.ok||!r.success)&&(i.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Test delivered`),e.json)return b(r,e.fields);j(`Mailbox ${n}`),l("Delivery",T.default.green("successful")),typeof r.status=="number"&&l("Endpoint",`HTTP ${r.status}`),c()}async function Gu(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let n=C(!e.json),i=e.forwardTo||null;n.start(`Updating forward for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({forward_to:i})}),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Forward ${i?"set":"removed"}`),e.json){b(o,e.fields);return}j(`Mailbox ${o.address}`),l("Forward to",o.forward_to?T.default.cyan(o.forward_to):T.default.dim("none")),c()}async function ja(e,t,n){let i=C(!t);i.start(`Checking email health for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop("Email health checked"),t){b(r,n);return}if(j(`Email Health ${v.domain(r.domain)}`),r.provider?l("Provider",T.default.cyan(br(r.provider))):l("Provider",T.default.dim("unknown")),r.mx.configured?l("MX",`${y.success} ${T.default.green("propagated")} ${T.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):l("MX",`${y.error} ${T.default.red("not configured")}`),r.spf.configured?l("SPF",`${y.success} ${T.default.green(r.spf.value)}`):l("SPF",`${y.error} ${T.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;l("DMARC",`${y.success} ${T.default.green(o)}`)}else l("DMARC",`${y.error} ${T.default.red("missing")}`);r.dkim.configured?l("DKIM",`${y.success} ${T.default.green("found")} ${T.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):l("DKIM",`${y.warning} ${T.default.yellow("not found")}`),c(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(ue("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),c()):(I("Set up email:",`domani email ${e} google`),c())}async function Sa(e,t,n,i){return t?Na(e,t,n,i):Da(e,n,i)}async function Da(e,t,n){let i=C(!t);i.start("Loading email providers");let s=await x(`/api/domains/${encodeURIComponent(e)}/connect`),r=await s.json();s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:n});let a=await lt({message:"Choose an email provider",options:o.map(d=>({value:d.name,label:br(d.name)}))});return de(a)&&process.exit(0),Na(e,a,t,n)}async function Na(e,t,n,i){if(n){let m=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),f=await m.json();m.ok||u(f.error||f.message,{hint:f.hint,status:m.status,json:n,fields:i}),b(f,i);return}let s=await x(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!s.ok){let m=await s.json();u(m.error||m.message,{hint:m.hint,status:s.status,json:n,fields:i})}let r=await s.json(),o=r.preview?.records??[],a=r.preview?.provider??t,d=br(a);if(j(`Email ${v.domain(e)}`),l("Provider",T.default.cyan(d)),o.length){c(),console.log(` ${T.default.bold("DNS Records")}`);let m=[8,24,40],f=tn(["Type","Name","Value"],o.map(S=>({cells:uu(S),status:"pending"})),m);f.start();let p=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await p.json();p.ok||(f.stop(),c(),u(g.error||g.message,{hint:g.hint,status:p.status,json:n,fields:i}));let $=g.records||[];for(let S=0;S<o.length;S++)$.find(R=>R.record.type===o[S].type&&R.record.name===o[S].name&&R.record.value===o[S].value)?.status==="already_set"||await Ot(60),f.markDone(S);await Ot(80),f.stop();let _=$.filter(S=>S.status==="created"||S.status==="updated").length,w=$.filter(S=>S.status==="already_set").length,k;w===$.length?k=`All ${w} records already set`:w>0?k=`${_} created, ${w} already set`:k=`${_} DNS records set`,c(),console.log(` ${y.success} ${T.default.green(`Email configured - ${k}`)}`)}else{let m=C(!0);m.start("Setting DNS records");let f=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),p=await f.json();f.ok||(m.stop("Failed"),u(p.error||p.message,{hint:p.hint,status:f.status,json:n,fields:i})),m.stop(`${y.success} Email configured via ${T.default.cyan(d)}`)}c(),I("Verify propagation:",`domani email ${e} --check`),c()}var T,yr,Ca,lu,cu,vr=_e(()=>{"use strict";z();In();T=N(F(),1);qe();L();ve();st();yr=require("node:crypto"),Ca=require("node:fs");qi();_a();lu=["setup","status","remove","list","create","delete","send","inbox","folders","drafts","draft","archive","trash","restore","read","unread","star","unstar","webhook","forward","check","connect","work","triage","notes","note","activity","changes","coordination","presence","release-presence","escalate","remind","contacts","contact-add","contact-remove","tone","search","threads","thread","label","facts","extract","spam","not-spam","sender-rules","sender-rule-add","sender-rule-remove"],cu={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var Ma={};fn(Ma,{dns:()=>kr,nextDnsRecords:()=>qa});function qa(e,t,n){let i=r=>r.type===t.type&&r.name===t.name;return n==="add"&&e.some(r=>i(r)&&r.value===t.value)?{kind:"unchanged"}:n==="add"&&t.type==="CNAME"&&e.some(i)?{kind:"cname_taken"}:{kind:"write",records:[...n==="add"?e:e.filter(r=>!i(r)),{...t,ttl:3600}]}}async function kr(e,t,n,i,s,r){e||(e=await be()),Y(e,r);let o=r?.json??!1,a=r?.type||n,d=r?.name||i,m=r?.value||s;if(!t||t==="get"){let f=C(!o);f.start(`Loading DNS for ${v.domain(e)}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns`),g=await p.json();if(p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields})),f.stop(`${g.records.length} record(s)`),o){b(g,r?.fields);return}if(g.records.length===0){c(),console.log(` ${Ce.default.dim(`No DNS records for ${e}`)}`),c(),I("Auto-configure DNS:",`domani connect ${e}`),c();return}let $=[8,24,40,8];j(`DNS ${v.domain(e)}`,$.reduce((w,k)=>w+k,0)+$.length-1);let _=g.records.map(w=>{let k=w.priority?Ce.default.dim(` pri=${w.priority}`):"";return[Ce.default.yellow(w.type),w.name,Ce.default.cyan(w.value)+k,Ce.default.dim(String(w.ttl))]});B(["Type","Name","Value","TTL"],_,$),c();return}if(t==="set"||t==="add"){let f=t==="add";if((!a||!d||!m)&&u(`Missing arguments for dns ${t}`,{hint:`Usage: domani dns <domain> ${t} --type A --name www --value 1.2.3.4`,code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return K(f?"dns_add":"dns_set",{domain:e,record:{type:a.toUpperCase(),name:d,value:m,ttl:3600}},o,r?.fields);let p=C(!o);p.start(`${f?"Adding":"Setting"} ${Ce.default.yellow(a.toUpperCase())} record`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),$=await g.json();g.ok||(p.stop("Failed"),u($.error||$.message||"Could not read the current DNS records; nothing was changed.",{hint:$.hint,status:g.status,json:o,fields:r?.fields}));let _=$.records??[],w=a.toUpperCase(),k=qa(_,{type:w,name:d,value:m},f?"add":"set");if(k.kind==="unchanged"){p.stop(`${y.success} ${Ce.default.yellow(w)} ${d} ${y.arrow} ${Ce.default.cyan(m)} already exists`),o&&b({records:_,unchanged:!0},r?.fields);return}k.kind==="cname_taken"&&(p.stop("Failed"),u(`${d} already has a CNAME record; a name can hold only one.`,{hint:`Replace it with: domani dns ${e} set --type CNAME --name ${d} --value ${m}`,code:"validation_error",json:o,fields:r?.fields}));let S=k.records,O=await x(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:S})}),R=await O.json();O.ok||(p.stop("Failed"),u(R.error||R.message,{hint:R.hint,status:O.status,json:o,fields:r?.fields})),p.stop(`${y.success} ${Ce.default.yellow(a.toUpperCase())} ${d} ${y.arrow} ${Ce.default.cyan(m)}`),o?b(R,r?.fields):(c(),I("Check propagation:",`domani status ${e}`),c());return}if(t==="delete"){if((!a||!d)&&u("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 K("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:d}},o,r?.fields);let f=C(!o);f.start(`Deleting ${Ce.default.yellow(a.toUpperCase())} ${d}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(d)}`,{method:"DELETE"}),g=await p.json();p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields})),f.stop(`${y.success} Deleted ${Ce.default.yellow(a.toUpperCase())} ${d}`),o?b(g,r?.fields):(c(),I("Check propagation:",`domani status ${e}`),c());return}if(t==="snapshot"){if(r?.dryRun)return K("dns_snapshot",{domain:e},o,r?.fields);let f=C(!o);f.start(`Capturing DNS snapshot for ${v.domain(e)}`);let p=await x(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),g=await p.json();p.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:p.status,json:o,fields:r?.fields}));let $=g.records?.length??0;if(f.stop(`${y.success} Captured ${$} record(s)`),o){b(g,r?.fields);return}let _=`${e}.dns.json`,w=(0,$r.resolve)(process.cwd(),_);(0,Wi.writeFileSync)(w,JSON.stringify(g,null,2)+`
181
+ `),j("DNS Snapshot"),l("Domain",v.domain(g.domain)),l("Records",String($)),l("Subdomains",String(g.subdomains?.length??0)),l("Sources",(g.sources||[]).join(", ")||"none"),l("Captured",g.capturedAt||g.captured_at||"now"),l("Saved to",Ce.default.cyan(_)),c(),I("Restore from this snapshot:",`domani dns ${e} restore --file ${_}`),c();return}if(t==="restore"){if(r?.dryRun)return K("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let f=C(!o),p;if(r?.file){let _=(0,$r.resolve)(process.cwd(),r.file);_.startsWith(process.cwd())||u("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let w=(0,Wi.readFileSync)(_,"utf-8"),k=JSON.parse(w);p=JSON.stringify({snapshot:k}),f.start(`Restoring DNS for ${v.domain(e)} from ${Ce.default.cyan(r.file)}`)}catch(w){u(`Failed to read snapshot file: ${w instanceof Error?w.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else f.start(`Restoring DNS for ${v.domain(e)} from server backup`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...p?{body:p}:{}}),$=await g.json();if(g.ok||(f.stop("Failed"),u($.error||$.message,{hint:$.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${y.success} Restored DNS`),o){b($,r?.fields);return}if(j("DNS Restored"),l("Domain",v.domain($.domain)),l("Applied",Ce.default.green(String($.applied??0))),l("Skipped",Ce.default.dim(String($.skipped??0))),$.errors?.length>0){l("Errors",Ce.default.red(String($.errors.length)));for(let _ of $.errors)console.log(` ${Ce.default.red("\u2022")} ${_}`)}c(),I("Verify DNS records:",`domani dns ${e}`),c();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'add', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ce,Wi,$r,_r=_e(()=>{"use strict";z();Ce=N(F(),1);L();ve();st();Wi=require("node:fs"),$r=require("node:path")});var Fa={};fn(Fa,{status:()=>xr});function Ku(e){return[ct.default.yellow(e.type),e.name,ct.default.cyan(e.value)+(e.priority?ct.default.dim(` pri=${e.priority}`):"")]}function zu(e){if(j(`Status ${v.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),n=e.days_until_expiry,i=n!=null&&n<30?ct.default.red:n!=null&&n<90?ct.default.yellow:ct.default.green;l("Expires",`${t} ${ct.default.dim("(")}${i(`${n} days`)}${ct.default.dim(")")}`)}}async function xr(e,t){if(e||(e=await be()),Y(e,t),t.json){let p=await x(`/api/domains/${encodeURIComponent(e)}/status`),g=await p.json();p.ok||u(g.error||g.message,{hint:g.hint,status:p.status,json:t.json,fields:t.fields}),b(g,t.fields);return}let n=C(!0);n.start(`Checking ${v.domain(e)}`);let i;try{i=await x(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{n.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!i.ok){n.stop("Failed");try{let p=await i.json();u(p.error||p.message,{hint:p.hint,status:i.status,json:t.json,fields:t.fields})}catch{u(`Server error (${i.status})`,{status:i.status,json:t.json,fields:t.fields})}}let s=i.body;s||(n.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,d=[],m=!1,f="";try{for await(let p of s){o+=r.decode(p,{stream:!0});let g=o.split(`
182
+ `);o=g.pop()??"";for(let $ of g)if($.startsWith("event: "))f=$.slice(7);else if($.startsWith("data: ")){let _=JSON.parse($.slice(6));if(f==="info"&&(n.stop("Status retrieved"),m=!0,zu(_)),f==="records")if(d=_,d.length>0){c(),console.log(` ${ct.default.bold("DNS Records")}`);let w=[8,10,34];a=tn(["Type","Name","Value"],d.map(k=>({cells:Ku(k),status:"pending"})),w),a.start()}else c(),l("DNS",ct.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${e}`);if(f==="propagation"&&a){let{index:w,propagated:k}=_,S=k?y.success:`${y.warning}`;a.markDone(w,S)}f==="done"&&a&&a.stop(),f==="error"&&(m||n.stop("Failed"),a&&a.stop(),u(_.message||"Status check failed"))}}}catch{m||n.stop("Failed"),a&&a.stop(),u("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:t.json,fields:t.fields})}m||n.stop("Done"),c()}var ct,jr=_e(()=>{"use strict";z();ct=N(F(),1);L();ve();st()});var Hn={};fn(Hn,{buy:()=>Cr});async function Sr(e){let t=await lt({message:`What's next for ${Oe.default.cyan(e)}?`,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(de(t)||t==="done"){c();return}if(c(),t==="connect"){let{connect:n}=await Promise.resolve().then(()=>(fr(),pa));await n(e,void 0,{})}else if(t==="email"){let n=await Ue({message:`Mailbox name for ${Oe.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(de(n)||!n){c();return}c();let{email:i}=await Promise.resolve().then(()=>(vr(),Ua));await i("create",void 0,{domain:e,slug:n})}else if(t==="dns"){let{dns:n}=await Promise.resolve().then(()=>(_r(),Ma));await n(e)}else if(t==="status"){let{status:n}=await Promise.resolve().then(()=>(jr(),Fa));await n(e,{})}}async function La(e,t,n){let i=C(!n.json);i.start("Purchasing");let s=await x("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e,...t!==void 0?{max_price:t}:{}})});if(!s.ok||!s.body){let f=await s.json().catch(()=>({})),p=Lt(f);if(p!==void 0)return i.stop("Price changed - nothing was charged"),{refused:{price:p,error:f.error,renewal_price:f.renewal_price,listed_price:f.listed_price}};i.stop("Purchase failed"),u(f.error||f.message,{hint:f.hint,fixUrl:f.setup_url||f.payment_options?.card?.setup_url,status:s.status,json:n.json,fields:n.fields})}let r={},o=new TextDecoder,a="",d="";for await(let f of s.body){a+=o.decode(f,{stream:!0});let p=a.split(`
183
+ `);a=p.pop()??"";for(let g of p)if(g.startsWith("event: "))d=g.slice(7).trim();else if(g.startsWith("data: ")){let $=JSON.parse(g.slice(6));if(d==="checking")i.message(`Checking ${v.domain($.domain)}`);else if(d==="payment")i.message(`Charging ${v.price($.total)}`);else if(d==="registering")i.message(`Registering ${v.domain($.domain)}`);else if(d==="registered")r=$;else if(d==="error"){let _=Lt($);if(_!==void 0)return i.stop("Price changed - nothing was charged"),{refused:{price:_,error:$.error,renewal_price:$.renewal_price,listed_price:$.listed_price}};i.stop("Purchase failed"),u($.error,{hint:$.hint,fixUrl:$.setup_url,status:s.status,json:n.json,fields:n.fields})}}}let m=r.expires?Oe.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";return i.stop(`${y.success} ${v.domain(r.domain)} is yours!${m}`),{registered:r}}async function Yu(e,t){Y(e,t);let n=nn(t.maxPrice,t),i;if(t.preChecked)i={available:!0,...t.preChecked};else{let a=C(!t.json);a.start(`Checking ${v.domain(e)}`);let d=await x(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await d.json(),d.ok||(a.stop("Search failed"),u(i.error,{hint:i.hint,status:d.status,json:t.json,fields:t.fields})),i.available||(a.stop(`${y.error} ${v.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),a.stop(`${y.success} ${v.domain(e)} ${y.dot} available ${y.dot} ${Oe.default.green(it(i.price,i.renewal_price))}`)}let s=n??(typeof i.price=="number"?Fn(i.price):void 0);if(t.dryRun)return K("buy",{domain:e,available:!0,price:i.price,...i.renewal_price!==void 0?{renewal_price:i.renewal_price}:{},currency:i.currency||"USD",max_price:s,acting_as:jt()},t.json,t.fields);if(!Ct(t)){let a=await He({message:`Purchase ${Oe.default.bold(e)} for ${Oe.default.green(it(i.price,i.renewal_price))}${qt()}?`});if(!a||typeof a=="symbol"){console.log(` ${Oe.default.dim("Cancelled.")}`);return}}let r=await La(e,s,t);for(;"refused"in r;){let a=await Ln(r.refused.price,s??i.price,r.refused,"Buy",t);if(a===void 0)return;s=a,r=await La(e,s,t)}let o=r.registered;if(t.json){b(o,t.fields);return}Te?await Sr(o.domain):(I("Connect to a service:",`domani connect ${o.domain}`),I("Set up email:",`domani email setup ${o.domain}`),I("Configure DNS:",`domani dns ${o.domain}`),c())}async function Xu(e,t){ua(e,t);let n=nn(t.maxPrice,t),i=!!t.json,s=C(!i);s.start(`Checking ${e.length} domains`);let r=await Promise.all(e.map(async k=>{try{let S=await x(`/api/domains/search?q=${encodeURIComponent(k)}`),O=await S.json();return{domain:k,available:S.ok&&O.available,price:O.price,renewal_price:O.renewal_price}}catch{return{domain:k,available:!1,price:void 0,renewal_price:void 0}}})),o=r.filter(k=>k.available),a=r.filter(k=>!k.available);o.length===0&&(s.stop(`${y.error} None of the ${e.length} domains are available`),process.exit(1));let d=o.reduce((k,S)=>k+(S.price||0),0),m=o.reduce((k,S)=>k+(S.renewal_price??S.price??0),0),f=lr(d,m)?`, then ${v.price(m.toFixed(2))}/yr`:"";if(s.stop(`${y.success} ${o.length}/${e.length} available ${y.dot} ${v.price(d.toFixed(2))} total`),a.length>0)for(let k of a)console.log(` ${y.error} ${v.domain(k.domain)} ${Oe.default.dim("not available")}`);let p=n??(o.every(k=>typeof k.price=="number")?Fn(d):void 0);if(t.dryRun)return K("buy_bulk",{domains:o.map(k=>({domain:k.domain,price:k.price,...k.renewal_price!==void 0?{renewal_price:k.renewal_price}:{}})),unavailable:a.map(k=>k.domain),total_price:parseFloat(d.toFixed(2)),max_price:p,acting_as:jt()},t.json,t.fields);if(!Ct(t)){let k=await He({message:`Purchase ${Oe.default.bold(String(o.length))} domain${o.length>1?"s":""} for ${v.price(d.toFixed(2))}${f}${qt()}?`});if(!k||typeof k=="symbol"){console.log(` ${Oe.default.dim("Cancelled.")}`);return}}c();let g,$;for(;;){let k=tn(["Domain","Price"],o.map(R=>({cells:[v.domain(R.domain),R.price?Oe.default.green(it(R.price,R.renewal_price)):""],status:"pending"})),[30,12],!i);k.start(),g=await x("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:o.map(R=>R.domain),...p!==void 0?{max_price:p}:{}})}),$=await g.json();let S=g.ok?void 0:Lt($);if(S===void 0){let R=new Set(($.results||[]).map(M=>M.domain));for(let M=0;M<o.length;M++){let H=o[M].domain.toLowerCase().trim();k.markDone(M,R.has(H)?y.success:y.error)}k.stop();break}for(let R=0;R<o.length;R++)k.markDone(R,Oe.default.dim("\xB7"));k.stop(),c();let O=await Ln(S,p??d,$,"Buy",t);if(O===void 0)return;p=O,c()}if(g.ok||u($.error,{hint:$.hint,fixUrl:$.setup_url,status:g.status,json:t.json,fields:t.fields}),i){b($,t.fields);return}c();let _=$.summary?.succeeded??0,w=$.summary?.failed??0;if(_>0&&console.log(` ${y.success} ${Oe.default.green(`${_} domain${_>1?"s":""} registered`)}`),w>0){console.log(` ${y.error} ${Oe.default.red(`${w} failed`)}`);for(let k of $.errors||[])console.log(` ${Oe.default.dim("\u2500")} ${v.domain(k.domain)}: ${Oe.default.dim(k.error)}${k.hint?` ${Oe.default.dim(`(${k.hint})`)}`:""}`)}if(c(),_>0&&Te){let k=($.results||[]).filter(S=>S.success).map(S=>S.domain);if(k.length===1)await Sr(k[0]);else{let S=await lt({message:"Set up one of your new domains?",options:[...k.map(O=>({value:O,label:Oe.default.cyan(O)})),{value:"done",label:"Done"}]});!de(S)&&S!=="done"?(c(),await Sr(S)):c()}}else _>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),c())}async function Cr(e,t){let n=e.filter(Boolean);if(n.length===0){Te||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let i=await Ue({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(de(i)||!i)&&process.exit(0),n=i.split(/\s+/).filter(Boolean)}return n.length===1?Yu(n[0],t):Xu(n,t)}var Oe,$n=_e(()=>{"use strict";z();qe();Oe=N(F(),1);L();De();ve();Ui();Ni()});var Xr=N(Yr(),1),{program:$f,createCommand:kf,createArgument:_f,createOption:xf,CommanderError:jf,InvalidArgumentError:Sf,InvalidOptionArgumentError:Cf,Command:Zr,Argument:Of,Option:If,Help:Af}=Xr.default;oi();var kt=N(F(),1);De();ar();L();In();De();var nt=N(F(),1);L();var Vc=new Set(["cli","mcp","plugin","skill","api"]);function Wc(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),n=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),i=!!(t?.length||n?.length||e.label||e.expiresIn),s=e.surface||"cli";if(!Vc.has(s))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let r=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(r!==void 0&&(!Number.isInteger(r)||r<3600||r>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:i,body:{...t?.length?{scopes:t}:{},...n?.length?{mailboxes:n}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:s,intent:"programmatic_access"}}}function ta(e){return e!=="default"||ot().some(n=>n.name!==e)?` ${nt.default.dim(`(account ${e})`)}`:""}async function na(e){let t=Ke(),n=C(!e.json),i;try{i=Wc(e)}catch($){u($ instanceof Error?$.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:s,delegated:r}=i,o=gn(),a=xs(o);if(a&&!r){n.start("Checking session");try{let $=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if($.ok){let _=await $.json();n.stop(`Already logged in as ${nt.default.bold(_.email)}${ta(o)}`),e.json&&b({status:"already_logged_in",email:_.email,account:o});return}}catch{}n.stop("Session expired, re-authenticating"),c()}n.start("Requesting auth code");let d=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!d.ok){n.stop("Failed to initiate login");try{let $=await d.json();u($.error||$.message||`Server error (${d.status})`,{hint:$.hint,code:"login_failed",json:e.json})}catch{u(`Could not reach ${t}. Check your connection and try again.`,{code:"network_error",json:e.json})}}let{code:m,auth_url:f,expires_in:p}=await d.json();if(n.stop("Auth code received"),e.json){b({status:"awaiting_approval",code:m,auth_url:f,expires_in:p,account:o});return}c(),console.log(` ${nt.default.dim("Verification code:")} ${nt.default.bold(nt.default.cyan(m))}`),e.open!==!1?(console.log(` ${nt.default.dim("Opening browser")} ${y.arrow} ${v.url(f)}`),Ve(f)):console.log(` ${nt.default.dim("Open this URL to approve:")} ${v.url(f)}`),c(),n.start("Waiting for approval");let g=120;for(let $=0;$<g;$++){await new Promise(k=>setTimeout(k,5e3));let _=await fetch(`${t}/api/auth/cli/poll?code=${m}`);!_.ok&&_.status!==202&&(n.stop("Login failed"),u(`Server error (${_.status})`,{code:"login_failed"}));let w=await _.json();if(w.status==="complete"){fi(o,{token:w.token,email:w.email,api_url:t}),n.stop(`Logged in as ${nt.default.bold(w.email)}${ta(o)}`),c();let k=Ge().active_account;if(k&&k!==o){console.log(` ${nt.default.dim(`Commands still act as the active account "${k}".`)}`),I("Switch to this one:",`domani use ${o}`),I("Or use it once:",`domani --account ${o} me`),c();return}console.log(` ${nt.default.bold("Get one real result:")}`),I("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),I("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),I("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${nt.default.dim("A custom domain can wait until this loop works.")}`),c();return}w.error&&(n.stop("Login failed"),u(w.error||w.message,{hint:w.hint,code:"login_failed"}))}n.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}De();var dr=N(F(),1);L();async function ia(e){let t=gn(),n=uo(t);if(!n){e.json?b({status:"not_logged_in",account:t}):console.log(` ${dr.default.dim(`Not logged in${t==="default"?"":` to the account "${t}"`}.`)}`);return}let i=ot().map(r=>r.name);if(e.json){b({status:"logged_out",account:t,email:n.email||null,remaining_accounts:i});return}let s=[n.email,i.length>0||t!=="default"?`account ${t}`:void 0].filter(Boolean).join(", ");console.log(` ${y.success} Logged out${s?` ${dr.default.dim(`(${s})`)}`:""}`),i.length>0&&!Ge().active_account&&I("Pick the account to use next:",`domani use ${i[0]}`)}z();De();var Mt=N(F(),1);L();async function ra(e){let[t,n]=await Promise.all([x("/api/me"),x("/api/me/activation")]),i=await t.json();t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields});let s=n.ok?await n.json():null,r=En(),o={name:r.name??null,source:r.source};if(e.json){b({...i,activation:s,cli_account:o},e.fields);return}if(j("Account"),l("Email",Mt.default.bold(i.email)),l("CLI account",r.source==="api_key_env"?Mt.default.dim("DOMANI_API_KEY"):`${r.name??"-"}${r.source==="flag"?Mt.default.dim(" (--account)"):r.source==="env"?Mt.default.dim(" (DOMANI_ACCOUNT)"):""}`),l("Payment",i.has_payment_method?`${y.success} ${Mt.default.green("active")}`:`${y.error} ${Mt.default.dim("none")}`),l("Domains",String(i.domain_count)),l("API tokens",String(i.token_count)),l("Referral code",i.referral_code||Mt.default.dim("-")),l("Created",new Date(i.created_at).toLocaleDateString()),s){l("Activation",s.status);let a=s.recommended_actions?.[0];a&&l("Next action",a.label)}c()}var ht=N(F(),1);De();L();var Hc={api_key_env:"DOMANI_API_KEY",flag:"--account",env:"DOMANI_ACCOUNT",active:"domani use",none:"none"};async function oa(e){let t=ot(),n=Ge().active_account??null,i=En();if(e.json){b({active:n,current:i.name??null,source:i.source,accounts:t.map(r=>({name:r.name,email:r.email??null,api_url:r.api_url??null,active:r.name===n,current:r.name===i.name}))});return}if(t.length===0){console.log(` ${ht.default.dim("No saved accounts.")}`),I("Log in:","domani login");return}j("Accounts");let s=Math.max(...t.map(r=>r.name.length));for(let r of t){let o=r.name===i.name?ht.default.green("*"):" ",a=[r.name===n?"active":void 0,r.name===i.name&&i.source!=="active"?`selected by ${Hc[i.source]}`:void 0].filter(Boolean);console.log(` ${o} ${ht.default.bold(r.name.padEnd(s))} ${r.email??ht.default.dim("unknown email")}${a.length?` ${ht.default.dim(a.join(", "))}`:""}`)}i.source==="api_key_env"&&(c(),console.log(` ${y.warning} ${ht.default.dim("DOMANI_API_KEY is set: every command uses that key, not these accounts.")}`)),c(),I("Switch:","domani use <name>"),I("Add one:","domani login --account <name>"),c()}async function aa(e,t){if(mi(e)||u(`Invalid account name: ${e}`,{code:"validation_error",hint:"Use letters, digits, dot, dash or underscore",json:t.json}),!mo(e)){let i=ot().map(s=>s.name);u(`No saved account named "${e}"`,{code:"account_not_found",hint:i.length?`Saved accounts: ${i.join(", ")}. Add one with 'domani login --account ${e}'`:`Log in with 'domani login --account ${e}'`,json:t.json})}let n=ot().find(i=>i.name===e)?.email??null;if(t.json){b({status:"switched",active:e,email:n});return}console.log(` ${y.success} Now using ${ht.default.bold(e)}${n?` ${ht.default.dim(`(${n})`)}`:""}`),process.env.DOMANI_ACCOUNT&&process.env.DOMANI_ACCOUNT!==e&&console.log(` ${y.warning} ${ht.default.dim(`DOMANI_ACCOUNT=${process.env.DOMANI_ACCOUNT} still overrides it in this shell.`)}`)}z();qe();var E=N(F(),1);L();ve();Ni();function Vt(e){return!e.available&&!e.error&&!e.registry_status&&e.price===0&&!!e.reason&&!on(e)}var Bi="not sold on Domani";function on(e){return e.tld_kind==="alt_root"}function Or(e){return e.reason||`${e.domain} does not resolve in public DNS: its TLD is not in the DNS root zone (IANA). Domani does not offer it.`}function gt(e){return e.registry_status==="premium"||e.registry_status==="reserved"}function _n(e){return e.registry_status==="reserved"?"reserved":e.registry_price!==void 0?`premium $${e.registry_price.toFixed(2)}`:"premium"}function Ir(e){if(e.reason)return e.reason;if(e.registry_status==="reserved")return`${e.domain} is reserved by the registry and cannot be registered.`;let t=e.registry_price!==void 0?`: the registry prices it at $${e.registry_price.toFixed(2)}`:" priced by the registry";return`${e.domain} is a premium name${t}. Premium names cannot be bought at the standard price.`}function an(e,t){let n=e.findIndex(i=>i.domain===t);return n!==-1&&e.splice(n,1),n}var Ze=10,kn=200,Hi=["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"],Ji=null;async function Va(){if(Ji)return Ji;try{let e=await xe("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let n=(await e.json()).tlds.map(i=>i.tld);if(n.length>0){let i=new Set(Hi),s=new Set(n),r=[...Hi.filter(o=>s.has(o)),...n.filter(o=>!i.has(o))];return Ji=r,r}}}catch{}return Ji=Hi,Hi}async function Zu(e,t,n,i,s){let r=[],o=[],a=Ze,d=0,m=!0,f=0,p=0,g=!1,$=!1,_=null,w="",k=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=0,O=setInterval(()=>{$||!m||(S=(S+1)%k.length,U())},80);function R(){f>0&&(process.stdout.write(`\x1B[${f}A\x1B[0J`),f=0)}function M(){if(m)return[];let A=Ze+p*Ze;return r.length>a||i&&A<s.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function ee(){let A=M();return Math.max(0,H().length+A.length-1)}let q=6;function U(){R();let A=[],W=H(),ne=!m&&W.length===0&&o.length>0,X=ne?o.slice(0,q):W,ae=X.reduce((ye,te)=>Math.max(ye,te.domain.length),0),ke=M();for(let ye=0;ye<X.length;ye++){let te=X[ye];if(ne)A.push(`${E.default.dim("\u2502")} ${E.default.dim("\u2715")} ${E.default.dim(te.domain.padEnd(ae))} ${E.default.dim(gt(te)?_n(te):Vt(te)?Bi:"taken")}`);else{let me=ye===d,mt=me?E.default.green("\u25CF"):E.default.dim("\u25CB"),Jt=te.domain.padEnd(ae),un=me?E.default.bold(E.default.cyan(Jt)):Jt,Sn=te.for_sale?E.default.cyan(`$${te.for_sale.price} (for sale)`):E.default.dim(it(te.price,te.renewal_price));A.push(`${E.default.dim("\u2502")} ${mt} ${un} ${Sn}`)}}if(ne&&o.length>q&&A.push(`${E.default.dim("\u2502")} ${E.default.dim(`\u2026 and ${o.length-q} more taken`)}`),m){let ye=w?E.default.dim(`checking ${w}\u2026`):E.default.dim("searching\u2026");A.push(`${E.default.dim("\u2502")} ${E.default.cyan(k[S])} ${ye}`)}else{let ye=Ze+p*Ze;i&&ye>=s.length&&A.push(`${E.default.dim("\u2502")} ${E.default.dim(`All ${Math.min(ye,s.length)} TLDs searched`)}`);for(let me=0;me<ke.length;me++){let un=H().length+me===d?E.default.green("\u25CF"):E.default.dim("\u25CB"),Sn=ke[me]==="more"?E.default.dim("More \u2192"):ke[me]==="new"?E.default.dim("New search \u2192"):E.default.dim("Skip");A.push(`${E.default.dim("\u2502")} ${un} ${Sn}`)}A.push(E.default.dim("\u2514"))}process.stdout.write(A.join(`
184
184
  `)+`
185
185
  `),f=A.length}process.stdout.write(`${E.default.cyan("\u25C6")} Register a domain?
186
- `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let ce=A=>{let W=A.toString();if(W==="\x1B[A")d=Math.max(0,d-1),U();else if(W==="\x1B[B")d=Math.min(ee(),d+1),U();else if(W==="\r"){let ne=H();if(m&&ne.length===0)return;if(d<ne.length)k=ne[d]?.domain??null,$=!0;else{let ae=M()[d-ne.length];ae==="more"?(a+=Xe,r.length<a?g=!0:(d=Math.min(d,ee()),U())):(ae==="new"&&(k="__new__"),$=!0)}}else(W===""||W==="\x1B")&&($=!0)};process.stdin.on("data",ce),U();async function le(A){let W=new TextDecoder,ne="",X="";for await(let ae of A){if($)break;ne+=W.decode(ae,{stream:!0});let $e=ne.split(`
187
- `);ne=$e.pop()??"";for(let ge of $e)if(ge.startsWith("event: "))X=ge.slice(7);else if(ge.startsWith("data: ")){let te=JSON.parse(ge.slice(6));if(X==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(te.message||te.error||"Search failed",{code:te.code||"error"})),X==="result"){w=te.domain,on(o,te.domain);let ue=on(r,te.domain);ue!==-1&&(ue<d&&d--,d=Math.min(d,ee()),U())}if(X==="result"&&(te.available||te.for_sale||n)&&!ht(te)&&!Lt(te)){if(p===0){let ue=r.findIndex(ut=>ut.price>te.price);ue===-1?r.push(te):(r.splice(ue,0,te),ue<=d&&d++)}else r.push(te);U()}else if(X==="result"&&!te.available&&!te.error)o.length<8&&o.push(te);else if(X==="done"){m=!1,d=Math.min(d,ee());let ue=Xe+p*Xe;r.length<a&&i&&ue<s.length&&(g=!0),g||U()}}}m=!1}for(await le(e);!$;)if(await new Promise(A=>{let W=setInterval(()=>{($||g)&&(clearInterval(W),A())},16)}),g&&!$){g=!1;let A=Xe+p*Xe,W=s.slice(A,A+Xe);p++,m=!0,d=Math.min(d,Math.max(0,r.length-1)),U();let ne=new URLSearchParams;ne.set("domains",W.map(X=>`${t}.${X}`).join(","));try{let X=await ke(`/api/domains/search?${ne}`,{headers:{Accept:"text/event-stream"}});X.ok&&X.body?await le(X.body):(m=!1,U())}catch{m=!1,U()}}clearInterval(C),process.stdin.removeListener("data",ce),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),R();let P=k==="__new__",he=P?null:k,ie=he?r.find(A=>A.domain===he)??null:null;return he?process.stdout.write(`${E.default.dim("\u25C7")} Register a domain?
188
- ${E.default.dim("\u2502")} ${E.default.bold(E.default.cyan(he))}
186
+ `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let ce=A=>{let W=A.toString();if(W==="\x1B[A")d=Math.max(0,d-1),U();else if(W==="\x1B[B")d=Math.min(ee(),d+1),U();else if(W==="\r"){let ne=H();if(m&&ne.length===0)return;if(d<ne.length)_=ne[d]?.domain??null,$=!0;else{let ae=M()[d-ne.length];ae==="more"?(a+=Ze,r.length<a?g=!0:(d=Math.min(d,ee()),U())):(ae==="new"&&(_="__new__"),$=!0)}}else(W===""||W==="\x1B")&&($=!0)};process.stdin.on("data",ce),U();async function le(A){let W=new TextDecoder,ne="",X="";for await(let ae of A){if($)break;ne+=W.decode(ae,{stream:!0});let ke=ne.split(`
187
+ `);ne=ke.pop()??"";for(let ye of ke)if(ye.startsWith("event: "))X=ye.slice(7);else if(ye.startsWith("data: ")){let te=JSON.parse(ye.slice(6));if(X==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(te.message||te.error||"Search failed",{code:te.code||"error"})),X==="result"){w=te.domain,an(o,te.domain);let me=an(r,te.domain);me!==-1&&(me<d&&d--,d=Math.min(d,ee()),U())}if(X==="result"&&(te.available||te.for_sale||n)&&!gt(te)&&!Vt(te)){if(p===0){let me=r.findIndex(mt=>mt.price>te.price);me===-1?r.push(te):(r.splice(me,0,te),me<=d&&d++)}else r.push(te);U()}else if(X==="result"&&!te.available&&!te.error)o.length<8&&o.push(te);else if(X==="done"){m=!1,d=Math.min(d,ee());let me=Ze+p*Ze;r.length<a&&i&&me<s.length&&(g=!0),g||U()}}}m=!1}for(await le(e);!$;)if(await new Promise(A=>{let W=setInterval(()=>{($||g)&&(clearInterval(W),A())},16)}),g&&!$){g=!1;let A=Ze+p*Ze,W=s.slice(A,A+Ze);p++,m=!0,d=Math.min(d,Math.max(0,r.length-1)),U();let ne=new URLSearchParams;ne.set("domains",W.map(X=>`${t}.${X}`).join(","));try{let X=await xe(`/api/domains/search?${ne}`,{headers:{Accept:"text/event-stream"}});X.ok&&X.body?await le(X.body):(m=!1,U())}catch{m=!1,U()}}clearInterval(O),process.stdin.removeListener("data",ce),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),R();let P=_==="__new__",ge=P?null:_,ie=ge?r.find(A=>A.domain===ge)??null:null;return ge?process.stdout.write(`${E.default.dim("\u25C7")} Register a domain?
188
+ ${E.default.dim("\u2502")} ${E.default.bold(E.default.cyan(ge))}
189
189
  ${E.default.dim("\u2514")}
190
190
  `):process.stdout.write(`${E.default.dim("\u2514")}
191
- `),{chosen:he,chosenResult:ie,searchAgain:P,allTaken:r.length===0&&o.length>0,expanded:p>0}}async function Aa(e,t,n){if(!e){Te||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:n.json});let P=await Ue({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(de(P)||!P)&&process.exit(0),e=P}let i=t.map(P=>P.replace(/^\./,"")),s=n.tlds?.split(",").map(P=>P.trim())||[],r=[...new Set([...i,...s])];if(r.length>0&&Ei(r,n),Y(e,n),e.includes(".")&&r.length===0){let P=O(!n.json);P.start(`Checking ${v.domain(e)}`);let[he,ie]=await Promise.all([ke(`/api/domains/search?q=${encodeURIComponent(e)}`),ke(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),A=await he.json();if(he.ok||(P.stop("Search failed"),u(A.error||A.message,{hint:A.hint,status:he.status,json:n.json,fields:n.fields})),n.json){let W=A.domain.split(".")[0];b({name:W,results:[A],total:1,available:A.available?1:0},n.fields);return}if(rn(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow("not in public DNS")}`),l(),console.log(` ${kr(A)}`),l();else if(Lt(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow(Wi)}`),l(),console.log(` ${A.reason}`),l();else if(ht(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow(_n(A))}`),l(),console.log(` ${xr(A)}`),l();else if(A.available)if(P.stop(`${y.success} ${v.domain(A.domain)} ${y.dot} available ${y.dot} ${E.default.green(nt(A.price,A.renewal_price))}`),Te&&!n.json){let{buy:W}=await Promise.resolve().then(()=>(vn(),Vn));await W([A.domain],{preChecked:{price:A.price,currency:A.currency,renewal_price:A.renewal_price}})}else l(),I("Register it:",`domani buy ${A.domain}`),l();else if(A.for_sale?.buyable)if(P.stop(`${y.info} ${v.domain(A.domain)} ${y.dot} ${E.default.cyan("for sale")} ${y.dot} ${v.price(A.for_sale.price)}`),Te&&!n.json){let{buy:W}=await Promise.resolve().then(()=>(vn(),Vn));await W([A.domain],{preChecked:{price:A.for_sale.price,currency:A.for_sale.currency,marketplace:!0}})}else l(),I("Buy it:",`domani buy ${A.domain}`),l();else if(A.error)P.stop(`${E.default.dim("?")} ${v.domain(A.domain)} ${y.dot} ${E.default.dim("lookup failed")}`);else{let W;try{if(ie?.ok){let X=await ie.json();X?.title&&(W=X.title)}}catch{}let ne=W?` ${y.dot} ${E.default.dim(`"${W}"`)}`:"";P.stop(`${y.error} ${v.domain(A.domain)} ${y.dot} ${E.default.red("taken")}${ne}`)}return}let o=e.split(".")[0];if(Te&&!n.json&&r.length>0){let P=new URLSearchParams;P.set("domains",r.map(J=>`${o}.${J}`).join(",")),n.maxPrice&&P.set("max_price",n.maxPrice);let he=await ke(`/api/domains/search?${P}`,{headers:{Accept:"text/event-stream"}});if(!he.ok||!he.body){u("Search failed",{json:n.json});return}let ie=[],A=new TextDecoder,W="",ne="",X=O(!0);X.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let J of he.body){W+=A.decode(J,{stream:!0});let un=W.split(`
192
- `);W=un.pop()??"";for(let ei of un)if(ei.startsWith("event: "))ne=ei.slice(7);else if(ei.startsWith("data: ")&&ne==="result"){let Er=JSON.parse(ei.slice(6));on(ie,Er.domain),ie.push(Er)}}X.stop("");let ae=Math.max(...r.map(J=>`${o}.${J}`.length))+2,$e=ie.filter(J=>J.available),ge=ie.filter(rn),te=ie.filter(Lt),ue=ie.filter(ht),ut=ie.filter(J=>!J.available&&!J.error&&!rn(J)&&!Lt(J)&&!ht(J)),Ht=ie.filter(J=>!J.available&&J.for_sale);for(let J of[...$e,...Ht,...ue,...ut.filter(un=>!un.for_sale),...te,...ge])rn(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow("not in public DNS")}`):Lt(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow(Wi)}`):ht(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow(_n(J))}`):J.available?console.log(` ${E.default.green("\u2713")} ${E.default.bold(E.default.white(J.domain.padEnd(ae)))} ${E.default.green(nt(J.price,J.renewal_price))}`):J.for_sale?console.log(` ${E.default.cyan("$")} ${E.default.bold(E.default.white(J.domain.padEnd(ae)))} ${E.default.cyan(v.price(J.for_sale.price))} ${E.default.dim("(for sale)")}`):console.log(` ${E.default.dim("\u2717")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.dim("taken")}`);if(ge.length>0||te.length>0||ue.length>0){l();for(let J of ue)console.log(` ${E.default.dim(xr(J))}`);for(let J of te)console.log(` ${E.default.dim(J.reason??"")}`);for(let J of ge)console.log(` ${E.default.dim(kr(J))}`)}if($e.length===0){console.log(` ${E.default.dim("No domains available")}`),l();return}let{buy:cn}=await Promise.resolve().then(()=>(vn(),Vn));if($e.length===1){await cn([$e[0].domain],{preChecked:{price:$e[0].price,currency:$e[0].currency,renewal_price:$e[0].renewal_price}});return}let{select:jn,isCancel:Vd}=await Promise.resolve().then(()=>(qe(),Qs)),Qn=await jn({message:"Register one?",options:[...$e.map(J=>({value:J.domain,label:v.domain(J.domain),hint:nt(J.price,J.renewal_price)})),{value:"__skip__",label:"Skip"}]});if(!Vd(Qn)&&Qn!=="__skip__"){l();let J=$e.find(un=>un.domain===Qn);await cn([Qn],{preChecked:J?{price:J.price,currency:J.currency,renewal_price:J.renewal_price}:void 0})}else l();return}if(Te&&!n.json){let P=await Ca();for(n.expand&&P.length>$n&&console.error(E.default.dim(` (--expand: checking the first ${$n} of ${P.length} TLDs - server limit per request)`));;){let he=n.expand?P.slice(0,$n):P.slice(0,Xe),ie=new URLSearchParams;ie.set("domains",he.map(ut=>`${o}.${ut}`).join(",")),n.maxPrice&&ie.set("max_price",n.maxPrice);let A=O(!0);A.start(`Searching available domains for ${E.default.bold(o)}`);let W=await ke(`/api/domains/search?${ie}`,{headers:{Accept:"text/event-stream"}});if(!W.ok||!W.body){A.stop("Search failed");break}A.stop("");let ne=!n.expand,{chosen:X,chosenResult:ae,searchAgain:$e}=await Eu(W.body,o,n.all??!1,ne,P);if(X){l();let{buy:ut}=await Promise.resolve().then(()=>(vn(),Vn)),Ht=ae?{price:ae.price,currency:ae.currency,renewal_price:ae.renewal_price}:void 0;await ut([X],{preChecked:Ht});return}if(!$e)break;let{text:ge,isCancel:te}=await Promise.resolve().then(()=>(qe(),Qs)),ue=await ge({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(te(ue)||!ue)break;o=ue.split(".")[0]}l();return}let a=o,d=await Ca(),m=r.length>0?r:n.expand?d.slice(0,$n):d.slice(0,Xe);n.expand&&r.length===0&&d.length>$n&&console.error(`(--expand: checking the first ${$n} of ${d.length} TLDs - server limit per request; use --tlds to target others)`);let f=m.map(P=>`${a}.${P}`),p=new URLSearchParams;p.set("domains",f.join(",")),n.maxPrice&&p.set("max_price",n.maxPrice);let g=O(!n.json);g.start(`Searching available domains for ${E.default.bold(a)}`);let $=await ke(`/api/domains/search?${p}`,{headers:{Accept:"text/event-stream"}});if(!$.ok){g.stop("Search failed");try{let P=await $.json();u(P.error||P.message||`Server error (${$.status})`,{hint:P.hint,status:$.status,json:n.json,fields:n.fields})}catch{u(`Server error (${$.status})`,{status:$.status,json:n.json,fields:n.fields})}}let k=$.body;k||(g.stop("Search failed"),u("Empty response",{code:"error",json:n.json,fields:n.fields}));let w=[],_=!1,S=0,C=!1,R=new Set,M=n.all??!1;function H(){_||(_=!0,g.stop(`Checking TLDs for ${E.default.bold(a)}`),l())}function ee(P){H(),rn(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow("not in public DNS")}`),console.log(` ${E.default.dim(kr(P))}`)):Lt(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow(Wi)}`),console.log(` ${E.default.dim(P.reason??"")}`)):ht(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow(_n(P))}`),console.log(` ${E.default.dim(xr(P))}`)):P.available?console.log(` ${y.success} ${v.domain(P.domain).padEnd(37)} ${E.default.green(nt(P.price,P.renewal_price))}`):P.for_sale?console.log(` ${y.info} ${v.domain(P.domain).padEnd(37)} ${E.default.cyan(v.price(P.for_sale.price))} ${E.default.dim("(for sale)")}`):P.error||console.log(` ${y.error} ${E.default.dim(P.domain.padEnd(38))} ${E.default.red("taken")}`)}function q(){_||g.message(`Checking TLDs for ${E.default.bold(a)} ${E.default.dim(`(${S} checked)`)}`)}let U=new TextDecoder,ce="",le="";for await(let P of k){ce+=U.decode(P,{stream:!0});let he=ce.split(`
193
- `);ce=he.pop()??"";for(let ie of he)if(ie.startsWith("event: "))le=ie.slice(7);else if(ie.startsWith("data: ")){let A=JSON.parse(ie.slice(6));if(le==="error")g.stop("Search failed"),u(A.message||A.error||"Search failed",{code:A.code||"error",json:n.json,fields:n.fields});else if(le==="result"){R.add(A.domain),S=R.size;let W=on(w,A.domain);(A.available||A.for_sale||M||rn(A)||Lt(A)||ht(A))&&w.splice(W===-1?w.length:W,0,A),n.json||q()}else if(le==="done"){if(n.json){w.sort((ae,$e)=>ae.price-$e.price),b({name:a,results:w,total:A.total,available:A.available},n.fields);return}C=!0;for(let ae of w)ee(ae);_&&console.log(` ${E.default.dim("\u2500".repeat(50))}`);let W=A.total-A.available,ne=A.total>=5&&W/A.total>=.5,X=`Checked ${A.total} TLDs \xB7 ${A.available} available${ne?" \xB7 popular name":""}`;console.log(` ${E.default.dim(X)}`),A.available===0&&!n.expand&&r.length===0&&(l(),I("Try more TLDs:",`domani search ${a} --expand`))}}}if(!C&&!n.json)for(let P of w)ee(P);l()}vn();z();var Wn=N(F(),1);V();we();Ni();function Ia(e,t,n=process.env){let i=nn(t,n);if(i!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...i!==void 0?{webhook_headers:i}:{}},preview:{...e?{webhook_url:e}:{},...i!==void 0?{webhook_header_names:sn(i)}:{}}}}Di();async function Ra(e,t){Y(e,t);let n={domain:e};t.slug&&(n.slug=t.slug),t.name&&(n.name=t.name);let i;try{i=Ia(t.webhook,t)}catch(m){u(m instanceof Error?m.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}Object.assign(n,i.request),t.years&&(n.years=Number(t.years));let s=tn(t.maxPrice,t);if(s!==void 0&&(n.max_price=s),t.paymentMethod&&(n.payment_method=t.paymentMethod),t.dryRun){let m={...n};delete m.webhook_headers,Object.assign(m,i.preview),K("POST /api/agents/provision",m,t.json,t.fields);return}let r=O(!t.json);r.start(`Provisioning ${v.domain(e)}`);let o=await x("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await o.json(),d=o.ok?void 0:Ft(a);if(d!==void 0&&(r.stop("Price changed - nothing was charged"),u(a.error,{code:"price_above_max",hint:ar(d),data:{price:d},json:t.json,fields:t.fields})),o.ok||(r.stop("Provisioning failed"),u(a.error||"Provisioning failed",{hint:a.hint,status:o.status,json:t.json,fields:t.fields})),r.stop(`${v.domain(e)} is ready`),t.json){b(a,t.fields);return}if(l(),j("Agent identity"),c("Domain",`${a.domain} (${a.domain_status})`),c("Mailbox",a.mailbox?Wn.default.green(a.mailbox.address):Wn.default.yellow("pending DNS")),c("Webhook",a.webhook?a.webhook.url:Wn.default.dim("none")),a.webhook?.header_names.length&&c("Webhook auth",a.webhook.header_names.join(", ")),a.webhook?.secret&&c("Signing secret",a.webhook.secret),a.warnings?.length){l();for(let m of a.warnings)_e(Wn.default.yellow(m))}if(a.next_steps?.length){l(),j("Next");for(let m of a.next_steps)_e(m)}l()}z();var It=N(F(),1);V();async function Ta(e){let t=O(!e.json);t.start("Loading domains");let n=await x("/api/domains"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${i.domains.length} domain(s)`),e.json){b({...i,count:i.domains.length},e.fields);return}if(i.domains.length===0){l(),console.log(` ${It.default.dim("No domains yet.")} Use: ${It.default.cyan("domani buy <domain>")}`),l();return}let s=[30,12,12,14];j(`Your Domains (${i.domains.length})`,s.reduce((o,a)=>o+a,0)+s.length-1);let r=i.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),d=o.status==="active"?It.default.green:o.status==="pending"?It.default.yellow:It.default.red,m=o.autoRenew?It.default.green("on"):It.default.dim("off");return[v.domain(o.domain),d(o.status),m,It.default.dim(a)]});G(["Domain","Status","Auto-renew","Expires"],r,s),l()}br();z();var gt=N(F(),1);V();function Pu(e){let t=new URLSearchParams;return e.kind&&t.set("kind",e.kind),e.maxPrice&&t.set("max_price",e.maxPrice),e.minPrice&&t.set("min_price",e.minPrice),e.sort&&t.set("sort",e.sort),e.search&&t.set("search",e.search),e.limit&&t.set("limit",e.limit),t.set("order","asc"),t.toString()}function Ea(e){return e==="second_level"?"second level":e==="alt_root"?"alt root, no public DNS":"tld"}async function Pa(e){let t=O(!e.json);t.start("Loading TLDs");let n=await ke(`/api/tlds?${Pu(e)}`),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${i.total} TLDs loaded`),e.json){b(i,e.fields);return}let s=i.tlds;if(s.length===0){l(),console.log(` ${gt.default.dim("No TLDs match your filters.")}`),l();return}j("TLD Pricing");let r=s.map(o=>[gt.default.bold(`.${o.tld}`),v.price(o.registration.toFixed(2))+gt.default.dim("/yr"),gt.default.dim("renew ")+v.price(o.renewal.toFixed(2))+gt.default.dim("/yr"),o.kind==="alt_root"?gt.default.yellow(Ea(o.kind)):gt.default.dim(Ea(o.kind))]);G(["TLD","Register","Renewal","Kind"],r,[22,16,20,24]),l(),console.log(` ${gt.default.dim(`${i.total} TLDs total`)}`),s.some(o=>o.kind==="alt_root")&&console.log(` ${y.warning} ${gt.default.yellow("alt root names are outside the IANA root zone: they do not resolve in public DNS, and Domani does not sell them.")}`),l()}z();var Ee=N(F(),1);V();we();async function Da(e,t){Y(e,t);let n=O(!t.json);n.start(`Looking up ${v.domain(e)}`);let[i,s]=await Promise.all([ke(`/api/domains/whois?q=${encodeURIComponent(e)}`),ke(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await i.json(),o=null;try{s?.ok&&(o=await s.json())}catch{}if(i.ok||(n.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:i.status,json:t.json,fields:t.fields})),n.stop("WHOIS data retrieved"),t.json){b({...r,...o?{og:o}:{}},t.fields);return}if(j(`WHOIS ${v.domain(r.domain)}`),!r.registered){c("Status",`${y.success} ${Ee.default.green("not registered")}`),l(),I("Register it:",`domani buy ${r.domain}`),l();return}if(c("Status",`${y.error} ${Ee.default.red("registered")}`),(o?.title||o?.description)&&(l(),console.log(` ${Ee.default.bold("Website preview")}`),console.log(` ${Ee.default.dim("\u2500".repeat(50))}`),o.title&&c("Title",o.title),o.description&&c("Description",Ee.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),l()),r.registrar&&c("Registrar",r.registrar),r.created&&c("Created",r.created),r.expires&&c("Expires",r.expires),r.days_until_expiry!=null){let d=r.days_until_expiry,m=d<30?Ee.default.red:d<90?Ee.default.yellow:Ee.default.green;c("Days left",m(String(d)))}r.updated&&c("Updated",r.updated),c("DNSSEC",r.dnssec?Ee.default.green("yes"):Ee.default.dim("no")),r.nameservers?.length>0&&c("Nameservers",r.nameservers.map(d=>Ee.default.cyan(d)).join(Ee.default.dim(", "))),r.status?.length>0&&c("Status codes",Ee.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(l(),console.log(` ${Ee.default.bold("Registrant")}`),console.log(` ${Ee.default.dim("\u2500".repeat(50))}`),a.name&&c("Name",a.name),a.organization&&c("Organization",a.organization),a.email&&c("Email",v.url(a.email)),a.country&&c("Country",a.country)):r.redacted&&c("Contact",Ee.default.dim("redacted (WHOIS privacy)")),l()}z();qe();var yt=N(F(),1);V();we();Pi();async function Na(e,t){if(!e){Te||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let w=await Ue({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(de(w)||!w)&&process.exit(0),e=w}let n=new URLSearchParams({prompt:e});if(t.count&&n.set("count",t.count),t.tlds&&n.set("tlds",t.tlds),t.tlds&&Ei(t.tlds.split(",").map(w=>w.trim()),t),t.style&&n.set("style",t.style),t.lang&&n.set("lang",t.lang),t.json){let w=O(!1);w.start("Finding available domains");let _=t.timeout?parseInt(t.timeout,10)*1e3:6e4,S;try{S=await ke(`/api/domains/suggest?${n}`,{signal:AbortSignal.timeout(_)})}catch{w.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:t.json,fields:t.fields})}let C=await S.json();S.ok||(w.stop("Failed"),u(C.error||C.message,{hint:C.hint,status:S.status,json:t.json,fields:t.fields})),b(C,t.fields);return}let i=O(!0);i.start("Finding available domains");let s=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await ke(`/api/domains/suggest?${n}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(s)})}catch{i.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){i.stop("Failed");try{let w=await r.json();u(w.error||w.message||`Server error (${r.status})`,{hint:w.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(i.stop("Failed"),u("Empty response"));let a=[],d=[],m=!1,f=0;function p(){m||(m=!0,i.stop("Finding available domains"),l())}let g=new TextDecoder,$="",k="";for await(let w of o){$+=g.decode(w,{stream:!0});let _=$.split(`
194
- `);$=_.pop()??"";for(let S of _)if(S.startsWith("event: "))k=S.slice(7);else if(S.startsWith("data: "))try{let C=JSON.parse(S.slice(6));if(k==="result")on(a,C.domain)!==-1||on(d,C.domain)!==-1||f++,C.available?a.push(C):d.push(C),m||i.message(`Finding available domains ${yt.default.dim(`(${f} checked, ${a.length} available)`)}`);else if(k==="iteration")m||i.message(`Finding available domains ${yt.default.dim(`(round ${C.n})`)}`);else if(k==="done"){p();for(let R of a){let M=R.reason?` ${yt.default.dim(R.reason)}`:"";console.log(` ${y.success} ${v.domain(R.domain).padEnd(37)} ${yt.default.green(nt(R.price,R.renewal_price))}${M}`)}for(let R of d)console.log(` ${y.error} ${yt.default.dim(R.domain.padEnd(38))} ${ht(R)?yt.default.yellow(_n(R)):yt.default.red("taken")}`);console.log(` ${yt.default.dim("\u2500".repeat(50))}`),console.log(` ${yt.default.dim(`Found ${C.total} available \xB7 checked ${C.checked} \xB7 ${C.iterations} round${C.iterations>1?"s":""}`)}`)}else k==="error"&&(m||i.stop("Failed"),u(C.message))}catch{}}a.length===0&&d.length===0&&(m||i.stop("No results"),u("Could not find available domains for this prompt.")),l(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),l())}cr();vr();z();qe();var bt=N(F(),1);V();De();we();Cn();async function Ua(e){let t=e.maxConsecutiveFailures??10,n=0;for(let i=1;i<=e.maxAttempts;i++){let s=await e.fetchPlan().catch(()=>null);if(e.onTick?.(s,i),s!==null){if(n=0,e.isEligible(s))return{status:"eligible",plan:s}}else if(n++,n>=t)return{status:"unreachable",failures:n};i<e.maxAttempts&&await e.sleep(e.intervalMs)}return{status:"timeout",attempts:e.maxAttempts}}var Hn=N(F(),1);V();function Jn(e){if(e){l(),console.log(` ${Hn.default.bold(`Exit path (${e.managed_via})`)}`),console.log(` ${Hn.default.dim("Unlock:")} ${e.unlock}`),console.log(` ${Hn.default.dim("Auth code:")} ${e.auth_code}`);for(let t of e.notes||[])console.log(` ${Hn.default.yellow("!")} ${t}`)}}var Du=6e4,Nu=1440;async function qa(e,t){Y(e,t);let n=O(!t.json);n.start(`Planning safe adoption for ${v.domain(e)}`);let i=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Check failed"),u(s.error,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),s.options?.transfer?.eligible)n.stop(`${y.success} Eligible for transfer`);else{n.stop(`${y.error} Not eligible`);let a=s.options?.transfer;if(t.watch&&a?.eligible_at){let d=await x("/api/domains/transfer-watch",{method:"POST",body:JSON.stringify({domain:e})}),m=await d.json();if(d.ok||u(m.error||m.message,{hint:m.hint,status:d.status,json:t.json,fields:t.fields}),t.json){b(m,t.fields);return}j("Transfer Watch Registered"),c("Domain",v.domain(e)),c("Eligible from",m.eligible_at||a.eligible_at),m.hint&&(l(),console.log(` ${bt.default.dim(m.hint)}`)),l();return}if(t.watch){t.json||(console.log(` ${bt.default.dim(a?.reason||"Domain is not eligible for transfer yet.")}`),Jn(a?.guidance),l());let d=O(!t.json);d.start(`Watching ${v.domain(e)} until it becomes transferable (every 60s, Ctrl+C to stop)`);let m=await Ua({fetchPlan:async()=>{let f=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`);return f.ok?f.json():null},isEligible:f=>!!f.options?.transfer?.eligible,sleep:f=>new Promise(p=>setTimeout(p,f)),intervalMs:Du,maxAttempts:Nu});m.status!=="eligible"&&(d.stop(`${y.error} Watch ended`),u(m.status==="timeout"?"Domain did not become eligible within 24 hours.":"Gave up after repeated failures fetching the adoption plan.",{hint:"The transfer lock is disabled at the losing registrar; rerun with --watch once you have flipped it.",code:m.status==="timeout"?"watch_timeout":"watch_unreachable",json:t.json,fields:t.fields})),s=m.plan,d.stop(`${y.success} Now eligible for transfer`)}else{t.json||Jn(a?.guidance);let d=a?.eligible_at?`Eligible from ${a.eligible_at}. Rerun with --watch to register a server watch (email + webhook when the date arrives).`:"Fix the blocker above, then rerun - or rerun with --watch to poll until the domain becomes eligible and continue automatically.",m=t.json&&a?.guidance?` The registrar exit playbook is in the adoption plan (options.transfer.guidance, \`domani adopt ${e} --json\`).`:"";u(a?.reason||"Domain is not eligible for transfer.",{hint:[d+m,...s.warnings?.length?[s.warnings.join(" ")]:[]].join(" "),code:"not_eligible",json:t.json,fields:t.fields})}}if(t.dryRun)return K("transfer",{domain:e,eligible:!0,price:s.options.transfer.price,currency:s.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:s.current.nameservers,dns_provider:s.current.dns_provider,dnssec_enabled:s.current.dnssec_enabled,acting_as:xt()},t.json,t.fields);if(!St(t)){j("Transfer Safety Plan"),c("Registrar",s.current.registrar||"Unknown"),c("DNS provider",s.current.dns_provider),c("Nameservers",`${s.current.nameservers.length} preserved`),c("DNSSEC",s.current.dnssec_enabled?bt.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),l();let a=s.options.transfer.price!=null?` for ${v.price(s.options.transfer.price.toFixed(2))}`:"",d=await We({message:`Transfer ${bt.default.bold(e)} to ${fn}${a}${Ut()}? Nameservers stay unchanged and 1 year is included.`});if(!d||typeof d=="symbol"){console.log(` ${bt.default.dim("Cancelled.")}`);return}}if(!t.authCode){(t.json||!process.stdout.isTTY)&&u("--auth-code is required",{hint:"The safety plan passed. Get the EPP/auth code from the current registrar and retry.",code:"validation_error",json:t.json,fields:t.fields}),s.options?.transfer?.guidance&&console.log(` ${bt.default.dim("Where to get it:")} ${s.options.transfer.guidance.auth_code}`);let a=await Ue({message:"Enter the EPP/auth code from your current registrar:",validate:d=>!d||d.trim().length===0?"Auth code is required":void 0});de(a)&&process.exit(0),t.authCode=a}n.start(`Initiating transfer for ${v.domain(e)}`);let r=await x("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:e,auth_code:t.authCode})}),o=await r.json();if(r.ok||(n.stop("Transfer failed"),u(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Transfer initiated`),t.json){b(o,t.fields);return}j("Transfer Initiated"),c("Domain",v.domain(o.domain)),c("Status",bt.default.yellow(o.status||"pending")),o.price&&c("Price",v.price(o.price)+bt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&c("Payment",o.payment_method),o.expires&&c("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(l(),console.log(` ${bt.default.dim(o.hint)}`)),l(),I("Check transfer progress:",`domani status ${o.domain}`),l()}z();var Bn=N(F(),1);V();we();async function Ma(e,t){Y(e,t);let n=O(!t.json);n.start(`Inspecting ${v.domain(e)}`);let i=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Inspection failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Adoption plan ready`),t.json){b(s,t.fields);return}if(j(`Adopt ${v.domain(s.domain)}`),c("Registrar",s.current.registrar||"Unknown"),c("DNS provider",s.current.dns_provider),c("Nameservers",s.current.nameservers.join(", ")||"None detected"),c("DNSSEC",s.current.dnssec_enabled?Bn.default.yellow("Enabled"):"Not enabled"),c("Account",s.account_state),c("Recommended",Bn.default.cyan(s.recommended_action)),l(),s.recommended_action==="connect"&&I("Connect free, without changing registrar or DNS:",`domani import ${s.domain}`),s.options.transfer.available){let r=s.options.transfer.price==null?"price unavailable":`$${s.options.transfer.price.toFixed(2)} ${s.options.transfer.currency}`;I(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${s.domain}`),!s.options.transfer.eligible&&s.options.transfer.reason&&(console.log(` ${Bn.default.yellow("!")} ${s.options.transfer.reason}`),I("Wait for eligibility and transfer in one go:",`domani transfer ${s.domain} --watch`)),Jn(s.options.transfer.guidance)}for(let r of s.warnings||[])console.log(` ${Bn.default.yellow("!")} ${r}`);l()}z();qe();var kn=N(F(),1);V();De();we();it();Di();async function Fa(e,t){e||(e=await ye()),Y(e,t);let n=t.years?parseInt(t.years,10):1;(isNaN(n)||n<1||n>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields});let i=tn(t.maxPrice,t),s=`${n} year${n>1?"s":""}`,r=O(!t.json);r.start(`Checking ${v.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}`),a=await o.json();o.ok||(r.stop("Lookup failed"),u(a.error,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}));let d=typeof a.renewal_price=="number"?a.renewal_price:void 0,m=d!==void 0?Mn(d*n):void 0;r.stop(d!==void 0?`${y.success} ${v.domain(e)} ${y.dot} renews at ${v.price(d.toFixed(2))}/yr`:`${v.domain(e)} ${y.dot} ${kn.default.dim("renewal price unknown")}`);let f=i??m;if(t.dryRun)return K("renew",{domain:e,years:n,price:m,currency:"USD",max_price:f,acting_as:xt()},t.json,t.fields);if(!St(t)){let k=await We({message:m!==void 0?`Renew ${kn.default.bold(e)} for ${s} for ${v.price(m.toFixed(2))}${Ut()}?`:`Renew ${kn.default.bold(e)} for ${s}${Ut()}? You will be charged.`});if(!k||typeof k=="symbol"){console.log(` ${kn.default.dim("Cancelled.")}`);return}}let p,g,$;for(;;){$=O(!t.json),$.start(`Renewing ${v.domain(e)}`),p=await x(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:n,...f!==void 0?{max_price:f}:{}})}),g=await p.json();let k=p.ok?void 0:Ft(g);if(k===void 0)break;$.stop("Price changed");let w=await Fn(k,f??k,g,"Renew",t);if(w===void 0)return;f=w}if(p.ok||($.stop("Renewal failed"),u(g.error||g.message,{hint:g.hint,fixUrl:g.setup_url||g.payment_options?.card?.setup_url,status:p.status,json:t.json,fields:t.fields})),$.stop(`${y.success} Domain renewed`),t.json){b(g,t.fields);return}j("Renewal Complete"),c("Domain",v.domain(g.domain)),c("Years",String(g.renewed_years)),c("New expiry",new Date(g.new_expiry).toLocaleDateString()),g.price&&c("Price",v.price(g.price.toFixed(2))+kn.default.dim(` ${g.currency||"USD"}`)),g.payment_method&&c("Payment",g.payment_method),l(),I("Verify renewal:",`domani status ${g.domain}`),l()}z();var wt=N(F(),1);V();we();async function La(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
195
- domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t);let n=t.verify?"/api/domains/import/verify":"/api/domains/import",i=O(!t.json);i.start(t.verify?`Verifying ownership of ${v.domain(e)}`:`Initiating import for ${v.domain(e)}`);let s=await x(n,{method:"POST",body:JSON.stringify({domain:e})}),r=await s.json();if(s.ok||(i.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),b(r,t.fields);return}t.verify?(i.stop(`${y.success} ${v.domain(e)} imported!`),j("Domain Imported"),c("Domain",v.domain(r.domain)),c("Status",wt.default.green(r.status||"active")),r.expires_at&&c("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&c("Registrar",r.registrar),l(),I("Check domain health:",`domani status ${r.domain}`),l()):(i.stop(`${y.success} Verification record ready`),j("Import Domain"),c("Domain",v.domain(r.domain)),c("Status",wt.default.yellow("pending verification")),l(),console.log(" Add this TXT record at your DNS provider:"),l(),console.log(` ${wt.default.dim("Type:")} ${wt.default.bold("TXT")}`),console.log(` ${wt.default.dim("Name:")} ${wt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${wt.default.dim("Value:")} ${wt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),l(),console.log(` ${wt.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),l(),I("Once the record is set, verify:",`domani import ${e} --verify`),l())}hr();De();V();function Va(e){let t=ot();if(t||(l(),u("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:e.json})),!e.reveal&&!e.json&&process.stdout.isTTY){let n=`${t.slice(0,12)}...${t.slice(-4)}`;console.log(n),console.log("Run 'domani token --reveal' to print the full key.");return}e.json?b({token:t}):console.log(t)}z();var Ve=N(F(),1);V();async function Wa(e,t){switch(e){case void 0:case"list":return Uu(t.json,t.fields);case"create":return qu(t);case"revoke":return Mu(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function Uu(e,t){let n=O(!e);n.start("Loading tokens");let i=await x("/api/tokens"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.tokens.length} token(s)`),e){b(s,t);return}if(s.tokens.length===0){l(),console.log(` ${Ve.default.dim("No tokens.")}`),l(),I("Create one:",'domani tokens create --name "My App"'),l();return}l(),j("API Tokens");let r=s.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 d=o.scopes.includes("*")?Ve.default.dim("all"):Ve.default.dim(o.scopes.join(", "));return[Ve.default.dim(o.id),Ve.default.bold(o.name),o.agent_identity?Ve.default.dim(o.agent_identity.name||o.agent_identity.slug):Ve.default.dim("-"),d,a]});G(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),l()}async function qu(e){let t={};if(e.name&&(t.name=e.name),e.scopes&&(t.scopes=e.scopes.split(",").map(r=>r.trim())),e.expiresIn){let r=Number(e.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&u("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:e.json,fields:e.fields}),t.expires_in=r}e.agentIdentity&&(t.agent_identity_id=e.agentIdentity);let n=O(!e.json);n.start("Creating token");let i=await x("/api/tokens",{method:"POST",body:JSON.stringify(t)}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Token created`),e.json){b(s,e.fields);return}l(),j("Token Created"),c("ID",s.id),c("Name",s.name),c("Scopes",s.scopes?.includes("*")?"All (full access)":s.scopes?.join(", ")||"All"),s.agent_identity&&c("Agent",s.agent_identity.name||s.agent_identity.slug),c("Expires",s.expiresAt?new Date(s.expiresAt).toLocaleString():"Never"),l(),console.log(` ${Ve.default.yellow("!")} ${Ve.default.bold("Key:")} ${s.key}`),console.log(` ${Ve.default.dim("Save this key - it will not be shown again.")}`),l()}async function Mu(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
196
- Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=O(!e.json);t.start("Revoking token");let n=await x(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Token revoked`),e.json){b(i,e.fields);return}console.log(` ${Ve.default.dim("Any applications using this key will need a new one.")}`),l()}z();var Pe=N(F(),1);V();we();it();async function Ha(e,t){e||(e=await ye()),Y(e,t);let n=t.autoRenew!==void 0,i=t.whoisPrivacy!==void 0,s=t.securityLock!==void 0;if(!n&&!i&&!s)return Fu(e,t.json,t.fields);let r={};if(n){let m=jr(t.autoRenew);m===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=m}if(i){let m=jr(t.whoisPrivacy);m===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=m}if(s){let m=jr(t.securityLock);m===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=m}if(t.dryRun)return K("settings_update",{domain:e,...r},t.json,t.fields);let o=O(!t.json);o.start(`Updating ${v.domain(e)}`);let a=await x(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${y.success} Settings updated`),t.json){b(d,t.fields);return}j("Settings Updated"),c("Domain",v.domain(d.domain)),d.auto_renew!==void 0&&c("Auto-renew",d.auto_renew?Pe.default.green("on"):Pe.default.dim("off")),d.whois_privacy!==void 0&&c("WHOIS privacy",d.whois_privacy?Pe.default.green("on"):Pe.default.dim("off")),d.security_lock!==void 0&&c("Security lock",d.security_lock?Pe.default.green("locked"):Pe.default.dim("unlocked")),d.hint&&c("",Pe.default.dim(d.hint)),l()}async function Fu(e,t,n){let i=O(!t);i.start(`Loading ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop(`${y.success} ${v.domain(e)}`),t){b(r,n);return}j("Domain Settings"),c("Domain",v.domain(r.domain)),c("Status",r.status==="active"?Pe.default.green(r.status):Pe.default.yellow(r.status)),c("Auto-renew",r.auto_renew?Pe.default.green("on"):Pe.default.dim("off")),r.registrar&&(c("WHOIS privacy",r.registrar.whois_privacy?Pe.default.green("on"):Pe.default.dim("off")),c("Security lock",r.registrar.security_lock?Pe.default.green("locked"):Pe.default.dim("unlocked"))),c("Expires",new Date(r.expires_at).toLocaleDateString()+Pe.default.dim(` (${r.days_until_expiry} days)`)),l(),I("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),I("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),I("Toggle security lock:",`domani settings ${e} --security-lock off`),I("Get transfer auth code:",`domani auth-code ${e}`),l()}function jr(e){let t=e.toLowerCase();return t==="on"||t==="true"||t==="1"||t==="enable"?!0:t==="off"||t==="false"||t==="0"||t==="disable"?!1:null}z();var Rt=N(F(),1);V();we();it();async function Ja(e,t){e||(e=await ye()),Y(e,t);let n=O(!t.json);n.start(`Getting auth code for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/auth-code`),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields}));let r=s.status==="requested";if(n.stop(r?`${y.success} Auth code requested`:`${y.success} Auth code retrieved`),t.json){b(s,t.fields);return}if(r){j("Auth Code"),c("Domain",v.domain(s.domain)),c("Status",Rt.default.yellow("Requested")),s.expected_by&&c("Ready by",new Date(s.expected_by).toLocaleString()),s.hint&&(l(),console.log(` ${Rt.default.dim(s.hint)}`)),l(),I("Read the code once you get the email:",`domani auth-code ${e}`),l();return}if(j("Auth Code"),c("Domain",v.domain(s.domain)),c("Auth code",Rt.default.bold(Rt.default.green(s.auth_code))),s.was_unlocked&&c("",Rt.default.yellow("Domain was automatically unlocked to allow transfer.")),s.hint&&(l(),console.log(` ${Rt.default.dim(s.hint)}`)),s.next_steps?.length){l();for(let o of s.next_steps)console.log(` ${Rt.default.dim("\u2192")} ${Rt.default.dim(o)}`)}l(),I("Check transfer status:",`domani transfer-away ${e}`),I("Re-lock domain:",`domani settings ${e} --security-lock on`),l()}z();var Tt=N(F(),1);V();we();it();var Lu={none:Tt.default.dim,pending:Tt.default.yellow,approved:Tt.default.yellow,completed:Tt.default.green,rejected:Tt.default.red,expired:Tt.default.red};async function Ba(e,t){e||(e=await ye()),Y(e,t);let n=O(!t.json);n.start(`Checking transfer status for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/transfer-away`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} ${v.domain(e)}`),t.json){b(s,t.fields);return}j("Transfer Away Status"),c("Domain",v.domain(s.domain));let r=Lu[s.status]||Tt.default.dim;c("Status",r(s.status)),s.gaining_registrar&&c("New registrar",s.gaining_registrar),s.request_date&&c("Requested",new Date(s.request_date).toLocaleDateString()),s.hint&&(l(),console.log(` ${Tt.default.dim(s.hint)}`)),l(),s.status==="none"?I("Get auth code to start:",`domani auth-code ${e}`):s.status==="pending"||s.status==="approved"?I("Check again later:",`domani transfer-away ${e}`):s.status==="completed"?I("Search for a new domain:","domani search <name>"):(s.status==="rejected"||s.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${e}`),l()}z();qe();var Hi=N(F(),1);V();async function Ga(e,t){return e==="set"?Wu(t):Vu(t)}async function Vu(e){let t=O(!e.json);t.start("Loading contact info");let n=await x("/api/me/contact"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Contact info`),e.json){b(i,e.fields);return}if(j("Contact Info"),!i.has_contact){console.log(` ${y.warning} ${Hi.default.yellow("No contact info set.")} Run ${Hi.default.bold("domani contact set")} to add.`),l(),console.log(` ${Hi.default.dim("Contact info is required before purchasing domains.")}`),l();return}let s=i.contact;c("Name",`${s.first_name} ${s.last_name}`),s.org_name&&c("Organization",s.org_name),c("Address",s.address1),s.address2&&c("",s.address2),c("",`${s.city}, ${s.state} ${s.postal_code}`),c("Country",s.country),c("Phone",s.phone),c("Email",s.email),l()}async function Wu(e){let t={},n=e.firstName||e.lastName||e.address1;if(!Te&&!n&&u("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:e.json}),n){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],d={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"},m=a.filter(f=>!e[f]);m.length>0&&u(`Missing required flags: ${m.map(f=>`--${f.replace(/[A-Z]/g,p=>`-${p.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[f,p]of Object.entries(d)){let g=e[f];g&&(t[p]=g)}}else{let a=await x("/api/me/contact"),m=(a.ok?await a.json():null)?.contact,f=[{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 p of f){let g=m?.[p.key]||"",$=await Ue({message:p.message,placeholder:p.placeholder,defaultValue:g,validate:p.required?w=>w?.trim()?void 0:`${p.message} is required`:void 0});de($)&&process.exit(0);let k=$.trim();k&&(t[p.key]=k)}}if(e.dryRun)return K("contact_set",t,e.json,e.fields);let i=O(!e.json);i.start("Saving contact info");let s=await x("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Contact info saved`),e.json){b(r,e.fields);return}j("Contact Saved");let o=r.contact;c("Name",`${o.first_name} ${o.last_name}`),o.org_name&&c("Organization",o.org_name),c("Address",o.address1),o.address2&&c("",o.address2),c("",`${o.city}, ${o.state} ${o.postal_code}`),c("Country",o.country),c("Phone",o.phone),c("Email",o.email),l(),I("Search for a domain:","domani search <name>"),l()}z();var Me=N(F(),1);V();we();it();async function Ya(e,t,n,i){if(e||(e=await ye()),Y(e,i),!t)return Hu(e,i.json,i.fields);switch(t){case"enable":case"on":return i.dryRun?K("parking_enable",{domain:e},i.json,i.fields):Ka(e,!0,i.json,i.fields);case"disable":case"off":return i.dryRun?K("parking_disable",{domain:e},i.json,i.fields):Ka(e,!1,i.json,i.fields);case"price":{n||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:i.json,fields:i.fields});let s=parseFloat(n);return(isNaN(s)||s<=0)&&u("Price must be a positive number",{hint:`Got: "${n}"`,code:"validation_error",json:i.json,fields:i.fields}),i.dryRun?K("parking_price",{domain:e,price:s},i.json,i.fields):za(e,s,i.json,i.fields)}case"unprice":case"unlist":return i.dryRun?K("parking_unlist",{domain:e},i.json,i.fields):za(e,null,i.json,i.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:i.json,fields:i.fields})}}async function Hu(e,t,n){let i=O(!t);i.start(`Loading ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop(`${y.success} ${v.domain(e)}`),t){b({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},n);return}j("Parking"),c("Domain",v.domain(r.domain)),c("Parking",r.parking_enabled?Me.default.green("enabled"):Me.default.dim("disabled")),c("Listing",r.listing_price?`${v.price(r.listing_price)} ${Me.default.dim("(for sale)")}`:Me.default.dim("not listed")),l(),I("Enable parking:",`domani parking ${e} enable`),I("Set sale price:",`domani parking ${e} price 499`),I("View analytics:",`domani analytics ${e}`),l()}async function Ka(e,t,n,i){let s=O(!n);s.start(`${t?"Enabling":"Disabling"} parking for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(s.stop(`${y.warning} DNS records will be replaced`),n){b(o,i);return}console.log(`
197
- ${Me.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${Me.default.dim(a.type)} ${a.name} ${Me.default.dim("\u2192")} ${a.value}`);console.log(`
198
- ${Me.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Me.default.dim("Or use the dashboard to confirm.")}`),l();return}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n,fields:i})),s.stop(`${y.success} Parking ${t?"enabled":"disabled"}`),n){b(o,i);return}j("Parking Updated"),c("Domain",v.domain(o.domain)),c("Parking",o.parking_enabled?Me.default.green("enabled"):Me.default.dim("disabled")),o.hint&&c("",Me.default.dim(o.hint)),l()}async function za(e,t,n,i){let s=O(!n);s.start(t!==null?`Setting price for ${v.domain(e)} to ${v.price(t)}`:`Removing listing for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n,fields:i})),s.stop(`${y.success} ${t!==null?"Price set":"Listing removed"}`),n){b(o,i);return}j("Listing Updated"),c("Domain",v.domain(o.domain)),c("Listing",o.listing_price?`${v.price(o.listing_price)} ${Me.default.dim("(for sale)")}`:Me.default.dim("not listed")),o.hint&&c("",Me.default.dim(o.hint)),l()}z();var Ze=N(F(),1);V();we();it();var Ju=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Bu(e){let t=Math.max(...e,1);return e.map(n=>Ju[Math.min(Math.round(n/t*8),8)]).join("")}async function Xa(e,t){e||(e=await ye()),Y(e,t);let n=O(!t.json);n.start(`Loading analytics for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/analytics`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop("Analytics loaded"),t.json){b(s,t.fields);return}if(l(),j(`Analytics: ${v.domain(e)}`),c("Views (7d)",Ze.default.cyan(s.views_7d.toLocaleString())),c("Views (30d)",Ze.default.cyan(s.views_30d.toLocaleString())),c("Inquiries",Ze.default.cyan(String(s.inquiries_30d))),c("Conversion",s.conversion_rate>0?Ze.default.green(`${s.conversion_rate}%`):Ze.default.dim("0%")),s.daily_views&&s.daily_views.length>0){let r=s.daily_views.map(m=>m.views),o=Bu(r),a=s.daily_views[0].date.slice(5),d=s.daily_views[s.daily_views.length-1].date.slice(5);l(),console.log(` ${Ze.default.dim(a)} ${Ze.default.cyan(o)} ${Ze.default.dim(d)}`)}if(s.recent_inquiries&&s.recent_inquiries.length>0){l(),console.log(` ${Ze.default.bold("Recent Inquiries")}`);let r=s.recent_inquiries.map(o=>[Ze.default.dim(o.email),o.offer?v.price(o.offer):Ze.default.dim("-"),Ze.default.dim(new Date(o.date).toLocaleDateString())]);G(["Email","Offer","Date"],r,[30,12,14])}l(),I("Set a listing price:",`domani parking ${e} price <amount>`),I("Set up email:",`domani email setup ${e}`),I("Domain settings:",`domani settings ${e}`),l()}z();var be=N(F(),1);V();Ni();async function Za(e,t){switch(e){case void 0:case"list":return Ku(t.json,t.fields);case"create":return zu(t);case"update":return Yu(t);case"delete":return Xu(t);case"deliveries":return Zu(t);case"replay":return Gu(t);case"events":return Qu(t.json,t.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, update, delete, deliveries, replay, events",code:"validation_error",json:t.json,fields:t.fields})}}async function Gu(e){(!e.webhookId||!e.deliveryId||!e.idempotencyKey)&&u("Webhook ID, delivery ID, and idempotency key are required",{hint:"Usage: domani webhooks replay --webhook-id <id> --delivery-id <id> --idempotency-key <stable-key>",code:"validation_error",json:e.json,fields:e.fields});let t=O(!e.json);t.start("Replaying webhook delivery");let n=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook replay ${i.status}`),e.json)return b(i,e.fields);j("Webhook Replay Receipt"),c("Delivery",i.delivery_id),c("Original",i.original_delivery_id),c("Status",i.status),c("Attempts",i.attempts),c("Idempotent retry",i.idempotent_replay?"yes":"no"),l()}async function Ku(e,t){let n=O(!e);n.start("Loading webhooks");let i=await x("/api/webhooks"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.webhooks.length} webhook(s)`),e){b(s,t);return}if(s.webhooks.length===0){l(),console.log(` ${be.default.dim("No webhooks configured.")}`),l(),I("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),I("List events:","domani webhooks events"),l();return}l(),j("Webhooks");let r=s.webhooks.map(o=>[be.default.dim(o.id),v.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||be.default.dim("none"),o.active?be.default.green("active"):be.default.dim("paused")]);G(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),l()}async function zu(e){e.url||u("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:e.json,fields:e.fields}),e.events||u("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
199
- Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:e.json,fields:e.fields});let t=e.events.split(",").map(o=>o.trim()),n;try{n=nn(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun)return K("webhook_create",{url:e.url,events:t,header_names:sn(n)},e.json,e.fields);let i=O(!e.json);i.start("Creating webhook");let s=await x("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...n!==void 0?{headers:n}:{}})}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Webhook created`),e.json){b(r,e.fields);return}l(),j("Webhook Created"),c("ID",r.id),c("URL",v.url(r.url)),c("Events",r.events.join(", ")),c("Auth headers",r.header_names?.join(", ")||be.default.dim("none")),c("Status",be.default.green("active")),l(),console.log(` ${be.default.yellow("!")} ${be.default.bold("Secret:")} ${r.secret}`),console.log(` ${be.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${be.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),l()}async function Yu(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:e.json,fields:e.fields});let t={};e.url&&(t.url=e.url),e.events&&(t.events=e.events.split(",").map(r=>r.trim())),e.active!==void 0&&(t.active=e.active==="on"||e.active==="true");try{let r=nn(e);r!==void 0&&(t.headers=r)}catch(r){u(r instanceof Error?r.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun){let{headers:r,...o}=t;return K("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:sn(r)}:{}},e.json,e.fields)}let n=O(!e.json);n.start("Updating webhook");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Webhook updated`),e.json){b(s,e.fields);return}j("Webhook Updated"),c("ID",s.id),c("URL",v.url(s.url)),c("Events",s.events.join(", ")),c("Auth headers",s.header_names?.join(", ")||be.default.dim("none")),c("Status",s.active?be.default.green("active"):be.default.dim("paused")),l()}async function Xu(e){if(e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=O(!e.json);t.start("Deleting webhook");let n=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook deleted`),e.json){b(i,e.fields);return}console.log(` ${be.default.dim("Pending deliveries have been cancelled.")}`),l()}async function Zu(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let t=e.limit?`?limit=${e.limit}`:"",n=O(!e.json);n.start("Loading deliveries");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} ${s.deliveries.length} delivery(ies)`),e.json){b(s,e.fields);return}if(s.deliveries.length===0){l(),console.log(` ${be.default.dim("No deliveries yet.")}`),l();return}l(),j("Deliveries");let r=s.deliveries.map(o=>{let a=o.status==="delivered"?be.default.green("delivered"):o.status==="failed"?be.default.red("failed"):be.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):be.default.dim("-"),String(o.attempts),be.default.dim(new Date(o.created_at).toLocaleString())]});G(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),l()}async function Qu(e,t){let n=O(!e);n.start("Loading event types");let i=await ke("/api/webhooks/events"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.events.length} event type(s)`),e){b(s,t);return}l(),j("Webhook Event Types");let r=s.events.map(o=>[be.default.cyan(o.type),be.default.dim(o.description)]);G(["Event","Description"],r,[24,50]),l()}z();var Ae=N(F(),1);V();we();async function Qa(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
191
+ `),{chosen:ge,chosenResult:ie,searchAgain:P,allTaken:r.length===0&&o.length>0,expanded:p>0}}async function Wa(e,t,n){if(!e){Te||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:n.json});let P=await Ue({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(de(P)||!P)&&process.exit(0),e=P}let i=t.map(P=>P.replace(/^\./,"")),s=n.tlds?.split(",").map(P=>P.trim())||[],r=[...new Set([...i,...s])];if(r.length>0&&Di(r,n),Y(e,n),e.includes(".")&&r.length===0){let P=C(!n.json);P.start(`Checking ${v.domain(e)}`);let[ge,ie]=await Promise.all([xe(`/api/domains/search?q=${encodeURIComponent(e)}`),xe(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),A=await ge.json();if(ge.ok||(P.stop("Search failed"),u(A.error||A.message,{hint:A.hint,status:ge.status,json:n.json,fields:n.fields})),n.json){let W=A.domain.split(".")[0];b({name:W,results:[A],total:1,available:A.available?1:0},n.fields);return}if(on(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow("not in public DNS")}`),c(),console.log(` ${Or(A)}`),c();else if(Vt(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow(Bi)}`),c(),console.log(` ${A.reason}`),c();else if(gt(A))P.stop(`${y.warning} ${v.domain(A.domain)} ${y.dot} ${E.default.yellow(_n(A))}`),c(),console.log(` ${Ir(A)}`),c();else if(A.available)if(P.stop(`${y.success} ${v.domain(A.domain)} ${y.dot} available ${y.dot} ${E.default.green(it(A.price,A.renewal_price))}`),Te&&!n.json){let{buy:W}=await Promise.resolve().then(()=>($n(),Hn));await W([A.domain],{preChecked:{price:A.price,currency:A.currency,renewal_price:A.renewal_price}})}else c(),I("Register it:",`domani buy ${A.domain}`),c();else if(A.for_sale?.buyable)if(P.stop(`${y.info} ${v.domain(A.domain)} ${y.dot} ${E.default.cyan("for sale")} ${y.dot} ${v.price(A.for_sale.price)}`),Te&&!n.json){let{buy:W}=await Promise.resolve().then(()=>($n(),Hn));await W([A.domain],{preChecked:{price:A.for_sale.price,currency:A.for_sale.currency,marketplace:!0}})}else c(),I("Buy it:",`domani buy ${A.domain}`),c();else if(A.error)P.stop(`${E.default.dim("?")} ${v.domain(A.domain)} ${y.dot} ${E.default.dim("lookup failed")}`);else{let W;try{if(ie?.ok){let X=await ie.json();X?.title&&(W=X.title)}}catch{}let ne=W?` ${y.dot} ${E.default.dim(`"${W}"`)}`:"";P.stop(`${y.error} ${v.domain(A.domain)} ${y.dot} ${E.default.red("taken")}${ne}`)}return}let o=e.split(".")[0];if(Te&&!n.json&&r.length>0){let P=new URLSearchParams;P.set("domains",r.map(J=>`${o}.${J}`).join(",")),n.maxPrice&&P.set("max_price",n.maxPrice);let ge=await xe(`/api/domains/search?${P}`,{headers:{Accept:"text/event-stream"}});if(!ge.ok||!ge.body){u("Search failed",{json:n.json});return}let ie=[],A=new TextDecoder,W="",ne="",X=C(!0);X.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let J of ge.body){W+=A.decode(J,{stream:!0});let mn=W.split(`
192
+ `);W=mn.pop()??"";for(let ni of mn)if(ni.startsWith("event: "))ne=ni.slice(7);else if(ni.startsWith("data: ")&&ne==="result"){let qr=JSON.parse(ni.slice(6));an(ie,qr.domain),ie.push(qr)}}X.stop("");let ae=Math.max(...r.map(J=>`${o}.${J}`.length))+2,ke=ie.filter(J=>J.available),ye=ie.filter(on),te=ie.filter(Vt),me=ie.filter(gt),mt=ie.filter(J=>!J.available&&!J.error&&!on(J)&&!Vt(J)&&!gt(J)),Jt=ie.filter(J=>!J.available&&J.for_sale);for(let J of[...ke,...Jt,...me,...mt.filter(mn=>!mn.for_sale),...te,...ye])on(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow("not in public DNS")}`):Vt(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow(Bi)}`):gt(J)?console.log(` ${E.default.yellow("!")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.yellow(_n(J))}`):J.available?console.log(` ${E.default.green("\u2713")} ${E.default.bold(E.default.white(J.domain.padEnd(ae)))} ${E.default.green(it(J.price,J.renewal_price))}`):J.for_sale?console.log(` ${E.default.cyan("$")} ${E.default.bold(E.default.white(J.domain.padEnd(ae)))} ${E.default.cyan(v.price(J.for_sale.price))} ${E.default.dim("(for sale)")}`):console.log(` ${E.default.dim("\u2717")} ${E.default.dim(J.domain.padEnd(ae))} ${E.default.dim("taken")}`);if(ye.length>0||te.length>0||me.length>0){c();for(let J of me)console.log(` ${E.default.dim(Ir(J))}`);for(let J of te)console.log(` ${E.default.dim(J.reason??"")}`);for(let J of ye)console.log(` ${E.default.dim(Or(J))}`)}if(ke.length===0){console.log(` ${E.default.dim("No domains available")}`),c();return}let{buy:un}=await Promise.resolve().then(()=>($n(),Hn));if(ke.length===1){await un([ke[0].domain],{preChecked:{price:ke[0].price,currency:ke[0].currency,renewal_price:ke[0].renewal_price}});return}let{select:Sn,isCancel:nl}=await Promise.resolve().then(()=>(qe(),nr)),ti=await Sn({message:"Register one?",options:[...ke.map(J=>({value:J.domain,label:v.domain(J.domain),hint:it(J.price,J.renewal_price)})),{value:"__skip__",label:"Skip"}]});if(!nl(ti)&&ti!=="__skip__"){c();let J=ke.find(mn=>mn.domain===ti);await un([ti],{preChecked:J?{price:J.price,currency:J.currency,renewal_price:J.renewal_price}:void 0})}else c();return}if(Te&&!n.json){let P=await Va();for(n.expand&&P.length>kn&&console.error(E.default.dim(` (--expand: checking the first ${kn} of ${P.length} TLDs - server limit per request)`));;){let ge=n.expand?P.slice(0,kn):P.slice(0,Ze),ie=new URLSearchParams;ie.set("domains",ge.map(mt=>`${o}.${mt}`).join(",")),n.maxPrice&&ie.set("max_price",n.maxPrice);let A=C(!0);A.start(`Searching available domains for ${E.default.bold(o)}`);let W=await xe(`/api/domains/search?${ie}`,{headers:{Accept:"text/event-stream"}});if(!W.ok||!W.body){A.stop("Search failed");break}A.stop("");let ne=!n.expand,{chosen:X,chosenResult:ae,searchAgain:ke}=await Zu(W.body,o,n.all??!1,ne,P);if(X){c();let{buy:mt}=await Promise.resolve().then(()=>($n(),Hn)),Jt=ae?{price:ae.price,currency:ae.currency,renewal_price:ae.renewal_price}:void 0;await mt([X],{preChecked:Jt});return}if(!ke)break;let{text:ye,isCancel:te}=await Promise.resolve().then(()=>(qe(),nr)),me=await ye({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(te(me)||!me)break;o=me.split(".")[0]}c();return}let a=o,d=await Va(),m=r.length>0?r:n.expand?d.slice(0,kn):d.slice(0,Ze);n.expand&&r.length===0&&d.length>kn&&console.error(`(--expand: checking the first ${kn} of ${d.length} TLDs - server limit per request; use --tlds to target others)`);let f=m.map(P=>`${a}.${P}`),p=new URLSearchParams;p.set("domains",f.join(",")),n.maxPrice&&p.set("max_price",n.maxPrice);let g=C(!n.json);g.start(`Searching available domains for ${E.default.bold(a)}`);let $=await xe(`/api/domains/search?${p}`,{headers:{Accept:"text/event-stream"}});if(!$.ok){g.stop("Search failed");try{let P=await $.json();u(P.error||P.message||`Server error (${$.status})`,{hint:P.hint,status:$.status,json:n.json,fields:n.fields})}catch{u(`Server error (${$.status})`,{status:$.status,json:n.json,fields:n.fields})}}let _=$.body;_||(g.stop("Search failed"),u("Empty response",{code:"error",json:n.json,fields:n.fields}));let w=[],k=!1,S=0,O=!1,R=new Set,M=n.all??!1;function H(){k||(k=!0,g.stop(`Checking TLDs for ${E.default.bold(a)}`),c())}function ee(P){H(),on(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow("not in public DNS")}`),console.log(` ${E.default.dim(Or(P))}`)):Vt(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow(Bi)}`),console.log(` ${E.default.dim(P.reason??"")}`)):gt(P)?(console.log(` ${y.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow(_n(P))}`),console.log(` ${E.default.dim(Ir(P))}`)):P.available?console.log(` ${y.success} ${v.domain(P.domain).padEnd(37)} ${E.default.green(it(P.price,P.renewal_price))}`):P.for_sale?console.log(` ${y.info} ${v.domain(P.domain).padEnd(37)} ${E.default.cyan(v.price(P.for_sale.price))} ${E.default.dim("(for sale)")}`):P.error||console.log(` ${y.error} ${E.default.dim(P.domain.padEnd(38))} ${E.default.red("taken")}`)}function q(){k||g.message(`Checking TLDs for ${E.default.bold(a)} ${E.default.dim(`(${S} checked)`)}`)}let U=new TextDecoder,ce="",le="";for await(let P of _){ce+=U.decode(P,{stream:!0});let ge=ce.split(`
193
+ `);ce=ge.pop()??"";for(let ie of ge)if(ie.startsWith("event: "))le=ie.slice(7);else if(ie.startsWith("data: ")){let A=JSON.parse(ie.slice(6));if(le==="error")g.stop("Search failed"),u(A.message||A.error||"Search failed",{code:A.code||"error",json:n.json,fields:n.fields});else if(le==="result"){R.add(A.domain),S=R.size;let W=an(w,A.domain);(A.available||A.for_sale||M||on(A)||Vt(A)||gt(A))&&w.splice(W===-1?w.length:W,0,A),n.json||q()}else if(le==="done"){if(n.json){w.sort((ae,ke)=>ae.price-ke.price),b({name:a,results:w,total:A.total,available:A.available},n.fields);return}O=!0;for(let ae of w)ee(ae);k&&console.log(` ${E.default.dim("\u2500".repeat(50))}`);let W=A.total-A.available,ne=A.total>=5&&W/A.total>=.5,X=`Checked ${A.total} TLDs \xB7 ${A.available} available${ne?" \xB7 popular name":""}`;console.log(` ${E.default.dim(X)}`),A.available===0&&!n.expand&&r.length===0&&(c(),I("Try more TLDs:",`domani search ${a} --expand`))}}}if(!O&&!n.json)for(let P of w)ee(P);c()}$n();z();var Jn=N(F(),1);L();ve();qi();function Ha(e,t,n=process.env){let i=sn(t,n);if(i!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...i!==void 0?{webhook_headers:i}:{}},preview:{...e?{webhook_url:e}:{},...i!==void 0?{webhook_header_names:rn(i)}:{}}}}Ui();async function Ja(e,t){Y(e,t);let n={domain:e};t.slug&&(n.slug=t.slug),t.name&&(n.name=t.name);let i;try{i=Ha(t.webhook,t)}catch(m){u(m instanceof Error?m.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}Object.assign(n,i.request),t.years&&(n.years=Number(t.years));let s=nn(t.maxPrice,t);if(s!==void 0&&(n.max_price=s),t.paymentMethod&&(n.payment_method=t.paymentMethod),t.dryRun){let m={...n};delete m.webhook_headers,Object.assign(m,i.preview),K("POST /api/agents/provision",m,t.json,t.fields);return}let r=C(!t.json);r.start(`Provisioning ${v.domain(e)}`);let o=await x("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await o.json(),d=o.ok?void 0:Lt(a);if(d!==void 0&&(r.stop("Price changed - nothing was charged"),u(a.error,{code:"price_above_max",hint:cr(d),data:{price:d},json:t.json,fields:t.fields})),o.ok||(r.stop("Provisioning failed"),u(a.error||"Provisioning failed",{hint:a.hint,status:o.status,json:t.json,fields:t.fields})),r.stop(`${v.domain(e)} is ready`),t.json){b(a,t.fields);return}if(c(),j("Agent identity"),l("Domain",`${a.domain} (${a.domain_status})`),l("Mailbox",a.mailbox?Jn.default.green(a.mailbox.address):Jn.default.yellow("pending DNS")),l("Webhook",a.webhook?a.webhook.url:Jn.default.dim("none")),a.webhook?.header_names.length&&l("Webhook auth",a.webhook.header_names.join(", ")),a.webhook?.secret&&l("Signing secret",a.webhook.secret),a.warnings?.length){c();for(let m of a.warnings)ue(Jn.default.yellow(m))}if(a.next_steps?.length){c(),j("Next");for(let m of a.next_steps)ue(m)}c()}z();var Rt=N(F(),1);L();async function Ba(e){let t=C(!e.json);t.start("Loading domains");let n=await x("/api/domains"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${i.domains.length} domain(s)`),e.json){b({...i,count:i.domains.length},e.fields);return}if(i.domains.length===0){c(),console.log(` ${Rt.default.dim("No domains yet.")} Use: ${Rt.default.cyan("domani buy <domain>")}`),c();return}let s=[30,12,12,14];j(`Your Domains (${i.domains.length})`,s.reduce((o,a)=>o+a,0)+s.length-1);let r=i.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),d=o.status==="active"?Rt.default.green:o.status==="pending"?Rt.default.yellow:Rt.default.red,m=o.autoRenew?Rt.default.green("on"):Rt.default.dim("off");return[v.domain(o.domain),d(o.status),m,Rt.default.dim(a)]});B(["Domain","Status","Auto-renew","Expires"],r,s),c()}_r();z();var yt=N(F(),1);L();function Qu(e){let t=new URLSearchParams;return e.kind&&t.set("kind",e.kind),e.maxPrice&&t.set("max_price",e.maxPrice),e.minPrice&&t.set("min_price",e.minPrice),e.sort&&t.set("sort",e.sort),e.search&&t.set("search",e.search),e.limit&&t.set("limit",e.limit),t.set("order","asc"),t.toString()}function Ga(e){return e==="second_level"?"second level":e==="alt_root"?"alt root, no public DNS":"tld"}async function Ka(e){let t=C(!e.json);t.start("Loading TLDs");let n=await xe(`/api/tlds?${Qu(e)}`),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${i.total} TLDs loaded`),e.json){b(i,e.fields);return}let s=i.tlds;if(s.length===0){c(),console.log(` ${yt.default.dim("No TLDs match your filters.")}`),c();return}j("TLD Pricing");let r=s.map(o=>[yt.default.bold(`.${o.tld}`),v.price(o.registration.toFixed(2))+yt.default.dim("/yr"),yt.default.dim("renew ")+v.price(o.renewal.toFixed(2))+yt.default.dim("/yr"),o.kind==="alt_root"?yt.default.yellow(Ga(o.kind)):yt.default.dim(Ga(o.kind))]);B(["TLD","Register","Renewal","Kind"],r,[22,16,20,24]),c(),console.log(` ${yt.default.dim(`${i.total} TLDs total`)}`),s.some(o=>o.kind==="alt_root")&&console.log(` ${y.warning} ${yt.default.yellow("alt root names are outside the IANA root zone: they do not resolve in public DNS, and Domani does not sell them.")}`),c()}z();var Ee=N(F(),1);L();ve();async function za(e,t){Y(e,t);let n=C(!t.json);n.start(`Looking up ${v.domain(e)}`);let[i,s]=await Promise.all([xe(`/api/domains/whois?q=${encodeURIComponent(e)}`),xe(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await i.json(),o=null;try{s?.ok&&(o=await s.json())}catch{}if(i.ok||(n.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:i.status,json:t.json,fields:t.fields})),n.stop("WHOIS data retrieved"),t.json){b({...r,...o?{og:o}:{}},t.fields);return}if(j(`WHOIS ${v.domain(r.domain)}`),!r.registered){l("Status",`${y.success} ${Ee.default.green("not registered")}`),c(),I("Register it:",`domani buy ${r.domain}`),c();return}if(l("Status",`${y.error} ${Ee.default.red("registered")}`),(o?.title||o?.description)&&(c(),console.log(` ${Ee.default.bold("Website preview")}`),console.log(` ${Ee.default.dim("\u2500".repeat(50))}`),o.title&&l("Title",o.title),o.description&&l("Description",Ee.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),c()),r.registrar&&l("Registrar",r.registrar),r.created&&l("Created",r.created),r.expires&&l("Expires",r.expires),r.days_until_expiry!=null){let d=r.days_until_expiry,m=d<30?Ee.default.red:d<90?Ee.default.yellow:Ee.default.green;l("Days left",m(String(d)))}r.updated&&l("Updated",r.updated),l("DNSSEC",r.dnssec?Ee.default.green("yes"):Ee.default.dim("no")),r.nameservers?.length>0&&l("Nameservers",r.nameservers.map(d=>Ee.default.cyan(d)).join(Ee.default.dim(", "))),r.status?.length>0&&l("Status codes",Ee.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(c(),console.log(` ${Ee.default.bold("Registrant")}`),console.log(` ${Ee.default.dim("\u2500".repeat(50))}`),a.name&&l("Name",a.name),a.organization&&l("Organization",a.organization),a.email&&l("Email",v.url(a.email)),a.country&&l("Country",a.country)):r.redacted&&l("Contact",Ee.default.dim("redacted (WHOIS privacy)")),c()}z();qe();var bt=N(F(),1);L();ve();Ni();async function Ya(e,t){if(!e){Te||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let w=await Ue({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(de(w)||!w)&&process.exit(0),e=w}let n=new URLSearchParams({prompt:e});if(t.count&&n.set("count",t.count),t.tlds&&n.set("tlds",t.tlds),t.tlds&&Di(t.tlds.split(",").map(w=>w.trim()),t),t.style&&n.set("style",t.style),t.lang&&n.set("lang",t.lang),t.json){let w=C(!1);w.start("Finding available domains");let k=t.timeout?parseInt(t.timeout,10)*1e3:6e4,S;try{S=await xe(`/api/domains/suggest?${n}`,{signal:AbortSignal.timeout(k)})}catch{w.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:t.json,fields:t.fields})}let O=await S.json();S.ok||(w.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:S.status,json:t.json,fields:t.fields})),b(O,t.fields);return}let i=C(!0);i.start("Finding available domains");let s=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await xe(`/api/domains/suggest?${n}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(s)})}catch{i.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){i.stop("Failed");try{let w=await r.json();u(w.error||w.message||`Server error (${r.status})`,{hint:w.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(i.stop("Failed"),u("Empty response"));let a=[],d=[],m=!1,f=0;function p(){m||(m=!0,i.stop("Finding available domains"),c())}let g=new TextDecoder,$="",_="";for await(let w of o){$+=g.decode(w,{stream:!0});let k=$.split(`
194
+ `);$=k.pop()??"";for(let S of k)if(S.startsWith("event: "))_=S.slice(7);else if(S.startsWith("data: "))try{let O=JSON.parse(S.slice(6));if(_==="result")an(a,O.domain)!==-1||an(d,O.domain)!==-1||f++,O.available?a.push(O):d.push(O),m||i.message(`Finding available domains ${bt.default.dim(`(${f} checked, ${a.length} available)`)}`);else if(_==="iteration")m||i.message(`Finding available domains ${bt.default.dim(`(round ${O.n})`)}`);else if(_==="done"){p();for(let R of a){let M=R.reason?` ${bt.default.dim(R.reason)}`:"";console.log(` ${y.success} ${v.domain(R.domain).padEnd(37)} ${bt.default.green(it(R.price,R.renewal_price))}${M}`)}for(let R of d)console.log(` ${y.error} ${bt.default.dim(R.domain.padEnd(38))} ${gt(R)?bt.default.yellow(_n(R)):bt.default.red("taken")}`);console.log(` ${bt.default.dim("\u2500".repeat(50))}`),console.log(` ${bt.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else _==="error"&&(m||i.stop("Failed"),u(O.message))}catch{}}a.length===0&&d.length===0&&(m||i.stop("No results"),u("Could not find available domains for this prompt.")),c(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),c())}fr();jr();z();qe();var wt=N(F(),1);L();De();ve();In();async function Xa(e){let t=e.maxConsecutiveFailures??10,n=0;for(let i=1;i<=e.maxAttempts;i++){let s=await e.fetchPlan().catch(()=>null);if(e.onTick?.(s,i),s!==null){if(n=0,e.isEligible(s))return{status:"eligible",plan:s}}else if(n++,n>=t)return{status:"unreachable",failures:n};i<e.maxAttempts&&await e.sleep(e.intervalMs)}return{status:"timeout",attempts:e.maxAttempts}}var Bn=N(F(),1);L();function Gn(e){if(e){c(),console.log(` ${Bn.default.bold(`Exit path (${e.managed_via})`)}`),console.log(` ${Bn.default.dim("Unlock:")} ${e.unlock}`),console.log(` ${Bn.default.dim("Auth code:")} ${e.auth_code}`);for(let t of e.notes||[])console.log(` ${Bn.default.yellow("!")} ${t}`)}}var em=6e4,tm=1440;async function Za(e,t){Y(e,t);let n=C(!t.json);n.start(`Planning safe adoption for ${v.domain(e)}`);let i=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Check failed"),u(s.error,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),s.options?.transfer?.eligible)n.stop(`${y.success} Eligible for transfer`);else{n.stop(`${y.error} Not eligible`);let a=s.options?.transfer;if(t.watch&&a?.eligible_at){let d=await x("/api/domains/transfer-watch",{method:"POST",body:JSON.stringify({domain:e})}),m=await d.json();if(d.ok||u(m.error||m.message,{hint:m.hint,status:d.status,json:t.json,fields:t.fields}),t.json){b(m,t.fields);return}j("Transfer Watch Registered"),l("Domain",v.domain(e)),l("Eligible from",m.eligible_at||a.eligible_at),m.hint&&(c(),console.log(` ${wt.default.dim(m.hint)}`)),c();return}if(t.watch){t.json||(console.log(` ${wt.default.dim(a?.reason||"Domain is not eligible for transfer yet.")}`),Gn(a?.guidance),c());let d=C(!t.json);d.start(`Watching ${v.domain(e)} until it becomes transferable (every 60s, Ctrl+C to stop)`);let m=await Xa({fetchPlan:async()=>{let f=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`);return f.ok?f.json():null},isEligible:f=>!!f.options?.transfer?.eligible,sleep:f=>new Promise(p=>setTimeout(p,f)),intervalMs:em,maxAttempts:tm});m.status!=="eligible"&&(d.stop(`${y.error} Watch ended`),u(m.status==="timeout"?"Domain did not become eligible within 24 hours.":"Gave up after repeated failures fetching the adoption plan.",{hint:"The transfer lock is disabled at the losing registrar; rerun with --watch once you have flipped it.",code:m.status==="timeout"?"watch_timeout":"watch_unreachable",json:t.json,fields:t.fields})),s=m.plan,d.stop(`${y.success} Now eligible for transfer`)}else{t.json||Gn(a?.guidance);let d=a?.eligible_at?`Eligible from ${a.eligible_at}. Rerun with --watch to register a server watch (email + webhook when the date arrives).`:"Fix the blocker above, then rerun - or rerun with --watch to poll until the domain becomes eligible and continue automatically.",m=t.json&&a?.guidance?` The registrar exit playbook is in the adoption plan (options.transfer.guidance, \`domani adopt ${e} --json\`).`:"";u(a?.reason||"Domain is not eligible for transfer.",{hint:[d+m,...s.warnings?.length?[s.warnings.join(" ")]:[]].join(" "),code:"not_eligible",json:t.json,fields:t.fields})}}if(t.dryRun)return K("transfer",{domain:e,eligible:!0,price:s.options.transfer.price,currency:s.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:s.current.nameservers,dns_provider:s.current.dns_provider,dnssec_enabled:s.current.dnssec_enabled,acting_as:jt()},t.json,t.fields);if(!Ct(t)){j("Transfer Safety Plan"),l("Registrar",s.current.registrar||"Unknown"),l("DNS provider",s.current.dns_provider),l("Nameservers",`${s.current.nameservers.length} preserved`),l("DNSSEC",s.current.dnssec_enabled?wt.default.yellow("Enabled, DS will be verified"):"Not enabled"),l("DNS migration","Not requested"),c();let a=s.options.transfer.price!=null?` for ${v.price(s.options.transfer.price.toFixed(2))}`:"",d=await He({message:`Transfer ${wt.default.bold(e)} to ${pn}${a}${qt()}? Nameservers stay unchanged and 1 year is included.`});if(!d||typeof d=="symbol"){console.log(` ${wt.default.dim("Cancelled.")}`);return}}if(!t.authCode){(t.json||!process.stdout.isTTY)&&u("--auth-code is required",{hint:"The safety plan passed. Get the EPP/auth code from the current registrar and retry.",code:"validation_error",json:t.json,fields:t.fields}),s.options?.transfer?.guidance&&console.log(` ${wt.default.dim("Where to get it:")} ${s.options.transfer.guidance.auth_code}`);let a=await Ue({message:"Enter the EPP/auth code from your current registrar:",validate:d=>!d||d.trim().length===0?"Auth code is required":void 0});de(a)&&process.exit(0),t.authCode=a}n.start(`Initiating transfer for ${v.domain(e)}`);let r=await x("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:e,auth_code:t.authCode})}),o=await r.json();if(r.ok||(n.stop("Transfer failed"),u(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Transfer initiated`),t.json){b(o,t.fields);return}j("Transfer Initiated"),l("Domain",v.domain(o.domain)),l("Status",wt.default.yellow(o.status||"pending")),o.price&&l("Price",v.price(o.price)+wt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&l("Payment",o.payment_method),o.expires&&l("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(c(),console.log(` ${wt.default.dim(o.hint)}`)),c(),I("Check transfer progress:",`domani status ${o.domain}`),c()}z();var Kn=N(F(),1);L();ve();async function Qa(e,t){Y(e,t);let n=C(!t.json);n.start(`Inspecting ${v.domain(e)}`);let i=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Inspection failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Adoption plan ready`),t.json){b(s,t.fields);return}if(j(`Adopt ${v.domain(s.domain)}`),l("Registrar",s.current.registrar||"Unknown"),l("DNS provider",s.current.dns_provider),l("Nameservers",s.current.nameservers.join(", ")||"None detected"),l("DNSSEC",s.current.dnssec_enabled?Kn.default.yellow("Enabled"):"Not enabled"),l("Account",s.account_state),l("Recommended",Kn.default.cyan(s.recommended_action)),c(),s.recommended_action==="connect"&&I("Connect free, without changing registrar or DNS:",`domani import ${s.domain}`),s.options.transfer.available){let r=s.options.transfer.price==null?"price unavailable":`$${s.options.transfer.price.toFixed(2)} ${s.options.transfer.currency}`;I(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${s.domain}`),!s.options.transfer.eligible&&s.options.transfer.reason&&(console.log(` ${Kn.default.yellow("!")} ${s.options.transfer.reason}`),I("Wait for eligibility and transfer in one go:",`domani transfer ${s.domain} --watch`)),Gn(s.options.transfer.guidance)}for(let r of s.warnings||[])console.log(` ${Kn.default.yellow("!")} ${r}`);c()}z();qe();var xn=N(F(),1);L();De();ve();st();Ui();async function ed(e,t){e||(e=await be()),Y(e,t);let n=t.years?parseInt(t.years,10):1;(isNaN(n)||n<1||n>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields});let i=nn(t.maxPrice,t),s=`${n} year${n>1?"s":""}`,r=C(!t.json);r.start(`Checking ${v.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}`),a=await o.json();o.ok||(r.stop("Lookup failed"),u(a.error,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}));let d=typeof a.renewal_price=="number"?a.renewal_price:void 0,m=d!==void 0?Fn(d*n):void 0;r.stop(d!==void 0?`${y.success} ${v.domain(e)} ${y.dot} renews at ${v.price(d.toFixed(2))}/yr`:`${v.domain(e)} ${y.dot} ${xn.default.dim("renewal price unknown")}`);let f=i??m;if(t.dryRun)return K("renew",{domain:e,years:n,price:m,currency:"USD",max_price:f,acting_as:jt()},t.json,t.fields);if(!Ct(t)){let _=await He({message:m!==void 0?`Renew ${xn.default.bold(e)} for ${s} for ${v.price(m.toFixed(2))}${qt()}?`:`Renew ${xn.default.bold(e)} for ${s}${qt()}? You will be charged.`});if(!_||typeof _=="symbol"){console.log(` ${xn.default.dim("Cancelled.")}`);return}}let p,g,$;for(;;){$=C(!t.json),$.start(`Renewing ${v.domain(e)}`),p=await x(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:n,...f!==void 0?{max_price:f}:{}})}),g=await p.json();let _=p.ok?void 0:Lt(g);if(_===void 0)break;$.stop("Price changed");let w=await Ln(_,f??_,g,"Renew",t);if(w===void 0)return;f=w}if(p.ok||($.stop("Renewal failed"),u(g.error||g.message,{hint:g.hint,fixUrl:g.setup_url||g.payment_options?.card?.setup_url,status:p.status,json:t.json,fields:t.fields})),$.stop(`${y.success} Domain renewed`),t.json){b(g,t.fields);return}j("Renewal Complete"),l("Domain",v.domain(g.domain)),l("Years",String(g.renewed_years)),l("New expiry",new Date(g.new_expiry).toLocaleDateString()),g.price&&l("Price",v.price(g.price.toFixed(2))+xn.default.dim(` ${g.currency||"USD"}`)),g.payment_method&&l("Payment",g.payment_method),c(),I("Verify renewal:",`domani status ${g.domain}`),c()}z();var vt=N(F(),1);L();ve();async function td(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
195
+ domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t);let n=t.verify?"/api/domains/import/verify":"/api/domains/import",i=C(!t.json);i.start(t.verify?`Verifying ownership of ${v.domain(e)}`:`Initiating import for ${v.domain(e)}`);let s=await x(n,{method:"POST",body:JSON.stringify({domain:e})}),r=await s.json();if(s.ok||(i.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),b(r,t.fields);return}t.verify?(i.stop(`${y.success} ${v.domain(e)} imported!`),j("Domain Imported"),l("Domain",v.domain(r.domain)),l("Status",vt.default.green(r.status||"active")),r.expires_at&&l("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&l("Registrar",r.registrar),c(),I("Check domain health:",`domani status ${r.domain}`),c()):(i.stop(`${y.success} Verification record ready`),j("Import Domain"),l("Domain",v.domain(r.domain)),l("Status",vt.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),console.log(` ${vt.default.dim("Type:")} ${vt.default.bold("TXT")}`),console.log(` ${vt.default.dim("Name:")} ${vt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${vt.default.dim("Value:")} ${vt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),c(),console.log(` ${vt.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),I("Once the record is set, verify:",`domani import ${e} --verify`),c())}vr();De();L();function nd(e){let t=at();if(t||(c(),u("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:e.json})),!e.reveal&&!e.json&&process.stdout.isTTY){let n=`${t.slice(0,12)}...${t.slice(-4)}`;console.log(n),console.log("Run 'domani token --reveal' to print the full key.");return}e.json?b({token:t}):console.log(t)}z();var We=N(F(),1);L();async function id(e,t){switch(e){case void 0:case"list":return nm(t.json,t.fields);case"create":return im(t);case"revoke":return sm(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function nm(e,t){let n=C(!e);n.start("Loading tokens");let i=await x("/api/tokens"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.tokens.length} token(s)`),e){b(s,t);return}if(s.tokens.length===0){c(),console.log(` ${We.default.dim("No tokens.")}`),c(),I("Create one:",'domani tokens create --name "My App"'),c();return}c(),j("API Tokens");let r=s.tokens.map(o=>{let a;o.expired?a=We.default.red("Expired"):o.expiresAt?a=We.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=We.default.dim("No expiration");let d=o.scopes.includes("*")?We.default.dim("all"):We.default.dim(o.scopes.join(", "));return[We.default.dim(o.id),We.default.bold(o.name),o.agent_identity?We.default.dim(o.agent_identity.name||o.agent_identity.slug):We.default.dim("-"),d,a]});B(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),c()}async function im(e){let t={};if(e.name&&(t.name=e.name),e.scopes&&(t.scopes=e.scopes.split(",").map(r=>r.trim())),e.expiresIn){let r=Number(e.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&u("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:e.json,fields:e.fields}),t.expires_in=r}e.agentIdentity&&(t.agent_identity_id=e.agentIdentity);let n=C(!e.json);n.start("Creating token");let i=await x("/api/tokens",{method:"POST",body:JSON.stringify(t)}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Token created`),e.json){b(s,e.fields);return}c(),j("Token Created"),l("ID",s.id),l("Name",s.name),l("Scopes",s.scopes?.includes("*")?"All (full access)":s.scopes?.join(", ")||"All"),s.agent_identity&&l("Agent",s.agent_identity.name||s.agent_identity.slug),l("Expires",s.expiresAt?new Date(s.expiresAt).toLocaleString():"Never"),c(),console.log(` ${We.default.yellow("!")} ${We.default.bold("Key:")} ${s.key}`),console.log(` ${We.default.dim("Save this key - it will not be shown again.")}`),c()}async function sm(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
196
+ Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=C(!e.json);t.start("Revoking token");let n=await x(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Token revoked`),e.json){b(i,e.fields);return}console.log(` ${We.default.dim("Any applications using this key will need a new one.")}`),c()}z();var Pe=N(F(),1);L();ve();st();async function sd(e,t){e||(e=await be()),Y(e,t);let n=t.autoRenew!==void 0,i=t.whoisPrivacy!==void 0,s=t.securityLock!==void 0;if(!n&&!i&&!s)return rm(e,t.json,t.fields);let r={};if(n){let m=Ar(t.autoRenew);m===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=m}if(i){let m=Ar(t.whoisPrivacy);m===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=m}if(s){let m=Ar(t.securityLock);m===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=m}if(t.dryRun)return K("settings_update",{domain:e,...r},t.json,t.fields);let o=C(!t.json);o.start(`Updating ${v.domain(e)}`);let a=await x(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${y.success} Settings updated`),t.json){b(d,t.fields);return}j("Settings Updated"),l("Domain",v.domain(d.domain)),d.auto_renew!==void 0&&l("Auto-renew",d.auto_renew?Pe.default.green("on"):Pe.default.dim("off")),d.whois_privacy!==void 0&&l("WHOIS privacy",d.whois_privacy?Pe.default.green("on"):Pe.default.dim("off")),d.security_lock!==void 0&&l("Security lock",d.security_lock?Pe.default.green("locked"):Pe.default.dim("unlocked")),d.hint&&l("",Pe.default.dim(d.hint)),c()}async function rm(e,t,n){let i=C(!t);i.start(`Loading ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop(`${y.success} ${v.domain(e)}`),t){b(r,n);return}j("Domain Settings"),l("Domain",v.domain(r.domain)),l("Status",r.status==="active"?Pe.default.green(r.status):Pe.default.yellow(r.status)),l("Auto-renew",r.auto_renew?Pe.default.green("on"):Pe.default.dim("off")),r.registrar&&(l("WHOIS privacy",r.registrar.whois_privacy?Pe.default.green("on"):Pe.default.dim("off")),l("Security lock",r.registrar.security_lock?Pe.default.green("locked"):Pe.default.dim("unlocked"))),l("Expires",new Date(r.expires_at).toLocaleDateString()+Pe.default.dim(` (${r.days_until_expiry} days)`)),c(),I("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),I("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),I("Toggle security lock:",`domani settings ${e} --security-lock off`),I("Get transfer auth code:",`domani auth-code ${e}`),c()}function Ar(e){let t=e.toLowerCase();return t==="on"||t==="true"||t==="1"||t==="enable"?!0:t==="off"||t==="false"||t==="0"||t==="disable"?!1:null}z();var Tt=N(F(),1);L();ve();st();async function rd(e,t){e||(e=await be()),Y(e,t);let n=C(!t.json);n.start(`Getting auth code for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/auth-code`),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields}));let r=s.status==="requested";if(n.stop(r?`${y.success} Auth code requested`:`${y.success} Auth code retrieved`),t.json){b(s,t.fields);return}if(r){j("Auth Code"),l("Domain",v.domain(s.domain)),l("Status",Tt.default.yellow("Requested")),s.expected_by&&l("Ready by",new Date(s.expected_by).toLocaleString()),s.hint&&(c(),console.log(` ${Tt.default.dim(s.hint)}`)),c(),I("Read the code once you get the email:",`domani auth-code ${e}`),c();return}if(j("Auth Code"),l("Domain",v.domain(s.domain)),l("Auth code",Tt.default.bold(Tt.default.green(s.auth_code))),s.was_unlocked&&l("",Tt.default.yellow("Domain was automatically unlocked to allow transfer.")),s.hint&&(c(),console.log(` ${Tt.default.dim(s.hint)}`)),s.next_steps?.length){c();for(let o of s.next_steps)console.log(` ${Tt.default.dim("\u2192")} ${Tt.default.dim(o)}`)}c(),I("Check transfer status:",`domani transfer-away ${e}`),I("Re-lock domain:",`domani settings ${e} --security-lock on`),c()}z();var Et=N(F(),1);L();ve();st();var om={none:Et.default.dim,pending:Et.default.yellow,approved:Et.default.yellow,completed:Et.default.green,rejected:Et.default.red,expired:Et.default.red};async function od(e,t){e||(e=await be()),Y(e,t);let n=C(!t.json);n.start(`Checking transfer status for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/transfer-away`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} ${v.domain(e)}`),t.json){b(s,t.fields);return}j("Transfer Away Status"),l("Domain",v.domain(s.domain));let r=om[s.status]||Et.default.dim;l("Status",r(s.status)),s.gaining_registrar&&l("New registrar",s.gaining_registrar),s.request_date&&l("Requested",new Date(s.request_date).toLocaleDateString()),s.hint&&(c(),console.log(` ${Et.default.dim(s.hint)}`)),c(),s.status==="none"?I("Get auth code to start:",`domani auth-code ${e}`):s.status==="pending"||s.status==="approved"?I("Check again later:",`domani transfer-away ${e}`):s.status==="completed"?I("Search for a new domain:","domani search <name>"):(s.status==="rejected"||s.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${e}`),c()}z();qe();var Gi=N(F(),1);L();async function ad(e,t){return e==="set"?dm(t):am(t)}async function am(e){let t=C(!e.json);t.start("Loading contact info");let n=await x("/api/me/contact"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Contact info`),e.json){b(i,e.fields);return}if(j("Contact Info"),!i.has_contact){console.log(` ${y.warning} ${Gi.default.yellow("No contact info set.")} Run ${Gi.default.bold("domani contact set")} to add.`),c(),console.log(` ${Gi.default.dim("Contact info is required before purchasing domains.")}`),c();return}let s=i.contact;l("Name",`${s.first_name} ${s.last_name}`),s.org_name&&l("Organization",s.org_name),l("Address",s.address1),s.address2&&l("",s.address2),l("",`${s.city}, ${s.state} ${s.postal_code}`),l("Country",s.country),l("Phone",s.phone),l("Email",s.email),c()}async function dm(e){let t={},n=e.firstName||e.lastName||e.address1;if(!Te&&!n&&u("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:e.json}),n){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],d={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"},m=a.filter(f=>!e[f]);m.length>0&&u(`Missing required flags: ${m.map(f=>`--${f.replace(/[A-Z]/g,p=>`-${p.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[f,p]of Object.entries(d)){let g=e[f];g&&(t[p]=g)}}else{let a=await x("/api/me/contact"),m=(a.ok?await a.json():null)?.contact,f=[{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 p of f){let g=m?.[p.key]||"",$=await Ue({message:p.message,placeholder:p.placeholder,defaultValue:g,validate:p.required?w=>w?.trim()?void 0:`${p.message} is required`:void 0});de($)&&process.exit(0);let _=$.trim();_&&(t[p.key]=_)}}if(e.dryRun)return K("contact_set",t,e.json,e.fields);let i=C(!e.json);i.start("Saving contact info");let s=await x("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Contact info saved`),e.json){b(r,e.fields);return}j("Contact Saved");let o=r.contact;l("Name",`${o.first_name} ${o.last_name}`),o.org_name&&l("Organization",o.org_name),l("Address",o.address1),o.address2&&l("",o.address2),l("",`${o.city}, ${o.state} ${o.postal_code}`),l("Country",o.country),l("Phone",o.phone),l("Email",o.email),c(),I("Search for a domain:","domani search <name>"),c()}z();var Fe=N(F(),1);L();ve();st();async function cd(e,t,n,i){if(e||(e=await be()),Y(e,i),!t)return lm(e,i.json,i.fields);switch(t){case"enable":case"on":return i.dryRun?K("parking_enable",{domain:e},i.json,i.fields):dd(e,!0,i.json,i.fields);case"disable":case"off":return i.dryRun?K("parking_disable",{domain:e},i.json,i.fields):dd(e,!1,i.json,i.fields);case"price":{n||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:i.json,fields:i.fields});let s=parseFloat(n);return(isNaN(s)||s<=0)&&u("Price must be a positive number",{hint:`Got: "${n}"`,code:"validation_error",json:i.json,fields:i.fields}),i.dryRun?K("parking_price",{domain:e,price:s},i.json,i.fields):ld(e,s,i.json,i.fields)}case"unprice":case"unlist":return i.dryRun?K("parking_unlist",{domain:e},i.json,i.fields):ld(e,null,i.json,i.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:i.json,fields:i.fields})}}async function lm(e,t,n){let i=C(!t);i.start(`Loading ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:n})),i.stop(`${y.success} ${v.domain(e)}`),t){b({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},n);return}j("Parking"),l("Domain",v.domain(r.domain)),l("Parking",r.parking_enabled?Fe.default.green("enabled"):Fe.default.dim("disabled")),l("Listing",r.listing_price?`${v.price(r.listing_price)} ${Fe.default.dim("(for sale)")}`:Fe.default.dim("not listed")),c(),I("Enable parking:",`domani parking ${e} enable`),I("Set sale price:",`domani parking ${e} price 499`),I("View analytics:",`domani analytics ${e}`),c()}async function dd(e,t,n,i){let s=C(!n);s.start(`${t?"Enabling":"Disabling"} parking for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(s.stop(`${y.warning} DNS records will be replaced`),n){b(o,i);return}console.log(`
197
+ ${Fe.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${Fe.default.dim(a.type)} ${a.name} ${Fe.default.dim("\u2192")} ${a.value}`);console.log(`
198
+ ${Fe.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Fe.default.dim("Or use the dashboard to confirm.")}`),c();return}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n,fields:i})),s.stop(`${y.success} Parking ${t?"enabled":"disabled"}`),n){b(o,i);return}j("Parking Updated"),l("Domain",v.domain(o.domain)),l("Parking",o.parking_enabled?Fe.default.green("enabled"):Fe.default.dim("disabled")),o.hint&&l("",Fe.default.dim(o.hint)),c()}async function ld(e,t,n,i){let s=C(!n);s.start(t!==null?`Setting price for ${v.domain(e)} to ${v.price(t)}`:`Removing listing for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n,fields:i})),s.stop(`${y.success} ${t!==null?"Price set":"Listing removed"}`),n){b(o,i);return}j("Listing Updated"),l("Domain",v.domain(o.domain)),l("Listing",o.listing_price?`${v.price(o.listing_price)} ${Fe.default.dim("(for sale)")}`:Fe.default.dim("not listed")),o.hint&&l("",Fe.default.dim(o.hint)),c()}z();var Qe=N(F(),1);L();ve();st();var cm=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function um(e){let t=Math.max(...e,1);return e.map(n=>cm[Math.min(Math.round(n/t*8),8)]).join("")}async function ud(e,t){e||(e=await be()),Y(e,t);let n=C(!t.json);n.start(`Loading analytics for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/analytics`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop("Analytics loaded"),t.json){b(s,t.fields);return}if(c(),j(`Analytics: ${v.domain(e)}`),l("Views (7d)",Qe.default.cyan(s.views_7d.toLocaleString())),l("Views (30d)",Qe.default.cyan(s.views_30d.toLocaleString())),l("Inquiries",Qe.default.cyan(String(s.inquiries_30d))),l("Conversion",s.conversion_rate>0?Qe.default.green(`${s.conversion_rate}%`):Qe.default.dim("0%")),s.daily_views&&s.daily_views.length>0){let r=s.daily_views.map(m=>m.views),o=um(r),a=s.daily_views[0].date.slice(5),d=s.daily_views[s.daily_views.length-1].date.slice(5);c(),console.log(` ${Qe.default.dim(a)} ${Qe.default.cyan(o)} ${Qe.default.dim(d)}`)}if(s.recent_inquiries&&s.recent_inquiries.length>0){c(),console.log(` ${Qe.default.bold("Recent Inquiries")}`);let r=s.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())]);B(["Email","Offer","Date"],r,[30,12,14])}c(),I("Set a listing price:",`domani parking ${e} price <amount>`),I("Set up email:",`domani email setup ${e}`),I("Domain settings:",`domani settings ${e}`),c()}z();var we=N(F(),1);L();qi();async function md(e,t){switch(e){case void 0:case"list":return fm(t.json,t.fields);case"create":return pm(t);case"update":return hm(t);case"delete":return gm(t);case"deliveries":return ym(t);case"replay":return mm(t);case"events":return bm(t.json,t.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, update, delete, deliveries, replay, events",code:"validation_error",json:t.json,fields:t.fields})}}async function mm(e){(!e.webhookId||!e.deliveryId||!e.idempotencyKey)&&u("Webhook ID, delivery ID, and idempotency key are required",{hint:"Usage: domani webhooks replay --webhook-id <id> --delivery-id <id> --idempotency-key <stable-key>",code:"validation_error",json:e.json,fields:e.fields});let t=C(!e.json);t.start("Replaying webhook delivery");let n=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook replay ${i.status}`),e.json)return b(i,e.fields);j("Webhook Replay Receipt"),l("Delivery",i.delivery_id),l("Original",i.original_delivery_id),l("Status",i.status),l("Attempts",i.attempts),l("Idempotent retry",i.idempotent_replay?"yes":"no"),c()}async function fm(e,t){let n=C(!e);n.start("Loading webhooks");let i=await x("/api/webhooks"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.webhooks.length} webhook(s)`),e){b(s,t);return}if(s.webhooks.length===0){c(),console.log(` ${we.default.dim("No webhooks configured.")}`),c(),I("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),I("List events:","domani webhooks events"),c();return}c(),j("Webhooks");let r=s.webhooks.map(o=>[we.default.dim(o.id),v.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||we.default.dim("none"),o.active?we.default.green("active"):we.default.dim("paused")]);B(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),c()}async function pm(e){e.url||u("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:e.json,fields:e.fields}),e.events||u("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
199
+ Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:e.json,fields:e.fields});let t=e.events.split(",").map(o=>o.trim()),n;try{n=sn(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun)return K("webhook_create",{url:e.url,events:t,header_names:rn(n)},e.json,e.fields);let i=C(!e.json);i.start("Creating webhook");let s=await x("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...n!==void 0?{headers:n}:{}})}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Webhook created`),e.json){b(r,e.fields);return}c(),j("Webhook Created"),l("ID",r.id),l("URL",v.url(r.url)),l("Events",r.events.join(", ")),l("Auth headers",r.header_names?.join(", ")||we.default.dim("none")),l("Status",we.default.green("active")),c(),console.log(` ${we.default.yellow("!")} ${we.default.bold("Secret:")} ${r.secret}`),console.log(` ${we.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${we.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),c()}async function hm(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:e.json,fields:e.fields});let t={};e.url&&(t.url=e.url),e.events&&(t.events=e.events.split(",").map(r=>r.trim())),e.active!==void 0&&(t.active=e.active==="on"||e.active==="true");try{let r=sn(e);r!==void 0&&(t.headers=r)}catch(r){u(r instanceof Error?r.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun){let{headers:r,...o}=t;return K("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:rn(r)}:{}},e.json,e.fields)}let n=C(!e.json);n.start("Updating webhook");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} Webhook updated`),e.json){b(s,e.fields);return}j("Webhook Updated"),l("ID",s.id),l("URL",v.url(s.url)),l("Events",s.events.join(", ")),l("Auth headers",s.header_names?.join(", ")||we.default.dim("none")),l("Status",s.active?we.default.green("active"):we.default.dim("paused")),c()}async function gm(e){if(e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return K("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=C(!e.json);t.start("Deleting webhook");let n=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook deleted`),e.json){b(i,e.fields);return}console.log(` ${we.default.dim("Pending deliveries have been cancelled.")}`),c()}async function ym(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let t=e.limit?`?limit=${e.limit}`:"",n=C(!e.json);n.start("Loading deliveries");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),n.stop(`${y.success} ${s.deliveries.length} delivery(ies)`),e.json){b(s,e.fields);return}if(s.deliveries.length===0){c(),console.log(` ${we.default.dim("No deliveries yet.")}`),c();return}c(),j("Deliveries");let r=s.deliveries.map(o=>{let a=o.status==="delivered"?we.default.green("delivered"):o.status==="failed"?we.default.red("failed"):we.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):we.default.dim("-"),String(o.attempts),we.default.dim(new Date(o.created_at).toLocaleString())]});B(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),c()}async function bm(e,t){let n=C(!e);n.start("Loading event types");let i=await xe("/api/webhooks/events"),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e,fields:t})),n.stop(`${y.success} ${s.events.length} event type(s)`),e){b(s,t);return}c(),j("Webhook Event Types");let r=s.events.map(o=>[we.default.cyan(o.type),we.default.dim(o.description)]);B(["Event","Description"],r,[24,50]),c()}z();var Ie=N(F(),1);L();ve();async function fd(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
200
200
  domani sell <domain> --verify
201
201
  domani sell <domain> --status
202
- domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t),t.status)return nm(e,t);if(t.verify)return tm(e,t);if(t.cancel)return im(e,t);if(t.transferCode)return sm(e,t.transferCode,t);if(t.price)return em(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
202
+ domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t),t.status)return $m(e,t);if(t.verify)return vm(e,t);if(t.cancel)return km(e,t);if(t.transferCode)return _m(e,t.transferCode,t);if(t.price)return wm(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
203
203
  domani sell <domain> --verify
204
204
  domani sell <domain> --status
205
205
  domani sell <domain> --cancel
206
- domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function em(e,t){let n=parseFloat(t.price);(isNaN(n)||n<=0)&&u("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:t.json,fields:t.fields});let i=O(!t.json);i.start(`Listing ${v.domain(e)} for sale`);let s={domain:e,price:n};t.description&&(s.description=t.description);let r=await x("/api/domains/sell",{method:"POST",body:JSON.stringify(s)}),o=await r.json();if(r.ok||(i.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){i.stop(""),b(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(i.stop(`${y.success} Listed for sale`),j("Sell Domain"),c("Domain",v.domain(o.listing?.domain||e)),c("Price",v.price(n)),c("Status",Ae.default.green("active")),l(),console.log(` ${Ae.default.dim("Your listing is live on the marketplace.")}`),l()):(i.stop(`${y.success} Verification record ready`),j("Sell Domain"),c("Domain",v.domain(o.listing?.domain||e)),c("Price",v.price(n)),c("Status",Ae.default.yellow("pending verification")),l(),console.log(" Add this TXT record at your DNS provider:"),l(),console.log(` ${Ae.default.dim("Type:")} ${Ae.default.bold("TXT")}`),console.log(` ${Ae.default.dim("Name:")} ${Ae.default.bold(o.txt_record?.name||"@")}`),console.log(` ${Ae.default.dim("Value:")} ${Ae.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),l(),console.log(` ${Ae.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),l(),I("Once the record is set, verify:",`domani sell ${e} --verify`),l())}async function tm(e,t){let n=O(!t.json);n.start(`Verifying ownership of ${v.domain(e)}`);let i=await x("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),s=await i.json();if(i.ok||(n.stop("Verification failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),t.json){n.stop(""),b(s,t.fields);return}n.stop(`${y.success} ${v.domain(e)} is now listed for sale!`),j("Domain Listed"),c("Domain",v.domain(s.domain||e)),c("Status",Ae.default.green(s.status||"active")),s.price&&c("Price",v.price(s.price)),l(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),l()}async function nm(e,t){let n=O(!t.json);n.start(`Checking listing status for ${v.domain(e)}`);let i=await x(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Listing status loaded`),t.json){b(s,t.fields);return}let r=s.listing;if(j("Listing Status"),c("Domain",v.domain(s.domain||e)),r){let o=r.status;c("Status",o==="active"?Ae.default.green(o):Ae.default.yellow(o||"unknown")),r.price&&c("Price",v.price(r.price)),r.description&&c("Description",r.description),r.created_at&&c("Listed",Ae.default.dim(new Date(r.created_at).toLocaleDateString()))}else c("Status",Ae.default.dim("No listing found"));s.deal&&c("Deal",`${s.deal.status} ($${s.deal.price})`),l()}async function im(e,t){let n=O(!t.json);n.start(`Removing ${v.domain(e)} from sale`);let i=await x(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),t.json){n.stop(""),b(s,t.fields);return}n.stop(`${y.success} ${v.domain(e)} removed from sale`),l()}async function sm(e,t,n){let i=O(!n.json);i.start(`Looking up active deal for ${v.domain(e)}`);let s=await x(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await s.json();s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:n.json,fields:n.fields}));let a=(r.deals||r.data||[]).filter(p=>p.domain.toLowerCase()===e.toLowerCase());a.length===0&&(i.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
207
- Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:n.json,fields:n.fields}));let d=a[0].id;i.message(`Submitting transfer code for deal ${Ae.default.dim(d)}`);let m=await x(`/api/deals/${encodeURIComponent(d)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),f=await m.json();if(m.ok||(i.stop("Failed"),u(f.error||f.message,{hint:f.hint,status:m.status,json:n.json,fields:n.fields})),n.json){i.stop(""),b(f,n.fields);return}i.stop(`${y.success} Transfer code submitted for ${v.domain(e)}`),j("Transfer Code Submitted"),c("Domain",v.domain(e)),c("Deal",Ae.default.dim(d)),c("Status",Ae.default.green(f.status||"code_submitted")),l(),I("Track the deal:",`domani deals ${d}`),l()}z();var xe=N(F(),1);V();async function ed(e,t){return e?am(e,t):om(t)}function rm(e){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function om(e){let t=O(!e.json);t.start("Loading deals");let n=rm(e),i=await x(`/api/deals${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.deals||s.data||[];if(t.stop(`${y.success} ${r.length} deal(s)`),e.json){b(s,e.fields);return}if(r.length===0){l(),console.log(` ${xe.default.dim("No deals found.")}`),l(),I("List a domain for sale:","domani sell <domain> --price <amount>"),l();return}l(),j("Deals");let o=r.map(a=>{let d=a.status==="completed"?xe.default.green:a.status==="active"?xe.default.cyan:a.status==="cancelled"?xe.default.red:xe.default.yellow;return[v.domain(a.domain),v.price(a.price),d(a.status),xe.default.dim(a.role||"-"),xe.default.dim(new Date(a.created_at).toLocaleDateString())]});G(["Domain","Price","Status","Role","Created"],o,[28,12,14,10,14]),l(),s.next_cursor&&(console.log(` ${xe.default.dim(`More: --cursor ${s.next_cursor}`)}`),l())}async function am(e,t){let n=O(!t.json);n.start(`Loading deal ${xe.default.dim(e)}`);let i=await x(`/api/deals/${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Deal loaded`),t.json){b(s,t.fields);return}let r=s.deal||s;j("Deal Details"),c("ID",xe.default.dim(r.id)),c("Domain",v.domain(r.domain)),c("Price",v.price(r.price));let o=r.status==="completed"?xe.default.green:r.status==="active"?xe.default.cyan:r.status==="cancelled"?xe.default.red:xe.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",xe.default.dim(r.buyer)),r.seller&&c("Seller",xe.default.dim(r.seller)),r.created_at&&c("Created",xe.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",xe.default.dim(new Date(r.updated_at).toLocaleDateString())),l();let a=r.events||[];if(a.length>0){j("Timeline");for(let d of a){let m=xe.default.dim(new Date(d.created_at).toLocaleString()),f=d.status==="completed"?y.success:d.status==="expired"||d.status==="refunded"?y.error:y.info;console.log(` ${f} ${m} ${d.detail||d.status}`)}l()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),l())}z();var He=N(F(),1);V();we();async function id(e,t,n){switch(e){case void 0:case"list":case"ls":return dm(n);case"request":case"acquire":case"new":return td(t,n);case"status":case"get":return nd(t,n);case"cancel":case"rm":return lm(t,n);default:return e.includes(".")?td(e,n):nd(e,n)}}async function td(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),Y(e,{json:t.json});let n=O(!t.json);n.start(`Requesting acquisition of ${v.domain(e)}`);let i={domain:e};if(t.maxBudget){let a=Number(t.maxBudget);(!Number.isFinite(a)||a<=0)&&u("--max-budget must be a positive number (USD).",{json:t.json}),i.max_budget=a}let s=await x("/api/broker",{method:"POST",body:JSON.stringify(i)}),r=await s.json();s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.request||r;if(n.stop(`${y.success} Acquisition requested`),t.json)return b(r,t.fields);j("Broker request"),c("Domain",v.domain(o.domain)),c("Status",Sr(o.status)),o.max_budget!=null&&c("Max budget",v.price(o.max_budget)),c("ID",He.default.dim(o.id)),l(),console.log(` ${He.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),l(),I("Check progress:",`domani broker status ${o.id}`),l()}async function dm(e){let t=O(!e.json);t.start("Loading broker requests");let n=e.status?`?status=${encodeURIComponent(e.status)}`:"",i=await x(`/api/broker${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.requests||s.data||[];if(t.stop(`${y.success} ${r.length} request(s)`),e.json)return b(s,e.fields);if(r.length===0){l(),console.log(` ${He.default.dim("No broker requests yet.")}`),l(),I("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),l();return}l(),j("Broker requests"),G(["Domain","Status","Budget","ID"],r.map(o=>[v.domain(o.domain),Sr(o.status),o.max_budget!=null?v.price(o.max_budget):He.default.dim("-"),He.default.dim(o.id)])),l()}async function nd(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let n=O(!t.json);n.start("Loading request");let i=await x(`/api/broker/${encodeURIComponent(e)}`),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields}));let r=s.request||s;if(n.stop(`${y.success} ${v.domain(r.domain)}`),t.json)return b(s,t.fields);j("Broker request"),c("Domain",v.domain(r.domain)),c("Status",Sr(r.status)),r.max_budget!=null&&c("Max budget",v.price(r.max_budget)),c("Contacted",r.contacted?He.default.green("yes"):He.default.dim("not yet")),r.failure_reason&&c("Reason",He.default.yellow(r.failure_reason)),c("ID",He.default.dim(r.id)),l(),r.negotiation_id?(console.log(` ${He.default.dim("The owner responded - an anonymous negotiation is open.")}`),l(),I("Review the offer:","domani deals"),l()):["sourcing","contacted","negotiating"].includes(r.status)&&(I("Cancel this request:",`domani broker cancel ${r.id}`),l())}async function lm(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let n=O(!t.json);n.start("Cancelling request");let i=await x(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Request cancelled`),t.json)return b(s,t.fields);l()}function Sr(e){return["completed","agreed"].includes(e)?He.default.green(e):["negotiating","contacted","sourcing"].includes(e)?He.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?He.default.dim(e):e}z();var Qe=N(F(),1);V();we();var cm={registered:Qe.default.dim,expiring:Qe.default.yellow,expired:Qe.default.yellow,redemption:Qe.default.red,pending_delete:Qe.default.red,available:Qe.default.green,unknown:Qe.default.dim};function um(e){return e==="pending_delete"?"pending delete":e==="unknown"?"checking":e}function sd(e){return(cm[e]??Qe.default.dim)(um(e))}function rd(e){return e?e.slice(0,10):"-"}function od(e){if(!e)return"-";let t=e.source||"for sale";return e.price!=null?`${t} $${e.price}`:t}function mm(e){return e.code==="WATCHLIST_LIMIT"?"limit_reached":void 0}async function ad(e,t){if(Y(e,t),t.dryRun)return K("follow",{domain:e},t.json,t.fields);let n=O(!t.json);n.start(`Following ${v.domain(e)}`);let i=await x("/api/watchlist",{method:"POST",body:JSON.stringify({domain:e})}),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,code:mm(s),json:t.json,fields:t.fields}));let r=s.watch;if(n.stop(i.status===201?`${y.success} Following ${v.domain(r.domain)}`:`${y.success} Already following ${v.domain(r.domain)}`),t.json){b(s,t.fields);return}l(),c("Now",sd(r.phase)),r.expires_at&&c("Expires",rd(r.expires_at)),r.for_sale&&c("For sale",od(r.for_sale)),l(),console.log(` ${Qe.default.dim("You get an alert in the app and by email at each next step, until it drops.")}`),r.phase==="available"?I("It is free now. Register it:",`domani buy ${r.domain}`):I("See every name you follow:","domani watchlist"),l()}async function dd(e,t){if(Y(e,t),t.dryRun)return K("unfollow",{domain:e},t.json,t.fields);let n=O(!t.json);n.start(`Unfollowing ${v.domain(e)}`);let i=await x(`/api/watchlist/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} No longer following ${v.domain(e)}`),t.json&&b(s,t.fields)}async function ld(e){let t=O(!e.json);t.start("Loading the names you follow");let n=await x("/api/watchlist"),i=await n.json();n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}));let s=i.watches||[];if(t.stop(`${y.success} ${s.length} followed`),e.json){b(i,e.fields);return}if(s.length===0){l(),console.log(` ${Qe.default.dim("You follow no names yet.")}`),l(),I("Follow a taken name for free:","domani follow <domain>"),l();return}j("Names you follow"),G(["Domain","Now","Expires","For sale","Backorder"],s.map(r=>[v.domain(r.domain),sd(r.phase),rd(r.expires_at),od(r.for_sale),r.backorder_id?Qe.default.green("yes"):Qe.default.dim("-")])),l(),I("Stop following one:","domani unfollow <domain>"),l()}z();var ve=N(F(),1);V();async function ud(e){return e.read?hm(e):pm(e)}function fm(e){let t=new URLSearchParams;e.unread&&t.set("unread","true"),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function pm(e){let t=O(!e.json);t.start("Loading notifications");let n=fm(e),i=await x(`/api/notifications${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.notifications||s.data||[],o=s.unread_count??r.filter(d=>!d.read).length;if(t.stop(`${y.success} ${r.length} notification(s)${o>0?` ${y.dot} ${ve.default.yellow(`${o} unread`)}`:""}`),e.json){b(s,e.fields);return}if(r.length===0){l(),console.log(` ${ve.default.dim("No notifications.")}`),l();return}l(),j("Notifications");let a=r.map(d=>{let m=d.read?ve.default.dim(y.dot):ve.default.cyan(y.info),f=gm(d.type),p=d.read?ve.default.dim(d.title):ve.default.white(d.title),g=d.body?d.read?ve.default.dim(cd(d.body,40)):ve.default.dim(cd(d.body,40)):ve.default.dim("-"),$=ve.default.dim(new Date(d.created_at).toLocaleDateString());return[m,f,p,g,$]});G(["","Type","Title","Body","Date"],a,[3,16,28,42,14]),l(),s.next_cursor&&(console.log(` ${ve.default.dim(`More: --cursor ${s.next_cursor}`)}`),l()),o>0&&(console.log(` ${ve.default.dim("Mark all as read:")} ${ve.default.cyan("domani notifications --read")}`),l())}async function hm(e){let t=O(!e.json);t.start("Marking all notifications as read");let n=await x("/api/notifications/read-all",{method:"POST"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),e.json){t.stop(""),b(i,e.fields);return}let s=i.count??0;t.stop(`${y.success} ${s} notification(s) marked as read`),l()}function gm(e){let t={deal:ve.default.cyan,sale:ve.default.green,purchase:ve.default.green,transfer:ve.default.yellow,expiry:ve.default.red,security:ve.default.red,billing:ve.default.yellow,email:ve.default.blue},n=e.split(".")[0].split("_")[0];return(t[n]||ve.default.dim)(e)}function cd(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}z();var Vt=N(F(),1);V();async function md(e){let t=e.limit?Number(e.limit):20,n=await x(`/api/billing/invoices?limit=${t}`),i=await n.json();if(n.ok||u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}),e.json){b({...i,count:i.invoices.length},e.fields);return}if(i.invoices.length===0){console.log(` ${Vt.default.dim("No invoices yet.")}`);return}j(`Invoices (${i.invoices.length})`),l();for(let s of i.invoices){let r=`$${(s.amount_paid/100).toFixed(2)}`,o=new Date(s.created).toLocaleDateString(),a=s.number||s.id;console.log(` ${y.success} ${Vt.default.bold(a)} ${Vt.default.green(r)} ${Vt.default.dim(o)}`),s.description&&console.log(` ${Vt.default.dim(s.description)}`),s.hosted_invoice_url&&console.log(` ${Vt.default.dim(s.hosted_invoice_url)}`)}l(),i.has_more&&(console.log(` ${Vt.default.dim(`Showing ${i.invoices.length} most recent. Use --limit to see more.`)}`),l())}z();var Gn=N(F(),1);V();async function fd(e){let t=O(!e?.json);t.start("Setting up billing session");let n=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),i.url||(t.stop("Failed"),u("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:e?.json})),t.stop("Checkout ready"),e?.json){b({url:i.url});return}l(),console.log(` ${Gn.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),l(),Le(i.url),console.log(` ${y.info} ${Gn.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Gn.default.dim(" After setup, you can purchase domains with")} ${Gn.default.cyan("domani buy")}`),l()}z();var Or=N(F(),1);V();async function pd(e){let t=O(!e?.json);t.start("Creating upgrade session");let n=await x("/api/billing/subscribe",{method:"POST"}),i=await n.json();if(!n.ok){t.stop("Failed"),i.code==="ALREADY_SUBSCRIBED"||i.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json});return}if(t.stop("Ready"),e?.json){b({url:i.url},e?.fields);return}l(),console.log(` ${Or.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),l(),Le(i.url),console.log(` ${y.info} ${Or.default.dim("Complete your plan upgrade in the browser.")}`),l()}z();var Cr=N(F(),1);V();async function hd(e){let t=O(!e?.json);t.start("Cancelling subscription");let n=await x("/api/billing/cancel",{method:"POST"}),i=await n.json();if(!n.ok){t.stop("Failed"),i.code==="NOT_PAID"||i.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json});return}if(t.stop("Done"),e?.json){b(i,e?.fields);return}l();let s=i.cancel_at?new Date(i.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${y.success} ${Cr.default.dim("Subscription cancelled.")} Access continues until ${Cr.default.cyan(s)}.`),l()}z();var ct=N(F(),1);V();we();it();async function gd(e,t,n){e||(e=await ye()),Y(e,n);let i=[];if(t?.length&&i.push(...t),n.set&&i.push(...n.set.split(",").map(s=>s.trim()).filter(Boolean)),i.length>0||n.reset){await bm(e,i,n);return}await ym(e,n)}async function ym(e,t){let n=O(!t.json);n.start(`Fetching nameservers for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`Nameservers for ${v.domain(e)}`),t.json){b(s,t.fields);return}if(l(),s.nameservers.length===0)console.log(` ${y.warning} ${ct.default.yellow("No nameservers configured.")}`),console.log(` ${ct.default.dim("DNS operations (parking, email, connect) will not work.")}`),l(),I("Set default nameservers:",`domani nameservers ${e} --reset`);else{j("Nameservers");for(let r of s.nameservers)console.log(` ${y.success} ${ct.default.cyan(r)}`);s.default_nameservers&&s.nameservers.length===s.default_nameservers.length&&s.nameservers.every(o=>s.default_nameservers.includes(o))&&(l(),console.log(` ${ct.default.dim("Using default nameservers.")}`))}s.default_nameservers?.length&&(l(),c("Defaults",s.default_nameservers.map(r=>ct.default.dim(r)).join(ct.default.dim(", ")))),l()}async function bm(e,t,n){let i=O(!n.json);if(n.reset){i.start(`Fetching default nameservers for ${v.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(i.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:n.json,fields:n.fields})),a.default_nameservers?.length||(i.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:n.json,fields:n.fields})),t=a.default_nameservers,i.stop(`Using defaults: ${t.map(d=>ct.default.cyan(d)).join(ct.default.dim(", "))}`)}if(t.length<2&&u("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:n.json,fields:n.fields}),n.dryRun)return K("nameservers_set",{domain:e,nameservers:t},n.json,n.fields);i.start(`Setting nameservers for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:n.json,fields:n.fields})),i.stop(`${y.success} Nameservers updated`),n.json){b(r,n.fields);return}l();for(let o of r.nameservers)console.log(` ${y.success} ${ct.default.cyan(o)}`);l(),console.log(` ${ct.default.dim("Changes may take up to 48 hours to propagate.")}`),l(),I("Check propagation:",`domani status ${e}`),l()}var yd=require("crypto"),Kn=N(require("fs"),1);De();var zn=N(F(),1);V();function wm(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(i[s]||0))return 1;if((n[s]||0)<(i[s]||0))return-1}return 0}async function bd(e){let t=!!e?.json,n=O(!t);n.start("Checking for updates");let i=Ge();try{let s=await fetch(`${i}/api/cli/version`);s.ok||(n.stop("Failed"),u("Could not check for updates"));let r=await s.json(),o=r.version,a=r.sha256;if(wm(o,Ie)<=0){n.stop(`${y.success} Already up to date (v${Ie})`),t&&b({current:Ie,latest:o,up_to_date:!0});return}if(t&&!e?.yes){n.stop(""),b({current:Ie,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}n.stop(t?"":`New version available: ${zn.default.cyan(Ie)} ${y.arrow} ${zn.default.green(o)}`);let d=O(!t);d.start("Downloading update");let m=`${i}/cli/domani.js`,f=await fetch(m);f.ok||(d.stop("Download failed"),u(`Failed to download from ${m}`));let p=await f.text();a&&(0,yd.createHash)("sha256").update(p).digest("hex")!==a&&(d.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let g=process.argv[1];g||(d.stop("Failed"),u("Could not determine binary path"));let $=Kn.default.realpathSync(g),k=$+".tmp";if(Kn.default.writeFileSync(k,p,{mode:493}),Kn.default.chmodSync(k,493),Kn.default.renameSync(k,$),d.stop(`${y.success} Updated to v${o}`),t){b({updated:!0,from:Ie,to:o});return}l(),console.log(` ${zn.default.dim("Restart your terminal or run")} domani --version ${zn.default.dim("to verify")}`),l()}catch(s){u(`Update failed: ${s instanceof Error?s.message:String(s)}`)}}var Ji=N(require("fs"),1),wd=N(require("path"),1),vd=N(require("os"),1);qe();var Yn=N(F(),1);V();De();gs();async function $d(){let e=process.argv[1],t=e?Ji.default.realpathSync(e):null,n=wd.default.join(vd.default.homedir(),".domani");if(l(),console.log(` ${Yn.default.bold("This will remove:")}`),t&&console.log(` ${y.dot} CLI binary: ${Yn.default.dim(t)}`),console.log(` ${y.dot} Config dir: ${Yn.default.dim(n)}`),l(),await We({message:"Uninstall domani?"})!==!0){console.log(` ${Yn.default.dim("Cancelled.")}`);return}for(let s of rt())s.token_in_keychain&&di(s.name);Ji.default.rmSync(n,{recursive:!0,force:!0}),t&&Ji.default.unlinkSync(t),l(),console.log(` ${y.success} domani uninstalled.`),l()}z();var re=N(F(),1);V();async function kd(e,t){let n=t?.json,i=t?.fields,s=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=O(!n);r.start("Loading schema");let o=await ke(s),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:n,fields:i})),r.stop("Schema loaded"),n){b(a,i);return}e?$m(e,a):vm(a.commands)}function vm(e){j("Commands");let t=Object.entries(e).map(([n,i])=>[re.default.bold(re.default.cyan(n)),i.description]);G(["Command","Description"],t,[20,50]),l(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),l()}function $m(e,t){if(j(`domani ${e}`),console.log(` ${t.description}`),l(),console.log(` ${v.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){l(),console.log(` ${re.default.bold("Arguments")}`);for(let[n,i]of Object.entries(t.arguments)){let s=i.required?re.default.red("*"):"",r=re.default.dim(`(${i.type}${i.variadic?", variadic":""})`);console.log(` ${re.default.cyan(n)}${s} ${r}`),i.description&&console.log(` ${re.default.dim(i.description)}`)}}if(t.options&&Object.keys(t.options).length>0){l(),console.log(` ${re.default.bold("Options")}`);for(let[n,i]of Object.entries(t.options)){let s=i.required?re.default.red("*"):"",r=re.default.dim(`(${i.type})`),o=i.choices?re.default.dim(` [${i.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${n}`)}${s} ${r}${o}`),console.log(` ${re.default.dim(i.description)}`)}}if(t.api)if(l(),console.log(` ${re.default.bold("API")}`),_m(t.api))_d(t.api);else for(let[n,i]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(n))}`),_d(i,6);t.errors&&t.errors.length>0&&(l(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(n=>re.default.dim(n)).join(re.default.dim(", "))}`)),l()}function _m(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function _d(e,t=4){let n=" ".repeat(t);if(console.log(`${n}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[i,s]of Object.entries(e.parameters)){let r=s.required?re.default.red("*"):"",o=[s.type];s.enum&&o.push(`enum: ${s.enum.join(", ")}`),s.minimum!==void 0&&o.push(`min: ${s.minimum}`),s.maximum!==void 0&&o.push(`max: ${s.maximum}`),s.maxItems!==void 0&&o.push(`maxItems: ${s.maxItems}`),s.items&&o.push(`items: ${s.items}`),s.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${n} ${re.default.cyan(i)}${r} ${a}`),s.description&&console.log(`${n} ${re.default.dim(s.description)}`)}}z();var Je=N(F(),1);qe();V();async function xd(e){let t=O(!e.json);t.start("Loading payment method");let n=await x("/api/me"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),e.json){t.stop(""),b(i.card?{has_payment_method:i.has_payment_method,card:i.card}:{has_payment_method:!1},e.fields);return}if(!i.has_payment_method||!i.card){t.stop("No payment method on file"),l(),console.log(` ${Je.default.dim("Add a card with")} ${Je.default.cyan("domani card add")}`),l();return}let{brand:s,last4:r,exp_month:o,exp_year:a}=i.card,d=`${String(o).padStart(2,"0")}/${a}`,m=s.charAt(0).toUpperCase()+s.slice(1);t.stop("Payment method loaded"),j("Payment method"),c("Card",`${Je.default.bold(m)} \u2022\u2022\u2022\u2022 ${Je.default.bold(r)}`),c("Expires",d),l(),console.log(` ${Je.default.dim("Update with")} ${Je.default.cyan("domani card add")}`),l()}async function jd(e){let t=O(!e?.json);t.start("Setting up payment session");let n=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),i.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){b({url:i.url},e?.fields);return}l(),console.log(` ${Je.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),l(),Le(i.url),console.log(` ${y.info} ${Je.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Je.default.dim(" After setup, you can purchase domains with")} ${Je.default.cyan("domani buy")}`),l()}async function Sd(e){if(!e?.yes&&!e?.json){let s=await We({message:"Remove your saved payment method?"});if(de(s)||!s){console.log(` ${Je.default.dim("Cancelled.")}`);return}}let t=O(!e?.json);t.start("Removing payment method");let n=await x("/api/billing/card",{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),t.stop(`${y.success} Payment method removed`),e?.json){b({removed:!0},e?.fields);return}l(),console.log(` ${Je.default.dim("Add a new card with")} ${Je.default.cyan("domani card add")}`),l()}var Ar=N(F(),1);z();V();async function pe(e,t,n,i){let s=O(!n.json);s.start(i);let r=await x(e,t),o=await r.json();return r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop(`${y.success} Done`),o}async function Od(e,t){if(!e||e==="list"){let n=await pe("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return b(n,t.fields);if(l(),j("Workspaces"),!n.workspaces.length){console.log(` ${Ar.default.dim("No workspaces yet.")}`),I("Create one:","domani workspace create --name Acme");return}G(["ID","Name","Role","Mailboxes","Members"],n.workspaces.map(i=>[i.id,i.name,i.role,String(i.mailbox_count),String(i.member_count)]),[28,28,10,10,8]),l();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let n=await pe("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return b(n,t.fields);l(),j("Workspace Created"),c("ID",n.id),c("Name",n.name),l();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return b(n,t.fields);l(),j(n.name),c("Role",n.role),c("Mailboxes",n.mailboxes.length),c("Members",n.members.length),l(),G(["Email","Role","Mailbox grants"],n.members.map(i=>[i.email,i.role,String(i.mailbox_grants.length)]),[42,12,16]),l();return}if(e==="access"){if(t.id||u("Workspace ID required",{hint:"Usage: domani workspace access --id <id>",code:"validation_error",json:t.json}),!t.subject&&!t.resource&&!t.profile){let a=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return b(a,t.fields);l(),j("Access Graph"),c("Principals",a.principals.length),c("Mailboxes",a.mailboxes.length),c("Groups",a.groups.length),c("Collections",a.collections.length),c("Active grants",a.grants.length),c("Pending offers",a.offers.length),l();return}(!t.subject||!t.resource||!t.profile)&&u("Subject, resource, and profile are required together",{hint:"Usage: domani workspace access --id <id> --subject human:<id> --resource mailbox:<id> --profile responder [--apply]",code:"validation_error",json:t.json});let[n,i]=t.subject.split(":",2),[s,r]=t.resource.split(":",2);(!i||!["human","agent","service","token","group"].includes(n))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(s))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:n==="group"?{type:"group",id:i}:{type:"principal",principal:{type:n,id:i}},resource:{type:s,id:r},profile:t.profile,expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,t.apply?"Applying access":"Planning access");if(t.json)return b(o,t.fields);l(),j(t.apply?"Access Applied":"Access Plan"),c("Action",o.action),c("Changed",String(o.changed)),o.grant_id&&c("Grant",o.grant_id),l();return}if(e==="group"){(!t.id||!t.name)&&u("Workspace ID and group name required",{hint:"Usage: domani workspace group --id <id> --name Support --principals human:u1,agent:a1",code:"validation_error",json:t.json});let n=(t.principals||"").split(",").map(s=>s.trim()).filter(Boolean).map(s=>{let[r,o]=s.split(":",2);return o||u(`Invalid principal: ${s}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),i=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:n})},t,"Syncing access group");if(t.json)return b(i,t.fields);l(),j("Access Group Synced"),c("ID",i.id),c("Principals",i.principal_count),l();return}if(e==="collection"){(!t.id||!t.name)&&u("Workspace ID and collection name required",{hint:"Usage: domani workspace collection --id <id> --name Admin --mailboxes mb1,mb2",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(i=>i.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return b(n,t.fields);l(),j("Mailbox Collection Synced"),c("ID",n.id),c("Mailboxes",n.mailbox_count),l();return}if(e==="offer"){(!t.id||!t.email)&&u("Workspace ID and recipient email required",{hint:"Usage: domani workspace offer --id <id> --email person@example.com --mailboxes mb1,mb2 --profile responder",code:"validation_error",json:t.json});let n=(t.mailboxes||"").split(",").map(s=>s.trim()).filter(Boolean).map(s=>({resource:{type:"mailbox",id:s},profile:t.profile||"responder"})),i=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:n,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return b(i,t.fields);l(),j("Access Offered"),c("Email",i.email),c("Expires",i.expires_at),l();return}if(e==="accept-offer"){t.token||u("Access offer token required",{hint:"Usage: domani workspace accept-offer --token <token>",code:"validation_error",json:t.json});let n=await pe("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return b(n,t.fields);l(),j("Access Accepted"),c("Workspace",n.workspace_name),c("Ownership",n.ownership),l();return}if(e==="revoke-access"){(!t.id||!t.grantId)&&u("Workspace and grant IDs required",{hint:"Usage: domani workspace revoke-access --id <id> --grant-id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/access/grants/${encodeURIComponent(t.grantId)}`,{method:"DELETE",body:JSON.stringify({expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,"Revoking access");if(t.json)return b(n,t.fields);l(),j("Access Revoked"),c("Grant",n.grant_id),c("Version",n.version),l();return}if(e==="rename"){(!t.id||!t.name)&&u("Workspace ID and name required",{hint:"Usage: domani workspace rename --id <id> --name <name>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return b(n,t.fields);l(),j("Workspace Renamed"),c("ID",n.id),c("Name",n.name),l();return}if(e==="invite"){(!t.id||!t.email)&&u("Workspace ID and email required",{hint:"Usage: domani workspace invite --id <id> --email person@example.com",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(i=>i.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return b(n,t.fields);l(),j("Invitation Sent"),c("Email",n.email),c("Role",n.role),c("Expires",n.expires_at),l();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let n=await pe("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return b(n,t.fields);l(),j("Workspace Joined"),c("Workspace",n.workspace_name),c("Role",n.role),l();return}if(e==="revoke-invite"){(!t.id||!t.invitationId)&&u("Workspace ID and invitation ID required",{hint:"Usage: domani workspace revoke-invite --id <id> --invitation-id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return b(n,t.fields);l(),j("Invitation Revoked"),c("Invitation",n.invitation_id),l();return}if(e==="member-role"){(!t.id||!t.membershipId||!t.role)&&u("Workspace ID, membership ID, and role required",{hint:"Usage: domani workspace member-role --id <id> --membership-id <id> --role admin|member",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"PATCH",body:JSON.stringify({role:t.role})},t,"Updating member role");if(t.json)return b(n,t.fields);l(),j("Member Updated"),c("Membership",n.id),c("Role",n.role),l();return}if(e==="remove-member"){(!t.id||!t.membershipId)&&u("Workspace ID and membership ID required",{hint:"Usage: domani workspace remove-member --id <id> --membership-id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return b(n,t.fields);l(),j("Member Removed"),c("Membership",n.membership_id),l();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return b(n,t.fields);l(),j("Workspace Left"),c("Workspace",n.workspace_id),l();return}if(e==="transfer"){(!t.id||!t.membershipId)&&u("Workspace ID and target membership ID required",{hint:"Usage: domani workspace transfer --id <workspace-id> --membership-id <membership-id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return b(n,t.fields);l(),j("Ownership Transfer Requested"),c("To",n.to_email),c("Expires",n.expires_at),c("Billing",n.billing),l();return}if(e==="accept-ownership"){t.token||u("Ownership transfer token required",{hint:"Usage: domani workspace accept-ownership --token <token>",code:"validation_error",json:t.json});let n=await pe("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return b(n,t.fields);l(),j("Ownership Transferred"),c("Workspace",n.workspace_id),c("Domains",n.domains_transferred),c("Mailboxes",n.mailboxes_transferred),c("Previous owner",n.previous_owner_role),l();return}if(e==="revoke-transfer"){(!t.id||!t.transferId)&&u("Workspace ID and transfer ID required",{hint:"Usage: domani workspace revoke-transfer --id <workspace-id> --transfer-id <transfer-id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return b(n,t.fields);l(),j("Ownership Transfer Revoked"),c("Transfer",n.transfer_id),l();return}if(e==="adopt-mailbox"){(!t.id||!t.mailboxId)&&u("Workspace ID and mailbox ID required",{hint:"Usage: domani workspace adopt-mailbox --id <workspace-id> --mailbox-id <mailbox-id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return b(n,t.fields);l(),j(n.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),c("Address",n.address),c("Mailboxes",n.mailbox_ids?.length??1),l();return}if(e==="grant"){(!t.id||!t.mailboxId||!t.membershipId||!t.role)&&u("Workspace, mailbox, membership, and role required",{hint:"Usage: domani workspace grant --id <id> --mailbox-id <id> --membership-id <id> --role viewer|responder|manager",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"PUT",body:JSON.stringify({membership_id:t.membershipId,role:t.role})},t,"Granting mailbox access");if(t.json)return b(n,t.fields);l(),j("Mailbox Access Granted"),c("Membership",n.membership_id),c("Mailbox",n.mailbox_id),c("Role",n.role),l();return}if(e==="revoke-grant"){(!t.id||!t.mailboxId||!t.membershipId)&&u("Workspace, mailbox, and membership required",{hint:"Usage: domani workspace revoke-grant --id <id> --mailbox-id <id> --membership-id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"DELETE",body:JSON.stringify({membership_id:t.membershipId})},t,"Revoking mailbox access");if(t.json)return b(n,t.fields);l(),j("Mailbox Access Revoked"),c("Membership",n.membership_id),c("Mailbox",n.mailbox_id),l();return}if(e==="checkout"){(!t.id||!t.plan)&&u("Workspace ID and plan required",{hint:"Usage: domani workspace checkout --id <id> --plan mail_team",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return b(n,t.fields);l(),j("Workspace Checkout"),c("Plan",n.plan),c("URL",n.url),l(),n.url&&t.open!==!1&&(console.log(` ${Ar.default.dim("Opening browser")} ${y.arrow} ${v.url(n.url)}`),Le(n.url));return}if(e==="cancel"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace cancel --id <id>",code:"validation_error",json:t.json});let n=await pe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return b(n,t.fields);l(),j("Cancellation Scheduled"),c("Message",n.message),n.cancel_at&&c("Cancels",n.cancel_at),l();return}u(`Unknown action: ${e}`,{hint:"Actions: list, create, show, access, group, collection, offer, accept-offer, revoke-access, rename, invite, accept, revoke-invite, member-role, remove-member, leave, transfer, accept-ownership, revoke-transfer, adopt-mailbox, grant, revoke-grant, checkout, cancel",code:"validation_error",json:t.json,fields:t.fields})}var Xn=N(F(),1);z();var Bi=N(require("node:crypto"),1),xn=N(require("node:fs"),1),Cd=N(require("node:os"),1),Gi=N(require("node:path"),1),km=process.env.DOMANI_CONFIG_DIR||Gi.default.join(Cd.default.homedir(),".domani"),Ad=Gi.default.join(km,"mutations");function xm(e){return Gi.default.join(Ad,`${Bi.default.createHash("sha256").update(e).digest("hex")}.json`)}function vt(e,t,n){let i=xm(e),s=Bi.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!n)try{let o=JSON.parse(xn.default.readFileSync(i,"utf8"));if(o.key&&o.fingerprint===s)return{key:o.key,complete:()=>{try{xn.default.unlinkSync(i)}catch{}}}}catch{}let r=n||`cli-${Bi.default.randomUUID()}`;return xn.default.mkdirSync(Ad,{recursive:!0,mode:448}),xn.default.writeFileSync(i,JSON.stringify({key:r,fingerprint:s}),{mode:384}),{key:r,complete:()=>{try{xn.default.unlinkSync(i)}catch{}}}}V();function Id(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[n,i]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!i)continue;let s=process.env[i];s||u(`Environment variable ${i} is empty`,{code:"validation_error",json:e.json}),t[n]=s}return Object.keys(t).length?t:void 0}async function an(e,t){let n=await e.json();return e.ok||u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields}),n}function Ki(e,t){if(t.json)return b(e,t.fields);let n=e.http_route||e;l(),j("HTTP Route"),c("ID",n.id),c("URL",n.url),c("Upstream",n.upstream),c("Status",n.status),c("Expires",n.expires_at),c("Browser mode",n.browser_mode||"stateless"),n.upstream_verification?.secret&&(c("Verification secret",Xn.default.yellow(n.upstream_verification.secret)),console.log(Xn.default.dim(" Save this secret now. It will not be shown again after this receipt."))),l()}function jm(e){let t=new URLSearchParams;e.domain&&t.set("domain",e.domain),e.hostname&&t.set("hostname",e.hostname),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Rd(e,t,n){if(!e||e==="list"){let i=await an(await x(`/api/http-routes${jm(n)}`),n);if(n.json)return b(i,n.fields);l(),j("HTTP Routes");for(let s of i.http_routes)console.log(` ${Xn.default.dim(s.id)} ${s.hostname} ${s.status} ${s.upstream}`);l(),i.next_cursor&&(console.log(` ${Xn.default.dim(`More: --cursor ${i.next_cursor}`)}`),l());return}if(e==="create"){n.upstream||u("--upstream is required",{code:"validation_error",json:n.json});let i=Id(n),s={...n.hostname?{hostname:n.hostname}:{},upstream:n.upstream,...n.expiresIn?{expires_in:Number(n.expiresIn)}:{},...n.hostHeader?{host_header:n.hostHeader}:{},...n.upstreamVerification?{upstream_verification:n.upstreamVerification}:{},...i?{upstream_headers:i}:{}},r=vt(`route:create:${n.hostname||"auto"}`,s,n.idempotencyKey),o=O(!n.json);o.start("Creating HTTP route");let a=await an(await x("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(s)}),n);return r.complete(),o.stop(`${y.success} HTTP route created`),Ki(a,n)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:n.json}),e==="get")return Ki(await an(await x(`/api/http-routes/${encodeURIComponent(t)}`),n),n);if(e==="delete"){let i=await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(i.ok||await an(i,n),n.json)return b({deleted:!0,id:t},n.fields);console.log(`${y.success} HTTP route deleted`);return}if(e==="refresh"){n.expiresIn||u("--expires-in is required",{code:"validation_error",json:n.json});let i={expires_in:Number(n.expiresIn)},s=vt(`route:refresh:${t}`,i,n.idempotencyKey),r=await an(await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":s.key},body:JSON.stringify(i)}),n);return s.complete(),Ki(r,n)}if(e==="rotate-verification"){let i=vt(`route:rotate-verification:${t}`,{},n.idempotencyKey),s=await an(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":i.key}}),n);return i.complete(),n.json?b(s,n.fields):Ki(s,n)}if(e==="rotate-headers"){let i=Id(n);i||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:n.json});let s=vt(`route:rotate-headers:${t}`,{upstream_headers:i},n.idempotencyKey),r=await an(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":s.key},body:JSON.stringify({upstream_headers:i})}),n);if(s.complete(),n.json)return b(r,n.fields);console.log(`${y.success} Upstream headers replaced: ${r.upstream_header_names.join(", ")||"none"}`);return}u(`Unknown action: ${e}`,{hint:"Actions: create, list, get, refresh, rotate-verification, rotate-headers, delete",code:"validation_error",json:n.json})}var Q=N(F(),1),Pd=require("node:fs");si();z();V();var Rr="mailzero-personal-ai.v1",Z=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="AssistantUsageError"}},Sm={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct",approve:"approve",reject:"reject",tag:"tag"},Om=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","approve","reject","tag","plan","activity","export","delete","brief","facts","sender","task","lease","release","effects","escalate","report","rules","approvals","suggestions","metrics"];function Ir(e,t,n){if(!e)throw new Z(`${t} is required`,n);try{return JSON.parse(e)}catch{throw new Z(`${t} must be valid JSON`,n)}}function zi(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Td(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function dn(e,t,n){let i=Number(e);if(!Number.isInteger(i)||i<n)throw new Z(`${t} must be an integer of at least ${n}`);return i}function Cm(e,t,n){let i=e||"today";switch(i){case"today":{let s=new URLSearchParams;n.category&&s.set("category",n.category.trim().toLowerCase()),n.tag&&s.set("tag",n.tag.trim().toLowerCase());let r=s.toString();return{method:"GET",path:r?`/api/assistant/today?${r}`:"/api/assistant/today"}}case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let s={};if(n.enable&&n.disable)throw new Z("Use either --enable or --disable");if(n.pause&&n.resume)throw new Z("Use either --pause or --resume");if(n.enable&&(s.enabled=!0),n.disable&&(s.enabled=!1),n.shadow!==void 0&&(s.shadow_enabled=n.shadow),n.pause&&(s.paused=!0),n.resume&&(s.paused=!1),n.none?s.mailbox_ids=[]:n.mailboxes!==void 0&&(s.mailbox_ids=Td(n.mailboxes)),n.days!==void 0&&(s.history_window_days=dn(n.days,"--days",1)),n.attachmentVision!==void 0){if(!["on","off"].includes(n.attachmentVision))throw new Z("--attachment-vision must be on or off");s.attachment_vision=n.attachmentVision==="on"}if(!Object.keys(s).length)throw new Z("Provide at least one setting","Options: --enable, --disable, --shadow, --no-shadow, --pause, --resume, --mailboxes <ids>, --none, --days <n>, --attachment-vision <on|off>");return{method:"PUT",path:"/api/assistant/settings",body:s}}case"preview":{if(!n.consent)throw new Z("--consent is required to start the assistant",`Consent means Domani may read the selected mailboxes and send bounded, minimized message content to the approved private model route (version ${Rr}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let s=Td(n.mailboxes);if(!s.length)throw new Z("--mailboxes is required","Pass owned mailbox IDs, comma-separated. List them with: domani assistant settings");return{method:"POST",path:"/api/assistant/preview",body:{mailbox_ids:s,history_window_days:n.days===void 0?30:dn(n.days,"--days",1),consent:!0,consent_version:Rr}}}case"backfill":return{method:"GET",path:"/api/assistant/backfill"};case"retry":return{method:"POST",path:"/api/assistant/backfill",idempotency:"assistant:retry"};case"item":if(!t)throw new Z("Work item ID is required","Usage: domani assistant item <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}`};case"brief":{if(t)return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/brief`};if(!n.correspondent)throw new Z("Work item ID or --correspondent is required","Usage: domani assistant brief <id> | domani assistant brief --correspondent ada@example.com [--mailbox hi@myapp.dev]");let s=new URLSearchParams({correspondent:n.correspondent});return n.mailbox&&s.set("mailbox",n.mailbox),{method:"GET",path:`/api/assistant/brief?${s}`}}case"facts":if(!t)throw new Z("Work item ID is required","Usage: domani assistant facts <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/facts`};case"sender":if(!t)throw new Z("Work item ID is required","Usage: domani assistant sender <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/sender`};case"plan":if(!t)throw new Z("Action plan ID is required","Usage: domani assistant plan <id>");return{method:"GET",path:`/api/assistant/action-plans/${encodeURIComponent(t)}`};case"activity":return{method:"GET",path:`/api/assistant/activity${n.limit!==void 0?`?limit=${dn(n.limit,"--limit",1)}`:""}`};case"rules":return{method:"GET",path:"/api/assistant/rules"};case"approvals":return{method:"GET",path:"/api/assistant/approvals"};case"suggestions":return{method:"GET",path:"/api/assistant/suggestions"};case"metrics":return{method:"GET",path:`/api/assistant/metrics${n.days!==void 0?`?window_days=${dn(n.days,"--days",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!n.yes)throw new Z("Deleting derived assistant data requires --yes","This removes analyses, Decisions, plans, receipts, imports, and settings. Source mail is never touched.");return{method:"DELETE",path:"/api/assistant/data"};case"task":if(!t)throw new Z("Task ID is required","Usage: domani assistant task <work item id>");return{method:"GET",path:`/api/assistant/tasks/${encodeURIComponent(t)}`};case"lease":{if(!t)throw new Z("Task ID is required","Usage: domani assistant lease <id> [--ttl <seconds>]");let s={};return n.ttl!==void 0&&(s.ttl_seconds=dn(n.ttl,"--ttl",30)),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`,body:s}}case"release":if(!t)throw new Z("Task ID is required","Usage: domani assistant release <id>");return{method:"DELETE",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`};case"effects":{if(!t)throw new Z("Task ID is required","Usage: domani assistant effects <id> --effects '<json array>'");let s=Ir(n.effects,"--effects",`A JSON array of effects, for example: --effects '[{"kind":"label","mailbox_id":"mbx_1","add":["finance"]}]'`);if(!Array.isArray(s)||!s.length)throw new Z("--effects must be a non-empty JSON array","Kinds: reply, forward, label, snooze, resolve, note, request");let r={effects:s};return n.text&&(r.note=n.text),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/effects`,body:r,idempotency:`assistant:effects:${t}`}}case"escalate":{if(!t)throw new Z("Task ID is required","Usage: domani assistant escalate <id> --question '<text>' [--options '<json>'] [--evidence <refs>]");if(!n.question)throw new Z("--question is required","What the owner must decide, with the evidence in --evidence");let s={question:n.question};n.options&&(s.options=Ir(n.options,"--options","A JSON array of { key, label, outcome }"));let r=zi(n.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/escalate`,body:s}}case"report":{if(!t)throw new Z("Task ID is required","Usage: domani assistant report <id> --outcome done|blocked|handed_back --summary '<text>' [--claims '<json>'] [--evidence <refs>]");if(!n.outcome||!["done","blocked","handed_back"].includes(n.outcome))throw new Z("--outcome must be done, blocked or handed_back");if(!n.summary)throw new Z("--summary is required","What was done and how it ended, in a few lines");let s={outcome:n.outcome,summary:n.summary};n.claims&&(s.claims=Ir(n.claims,"--claims","A JSON array of { kind, ref } the platform reconciles with its receipts"));let r=zi(n.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/report`,body:s}}case"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":case"approve":case"reject":case"tag":{if(!t)throw new Z("Work item ID is required",`Usage: domani assistant ${i} <id> --item-version <work_item_version>`);if(n.itemVersion===void 0)throw new Z("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let s=Sm[i],r={type:s,work_item_version:dn(n.itemVersion,"--item-version",1)};if(s==="ignore"&&n.scope){if(!["item","sender","sender_domain","situation"].includes(n.scope))throw new Z("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=n.scope}if(s==="choose"){if(!n.option||!n.decision||n.decisionVersion===void 0)throw new Z("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=n.decision,r.decision_version=dn(n.decisionVersion,"--decision-version",1),r.option_id=n.option}if(s==="instruct"){if(!n.text)throw new Z("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=n.text}if(s==="snooze"){if(!n.until)throw new Z("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=n.until}if(s==="correct"){if(!n.field||!n.text)throw new Z("--field and --text are required","Name the analysis field to correct and the correct value");r.field=n.field,r.correction=n.text}if(s==="tag"){let o=zi(n.add),a=zi(n.remove);if(!o.length&&!a.length)throw new Z("--add or --remove is required","Example: domani assistant tag <id> --item-version 3 --add lumenworks --remove draft");o.length&&(r.add=o),a.length&&(r.remove=a)}if(s==="approve"||s==="reject"){if(!n.plan)throw new Z("--plan is required","The waiting action plan shown by: domani assistant task <id>");r.plan_id=n.plan,s==="reject"&&n.text&&(r.reason=n.text)}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${s}:${t}`}}default:throw new Z(`Unknown action: ${i}`,`Actions: ${Om.join(", ")}`)}}async function Am(e,t){let n=await e.json();if(e.ok)return n;n.code==="NOT_AVAILABLE"&&u(`The ${Et.mailProductName} assistant is in private preview`,{hint:"It is enabled per account during the private beta. Ask for access at https://domani.run/support or wait for general availability.",code:"not_available",status:e.status,json:t.json,fields:t.fields}),n.code==="INSUFFICIENT_SCOPE"&&u(n.error||"Missing assistant scope",{hint:"This token needs the assistant:read scope for reads and assistant:write for changes. Create one with: domani tokens create --scopes assistant:read,assistant:write",code:"insufficient_scope",status:e.status,json:t.json,fields:t.fields}),u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields})}function Im(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",n=e.recurrence?.count&&e.recurrence.count>1?Q.default.dim(`x${e.recurrence.count}`):"",i=[e.category?e.category.replace(/_/g," "):"",...(e.tags??[]).map(s=>`#${s}`)].filter(Boolean).join(" ");return[Q.default.dim(e.id),t,i,`${(e.title||e.summary||"").slice(0,60)} ${n}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function Rm(e,t){if(t.json)return b(e,t.fields);l(),j("Today");let n=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],i=0;for(let[a,d]of n){let m=e.sections&&typeof e.sections=="object"?e.sections:e,f=Array.isArray(m[a])?m[a]:[];f.length&&(i+=f.length,console.log(` ${Q.default.bold(d)} ${Q.default.dim(`(${f.length})`)}`),G(["ID","Who","Kind","Summary","Deadline"],f.map(Im)),l())}i||console.log(Q.default.dim(t.tag?` Nothing tagged ${t.tag} right now.`:t.category?` Nothing of the kind ${t.category} right now.`:" Nothing needs you right now."));let s=e.categories&&typeof e.categories=="object"?Object.entries(e.categories).sort((a,d)=>d[1]-a[1]):[];s.length>1&&console.log(Q.default.dim(` Kinds: ${s.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --category)`));let r=e.tags&&typeof e.tags=="object"?Object.entries(e.tags).sort((a,d)=>d[1]-a[1]):[];r.length&&console.log(Q.default.dim(` Tags: ${r.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --tag)`));let o=typeof e.as_of=="string"?e.as_of:void 0;o&&console.log(Q.default.dim(` As of ${o}`)),l()}function Tm(e,t){if(t.json)return b(e,t.fields);let n=e.brief??e;if(e.correspondent&&!e.brief){l(),j(`Brief for ${e.correspondent}`),console.log(` ${Q.default.dim("Nothing analysed from this person yet.")}`);for(let i of e.recent_mail||[])c(i.received_at.slice(0,10),`${i.subject||""} (${i.mailbox})`);return}l(),j(n.title||"Brief"),n.situation&&c("Status",`${n.situation.status||""}${n.situation.attention?.level?` \xB7 ${n.situation.attention.level}`:""}${n.situation.occurrences&&n.situation.occurrences>1?` \xB7 ${n.situation.occurrences} messages`:""}`),n.situation?.sender?.address&&c("With",`${n.situation.sender.name?`${n.situation.sender.name} `:""}<${n.situation.sender.address}>`),n.summary&&c("Summary",n.summary),n.ask&&c("Ask",n.ask);for(let i of n.story||[])c(i.occurred_at.slice(0,10),`${i.title}${i.analysed?"":Q.default.dim(" (not analysed)")}`);for(let i of n.facts||[])c("Fact",`${i.subject||""} ${i.predicate||""} ${i.value?.value??i.object??""}${i.value?.currency?` ${i.value.currency}`:""}`.trim());for(let i of n.awaiting||[])c(i.overdue?Q.default.red("Awaited"):"Awaited",`${i.who}: ${i.what} (since ${i.since.slice(0,10)})`);for(let i of n.commitments||[])c(i.overdue?Q.default.red("Promised"):"Promised",`${i.who}: ${i.what}`);for(let i of(n.settled||[]).slice(0,5))c("Settled",`${i.what} (${i.status}, ${i.at.slice(0,10)})`);n.decision?.question&&c("Decision",`${n.decision.question} ${(n.decision.options||[]).map(i=>`${i.recommended?"\u2605 ":""}${i.label}`).join(" / ")}`),n.suggested_next&&c("Next",`${n.suggested_next.action} ${Q.default.dim(`(${n.suggested_next.reason})`)}`),e.related&&e.related.length&&c("Also",`${e.related.length} other item(s) from this person`)}function Em(e,t){if(t.json)return b(e,t.fields);let n=e;l(),j(n.sender?`${n.sender.name?`${n.sender.name} `:""}<${n.sender.address}>`:"Sender"),n.organisation?(c("Organisation",`${n.organisation.name||n.sender?.domain||""}${n.organisation.legal_name&&n.organisation.legal_name!==n.organisation.name?` (${n.organisation.legal_name})`:""}${n.organisation.fresh?"":Q.default.dim(" (profile ageing)")}`),n.organisation.pitch&&c("About",n.organisation.pitch),n.organisation.registered_at&&c("Domain since",n.organisation.registered_at.slice(0,10)),c("Mail",`${n.organisation.mail.provider||"unknown provider"} \xB7 spf ${n.organisation.mail.spf===null?"?":n.organisation.mail.spf?"yes":"no"} \xB7 dmarc ${n.organisation.mail.dmarc}`)):n.sender?.shared_domain?c("Organisation",Q.default.dim(`${n.sender.domain} is a shared mail domain`)):n.sender?.domain&&c("Organisation",Q.default.dim(`${n.sender.domain} not analysed yet`));let i=n.relationship;if(i){let s=i.first_received_at&&i.last_received_at?` between ${i.first_received_at.slice(0,10)} and ${i.last_received_at.slice(0,10)}`:"";c("Received",i.received?`${i.received_capped?"50+":i.received} message(s)${s}`:"nothing before this");for(let r of i.matters.slice(0,5))c(r.last_seen_at.slice(0,10),`${r.title} ${Q.default.dim(`(${r.status}, ${r.id})`)}`);i.organisation?.matters.length&&c("Colleagues",`${i.organisation.other_senders.join(", ")}: ${i.organisation.matters.slice(0,3).map(r=>r.title).join(" / ")}`)}for(let s of n.participants||[])c(s.roles.join("+"),`${s.name?`${s.name} `:""}<${s.address}>${s.messages>1?Q.default.dim(` \xD7${s.messages}`):""}${s.same_organisation?"":Q.default.dim(" (outside)")}`)}function Ed(e,t){if(t.json)return b(e,t.fields);let n=e.work_item||e;if(l(),j("Work item"),c("ID",n.id),c("Version",String(n.version??"")),c("Status",n.status||""),c("Mailbox",n.mailbox?.name?`${n.mailbox.name} <${n.mailbox.address||""}>`:n.mailbox?.address||""),n.title&&c("Title",n.title),n.sender?.address&&c("From",`${n.sender.name?`${n.sender.name} `:""}<${n.sender.address}>${n.sender.kind&&n.sender.kind!=="human"?` (${n.sender.kind})`:""}`),n.ask&&c("Ask",n.ask),n.recurrence?.count&&n.recurrence.count>1&&c("Recurrence",`${n.recurrence.count} messages since ${(n.recurrence.first_seen_at||"").slice(0,10)}`),c("Summary",n.summary||""),n.attention?.reason&&c("Why",n.attention.reason),n.attention?.deadline&&c("Deadline",n.attention.deadline),n.source?.event_id&&c("Source",`${n.source.type||"mail"} ${n.source.event_id}`),n.decision?.options?.length){l(),console.log(` ${Q.default.bold("Decision")} ${Q.default.dim(`${n.decision.id} v${n.decision.version??1}`)}`);for(let i of n.decision.options)console.log(` ${Q.default.dim(i.id)} ${i.label}${i.recommended?Q.default.green(" recommended"):""}`);console.log(Q.default.dim(` Choose with: domani assistant choose ${n.id} --version ${n.version??1} --decision ${n.decision.id} --decision-version ${n.decision.version??1} --option <id>`))}n.plan?.id&&c("Plan",`${n.plan.id} (preview with: domani assistant plan ${n.plan.id})`),l()}function Pm(e,t){if(t.json)return b(e,t.fields);l(),j(`${Et.mailProductName} assistant`),c("Enabled",e.enabled?"yes":"no"),c("Shadow",e.shadow_enabled?"yes":"no"),c("Paused",e.paused?"yes":"no"),c("History window",`${e.history_window_days} days`),c("Privacy route",String(e.privacy_route||"")),c("Consent",e.consent?.accepted_version?`${e.consent.accepted_version} at ${e.consent.accepted_at}`:`none (required: ${e.consent?.required_version||Rr})`),l();let n=new Set(e.mailbox_ids||[]),i=e.mailboxes||[];i.length&&G(["ID","Address","AI"],i.map(s=>[Q.default.dim(s.id),s.address,n.has(s.id)?Q.default.green("on"):Q.default.dim("off")])),l()}function Dm(e,t){if(t.json)return b(e,t.fields);let n=e.backfill;if(l(),j("History import"),!n){console.log(Q.default.dim(" No import has run yet.")),l();return}c("Status",`${n.status} (${n.phase})`),c("Progress",`${n.processed}/${n.total}${n.percent===null||n.percent===void 0?"":` (${n.percent}%)`}`),c("Failed",String(n.failed??0)),c("Paused",n.paused?"yes":"no"),n.estimated_completion_at&&c("ETA",n.estimated_completion_at),n.can_close_app&&console.log(Q.default.dim(" The import continues in the background.")),l()}function Nm(e,t){if(t.json)return b(e,t.fields);let n=e.action_plan||e.plan||e;l(),j("Action preview"),c("ID",n.id),c("Status",n.status||""),n.expires_at&&c("Expires",n.expires_at);for(let i of n.effects||[])l(),console.log(` ${Q.default.bold(i.kind||"effect")} ${Q.default.dim(`mailbox ${i.mailbox_id||""}`)}${i.reply_to_message_id?Q.default.dim(` in reply to ${i.reply_to_message_id}`):""}`),i.body&&console.log(`
206
+ domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function wm(e,t){let n=parseFloat(t.price);(isNaN(n)||n<=0)&&u("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:t.json,fields:t.fields});let i=C(!t.json);i.start(`Listing ${v.domain(e)} for sale`);let s={domain:e,price:n};t.description&&(s.description=t.description);let r=await x("/api/domains/sell",{method:"POST",body:JSON.stringify(s)}),o=await r.json();if(r.ok||(i.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){i.stop(""),b(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(i.stop(`${y.success} Listed for sale`),j("Sell Domain"),l("Domain",v.domain(o.listing?.domain||e)),l("Price",v.price(n)),l("Status",Ie.default.green("active")),c(),console.log(` ${Ie.default.dim("Your listing is live on the marketplace.")}`),c()):(i.stop(`${y.success} Verification record ready`),j("Sell Domain"),l("Domain",v.domain(o.listing?.domain||e)),l("Price",v.price(n)),l("Status",Ie.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),console.log(` ${Ie.default.dim("Type:")} ${Ie.default.bold("TXT")}`),console.log(` ${Ie.default.dim("Name:")} ${Ie.default.bold(o.txt_record?.name||"@")}`),console.log(` ${Ie.default.dim("Value:")} ${Ie.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),c(),console.log(` ${Ie.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),I("Once the record is set, verify:",`domani sell ${e} --verify`),c())}async function vm(e,t){let n=C(!t.json);n.start(`Verifying ownership of ${v.domain(e)}`);let i=await x("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),s=await i.json();if(i.ok||(n.stop("Verification failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),t.json){n.stop(""),b(s,t.fields);return}n.stop(`${y.success} ${v.domain(e)} is now listed for sale!`),j("Domain Listed"),l("Domain",v.domain(s.domain||e)),l("Status",Ie.default.green(s.status||"active")),s.price&&l("Price",v.price(s.price)),c(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),c()}async function $m(e,t){let n=C(!t.json);n.start(`Checking listing status for ${v.domain(e)}`);let i=await x(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Listing status loaded`),t.json){b(s,t.fields);return}let r=s.listing;if(j("Listing Status"),l("Domain",v.domain(s.domain||e)),r){let o=r.status;l("Status",o==="active"?Ie.default.green(o):Ie.default.yellow(o||"unknown")),r.price&&l("Price",v.price(r.price)),r.description&&l("Description",r.description),r.created_at&&l("Listed",Ie.default.dim(new Date(r.created_at).toLocaleDateString()))}else l("Status",Ie.default.dim("No listing found"));s.deal&&l("Deal",`${s.deal.status} ($${s.deal.price})`),c()}async function km(e,t){let n=C(!t.json);n.start(`Removing ${v.domain(e)} from sale`);let i=await x(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),t.json){n.stop(""),b(s,t.fields);return}n.stop(`${y.success} ${v.domain(e)} removed from sale`),c()}async function _m(e,t,n){let i=C(!n.json);i.start(`Looking up active deal for ${v.domain(e)}`);let s=await x(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await s.json();s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:n.json,fields:n.fields}));let a=(r.deals||r.data||[]).filter(p=>p.domain.toLowerCase()===e.toLowerCase());a.length===0&&(i.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
207
+ Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:n.json,fields:n.fields}));let d=a[0].id;i.message(`Submitting transfer code for deal ${Ie.default.dim(d)}`);let m=await x(`/api/deals/${encodeURIComponent(d)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),f=await m.json();if(m.ok||(i.stop("Failed"),u(f.error||f.message,{hint:f.hint,status:m.status,json:n.json,fields:n.fields})),n.json){i.stop(""),b(f,n.fields);return}i.stop(`${y.success} Transfer code submitted for ${v.domain(e)}`),j("Transfer Code Submitted"),l("Domain",v.domain(e)),l("Deal",Ie.default.dim(d)),l("Status",Ie.default.green(f.status||"code_submitted")),c(),I("Track the deal:",`domani deals ${d}`),c()}z();var je=N(F(),1);L();async function pd(e,t){return e?Sm(e,t):jm(t)}function xm(e){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function jm(e){let t=C(!e.json);t.start("Loading deals");let n=xm(e),i=await x(`/api/deals${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.deals||s.data||[];if(t.stop(`${y.success} ${r.length} deal(s)`),e.json){b(s,e.fields);return}if(r.length===0){c(),console.log(` ${je.default.dim("No deals found.")}`),c(),I("List a domain for sale:","domani sell <domain> --price <amount>"),c();return}c(),j("Deals");let o=r.map(a=>{let d=a.status==="completed"?je.default.green:a.status==="active"?je.default.cyan:a.status==="cancelled"?je.default.red:je.default.yellow;return[v.domain(a.domain),v.price(a.price),d(a.status),je.default.dim(a.role||"-"),je.default.dim(new Date(a.created_at).toLocaleDateString())]});B(["Domain","Price","Status","Role","Created"],o,[28,12,14,10,14]),c(),s.next_cursor&&(console.log(` ${je.default.dim(`More: --cursor ${s.next_cursor}`)}`),c())}async function Sm(e,t){let n=C(!t.json);n.start(`Loading deal ${je.default.dim(e)}`);let i=await x(`/api/deals/${encodeURIComponent(e)}`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Deal loaded`),t.json){b(s,t.fields);return}let r=s.deal||s;j("Deal Details"),l("ID",je.default.dim(r.id)),l("Domain",v.domain(r.domain)),l("Price",v.price(r.price));let o=r.status==="completed"?je.default.green:r.status==="active"?je.default.cyan:r.status==="cancelled"?je.default.red:je.default.yellow;l("Status",o(r.status)),r.role&&l("Your Role",r.role),r.buyer&&l("Buyer",je.default.dim(r.buyer)),r.seller&&l("Seller",je.default.dim(r.seller)),r.created_at&&l("Created",je.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&l("Updated",je.default.dim(new Date(r.updated_at).toLocaleDateString())),c();let a=r.events||[];if(a.length>0){j("Timeline");for(let d of a){let m=je.default.dim(new Date(d.created_at).toLocaleString()),f=d.status==="completed"?y.success:d.status==="expired"||d.status==="refunded"?y.error:y.info;console.log(` ${f} ${m} ${d.detail||d.status}`)}c()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),c())}z();var Je=N(F(),1);L();ve();async function yd(e,t,n){switch(e){case void 0:case"list":case"ls":return Cm(n);case"request":case"acquire":case"new":return hd(t,n);case"status":case"get":return gd(t,n);case"cancel":case"rm":return Om(t,n);default:return e.includes(".")?hd(e,n):gd(e,n)}}async function hd(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),Y(e,{json:t.json});let n=C(!t.json);n.start(`Requesting acquisition of ${v.domain(e)}`);let i={domain:e};if(t.maxBudget){let a=Number(t.maxBudget);(!Number.isFinite(a)||a<=0)&&u("--max-budget must be a positive number (USD).",{json:t.json}),i.max_budget=a}let s=await x("/api/broker",{method:"POST",body:JSON.stringify(i)}),r=await s.json();s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.request||r;if(n.stop(`${y.success} Acquisition requested`),t.json)return b(r,t.fields);j("Broker request"),l("Domain",v.domain(o.domain)),l("Status",Rr(o.status)),o.max_budget!=null&&l("Max budget",v.price(o.max_budget)),l("ID",Je.default.dim(o.id)),c(),console.log(` ${Je.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),c(),I("Check progress:",`domani broker status ${o.id}`),c()}async function Cm(e){let t=C(!e.json);t.start("Loading broker requests");let n=e.status?`?status=${encodeURIComponent(e.status)}`:"",i=await x(`/api/broker${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.requests||s.data||[];if(t.stop(`${y.success} ${r.length} request(s)`),e.json)return b(s,e.fields);if(r.length===0){c(),console.log(` ${Je.default.dim("No broker requests yet.")}`),c(),I("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),c();return}c(),j("Broker requests"),B(["Domain","Status","Budget","ID"],r.map(o=>[v.domain(o.domain),Rr(o.status),o.max_budget!=null?v.price(o.max_budget):Je.default.dim("-"),Je.default.dim(o.id)])),c()}async function gd(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let n=C(!t.json);n.start("Loading request");let i=await x(`/api/broker/${encodeURIComponent(e)}`),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields}));let r=s.request||s;if(n.stop(`${y.success} ${v.domain(r.domain)}`),t.json)return b(s,t.fields);j("Broker request"),l("Domain",v.domain(r.domain)),l("Status",Rr(r.status)),r.max_budget!=null&&l("Max budget",v.price(r.max_budget)),l("Contacted",r.contacted?Je.default.green("yes"):Je.default.dim("not yet")),r.failure_reason&&l("Reason",Je.default.yellow(r.failure_reason)),l("ID",Je.default.dim(r.id)),c(),r.negotiation_id?(console.log(` ${Je.default.dim("The owner responded - an anonymous negotiation is open.")}`),c(),I("Review the offer:","domani deals"),c()):["sourcing","contacted","negotiating"].includes(r.status)&&(I("Cancel this request:",`domani broker cancel ${r.id}`),c())}async function Om(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let n=C(!t.json);n.start("Cancelling request");let i=await x(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} Request cancelled`),t.json)return b(s,t.fields);c()}function Rr(e){return["completed","agreed"].includes(e)?Je.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Je.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Je.default.dim(e):e}z();var et=N(F(),1);L();ve();var Im={registered:et.default.dim,expiring:et.default.yellow,expired:et.default.yellow,redemption:et.default.red,pending_delete:et.default.red,available:et.default.green,unknown:et.default.dim};function Am(e){return e==="pending_delete"?"pending delete":e==="unknown"?"checking":e}function bd(e){return(Im[e]??et.default.dim)(Am(e))}function wd(e){return e?e.slice(0,10):"-"}function vd(e){if(!e)return"-";let t=e.source||"for sale";return e.price!=null?`${t} $${e.price}`:t}function Rm(e){return e.code==="WATCHLIST_LIMIT"?"limit_reached":void 0}async function $d(e,t){if(Y(e,t),t.dryRun)return K("follow",{domain:e},t.json,t.fields);let n=C(!t.json);n.start(`Following ${v.domain(e)}`);let i=await x("/api/watchlist",{method:"POST",body:JSON.stringify({domain:e})}),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,code:Rm(s),json:t.json,fields:t.fields}));let r=s.watch;if(n.stop(i.status===201?`${y.success} Following ${v.domain(r.domain)}`:`${y.success} Already following ${v.domain(r.domain)}`),t.json){b(s,t.fields);return}c(),l("Now",bd(r.phase)),r.expires_at&&l("Expires",wd(r.expires_at)),r.for_sale&&l("For sale",vd(r.for_sale)),c(),console.log(` ${et.default.dim("You get an alert in the app and by email at each next step, until it drops.")}`),r.phase==="available"?I("It is free now. Register it:",`domani buy ${r.domain}`):I("See every name you follow:","domani watchlist"),c()}async function kd(e,t){if(Y(e,t),t.dryRun)return K("unfollow",{domain:e},t.json,t.fields);let n=C(!t.json);n.start(`Unfollowing ${v.domain(e)}`);let i=await x(`/api/watchlist/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await i.json();i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`${y.success} No longer following ${v.domain(e)}`),t.json&&b(s,t.fields)}async function _d(e){let t=C(!e.json);t.start("Loading the names you follow");let n=await x("/api/watchlist"),i=await n.json();n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}));let s=i.watches||[];if(t.stop(`${y.success} ${s.length} followed`),e.json){b(i,e.fields);return}if(s.length===0){c(),console.log(` ${et.default.dim("You follow no names yet.")}`),c(),I("Follow a taken name for free:","domani follow <domain>"),c();return}j("Names you follow"),B(["Domain","Now","Expires","For sale","Backorder"],s.map(r=>[v.domain(r.domain),bd(r.phase),wd(r.expires_at),vd(r.for_sale),r.backorder_id?et.default.green("yes"):et.default.dim("-")])),c(),I("Stop following one:","domani unfollow <domain>"),c()}z();var $e=N(F(),1);L();async function jd(e){return e.read?Pm(e):Em(e)}function Tm(e){let t=new URLSearchParams;e.unread&&t.set("unread","true"),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Em(e){let t=C(!e.json);t.start("Loading notifications");let n=Tm(e),i=await x(`/api/notifications${n}`),s=await i.json();i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}));let r=s.notifications||s.data||[],o=s.unread_count??r.filter(d=>!d.read).length;if(t.stop(`${y.success} ${r.length} notification(s)${o>0?` ${y.dot} ${$e.default.yellow(`${o} unread`)}`:""}`),e.json){b(s,e.fields);return}if(r.length===0){c(),console.log(` ${$e.default.dim("No notifications.")}`),c();return}c(),j("Notifications");let a=r.map(d=>{let m=d.read?$e.default.dim(y.dot):$e.default.cyan(y.info),f=Dm(d.type),p=d.read?$e.default.dim(d.title):$e.default.white(d.title),g=d.body?d.read?$e.default.dim(xd(d.body,40)):$e.default.dim(xd(d.body,40)):$e.default.dim("-"),$=$e.default.dim(new Date(d.created_at).toLocaleDateString());return[m,f,p,g,$]});B(["","Type","Title","Body","Date"],a,[3,16,28,42,14]),c(),s.next_cursor&&(console.log(` ${$e.default.dim(`More: --cursor ${s.next_cursor}`)}`),c()),o>0&&(console.log(` ${$e.default.dim("Mark all as read:")} ${$e.default.cyan("domani notifications --read")}`),c())}async function Pm(e){let t=C(!e.json);t.start("Marking all notifications as read");let n=await x("/api/notifications/read-all",{method:"POST"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),e.json){t.stop(""),b(i,e.fields);return}let s=i.count??0;t.stop(`${y.success} ${s} notification(s) marked as read`),c()}function Dm(e){let t={deal:$e.default.cyan,sale:$e.default.green,purchase:$e.default.green,transfer:$e.default.yellow,expiry:$e.default.red,security:$e.default.red,billing:$e.default.yellow,email:$e.default.blue},n=e.split(".")[0].split("_")[0];return(t[n]||$e.default.dim)(e)}function xd(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}z();var Wt=N(F(),1);L();async function Sd(e){let t=e.limit?Number(e.limit):20,n=await x(`/api/billing/invoices?limit=${t}`),i=await n.json();if(n.ok||u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields}),e.json){b({...i,count:i.invoices.length},e.fields);return}if(i.invoices.length===0){console.log(` ${Wt.default.dim("No invoices yet.")}`);return}j(`Invoices (${i.invoices.length})`),c();for(let s of i.invoices){let r=`$${(s.amount_paid/100).toFixed(2)}`,o=new Date(s.created).toLocaleDateString(),a=s.number||s.id;console.log(` ${y.success} ${Wt.default.bold(a)} ${Wt.default.green(r)} ${Wt.default.dim(o)}`),s.description&&console.log(` ${Wt.default.dim(s.description)}`),s.hosted_invoice_url&&console.log(` ${Wt.default.dim(s.hosted_invoice_url)}`)}c(),i.has_more&&(console.log(` ${Wt.default.dim(`Showing ${i.invoices.length} most recent. Use --limit to see more.`)}`),c())}z();var zn=N(F(),1);L();async function Cd(e){let t=C(!e?.json);t.start("Setting up billing session");let n=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),i.url||(t.stop("Failed"),u("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:e?.json})),t.stop("Checkout ready"),e?.json){b({url:i.url});return}c(),console.log(` ${zn.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),c(),Ve(i.url),console.log(` ${y.info} ${zn.default.dim("Complete payment setup in your browser.")}`),console.log(` ${zn.default.dim(" After setup, you can purchase domains with")} ${zn.default.cyan("domani buy")}`),c()}z();var Tr=N(F(),1);L();async function Od(e){let t=C(!e?.json);t.start("Creating upgrade session");let n=await x("/api/billing/subscribe",{method:"POST"}),i=await n.json();if(!n.ok){t.stop("Failed"),i.code==="ALREADY_SUBSCRIBED"||i.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json});return}if(t.stop("Ready"),e?.json){b({url:i.url},e?.fields);return}c(),console.log(` ${Tr.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),c(),Ve(i.url),console.log(` ${y.info} ${Tr.default.dim("Complete your plan upgrade in the browser.")}`),c()}z();var Er=N(F(),1);L();async function Id(e){let t=C(!e?.json);t.start("Cancelling subscription");let n=await x("/api/billing/cancel",{method:"POST"}),i=await n.json();if(!n.ok){t.stop("Failed"),i.code==="NOT_PAID"||i.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json});return}if(t.stop("Done"),e?.json){b(i,e?.fields);return}c();let s=i.cancel_at?new Date(i.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${y.success} ${Er.default.dim("Subscription cancelled.")} Access continues until ${Er.default.cyan(s)}.`),c()}z();var ut=N(F(),1);L();ve();st();async function Ad(e,t,n){e||(e=await be()),Y(e,n);let i=[];if(t?.length&&i.push(...t),n.set&&i.push(...n.set.split(",").map(s=>s.trim()).filter(Boolean)),i.length>0||n.reset){await Um(e,i,n);return}await Nm(e,n)}async function Nm(e,t){let n=C(!t.json);n.start(`Fetching nameservers for ${v.domain(e)}`);let i=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),s=await i.json();if(i.ok||(n.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:t.json,fields:t.fields})),n.stop(`Nameservers for ${v.domain(e)}`),t.json){b(s,t.fields);return}if(c(),s.nameservers.length===0)console.log(` ${y.warning} ${ut.default.yellow("No nameservers configured.")}`),console.log(` ${ut.default.dim("DNS operations (parking, email, connect) will not work.")}`),c(),I("Set default nameservers:",`domani nameservers ${e} --reset`);else{j("Nameservers");for(let r of s.nameservers)console.log(` ${y.success} ${ut.default.cyan(r)}`);s.default_nameservers&&s.nameservers.length===s.default_nameservers.length&&s.nameservers.every(o=>s.default_nameservers.includes(o))&&(c(),console.log(` ${ut.default.dim("Using default nameservers.")}`))}s.default_nameservers?.length&&(c(),l("Defaults",s.default_nameservers.map(r=>ut.default.dim(r)).join(ut.default.dim(", ")))),c()}async function Um(e,t,n){let i=C(!n.json);if(n.reset){i.start(`Fetching default nameservers for ${v.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(i.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:n.json,fields:n.fields})),a.default_nameservers?.length||(i.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:n.json,fields:n.fields})),t=a.default_nameservers,i.stop(`Using defaults: ${t.map(d=>ut.default.cyan(d)).join(ut.default.dim(", "))}`)}if(t.length<2&&u("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:n.json,fields:n.fields}),n.dryRun)return K("nameservers_set",{domain:e,nameservers:t},n.json,n.fields);i.start(`Setting nameservers for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:n.json,fields:n.fields})),i.stop(`${y.success} Nameservers updated`),n.json){b(r,n.fields);return}c();for(let o of r.nameservers)console.log(` ${y.success} ${ut.default.cyan(o)}`);c(),console.log(` ${ut.default.dim("Changes may take up to 48 hours to propagate.")}`),c(),I("Check propagation:",`domani status ${e}`),c()}var Rd=require("crypto"),Yn=N(require("fs"),1);De();var Xn=N(F(),1);L();function qm(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(i[s]||0))return 1;if((n[s]||0)<(i[s]||0))return-1}return 0}async function Td(e){let t=!!e?.json,n=C(!t);n.start("Checking for updates");let i=Ke();try{let s=await fetch(`${i}/api/cli/version`);s.ok||(n.stop("Failed"),u("Could not check for updates"));let r=await s.json(),o=r.version,a=r.sha256;if(qm(o,Ae)<=0){n.stop(`${y.success} Already up to date (v${Ae})`),t&&b({current:Ae,latest:o,up_to_date:!0});return}if(t&&!e?.yes){n.stop(""),b({current:Ae,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}n.stop(t?"":`New version available: ${Xn.default.cyan(Ae)} ${y.arrow} ${Xn.default.green(o)}`);let d=C(!t);d.start("Downloading update");let m=`${i}/cli/domani.js`,f=await fetch(m);f.ok||(d.stop("Download failed"),u(`Failed to download from ${m}`));let p=await f.text();a&&(0,Rd.createHash)("sha256").update(p).digest("hex")!==a&&(d.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let g=process.argv[1];g||(d.stop("Failed"),u("Could not determine binary path"));let $=Yn.default.realpathSync(g),_=$+".tmp";if(Yn.default.writeFileSync(_,p,{mode:493}),Yn.default.chmodSync(_,493),Yn.default.renameSync(_,$),d.stop(`${y.success} Updated to v${o}`),t){b({updated:!0,from:Ae,to:o});return}c(),console.log(` ${Xn.default.dim("Restart your terminal or run")} domani --version ${Xn.default.dim("to verify")}`),c()}catch(s){u(`Update failed: ${s instanceof Error?s.message:String(s)}`)}}var Ki=N(require("fs"),1),Ed=N(require("path"),1),Pd=N(require("os"),1);qe();var Zn=N(F(),1);L();De();ws();async function Dd(){let e=process.argv[1],t=e?Ki.default.realpathSync(e):null,n=Ed.default.join(Pd.default.homedir(),".domani");if(c(),console.log(` ${Zn.default.bold("This will remove:")}`),t&&console.log(` ${y.dot} CLI binary: ${Zn.default.dim(t)}`),console.log(` ${y.dot} Config dir: ${Zn.default.dim(n)}`),c(),await He({message:"Uninstall domani?"})!==!0){console.log(` ${Zn.default.dim("Cancelled.")}`);return}for(let s of ot())s.token_in_keychain&&ci(s.name);Ki.default.rmSync(n,{recursive:!0,force:!0}),t&&Ki.default.unlinkSync(t),c(),console.log(` ${y.success} domani uninstalled.`),c()}z();var re=N(F(),1);L();async function Ud(e,t){let n=t?.json,i=t?.fields,s=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=C(!n);r.start("Loading schema");let o=await xe(s),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:n,fields:i})),r.stop("Schema loaded"),n){b(a,i);return}e?Fm(e,a):Mm(a.commands)}function Mm(e){j("Commands");let t=Object.entries(e).map(([n,i])=>[re.default.bold(re.default.cyan(n)),i.description]);B(["Command","Description"],t,[20,50]),c(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),c()}function Fm(e,t){if(j(`domani ${e}`),console.log(` ${t.description}`),c(),console.log(` ${v.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){c(),console.log(` ${re.default.bold("Arguments")}`);for(let[n,i]of Object.entries(t.arguments)){let s=i.required?re.default.red("*"):"",r=re.default.dim(`(${i.type}${i.variadic?", variadic":""})`);console.log(` ${re.default.cyan(n)}${s} ${r}`),i.description&&console.log(` ${re.default.dim(i.description)}`)}}if(t.options&&Object.keys(t.options).length>0){c(),console.log(` ${re.default.bold("Options")}`);for(let[n,i]of Object.entries(t.options)){let s=i.required?re.default.red("*"):"",r=re.default.dim(`(${i.type})`),o=i.choices?re.default.dim(` [${i.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${n}`)}${s} ${r}${o}`),console.log(` ${re.default.dim(i.description)}`)}}if(t.api)if(c(),console.log(` ${re.default.bold("API")}`),Lm(t.api))Nd(t.api);else for(let[n,i]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(n))}`),Nd(i,6);t.errors&&t.errors.length>0&&(c(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(n=>re.default.dim(n)).join(re.default.dim(", "))}`)),c()}function Lm(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Nd(e,t=4){let n=" ".repeat(t);if(console.log(`${n}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[i,s]of Object.entries(e.parameters)){let r=s.required?re.default.red("*"):"",o=[s.type];s.enum&&o.push(`enum: ${s.enum.join(", ")}`),s.minimum!==void 0&&o.push(`min: ${s.minimum}`),s.maximum!==void 0&&o.push(`max: ${s.maximum}`),s.maxItems!==void 0&&o.push(`maxItems: ${s.maxItems}`),s.items&&o.push(`items: ${s.items}`),s.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${n} ${re.default.cyan(i)}${r} ${a}`),s.description&&console.log(`${n} ${re.default.dim(s.description)}`)}}z();var Be=N(F(),1);qe();L();async function qd(e){let t=C(!e.json);t.start("Loading payment method");let n=await x("/api/me"),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e.json,fields:e.fields})),e.json){t.stop(""),b(i.card?{has_payment_method:i.has_payment_method,card:i.card}:{has_payment_method:!1},e.fields);return}if(!i.has_payment_method||!i.card){t.stop("No payment method on file"),c(),console.log(` ${Be.default.dim("Add a card with")} ${Be.default.cyan("domani card add")}`),c();return}let{brand:s,last4:r,exp_month:o,exp_year:a}=i.card,d=`${String(o).padStart(2,"0")}/${a}`,m=s.charAt(0).toUpperCase()+s.slice(1);t.stop("Payment method loaded"),j("Payment method"),l("Card",`${Be.default.bold(m)} \u2022\u2022\u2022\u2022 ${Be.default.bold(r)}`),l("Expires",d),c(),console.log(` ${Be.default.dim("Update with")} ${Be.default.cyan("domani card add")}`),c()}async function Md(e){let t=C(!e?.json);t.start("Setting up payment session");let n=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),i.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){b({url:i.url},e?.fields);return}c(),console.log(` ${Be.default.dim("Opening browser")} ${y.arrow} ${v.url(i.url)}`),c(),Ve(i.url),console.log(` ${y.info} ${Be.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Be.default.dim(" After setup, you can purchase domains with")} ${Be.default.cyan("domani buy")}`),c()}async function Fd(e){if(!e?.yes&&!e?.json){let s=await He({message:"Remove your saved payment method?"});if(de(s)||!s){console.log(` ${Be.default.dim("Cancelled.")}`);return}}let t=C(!e?.json);t.start("Removing payment method");let n=await x("/api/billing/card",{method:"DELETE"}),i=await n.json();if(n.ok||(t.stop("Failed"),u(i.error||i.message,{hint:i.hint,status:n.status,json:e?.json})),t.stop(`${y.success} Payment method removed`),e?.json){b({removed:!0},e?.fields);return}c(),console.log(` ${Be.default.dim("Add a new card with")} ${Be.default.cyan("domani card add")}`),c()}var Pr=N(F(),1);z();L();async function he(e,t,n,i){let s=C(!n.json);s.start(i);let r=await x(e,t),o=await r.json();return r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:n.json,fields:n.fields})),s.stop(`${y.success} Done`),o}async function Ld(e,t){if(!e||e==="list"){let n=await he("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return b(n,t.fields);if(c(),j("Workspaces"),!n.workspaces.length){console.log(` ${Pr.default.dim("No workspaces yet.")}`),I("Create one:","domani workspace create --name Acme");return}B(["ID","Name","Role","Mailboxes","Members"],n.workspaces.map(i=>[i.id,i.name,i.role,String(i.mailbox_count),String(i.member_count)]),[28,28,10,10,8]),c();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let n=await he("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return b(n,t.fields);c(),j("Workspace Created"),l("ID",n.id),l("Name",n.name),c();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return b(n,t.fields);c(),j(n.name),l("Role",n.role),l("Mailboxes",n.mailboxes.length),l("Members",n.members.length),c(),B(["Email","Role","Mailbox grants"],n.members.map(i=>[i.email,i.role,String(i.mailbox_grants.length)]),[42,12,16]),c();return}if(e==="access"){if(t.id||u("Workspace ID required",{hint:"Usage: domani workspace access --id <id>",code:"validation_error",json:t.json}),!t.subject&&!t.resource&&!t.profile){let a=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return b(a,t.fields);c(),j("Access Graph"),l("Principals",a.principals.length),l("Mailboxes",a.mailboxes.length),l("Groups",a.groups.length),l("Collections",a.collections.length),l("Active grants",a.grants.length),l("Pending offers",a.offers.length),c();return}(!t.subject||!t.resource||!t.profile)&&u("Subject, resource, and profile are required together",{hint:"Usage: domani workspace access --id <id> --subject human:<id> --resource mailbox:<id> --profile responder [--apply]",code:"validation_error",json:t.json});let[n,i]=t.subject.split(":",2),[s,r]=t.resource.split(":",2);(!i||!["human","agent","service","token","group"].includes(n))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(s))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:n==="group"?{type:"group",id:i}:{type:"principal",principal:{type:n,id:i}},resource:{type:s,id:r},profile:t.profile,expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,t.apply?"Applying access":"Planning access");if(t.json)return b(o,t.fields);c(),j(t.apply?"Access Applied":"Access Plan"),l("Action",o.action),l("Changed",String(o.changed)),o.grant_id&&l("Grant",o.grant_id),c();return}if(e==="group"){(!t.id||!t.name)&&u("Workspace ID and group name required",{hint:"Usage: domani workspace group --id <id> --name Support --principals human:u1,agent:a1",code:"validation_error",json:t.json});let n=(t.principals||"").split(",").map(s=>s.trim()).filter(Boolean).map(s=>{let[r,o]=s.split(":",2);return o||u(`Invalid principal: ${s}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),i=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:n})},t,"Syncing access group");if(t.json)return b(i,t.fields);c(),j("Access Group Synced"),l("ID",i.id),l("Principals",i.principal_count),c();return}if(e==="collection"){(!t.id||!t.name)&&u("Workspace ID and collection name required",{hint:"Usage: domani workspace collection --id <id> --name Admin --mailboxes mb1,mb2",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(i=>i.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return b(n,t.fields);c(),j("Mailbox Collection Synced"),l("ID",n.id),l("Mailboxes",n.mailbox_count),c();return}if(e==="offer"){(!t.id||!t.email)&&u("Workspace ID and recipient email required",{hint:"Usage: domani workspace offer --id <id> --email person@example.com --mailboxes mb1,mb2 --profile responder",code:"validation_error",json:t.json});let n=(t.mailboxes||"").split(",").map(s=>s.trim()).filter(Boolean).map(s=>({resource:{type:"mailbox",id:s},profile:t.profile||"responder"})),i=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:n,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return b(i,t.fields);c(),j("Access Offered"),l("Email",i.email),l("Expires",i.expires_at),c();return}if(e==="accept-offer"){t.token||u("Access offer token required",{hint:"Usage: domani workspace accept-offer --token <token>",code:"validation_error",json:t.json});let n=await he("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return b(n,t.fields);c(),j("Access Accepted"),l("Workspace",n.workspace_name),l("Ownership",n.ownership),c();return}if(e==="revoke-access"){(!t.id||!t.grantId)&&u("Workspace and grant IDs required",{hint:"Usage: domani workspace revoke-access --id <id> --grant-id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/access/grants/${encodeURIComponent(t.grantId)}`,{method:"DELETE",body:JSON.stringify({expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,"Revoking access");if(t.json)return b(n,t.fields);c(),j("Access Revoked"),l("Grant",n.grant_id),l("Version",n.version),c();return}if(e==="rename"){(!t.id||!t.name)&&u("Workspace ID and name required",{hint:"Usage: domani workspace rename --id <id> --name <name>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return b(n,t.fields);c(),j("Workspace Renamed"),l("ID",n.id),l("Name",n.name),c();return}if(e==="invite"){(!t.id||!t.email)&&u("Workspace ID and email required",{hint:"Usage: domani workspace invite --id <id> --email person@example.com",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(i=>i.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return b(n,t.fields);c(),j("Invitation Sent"),l("Email",n.email),l("Role",n.role),l("Expires",n.expires_at),c();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let n=await he("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return b(n,t.fields);c(),j("Workspace Joined"),l("Workspace",n.workspace_name),l("Role",n.role),c();return}if(e==="revoke-invite"){(!t.id||!t.invitationId)&&u("Workspace ID and invitation ID required",{hint:"Usage: domani workspace revoke-invite --id <id> --invitation-id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return b(n,t.fields);c(),j("Invitation Revoked"),l("Invitation",n.invitation_id),c();return}if(e==="member-role"){(!t.id||!t.membershipId||!t.role)&&u("Workspace ID, membership ID, and role required",{hint:"Usage: domani workspace member-role --id <id> --membership-id <id> --role admin|member",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"PATCH",body:JSON.stringify({role:t.role})},t,"Updating member role");if(t.json)return b(n,t.fields);c(),j("Member Updated"),l("Membership",n.id),l("Role",n.role),c();return}if(e==="remove-member"){(!t.id||!t.membershipId)&&u("Workspace ID and membership ID required",{hint:"Usage: domani workspace remove-member --id <id> --membership-id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return b(n,t.fields);c(),j("Member Removed"),l("Membership",n.membership_id),c();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return b(n,t.fields);c(),j("Workspace Left"),l("Workspace",n.workspace_id),c();return}if(e==="transfer"){(!t.id||!t.membershipId)&&u("Workspace ID and target membership ID required",{hint:"Usage: domani workspace transfer --id <workspace-id> --membership-id <membership-id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return b(n,t.fields);c(),j("Ownership Transfer Requested"),l("To",n.to_email),l("Expires",n.expires_at),l("Billing",n.billing),c();return}if(e==="accept-ownership"){t.token||u("Ownership transfer token required",{hint:"Usage: domani workspace accept-ownership --token <token>",code:"validation_error",json:t.json});let n=await he("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return b(n,t.fields);c(),j("Ownership Transferred"),l("Workspace",n.workspace_id),l("Domains",n.domains_transferred),l("Mailboxes",n.mailboxes_transferred),l("Previous owner",n.previous_owner_role),c();return}if(e==="revoke-transfer"){(!t.id||!t.transferId)&&u("Workspace ID and transfer ID required",{hint:"Usage: domani workspace revoke-transfer --id <workspace-id> --transfer-id <transfer-id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return b(n,t.fields);c(),j("Ownership Transfer Revoked"),l("Transfer",n.transfer_id),c();return}if(e==="adopt-mailbox"){(!t.id||!t.mailboxId)&&u("Workspace ID and mailbox ID required",{hint:"Usage: domani workspace adopt-mailbox --id <workspace-id> --mailbox-id <mailbox-id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return b(n,t.fields);c(),j(n.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),l("Address",n.address),l("Mailboxes",n.mailbox_ids?.length??1),c();return}if(e==="grant"){(!t.id||!t.mailboxId||!t.membershipId||!t.role)&&u("Workspace, mailbox, membership, and role required",{hint:"Usage: domani workspace grant --id <id> --mailbox-id <id> --membership-id <id> --role viewer|responder|manager",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"PUT",body:JSON.stringify({membership_id:t.membershipId,role:t.role})},t,"Granting mailbox access");if(t.json)return b(n,t.fields);c(),j("Mailbox Access Granted"),l("Membership",n.membership_id),l("Mailbox",n.mailbox_id),l("Role",n.role),c();return}if(e==="revoke-grant"){(!t.id||!t.mailboxId||!t.membershipId)&&u("Workspace, mailbox, and membership required",{hint:"Usage: domani workspace revoke-grant --id <id> --mailbox-id <id> --membership-id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"DELETE",body:JSON.stringify({membership_id:t.membershipId})},t,"Revoking mailbox access");if(t.json)return b(n,t.fields);c(),j("Mailbox Access Revoked"),l("Membership",n.membership_id),l("Mailbox",n.mailbox_id),c();return}if(e==="checkout"){(!t.id||!t.plan)&&u("Workspace ID and plan required",{hint:"Usage: domani workspace checkout --id <id> --plan mail_team",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return b(n,t.fields);c(),j("Workspace Checkout"),l("Plan",n.plan),l("URL",n.url),c(),n.url&&t.open!==!1&&(console.log(` ${Pr.default.dim("Opening browser")} ${y.arrow} ${v.url(n.url)}`),Ve(n.url));return}if(e==="cancel"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace cancel --id <id>",code:"validation_error",json:t.json});let n=await he(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return b(n,t.fields);c(),j("Cancellation Scheduled"),l("Message",n.message),n.cancel_at&&l("Cancels",n.cancel_at),c();return}u(`Unknown action: ${e}`,{hint:"Actions: list, create, show, access, group, collection, offer, accept-offer, revoke-access, rename, invite, accept, revoke-invite, member-role, remove-member, leave, transfer, accept-ownership, revoke-transfer, adopt-mailbox, grant, revoke-grant, checkout, cancel",code:"validation_error",json:t.json,fields:t.fields})}var Qn=N(F(),1);z();var zi=N(require("node:crypto"),1),jn=N(require("node:fs"),1),Vd=N(require("node:os"),1),Yi=N(require("node:path"),1),Vm=process.env.DOMANI_CONFIG_DIR||Yi.default.join(Vd.default.homedir(),".domani"),Wd=Yi.default.join(Vm,"mutations");function Wm(e){return Yi.default.join(Wd,`${zi.default.createHash("sha256").update(e).digest("hex")}.json`)}function $t(e,t,n){let i=Wm(e),s=zi.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!n)try{let o=JSON.parse(jn.default.readFileSync(i,"utf8"));if(o.key&&o.fingerprint===s)return{key:o.key,complete:()=>{try{jn.default.unlinkSync(i)}catch{}}}}catch{}let r=n||`cli-${zi.default.randomUUID()}`;return jn.default.mkdirSync(Wd,{recursive:!0,mode:448}),jn.default.writeFileSync(i,JSON.stringify({key:r,fingerprint:s}),{mode:384}),{key:r,complete:()=>{try{jn.default.unlinkSync(i)}catch{}}}}L();function Hd(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[n,i]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!i)continue;let s=process.env[i];s||u(`Environment variable ${i} is empty`,{code:"validation_error",json:e.json}),t[n]=s}return Object.keys(t).length?t:void 0}async function dn(e,t){let n=await e.json();return e.ok||u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields}),n}function Xi(e,t){if(t.json)return b(e,t.fields);let n=e.http_route||e;c(),j("HTTP Route"),l("ID",n.id),l("URL",n.url),l("Upstream",n.upstream),l("Status",n.status),l("Expires",n.expires_at),l("Browser mode",n.browser_mode||"stateless"),n.upstream_verification?.secret&&(l("Verification secret",Qn.default.yellow(n.upstream_verification.secret)),console.log(Qn.default.dim(" Save this secret now. It will not be shown again after this receipt."))),c()}function Hm(e){let t=new URLSearchParams;e.domain&&t.set("domain",e.domain),e.hostname&&t.set("hostname",e.hostname),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Jd(e,t,n){if(!e||e==="list"){let i=await dn(await x(`/api/http-routes${Hm(n)}`),n);if(n.json)return b(i,n.fields);c(),j("HTTP Routes");for(let s of i.http_routes)console.log(` ${Qn.default.dim(s.id)} ${s.hostname} ${s.status} ${s.upstream}`);c(),i.next_cursor&&(console.log(` ${Qn.default.dim(`More: --cursor ${i.next_cursor}`)}`),c());return}if(e==="create"){n.upstream||u("--upstream is required",{code:"validation_error",json:n.json});let i=Hd(n),s={...n.hostname?{hostname:n.hostname}:{},upstream:n.upstream,...n.expiresIn?{expires_in:Number(n.expiresIn)}:{},...n.hostHeader?{host_header:n.hostHeader}:{},...n.upstreamVerification?{upstream_verification:n.upstreamVerification}:{},...i?{upstream_headers:i}:{}},r=$t(`route:create:${n.hostname||"auto"}`,s,n.idempotencyKey),o=C(!n.json);o.start("Creating HTTP route");let a=await dn(await x("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(s)}),n);return r.complete(),o.stop(`${y.success} HTTP route created`),Xi(a,n)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:n.json}),e==="get")return Xi(await dn(await x(`/api/http-routes/${encodeURIComponent(t)}`),n),n);if(e==="delete"){let i=await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(i.ok||await dn(i,n),n.json)return b({deleted:!0,id:t},n.fields);console.log(`${y.success} HTTP route deleted`);return}if(e==="refresh"){n.expiresIn||u("--expires-in is required",{code:"validation_error",json:n.json});let i={expires_in:Number(n.expiresIn)},s=$t(`route:refresh:${t}`,i,n.idempotencyKey),r=await dn(await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":s.key},body:JSON.stringify(i)}),n);return s.complete(),Xi(r,n)}if(e==="rotate-verification"){let i=$t(`route:rotate-verification:${t}`,{},n.idempotencyKey),s=await dn(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":i.key}}),n);return i.complete(),n.json?b(s,n.fields):Xi(s,n)}if(e==="rotate-headers"){let i=Hd(n);i||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:n.json});let s=$t(`route:rotate-headers:${t}`,{upstream_headers:i},n.idempotencyKey),r=await dn(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":s.key},body:JSON.stringify({upstream_headers:i})}),n);if(s.complete(),n.json)return b(r,n.fields);console.log(`${y.success} Upstream headers replaced: ${r.upstream_header_names.join(", ")||"none"}`);return}u(`Unknown action: ${e}`,{hint:"Actions: create, list, get, refresh, rotate-verification, rotate-headers, delete",code:"validation_error",json:n.json})}var Q=N(F(),1),Kd=require("node:fs");oi();z();L();var Nr="mailzero-personal-ai.v1",Z=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="AssistantUsageError"}},Jm={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct",approve:"approve",reject:"reject",tag:"tag"},Bm=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","approve","reject","tag","plan","activity","export","delete","brief","facts","sender","task","lease","release","effects","escalate","report","rules","approvals","suggestions","metrics"];function Dr(e,t,n){if(!e)throw new Z(`${t} is required`,n);try{return JSON.parse(e)}catch{throw new Z(`${t} must be valid JSON`,n)}}function Zi(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Bd(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function ln(e,t,n){let i=Number(e);if(!Number.isInteger(i)||i<n)throw new Z(`${t} must be an integer of at least ${n}`);return i}function Gm(e,t,n){let i=e||"today";switch(i){case"today":{let s=new URLSearchParams;n.category&&s.set("category",n.category.trim().toLowerCase()),n.tag&&s.set("tag",n.tag.trim().toLowerCase());let r=s.toString();return{method:"GET",path:r?`/api/assistant/today?${r}`:"/api/assistant/today"}}case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let s={};if(n.enable&&n.disable)throw new Z("Use either --enable or --disable");if(n.pause&&n.resume)throw new Z("Use either --pause or --resume");if(n.enable&&(s.enabled=!0),n.disable&&(s.enabled=!1),n.shadow!==void 0&&(s.shadow_enabled=n.shadow),n.pause&&(s.paused=!0),n.resume&&(s.paused=!1),n.none?s.mailbox_ids=[]:n.mailboxes!==void 0&&(s.mailbox_ids=Bd(n.mailboxes)),n.days!==void 0&&(s.history_window_days=ln(n.days,"--days",1)),n.attachmentVision!==void 0){if(!["on","off"].includes(n.attachmentVision))throw new Z("--attachment-vision must be on or off");s.attachment_vision=n.attachmentVision==="on"}if(!Object.keys(s).length)throw new Z("Provide at least one setting","Options: --enable, --disable, --shadow, --no-shadow, --pause, --resume, --mailboxes <ids>, --none, --days <n>, --attachment-vision <on|off>");return{method:"PUT",path:"/api/assistant/settings",body:s}}case"preview":{if(!n.consent)throw new Z("--consent is required to start the assistant",`Consent means Domani may read the selected mailboxes and send bounded, minimized message content to the approved private model route (version ${Nr}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let s=Bd(n.mailboxes);if(!s.length)throw new Z("--mailboxes is required","Pass owned mailbox IDs, comma-separated. List them with: domani assistant settings");return{method:"POST",path:"/api/assistant/preview",body:{mailbox_ids:s,history_window_days:n.days===void 0?30:ln(n.days,"--days",1),consent:!0,consent_version:Nr}}}case"backfill":return{method:"GET",path:"/api/assistant/backfill"};case"retry":return{method:"POST",path:"/api/assistant/backfill",idempotency:"assistant:retry"};case"item":if(!t)throw new Z("Work item ID is required","Usage: domani assistant item <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}`};case"brief":{if(t)return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/brief`};if(!n.correspondent)throw new Z("Work item ID or --correspondent is required","Usage: domani assistant brief <id> | domani assistant brief --correspondent ada@example.com [--mailbox hi@myapp.dev]");let s=new URLSearchParams({correspondent:n.correspondent});return n.mailbox&&s.set("mailbox",n.mailbox),{method:"GET",path:`/api/assistant/brief?${s}`}}case"facts":if(!t)throw new Z("Work item ID is required","Usage: domani assistant facts <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/facts`};case"sender":if(!t)throw new Z("Work item ID is required","Usage: domani assistant sender <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/sender`};case"plan":if(!t)throw new Z("Action plan ID is required","Usage: domani assistant plan <id>");return{method:"GET",path:`/api/assistant/action-plans/${encodeURIComponent(t)}`};case"activity":return{method:"GET",path:`/api/assistant/activity${n.limit!==void 0?`?limit=${ln(n.limit,"--limit",1)}`:""}`};case"rules":return{method:"GET",path:"/api/assistant/rules"};case"approvals":return{method:"GET",path:"/api/assistant/approvals"};case"suggestions":return{method:"GET",path:"/api/assistant/suggestions"};case"metrics":return{method:"GET",path:`/api/assistant/metrics${n.days!==void 0?`?window_days=${ln(n.days,"--days",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!n.yes)throw new Z("Deleting derived assistant data requires --yes","This removes analyses, Decisions, plans, receipts, imports, and settings. Source mail is never touched.");return{method:"DELETE",path:"/api/assistant/data"};case"task":if(!t)throw new Z("Task ID is required","Usage: domani assistant task <work item id>");return{method:"GET",path:`/api/assistant/tasks/${encodeURIComponent(t)}`};case"lease":{if(!t)throw new Z("Task ID is required","Usage: domani assistant lease <id> [--ttl <seconds>]");let s={};return n.ttl!==void 0&&(s.ttl_seconds=ln(n.ttl,"--ttl",30)),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`,body:s}}case"release":if(!t)throw new Z("Task ID is required","Usage: domani assistant release <id>");return{method:"DELETE",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`};case"effects":{if(!t)throw new Z("Task ID is required","Usage: domani assistant effects <id> --effects '<json array>'");let s=Dr(n.effects,"--effects",`A JSON array of effects, for example: --effects '[{"kind":"label","mailbox_id":"mbx_1","add":["finance"]}]'`);if(!Array.isArray(s)||!s.length)throw new Z("--effects must be a non-empty JSON array","Kinds: reply, forward, label, snooze, resolve, note, request");let r={effects:s};return n.text&&(r.note=n.text),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/effects`,body:r,idempotency:`assistant:effects:${t}`}}case"escalate":{if(!t)throw new Z("Task ID is required","Usage: domani assistant escalate <id> --question '<text>' [--options '<json>'] [--evidence <refs>]");if(!n.question)throw new Z("--question is required","What the owner must decide, with the evidence in --evidence");let s={question:n.question};n.options&&(s.options=Dr(n.options,"--options","A JSON array of { key, label, outcome }"));let r=Zi(n.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/escalate`,body:s}}case"report":{if(!t)throw new Z("Task ID is required","Usage: domani assistant report <id> --outcome done|blocked|handed_back --summary '<text>' [--claims '<json>'] [--evidence <refs>]");if(!n.outcome||!["done","blocked","handed_back"].includes(n.outcome))throw new Z("--outcome must be done, blocked or handed_back");if(!n.summary)throw new Z("--summary is required","What was done and how it ended, in a few lines");let s={outcome:n.outcome,summary:n.summary};n.claims&&(s.claims=Dr(n.claims,"--claims","A JSON array of { kind, ref } the platform reconciles with its receipts"));let r=Zi(n.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/report`,body:s}}case"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":case"approve":case"reject":case"tag":{if(!t)throw new Z("Work item ID is required",`Usage: domani assistant ${i} <id> --item-version <work_item_version>`);if(n.itemVersion===void 0)throw new Z("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let s=Jm[i],r={type:s,work_item_version:ln(n.itemVersion,"--item-version",1)};if(s==="ignore"&&n.scope){if(!["item","sender","sender_domain","situation"].includes(n.scope))throw new Z("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=n.scope}if(s==="choose"){if(!n.option||!n.decision||n.decisionVersion===void 0)throw new Z("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=n.decision,r.decision_version=ln(n.decisionVersion,"--decision-version",1),r.option_id=n.option}if(s==="instruct"){if(!n.text)throw new Z("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=n.text}if(s==="snooze"){if(!n.until)throw new Z("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=n.until}if(s==="correct"){if(!n.field||!n.text)throw new Z("--field and --text are required","Name the analysis field to correct and the correct value");r.field=n.field,r.correction=n.text}if(s==="tag"){let o=Zi(n.add),a=Zi(n.remove);if(!o.length&&!a.length)throw new Z("--add or --remove is required","Example: domani assistant tag <id> --item-version 3 --add lumenworks --remove draft");o.length&&(r.add=o),a.length&&(r.remove=a)}if(s==="approve"||s==="reject"){if(!n.plan)throw new Z("--plan is required","The waiting action plan shown by: domani assistant task <id>");r.plan_id=n.plan,s==="reject"&&n.text&&(r.reason=n.text)}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${s}:${t}`}}default:throw new Z(`Unknown action: ${i}`,`Actions: ${Bm.join(", ")}`)}}async function Km(e,t){let n=await e.json();if(e.ok)return n;n.code==="NOT_AVAILABLE"&&u(`The ${Pt.mailProductName} assistant is in private preview`,{hint:"It is enabled per account during the private beta. Ask for access at https://domani.run/support or wait for general availability.",code:"not_available",status:e.status,json:t.json,fields:t.fields}),n.code==="INSUFFICIENT_SCOPE"&&u(n.error||"Missing assistant scope",{hint:"This token needs the assistant:read scope for reads and assistant:write for changes. Create one with: domani tokens create --scopes assistant:read,assistant:write",code:"insufficient_scope",status:e.status,json:t.json,fields:t.fields}),u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields})}function zm(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",n=e.recurrence?.count&&e.recurrence.count>1?Q.default.dim(`x${e.recurrence.count}`):"",i=[e.category?e.category.replace(/_/g," "):"",...(e.tags??[]).map(s=>`#${s}`)].filter(Boolean).join(" ");return[Q.default.dim(e.id),t,i,`${(e.title||e.summary||"").slice(0,60)} ${n}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function Ym(e,t){if(t.json)return b(e,t.fields);c(),j("Today");let n=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],i=0;for(let[a,d]of n){let m=e.sections&&typeof e.sections=="object"?e.sections:e,f=Array.isArray(m[a])?m[a]:[];f.length&&(i+=f.length,console.log(` ${Q.default.bold(d)} ${Q.default.dim(`(${f.length})`)}`),B(["ID","Who","Kind","Summary","Deadline"],f.map(zm)),c())}i||console.log(Q.default.dim(t.tag?` Nothing tagged ${t.tag} right now.`:t.category?` Nothing of the kind ${t.category} right now.`:" Nothing needs you right now."));let s=e.categories&&typeof e.categories=="object"?Object.entries(e.categories).sort((a,d)=>d[1]-a[1]):[];s.length>1&&console.log(Q.default.dim(` Kinds: ${s.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --category)`));let r=e.tags&&typeof e.tags=="object"?Object.entries(e.tags).sort((a,d)=>d[1]-a[1]):[];r.length&&console.log(Q.default.dim(` Tags: ${r.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --tag)`));let o=typeof e.as_of=="string"?e.as_of:void 0;o&&console.log(Q.default.dim(` As of ${o}`)),c()}function Xm(e,t){if(t.json)return b(e,t.fields);let n=e.brief??e;if(e.correspondent&&!e.brief){c(),j(`Brief for ${e.correspondent}`),console.log(` ${Q.default.dim("Nothing analysed from this person yet.")}`);for(let i of e.recent_mail||[])l(i.received_at.slice(0,10),`${i.subject||""} (${i.mailbox})`);return}c(),j(n.title||"Brief"),n.situation&&l("Status",`${n.situation.status||""}${n.situation.attention?.level?` \xB7 ${n.situation.attention.level}`:""}${n.situation.occurrences&&n.situation.occurrences>1?` \xB7 ${n.situation.occurrences} messages`:""}`),n.situation?.sender?.address&&l("With",`${n.situation.sender.name?`${n.situation.sender.name} `:""}<${n.situation.sender.address}>`),n.summary&&l("Summary",n.summary),n.ask&&l("Ask",n.ask);for(let i of n.story||[])l(i.occurred_at.slice(0,10),`${i.title}${i.analysed?"":Q.default.dim(" (not analysed)")}`);for(let i of n.facts||[])l("Fact",`${i.subject||""} ${i.predicate||""} ${i.value?.value??i.object??""}${i.value?.currency?` ${i.value.currency}`:""}`.trim());for(let i of n.awaiting||[])l(i.overdue?Q.default.red("Awaited"):"Awaited",`${i.who}: ${i.what} (since ${i.since.slice(0,10)})`);for(let i of n.commitments||[])l(i.overdue?Q.default.red("Promised"):"Promised",`${i.who}: ${i.what}`);for(let i of(n.settled||[]).slice(0,5))l("Settled",`${i.what} (${i.status}, ${i.at.slice(0,10)})`);n.decision?.question&&l("Decision",`${n.decision.question} ${(n.decision.options||[]).map(i=>`${i.recommended?"\u2605 ":""}${i.label}`).join(" / ")}`),n.suggested_next&&l("Next",`${n.suggested_next.action} ${Q.default.dim(`(${n.suggested_next.reason})`)}`),e.related&&e.related.length&&l("Also",`${e.related.length} other item(s) from this person`)}function Zm(e,t){if(t.json)return b(e,t.fields);let n=e;c(),j(n.sender?`${n.sender.name?`${n.sender.name} `:""}<${n.sender.address}>`:"Sender"),n.organisation?(l("Organisation",`${n.organisation.name||n.sender?.domain||""}${n.organisation.legal_name&&n.organisation.legal_name!==n.organisation.name?` (${n.organisation.legal_name})`:""}${n.organisation.fresh?"":Q.default.dim(" (profile ageing)")}`),n.organisation.pitch&&l("About",n.organisation.pitch),n.organisation.registered_at&&l("Domain since",n.organisation.registered_at.slice(0,10)),l("Mail",`${n.organisation.mail.provider||"unknown provider"} \xB7 spf ${n.organisation.mail.spf===null?"?":n.organisation.mail.spf?"yes":"no"} \xB7 dmarc ${n.organisation.mail.dmarc}`)):n.sender?.shared_domain?l("Organisation",Q.default.dim(`${n.sender.domain} is a shared mail domain`)):n.sender?.domain&&l("Organisation",Q.default.dim(`${n.sender.domain} not analysed yet`));let i=n.relationship;if(i){let s=i.first_received_at&&i.last_received_at?` between ${i.first_received_at.slice(0,10)} and ${i.last_received_at.slice(0,10)}`:"";l("Received",i.received?`${i.received_capped?"50+":i.received} message(s)${s}`:"nothing before this");for(let r of i.matters.slice(0,5))l(r.last_seen_at.slice(0,10),`${r.title} ${Q.default.dim(`(${r.status}, ${r.id})`)}`);i.organisation?.matters.length&&l("Colleagues",`${i.organisation.other_senders.join(", ")}: ${i.organisation.matters.slice(0,3).map(r=>r.title).join(" / ")}`)}for(let s of n.participants||[])l(s.roles.join("+"),`${s.name?`${s.name} `:""}<${s.address}>${s.messages>1?Q.default.dim(` \xD7${s.messages}`):""}${s.same_organisation?"":Q.default.dim(" (outside)")}`)}function Gd(e,t){if(t.json)return b(e,t.fields);let n=e.work_item||e;if(c(),j("Work item"),l("ID",n.id),l("Version",String(n.version??"")),l("Status",n.status||""),l("Mailbox",n.mailbox?.name?`${n.mailbox.name} <${n.mailbox.address||""}>`:n.mailbox?.address||""),n.title&&l("Title",n.title),n.sender?.address&&l("From",`${n.sender.name?`${n.sender.name} `:""}<${n.sender.address}>${n.sender.kind&&n.sender.kind!=="human"?` (${n.sender.kind})`:""}`),n.ask&&l("Ask",n.ask),n.recurrence?.count&&n.recurrence.count>1&&l("Recurrence",`${n.recurrence.count} messages since ${(n.recurrence.first_seen_at||"").slice(0,10)}`),l("Summary",n.summary||""),n.attention?.reason&&l("Why",n.attention.reason),n.attention?.deadline&&l("Deadline",n.attention.deadline),n.source?.event_id&&l("Source",`${n.source.type||"mail"} ${n.source.event_id}`),n.decision?.options?.length){c(),console.log(` ${Q.default.bold("Decision")} ${Q.default.dim(`${n.decision.id} v${n.decision.version??1}`)}`);for(let i of n.decision.options)console.log(` ${Q.default.dim(i.id)} ${i.label}${i.recommended?Q.default.green(" recommended"):""}`);console.log(Q.default.dim(` Choose with: domani assistant choose ${n.id} --version ${n.version??1} --decision ${n.decision.id} --decision-version ${n.decision.version??1} --option <id>`))}n.plan?.id&&l("Plan",`${n.plan.id} (preview with: domani assistant plan ${n.plan.id})`),c()}function Qm(e,t){if(t.json)return b(e,t.fields);c(),j(`${Pt.mailProductName} assistant`),l("Enabled",e.enabled?"yes":"no"),l("Shadow",e.shadow_enabled?"yes":"no"),l("Paused",e.paused?"yes":"no"),l("History window",`${e.history_window_days} days`),l("Privacy route",String(e.privacy_route||"")),l("Consent",e.consent?.accepted_version?`${e.consent.accepted_version} at ${e.consent.accepted_at}`:`none (required: ${e.consent?.required_version||Nr})`),c();let n=new Set(e.mailbox_ids||[]),i=e.mailboxes||[];i.length&&B(["ID","Address","AI"],i.map(s=>[Q.default.dim(s.id),s.address,n.has(s.id)?Q.default.green("on"):Q.default.dim("off")])),c()}function ef(e,t){if(t.json)return b(e,t.fields);let n=e.backfill;if(c(),j("History import"),!n){console.log(Q.default.dim(" No import has run yet.")),c();return}l("Status",`${n.status} (${n.phase})`),l("Progress",`${n.processed}/${n.total}${n.percent===null||n.percent===void 0?"":` (${n.percent}%)`}`),l("Failed",String(n.failed??0)),l("Paused",n.paused?"yes":"no"),n.estimated_completion_at&&l("ETA",n.estimated_completion_at),n.can_close_app&&console.log(Q.default.dim(" The import continues in the background.")),c()}function tf(e,t){if(t.json)return b(e,t.fields);let n=e.action_plan||e.plan||e;c(),j("Action preview"),l("ID",n.id),l("Status",n.status||""),n.expires_at&&l("Expires",n.expires_at);for(let i of n.effects||[])c(),console.log(` ${Q.default.bold(i.kind||"effect")} ${Q.default.dim(`mailbox ${i.mailbox_id||""}`)}${i.reply_to_message_id?Q.default.dim(` in reply to ${i.reply_to_message_id}`):""}`),i.body&&console.log(`
208
208
  ${String(i.body).split(`
209
209
  `).map(s=>` ${s}`).join(`
210
210
  `)}
211
- `);console.log(Q.default.dim(` Nothing is sent by this command. Send through the reply endpoint with assistant_plan_id=${n.id} or from the app.`)),l()}function Um(e,t){if(t.json)return b(e,t.fields);let n=e.events||[];l(),j("Assistant activity"),n.length?G(["When","Kind","Action","Work item"],n.map(i=>[i.occurred_at||"",i.kind||"",i.action||i.type||"",Q.default.dim(i.work_item?.id||i.work_item_id||"")])):console.log(Q.default.dim(" No activity yet.")),l()}async function Dd(e,t,n){let i;try{i=Cm(e,t,n)}catch(p){throw p instanceof Z&&u(p.message,{hint:p.hint,code:"validation_error",json:n.json}),p}let s=e||"today",r={},o;i.idempotency&&(o=vt(i.idempotency,i.body||{},n.idempotencyKey),r["Idempotency-Key"]=o.key,i.body&&i.path.endsWith("/interactions")&&(i.body.idempotency_key=o.key));let a={set:"Updating assistant settings",preview:"Recording consent and starting the history import",retry:"Requeuing failed messages",delete:"Deleting derived assistant data"}[s]||(i.method!=="GET"?"Recording your decision":void 0),d=O(!n.json&&!!a);a&&d.start(a);let m=await x(i.path,{method:i.method,headers:r,...i.body?{body:JSON.stringify(i.body)}:{}}),f=await Am(m,n);switch(o?.complete(),a&&d.stop(`${y.success} Done`),s){case"today":return Rm(f,n);case"settings":return Pm(f,n);case"backfill":return Dm(f,n);case"item":return Ed(f,n);case"brief":return Tm(f,n);case"facts":return b(f,n.fields);case"sender":return Em(f,n);case"plan":return Nm(f,n);case"activity":return Um(f,n);case"export":{let p=`${JSON.stringify(f,null,2)}
212
- `;if(n.out){if((0,Pd.writeFileSync)(n.out,p,"utf8"),n.json)return b({exported:!0,path:n.out},n.fields);console.log(`${y.success} Derived assistant data exported to ${n.out}`);return}process.stdout.write(p);return}case"delete":if(n.json)return b(f,n.fields);console.log(`${y.success} Derived assistant data deleted. Source mail is untouched.`);return;default:if(n.json)return b(f,n.fields);if(s==="set"||s==="preview"||s==="retry"){s==="preview"&&console.log(Q.default.dim(` Import ${f.preview?.backfill_id||""} runs in the background. Follow it with: domani assistant backfill`)),s==="retry"&&console.log(` Requeued ${f.retried??f.requeued??0} messages`),s==="set"&&console.log(` enabled=${f.enabled?"yes":"no"} shadow=${f.shadow_enabled?"yes":"no"} paused=${f.paused?"yes":"no"} mailboxes=${(f.mailbox_ids||[]).length}`);return}return f.work_item?Ed(f,n):b(f,n.fields)}}z();var Yi=N(F(),1);V();var qm=["list","token","tokens","revoke-token"],ln=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="AgentsUsageError"}};function Mm(e,t,n){switch(e||"list"){case"list":return{method:"GET",path:"/api/agents/identity"};case"token":{if(!t)throw new ln("Agent handle is required",'Usage: domani agents token <slug> [--name "Dave on the pod"] [--mailboxes mb_1,mb_2]');let i=(n.mailboxes||"").split(",").map(s=>s.trim()).filter(Boolean);return{method:"POST",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`,body:{...n.name?{name:n.name}:{},...i.length?{mailbox_ids:i}:{}}}}case"tokens":if(!t)throw new ln("Agent handle is required","Usage: domani agents tokens <slug>");return{method:"GET",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`};case"revoke-token":if(!t||!n.tokenId)throw new ln("Agent handle and --token-id are required","Usage: domani agents revoke-token <slug> --token-id <id>");return{method:"DELETE",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens/${encodeURIComponent(n.tokenId)}`};default:throw new ln(`Unknown action: ${e}`,`Actions: ${qm.join(", ")}`)}}async function Nd(e,t,n){let i;try{i=Mm(e,t,n)}catch(o){if(o instanceof ln)return u(o.message,{hint:o.hint,code:"validation_error",json:n.json,fields:n.fields});throw o}let s=await x(i.path,{method:i.method,...i.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(i.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:n.json,fields:n.fields});if(n.json)return b(r,n.fields);switch(e||"list"){case"list":{let o=r.identities||r.items||[];if(j("Agent identities"),!o.length){console.log(` ${Yi.default.dim("No agent identity yet. Claim one: domani agents claim is on the web at /agents")}`);return}G(["Handle","Name","Email"],o.map(a=>[a.slug,a.name||"",a.email||""]),[24,30,40]);return}case"token":{j("Agent API key"),c("Key",r.key||r.token||""),r.scopes&&c("Scopes",r.scopes.join(", ")),r.mailbox_ids?.length&&c("Mailboxes",r.mailbox_ids.join(", ")),_e("Shown once. The key sees only this agent's mailboxes and the items handed to it.");return}case"tokens":{let o=r.tokens||[];if(j("Agent API keys"),!o.length){console.log(` ${Yi.default.dim("No key yet: domani agents token <slug>")}`);return}G(["ID","Name","Scopes","Last used"],o.map(a=>[a.id,a.name||"",(a.scopes||[]).join(","),a.last_used_at||"never"]),[28,24,40,20]);return}case"revoke-token":console.log(`${Yi.default.green("\u2713")} Token revoked`);return}}z();var Wt=N(F(),1);V();var Fm=["providers","connect","connector","import","verify","disconnect"],st=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="MailboxUsageError"}};function Lm(e,t,n){switch(e){case"providers":return{path:"/api/emails/connect/providers",method:"GET"};case"connect":{if(t==="forwarding"){if(!n.address)throw new st("--address is required.","domani mailbox connect forwarding --address someone@gmail.com");return{path:"/api/emails/connect/forwarding",method:"POST",body:{address:n.address,...n.workspace?{workspace_id:n.workspace}:{}}}}let i=t??"gmail";if(i!=="gmail"&&i!=="outlook")throw new st(`Unknown provider "${t}".`,"gmail or outlook (the APIs), or forwarding (a rule at any provider).");if(n.since&&n.window)throw new st("Use --since or --window, not both.");return{path:`/api/emails/connect/${i}`,method:"POST",body:{...n.since?{since:n.since}:{},...n.window?{window:n.window}:{},...n.workspace?{workspace_id:n.workspace}:{}}}}case"connector":if(!t)throw new st("Address required.","domani mailbox connector someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"GET"};case"import":if(!t)throw new st("Address required.","domani mailbox import someone@gmail.com --since 2026-06-01");if(!n.since)throw new st("--since is required.","The date the import should reach back to, for example --since 2026-06-01.");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/import`,method:"POST",body:{since:n.since}};case"verify":if(!t)throw new st("Address required.","domani mailbox verify someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector/verify`,method:"POST"};case"disconnect":if(!t)throw new st("Address required.","domani mailbox disconnect someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"DELETE"};default:throw new st(`Unknown action "${e??""}".`,`Actions: ${Fm.join(", ")}.`)}}function Vm(e){j(`${e.address} (${e.kind})`),c("Status",String(e.status)),c("Phase",String(e.phase)+(e.paused_reason?` (${e.paused_reason})`:"")),c("Imported since",e.import_since?new Date(String(e.import_since)).toLocaleString():"-");let t=e.forwarding;if(t){c("Forward to",String(t.address??"-")),c("Forwarded",`${t.forwarded??0}${t.last_forwarded_at?`, last ${new Date(t.last_forwarded_at).toLocaleString()}`:""}`),t.confirmation&&c("Gmail confirmation",`${Wt.default.bold(t.confirmation.code)}${t.confirmation.url?` ${t.confirmation.url}`:""}`);let i=t.guide;i&&c("Provider",`${i.name??"unknown"}${i.settings_url?` ${i.settings_url}`:""}${i.limits?.includes("paid_plan")?" (forwarding needs a paid plan there)":""}`),t.probe&&c("Probe",t.probe.returned_at?`came back ${new Date(t.probe.returned_at).toLocaleString()}`:`sent ${new Date(t.probe.sent_at).toLocaleString()}, not back yet`)}let n=e.import_run;n&&c("Import",`${n.status}: ${n.copied} copied, ${n.analysed}/${n.to_analyse} analysed${n.listing_done?"":", still listing"}`),e.source_messages_total&&c("In the source",`${e.source_messages_total} messages`),c("Last sync",e.last_sync_at?new Date(String(e.last_sync_at)).toLocaleString():"never"),e.last_error&&c("Last error",Wt.default.yellow(String(e.last_error)))}async function Ud(e,t,n){let i;try{i=Lm(e,t,n)}catch(o){if(o instanceof st)return u(o.message,{hint:o.hint,code:"validation_error",json:n.json});throw o}let s=await x(i.path,{method:i.method,...i.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(i.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:n.json,code:String(r.code??"request_failed")});if(e==="connect"&&t==="forwarding"){if(n.json)return b(r,n.fields);j("Connect your inbox by forwarding"),c("Inbox",String(r.address)),c("Forward to",Wt.default.cyan(String(r.forwarding_address))),c("Status",String(r.status));let o=r.instructions;for(let[a,d]of Object.entries(o??{}))console.log(`
213
- ${Wt.default.bold(a==="gmail"?"Gmail":a==="outlook"?"Outlook":"Any provider")}`),d.forEach((m,f)=>console.log(` ${f+1}. ${m}`));_e(`Then: domani mailbox verify ${r.address} sends a probe; domani mailbox connector ${r.address} shows the confirmation code and the status.`);return}if(e==="connect"){if(n.json&&!n.wait)return b(r,n.fields);if(j("Connect your Gmail inbox"),c("Import since",new Date(String(r.import_since)).toLocaleString()),console.log(`
211
+ `);console.log(Q.default.dim(` Nothing is sent by this command. Send through the reply endpoint with assistant_plan_id=${n.id} or from the app.`)),c()}function nf(e,t){if(t.json)return b(e,t.fields);let n=e.events||[];c(),j("Assistant activity"),n.length?B(["When","Kind","Action","Work item"],n.map(i=>[i.occurred_at||"",i.kind||"",i.action||i.type||"",Q.default.dim(i.work_item?.id||i.work_item_id||"")])):console.log(Q.default.dim(" No activity yet.")),c()}async function zd(e,t,n){let i;try{i=Gm(e,t,n)}catch(p){throw p instanceof Z&&u(p.message,{hint:p.hint,code:"validation_error",json:n.json}),p}let s=e||"today",r={},o;i.idempotency&&(o=$t(i.idempotency,i.body||{},n.idempotencyKey),r["Idempotency-Key"]=o.key,i.body&&i.path.endsWith("/interactions")&&(i.body.idempotency_key=o.key));let a={set:"Updating assistant settings",preview:"Recording consent and starting the history import",retry:"Requeuing failed messages",delete:"Deleting derived assistant data"}[s]||(i.method!=="GET"?"Recording your decision":void 0),d=C(!n.json&&!!a);a&&d.start(a);let m=await x(i.path,{method:i.method,headers:r,...i.body?{body:JSON.stringify(i.body)}:{}}),f=await Km(m,n);switch(o?.complete(),a&&d.stop(`${y.success} Done`),s){case"today":return Ym(f,n);case"settings":return Qm(f,n);case"backfill":return ef(f,n);case"item":return Gd(f,n);case"brief":return Xm(f,n);case"facts":return b(f,n.fields);case"sender":return Zm(f,n);case"plan":return tf(f,n);case"activity":return nf(f,n);case"export":{let p=`${JSON.stringify(f,null,2)}
212
+ `;if(n.out){if((0,Kd.writeFileSync)(n.out,p,"utf8"),n.json)return b({exported:!0,path:n.out},n.fields);console.log(`${y.success} Derived assistant data exported to ${n.out}`);return}process.stdout.write(p);return}case"delete":if(n.json)return b(f,n.fields);console.log(`${y.success} Derived assistant data deleted. Source mail is untouched.`);return;default:if(n.json)return b(f,n.fields);if(s==="set"||s==="preview"||s==="retry"){s==="preview"&&console.log(Q.default.dim(` Import ${f.preview?.backfill_id||""} runs in the background. Follow it with: domani assistant backfill`)),s==="retry"&&console.log(` Requeued ${f.retried??f.requeued??0} messages`),s==="set"&&console.log(` enabled=${f.enabled?"yes":"no"} shadow=${f.shadow_enabled?"yes":"no"} paused=${f.paused?"yes":"no"} mailboxes=${(f.mailbox_ids||[]).length}`);return}return f.work_item?Gd(f,n):b(f,n.fields)}}z();var Qi=N(F(),1);L();var sf=["list","token","tokens","revoke-token"],cn=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="AgentsUsageError"}};function rf(e,t,n){switch(e||"list"){case"list":return{method:"GET",path:"/api/agents/identity"};case"token":{if(!t)throw new cn("Agent handle is required",'Usage: domani agents token <slug> [--name "Dave on the pod"] [--mailboxes mb_1,mb_2]');let i=(n.mailboxes||"").split(",").map(s=>s.trim()).filter(Boolean);return{method:"POST",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`,body:{...n.name?{name:n.name}:{},...i.length?{mailbox_ids:i}:{}}}}case"tokens":if(!t)throw new cn("Agent handle is required","Usage: domani agents tokens <slug>");return{method:"GET",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`};case"revoke-token":if(!t||!n.tokenId)throw new cn("Agent handle and --token-id are required","Usage: domani agents revoke-token <slug> --token-id <id>");return{method:"DELETE",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens/${encodeURIComponent(n.tokenId)}`};default:throw new cn(`Unknown action: ${e}`,`Actions: ${sf.join(", ")}`)}}async function Yd(e,t,n){let i;try{i=rf(e,t,n)}catch(o){if(o instanceof cn)return u(o.message,{hint:o.hint,code:"validation_error",json:n.json,fields:n.fields});throw o}let s=await x(i.path,{method:i.method,...i.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(i.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:n.json,fields:n.fields});if(n.json)return b(r,n.fields);switch(e||"list"){case"list":{let o=r.identities||r.items||[];if(j("Agent identities"),!o.length){console.log(` ${Qi.default.dim("No agent identity yet. Claim one: domani agents claim is on the web at /agents")}`);return}B(["Handle","Name","Email"],o.map(a=>[a.slug,a.name||"",a.email||""]),[24,30,40]);return}case"token":{j("Agent API key"),l("Key",r.key||r.token||""),r.scopes&&l("Scopes",r.scopes.join(", ")),r.mailbox_ids?.length&&l("Mailboxes",r.mailbox_ids.join(", ")),ue("Shown once. The key sees only this agent's mailboxes and the items handed to it.");return}case"tokens":{let o=r.tokens||[];if(j("Agent API keys"),!o.length){console.log(` ${Qi.default.dim("No key yet: domani agents token <slug>")}`);return}B(["ID","Name","Scopes","Last used"],o.map(a=>[a.id,a.name||"",(a.scopes||[]).join(","),a.last_used_at||"never"]),[28,24,40,20]);return}case"revoke-token":console.log(`${Qi.default.green("\u2713")} Token revoked`);return}}z();var Ht=N(F(),1);L();var of=["providers","connect","connector","import","verify","disconnect"],rt=class extends Error{constructor(n,i){super(n);this.hint=i;this.name="MailboxUsageError"}};function af(e,t,n){switch(e){case"providers":return{path:"/api/emails/connect/providers",method:"GET"};case"connect":{if(t==="forwarding"){if(!n.address)throw new rt("--address is required.","domani mailbox connect forwarding --address someone@gmail.com");return{path:"/api/emails/connect/forwarding",method:"POST",body:{address:n.address,...n.workspace?{workspace_id:n.workspace}:{}}}}let i=t??"gmail";if(i!=="gmail"&&i!=="outlook")throw new rt(`Unknown provider "${t}".`,"gmail or outlook (the APIs), or forwarding (a rule at any provider).");if(n.since&&n.window)throw new rt("Use --since or --window, not both.");return{path:`/api/emails/connect/${i}`,method:"POST",body:{...n.since?{since:n.since}:{},...n.window?{window:n.window}:{},...n.workspace?{workspace_id:n.workspace}:{}}}}case"connector":if(!t)throw new rt("Address required.","domani mailbox connector someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"GET"};case"import":if(!t)throw new rt("Address required.","domani mailbox import someone@gmail.com --since 2026-06-01");if(!n.since)throw new rt("--since is required.","The date the import should reach back to, for example --since 2026-06-01.");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/import`,method:"POST",body:{since:n.since}};case"verify":if(!t)throw new rt("Address required.","domani mailbox verify someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector/verify`,method:"POST"};case"disconnect":if(!t)throw new rt("Address required.","domani mailbox disconnect someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"DELETE"};default:throw new rt(`Unknown action "${e??""}".`,`Actions: ${of.join(", ")}.`)}}function df(e){j(`${e.address} (${e.kind})`),l("Status",String(e.status)),l("Phase",String(e.phase)+(e.paused_reason?` (${e.paused_reason})`:"")),l("Imported since",e.import_since?new Date(String(e.import_since)).toLocaleString():"-");let t=e.forwarding;if(t){l("Forward to",String(t.address??"-")),l("Forwarded",`${t.forwarded??0}${t.last_forwarded_at?`, last ${new Date(t.last_forwarded_at).toLocaleString()}`:""}`),t.confirmation&&l("Gmail confirmation",`${Ht.default.bold(t.confirmation.code)}${t.confirmation.url?` ${t.confirmation.url}`:""}`);let i=t.guide;i&&l("Provider",`${i.name??"unknown"}${i.settings_url?` ${i.settings_url}`:""}${i.limits?.includes("paid_plan")?" (forwarding needs a paid plan there)":""}`),t.probe&&l("Probe",t.probe.returned_at?`came back ${new Date(t.probe.returned_at).toLocaleString()}`:`sent ${new Date(t.probe.sent_at).toLocaleString()}, not back yet`)}let n=e.import_run;n&&l("Import",`${n.status}: ${n.copied} copied, ${n.analysed}/${n.to_analyse} analysed${n.listing_done?"":", still listing"}`),e.source_messages_total&&l("In the source",`${e.source_messages_total} messages`),l("Last sync",e.last_sync_at?new Date(String(e.last_sync_at)).toLocaleString():"never"),e.last_error&&l("Last error",Ht.default.yellow(String(e.last_error)))}async function Xd(e,t,n){let i;try{i=af(e,t,n)}catch(o){if(o instanceof rt)return u(o.message,{hint:o.hint,code:"validation_error",json:n.json});throw o}let s=await x(i.path,{method:i.method,...i.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(i.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:n.json,code:String(r.code??"request_failed")});if(e==="connect"&&t==="forwarding"){if(n.json)return b(r,n.fields);j("Connect your inbox by forwarding"),l("Inbox",String(r.address)),l("Forward to",Ht.default.cyan(String(r.forwarding_address))),l("Status",String(r.status));let o=r.instructions;for(let[a,d]of Object.entries(o??{}))console.log(`
213
+ ${Ht.default.bold(a==="gmail"?"Gmail":a==="outlook"?"Outlook":"Any provider")}`),d.forEach((m,f)=>console.log(` ${f+1}. ${m}`));ue(`Then: domani mailbox verify ${r.address} sends a probe; domani mailbox connector ${r.address} shows the confirmation code and the status.`);return}if(e==="connect"){if(n.json&&!n.wait)return b(r,n.fields);if(j("Connect your Gmail inbox"),l("Import since",new Date(String(r.import_since)).toLocaleString()),console.log(`
214
214
  Open this link in your browser and choose the Google account:
215
- ${Wt.default.cyan(String(r.auth_url))}
216
- `),n.open!==!1&&Le(String(r.auth_url)),_e("After consent, the inbox appears as a connected mailbox at its own address; check it with: domani mailbox connector <address>"),n.wait){let o=Date.now();for(let a=0;a<180;a+=1){await Ot(5e3);let f=((await(await x("/api/emails?limit=50")).json().catch(()=>({}))).mailboxes??[]).find(p=>p.kind==="connected"&&p.created_at&&Date.parse(p.created_at)>=o-6e4);if(f){let p=f.address??f.email;if(n.json)return b({status:"connected",address:p},n.fields);console.log(`
217
- ${Wt.default.green("Connected")} ${p}`);return}}return u("No inbox was connected within 15 minutes.",{code:"connect_timeout",json:n.json})}return}if(n.json)return b(r,n.fields);if(e==="providers"){j("Mailbox providers");for(let o of r.providers??[])c(String(o.name),o.configured?`ready (${o.access.join(", ")}${o.imports_history?", imports older mail":""})`:Wt.default.yellow(`not set up: ${o.reason}`));_e("domani mailbox connect gmail | outlook | forwarding --address me@company.com");return}if(e==="connector")return Vm(r);if(e==="verify"){j("Probe sent"),c("To",String(r.sent_to)),c("Comes back through",String(r.forwarding_address)),_e("When the rule brings it back, the connection is active: domani mailbox connector <address>");return}if(e==="import"){j("Importing older mail"),c("From",new Date(String(r.import_since)).toLocaleString()),c("To",new Date(String(r.import_until)).toLocaleString()),_e(`Progress: domani mailbox connector ${t}`);return}e==="disconnect"&&(j("Disconnected"),c("Address",String(r.address)),c("Removed",`${r.removed_messages} messages, ${r.removed_attachments} attachments`))}var qd=N(F(),1);z();V();async function Wm(e,t){let n=await e.json();return e.ok||u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields}),n}async function Md(e,t,n,i){let s=`/api/domains/${encodeURIComponent(e)}/hostname-bindings`,r;if(!t||t==="list")r=await x(s);else if(t==="plan")i.hostname||u("--hostname is required",{code:"validation_error",json:i.json}),r=await x(`${s}/plan`,{method:"POST",body:JSON.stringify({hostname:i.hostname,browser_mode:i.browserMode})});else if(t==="create"){i.hostname||u("--hostname is required",{code:"validation_error",json:i.json});let d={hostname:i.hostname,browser_mode:i.browserMode,expected_zone_version:i.expectedZoneVersion,acknowledgements:i.acknowledgements?.split(",").map(f=>f.trim())},m=vt(`binding:create:${e}:${i.hostname}`,d);r=await x(s,{method:"POST",headers:{"Idempotency-Key":m.key},body:JSON.stringify(d)}),r.ok&&m.complete()}else{n||u("Binding ID is required",{hint:`Usage: domani binding ${e} ${t} <id>`,code:"validation_error",json:i.json});let d=`${s}/${encodeURIComponent(n)}`;if(t==="get")r=await x(d);else if(t==="verify")r=await x(`${d}/verify`,{method:"POST"});else if(t==="delete")r=await x(d,{method:"DELETE"});else if(t==="update"){i.browserMode||u("--browser-mode is required",{code:"validation_error",json:i.json});let m={browser_mode:i.browserMode,acknowledgements:i.acknowledgements?.split(",").map(p=>p.trim())},f=vt(`binding:update:${e}:${n}`,m);r=await x(d,{method:"PATCH",headers:{"Idempotency-Key":f.key},body:JSON.stringify(m)}),r.ok&&f.complete()}else return u(`Unknown action: ${t}`,{hint:"Actions: list, plan, create, get, update, verify, delete",code:"validation_error",json:i.json})}if(r.status===204){if(i.json)return b({disabled:!0,id:n},i.fields);console.log("Hostname binding disabled");return}let o=await Wm(r,i);if(i.json)return b(o,i.fields);l(),j(t==="plan"?"Hostname Binding Plan":"Hostname Bindings");let a=o.hostname_bindings||(o.hostname_binding?[o.hostname_binding]:[]);if(a.length)for(let d of a)console.log(` ${qd.default.dim(d.id)} ${d.hostname_pattern} ${d.status} ${d.browser_mode}`);else console.log(JSON.stringify(o,null,2));l()}var Fd=N(require("node:readline"),1);De();function Hm(e){return(Array.isArray(e)?e:[e]).filter(n=>!!n&&typeof n=="object")}function Tr(e,t,n,i){return{jsonrpc:"2.0",id:e,error:{code:t,message:n,...i?{data:i}:{}}}}function Zn(e,t,n,i){let s=Hm(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>Tr(r.id??null,t,n,i));if(s.length!==0)return Array.isArray(e)?s:s[0]}function Jm(e){let t=[];for(let n of e.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let i=n.slice(5).trim();if(!(!i||i==="[DONE]"))try{t.push(JSON.parse(i))}catch{}}return t}async function Bm(e,t={}){let n=t.fetchImpl??fetch,i=t.getAuthToken?t.getAuthToken():ot(),s=(t.apiUrl??Ge()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};i&&(r.Authorization=`Bearer ${i}`);let o=()=>n(`${s}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(f){let p=f instanceof Error?f.message:"Unknown network error",g=Zn(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${s} is reachable.`,detail:p});return g===void 0?[]:[g]}if(a.status===401){let f=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:ot({refreshKeychain:!0});if(f&&f!==i){await a.body?.cancel(),i=f,r.Authorization=`Bearer ${i}`;try{a=await o()}catch(p){let g=p instanceof Error?p.message:"Unknown network error",$=Zn(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${s} is reachable.`,detail:g});return $===void 0?[]:[$]}}}if(a.status===202||a.status===204)return[];let d=await a.text();if(a.status===401){let{name:f,source:p}=t.getAuthToken?{name:void 0,source:"none"}:Pt(),g=`npx -y domani-cli@latest login${p==="flag"||p==="env"?` --account ${f}`:""}`,$=Zn(e,-32001,"Domani authentication required",{code:"AUTH_REQUIRED",hint:`Run \`${g}\`, approve access in the browser, then retry. Never paste an API key into chat.`,fix_command:g});return $===void 0?[]:[$]}if(!a.ok){let f=Zn(e,-32e3,`Domani MCP request failed (${a.status})`,{code:"MCP_HTTP_ERROR",hint:"Retry once. If the error persists, check https://domani.run/status."});return f===void 0?[]:[f]}if(!d.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return Jm(d);try{return[JSON.parse(d)]}catch{let f=Zn(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return f===void 0?[]:[f]}}async function Ld(e={}){let t=e.stderr??process.stderr,n=Fd.default.createInterface({input:process.stdin,crlfDelay:1/0}),i=new Set;e.verbose&&t.write(`domani MCP bridge ready
218
- `);for await(let s of n){if(!s.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(s)}catch{process.stdout.write(`${JSON.stringify(Tr(null,-32700,"Parse error"))}
219
- `);return}let a=await Bm(o,e);for(let d of a)process.stdout.write(`${JSON.stringify(d)}
215
+ ${Ht.default.cyan(String(r.auth_url))}
216
+ `),n.open!==!1&&Ve(String(r.auth_url)),ue("After consent, the inbox appears as a connected mailbox at its own address; check it with: domani mailbox connector <address>"),n.wait){let o=Date.now();for(let a=0;a<180;a+=1){await Ot(5e3);let f=((await(await x("/api/emails?limit=50")).json().catch(()=>({}))).mailboxes??[]).find(p=>p.kind==="connected"&&p.created_at&&Date.parse(p.created_at)>=o-6e4);if(f){let p=f.address??f.email;if(n.json)return b({status:"connected",address:p},n.fields);console.log(`
217
+ ${Ht.default.green("Connected")} ${p}`);return}}return u("No inbox was connected within 15 minutes.",{code:"connect_timeout",json:n.json})}return}if(n.json)return b(r,n.fields);if(e==="providers"){j("Mailbox providers");for(let o of r.providers??[])l(String(o.name),o.configured?`ready (${o.access.join(", ")}${o.imports_history?", imports older mail":""})`:Ht.default.yellow(`not set up: ${o.reason}`));ue("domani mailbox connect gmail | outlook | forwarding --address me@company.com");return}if(e==="connector")return df(r);if(e==="verify"){j("Probe sent"),l("To",String(r.sent_to)),l("Comes back through",String(r.forwarding_address)),ue("When the rule brings it back, the connection is active: domani mailbox connector <address>");return}if(e==="import"){j("Importing older mail"),l("From",new Date(String(r.import_since)).toLocaleString()),l("To",new Date(String(r.import_until)).toLocaleString()),ue(`Progress: domani mailbox connector ${t}`);return}e==="disconnect"&&(j("Disconnected"),l("Address",String(r.address)),l("Removed",`${r.removed_messages} messages, ${r.removed_attachments} attachments`))}var Zd=N(F(),1);z();L();async function lf(e,t){let n=await e.json();return e.ok||u(n.error||n.message,{hint:n.hint,status:e.status,json:t.json,fields:t.fields}),n}async function Qd(e,t,n,i){let s=`/api/domains/${encodeURIComponent(e)}/hostname-bindings`,r;if(!t||t==="list")r=await x(s);else if(t==="plan")i.hostname||u("--hostname is required",{code:"validation_error",json:i.json}),r=await x(`${s}/plan`,{method:"POST",body:JSON.stringify({hostname:i.hostname,browser_mode:i.browserMode})});else if(t==="create"){i.hostname||u("--hostname is required",{code:"validation_error",json:i.json});let d={hostname:i.hostname,browser_mode:i.browserMode,expected_zone_version:i.expectedZoneVersion,acknowledgements:i.acknowledgements?.split(",").map(f=>f.trim())},m=$t(`binding:create:${e}:${i.hostname}`,d);r=await x(s,{method:"POST",headers:{"Idempotency-Key":m.key},body:JSON.stringify(d)}),r.ok&&m.complete()}else{n||u("Binding ID is required",{hint:`Usage: domani binding ${e} ${t} <id>`,code:"validation_error",json:i.json});let d=`${s}/${encodeURIComponent(n)}`;if(t==="get")r=await x(d);else if(t==="verify")r=await x(`${d}/verify`,{method:"POST"});else if(t==="delete")r=await x(d,{method:"DELETE"});else if(t==="update"){i.browserMode||u("--browser-mode is required",{code:"validation_error",json:i.json});let m={browser_mode:i.browserMode,acknowledgements:i.acknowledgements?.split(",").map(p=>p.trim())},f=$t(`binding:update:${e}:${n}`,m);r=await x(d,{method:"PATCH",headers:{"Idempotency-Key":f.key},body:JSON.stringify(m)}),r.ok&&f.complete()}else return u(`Unknown action: ${t}`,{hint:"Actions: list, plan, create, get, update, verify, delete",code:"validation_error",json:i.json})}if(r.status===204){if(i.json)return b({disabled:!0,id:n},i.fields);console.log("Hostname binding disabled");return}let o=await lf(r,i);if(i.json)return b(o,i.fields);c(),j(t==="plan"?"Hostname Binding Plan":"Hostname Bindings");let a=o.hostname_bindings||(o.hostname_binding?[o.hostname_binding]:[]);if(a.length)for(let d of a)console.log(` ${Zd.default.dim(d.id)} ${d.hostname_pattern} ${d.status} ${d.browser_mode}`);else console.log(JSON.stringify(o,null,2));c()}var el=N(require("node:readline"),1);De();function cf(e){return(Array.isArray(e)?e:[e]).filter(n=>!!n&&typeof n=="object")}function Ur(e,t,n,i){return{jsonrpc:"2.0",id:e,error:{code:t,message:n,...i?{data:i}:{}}}}function ei(e,t,n,i){let s=cf(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>Ur(r.id??null,t,n,i));if(s.length!==0)return Array.isArray(e)?s:s[0]}function uf(e){let t=[];for(let n of e.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let i=n.slice(5).trim();if(!(!i||i==="[DONE]"))try{t.push(JSON.parse(i))}catch{}}return t}async function mf(e,t={}){let n=t.fetchImpl??fetch,i=t.getAuthToken?t.getAuthToken():at(),s=(t.apiUrl??Ke()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};i&&(r.Authorization=`Bearer ${i}`);let o=()=>n(`${s}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(f){let p=f instanceof Error?f.message:"Unknown network error",g=ei(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${s} is reachable.`,detail:p});return g===void 0?[]:[g]}if(a.status===401){let f=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:at({refreshKeychain:!0});if(f&&f!==i){await a.body?.cancel(),i=f,r.Authorization=`Bearer ${i}`;try{a=await o()}catch(p){let g=p instanceof Error?p.message:"Unknown network error",$=ei(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${s} is reachable.`,detail:g});return $===void 0?[]:[$]}}}if(a.status===202||a.status===204)return[];let d=await a.text();if(a.status===401){let{name:f,source:p}=t.getAuthToken?{name:void 0,source:"none"}:Dt(),g=`npx -y domani-cli@latest login${p==="flag"||p==="env"?` --account ${f}`:""}`,$=ei(e,-32001,"Domani authentication required",{code:"AUTH_REQUIRED",hint:`Run \`${g}\`, approve access in the browser, then retry. Never paste an API key into chat.`,fix_command:g});return $===void 0?[]:[$]}if(!a.ok){let f=ei(e,-32e3,`Domani MCP request failed (${a.status})`,{code:"MCP_HTTP_ERROR",hint:"Retry once. If the error persists, check https://domani.run/status."});return f===void 0?[]:[f]}if(!d.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return uf(d);try{return[JSON.parse(d)]}catch{let f=ei(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return f===void 0?[]:[f]}}async function tl(e={}){let t=e.stderr??process.stderr,n=el.default.createInterface({input:process.stdin,crlfDelay:1/0}),i=new Set;e.verbose&&t.write(`domani MCP bridge ready
218
+ `);for await(let s of n){if(!s.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(s)}catch{process.stdout.write(`${JSON.stringify(Ur(null,-32700,"Parse error"))}
219
+ `);return}let a=await mf(o,e);for(let d of a)process.stdout.write(`${JSON.stringify(d)}
220
220
  `)})().catch(o=>{if(e.verbose){let a=o instanceof Error?o.message:String(o);t.write(`domani MCP bridge internal error: ${a}
221
- `)}process.stdout.write(`${JSON.stringify(Tr(null,-32603,"Domani MCP bridge internal error"))}
222
- `)});i.add(r),r.then(()=>i.delete(r))}await Promise.all(i)}process.stdin.setMaxListeners(50);var L=new Gr;L.name("domani").description(`Domain names for developers and AI agents - ${fn}`).version(Ie).option("--api-url <url>","Override API base URL").option("--account <name>","Act as this saved CLI account (overrides DOMANI_ACCOUNT and 'domani use')").configureOutput({outputError:(e,t)=>{let n=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${$t.default.red("\u2717")} ${n}
223
- `),/unknown option|missing required|expected argument/i.test(n)){let i=process.argv[2],s=i&&!i.startsWith("-")?`domani ${i} --help`:"domani --help";t(`${$t.default.dim(` Run \`${s}\` to see available options.`)}
224
- `)}}}).hook("preAction",async(e,t)=>{let n=e.opts();n.apiUrl&&no(n.apiUrl);for(let[s,r]of[["--account",n.account],["DOMANI_ACCOUNT",process.env.DOMANI_ACCOUNT]])r&&!ci(r)&&u(`Invalid ${s} name: ${r}`,{code:"validation_error",hint:"Use letters, digits, dot, dash or underscore (up to 63 characters)"});n.account&&io(n.account),process.stdout.isTTY||t.options.some(r=>r.long==="--json")&&t.setOptionValue("json",!0),["login","logout","accounts","use","search","suggest","tlds","whois","schema","update","uninstall","mcp"].includes(t.name())||await zo()});L.command("login").description(`Log in to ${fn} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--mailboxes <addresses>","Confine the credential to these comma-separated mailbox addresses").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
221
+ `)}process.stdout.write(`${JSON.stringify(Ur(null,-32603,"Domani MCP bridge internal error"))}
222
+ `)});i.add(r),r.then(()=>i.delete(r))}await Promise.all(i)}process.stdin.setMaxListeners(50);var V=new Zr;V.name("domani").description(`Domain names for developers and AI agents - ${pn}`).version(Ae).option("--api-url <url>","Override API base URL").option("--account <name>","Act as this saved CLI account (overrides DOMANI_ACCOUNT and 'domani use')").configureOutput({outputError:(e,t)=>{let n=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${kt.default.red("\u2717")} ${n}
223
+ `),/unknown option|missing required|expected argument/i.test(n)){let i=process.argv[2],s=i&&!i.startsWith("-")?`domani ${i} --help`:"domani --help";t(`${kt.default.dim(` Run \`${s}\` to see available options.`)}
224
+ `)}}}).hook("preAction",async(e,t)=>{let n=e.opts();n.apiUrl&&ao(n.apiUrl);for(let[s,r]of[["--account",n.account],["DOMANI_ACCOUNT",process.env.DOMANI_ACCOUNT]])r&&!mi(r)&&u(`Invalid ${s} name: ${r}`,{code:"validation_error",hint:"Use letters, digits, dot, dash or underscore (up to 63 characters)"});n.account&&lo(n.account),process.stdout.isTTY||t.options.some(r=>r.long==="--json")&&t.setOptionValue("json",!0),["login","logout","accounts","use","search","suggest","tlds","whois","schema","update","uninstall","mcp"].includes(t.name())||await ea()});V.command("login").description(`Log in to ${pn} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--mailboxes <addresses>","Confine the credential to these comma-separated mailbox addresses").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
225
225
  Examples:
226
226
  domani login # interactive login (opens browser)
227
227
  domani login --scopes domains:read,search --label "Project agent" --expires-in 86400
@@ -231,7 +231,7 @@ Examples:
231
231
  domani login --json # non-interactive (returns auth_url)
232
232
  domani login --no-open # print login URL without opening browser
233
233
  domani login --account work # save a second Domani account as "work"
234
- DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(Xo);L.command("logout").description("Forget the saved login of the current account (or --account <name>)").option("--yes","Skip confirmation").option("--json","Output as JSON").action(Zo);L.command("accounts").description("List the Domani accounts saved in this CLI and the one in use").option("--json","Output as JSON").addHelpText("after",`
234
+ DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(na);V.command("logout").description("Forget the saved login of the current account (or --account <name>)").option("--yes","Skip confirmation").option("--json","Output as JSON").action(ia);V.command("accounts").description("List the Domani accounts saved in this CLI and the one in use").option("--json","Output as JSON").addHelpText("after",`
235
235
  Examples:
236
236
  domani accounts # list saved accounts, * marks the one in use
237
237
  domani login --account work # add another account
@@ -239,11 +239,11 @@ Examples:
239
239
  domani --account work list # use it for one command
240
240
  DOMANI_ACCOUNT=work domani mcp serve # pin an agent's MCP bridge to it
241
241
 
242
- Precedence: DOMANI_API_KEY, then --account, then DOMANI_ACCOUNT, then 'domani use'.`).action(ta);L.command("use <name>").description("Switch the active account (see: domani accounts)").option("--json","Output as JSON").action(na);L.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
242
+ Precedence: DOMANI_API_KEY, then --account, then DOMANI_ACCOUNT, then 'domani use'.`).action(oa);V.command("use <name>").description("Switch the active account (see: domani accounts)").option("--json","Output as JSON").action(aa);V.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
243
243
  Examples:
244
244
  domani me # show account overview
245
245
  domani me --json # machine-readable account info
246
- domani me --json --fields email,plan # just email and plan`).action(ea);L.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(md);L.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(e,t)=>{if(!e||e==="list")return xd(t);if(e==="add")return jd(t);if(e==="remove")return Sd(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});L.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(pd);L.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(hd);L.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(fd);L.command("token").description("Print your API key (masked on a terminal; --reveal for the full key)").option("--json","Output as JSON").option("--reveal","Print the full key even on an interactive terminal").action(Va);L.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
246
+ domani me --json --fields email,plan # just email and plan`).action(ra);V.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(Sd);V.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(e,t)=>{if(!e||e==="list")return qd(t);if(e==="add")return Md(t);if(e==="remove")return Fd(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});V.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(Od);V.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(Id);V.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(Cd);V.command("token").description("Print your API key (masked on a terminal; --reveal for the full key)").option("--json","Output as JSON").option("--reveal","Print the full key even on an interactive terminal").action(nd);V.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
247
247
  Examples:
248
248
  domani login # authenticate once in your browser
249
249
  domani mcp serve # stdio bridge for agent plugins
@@ -251,49 +251,49 @@ Examples:
251
251
  DOMANI_ACCOUNT=work domani mcp serve # same, from the plugin's environment
252
252
 
253
253
  The bridge reads the API token from the OS keychain. It never prints the token
254
- or places it in an MCP/plugin configuration file.`).action(async(e,t)=>{if(e&&e!=="serve"){u(`Unknown action: ${e}`,{hint:"Use: domani mcp serve"});return}await Ld({verbose:t.verbose})});L.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("--agent-identity <id>","Bind this token to an owned agent identity").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
254
+ or places it in an MCP/plugin configuration file.`).action(async(e,t)=>{if(e&&e!=="serve"){u(`Unknown action: ${e}`,{hint:"Use: domani mcp serve"});return}await tl({verbose:t.verbose})});V.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("--agent-identity <id>","Bind this token to an owned agent identity").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
255
255
  Examples:
256
256
  domani tokens list # list all tokens
257
257
  domani tokens create --name "CI" --scopes "domains:read,search"
258
258
  domani tokens create --name "Support agent" --agent-identity agent_abc123
259
- domani tokens revoke --token-id tok_abc123`).action(Wa);L.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",`
259
+ domani tokens revoke --token-id tok_abc123`).action(id);V.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",`
260
260
  Examples:
261
261
  domani search myapp # check popular TLDs
262
262
  domani search myapp .io .fm .xyz # specific TLDs
263
263
  domani search myapp --expand # check 30+ TLDs
264
264
  domani search myapp --max-price 20 # only affordable options
265
- domani search myapp --json # machine-readable output`).action(Aa);L.command("tlds").description("List the TLDs Domani sells, with pricing").option("--kind <kinds>","Kinds to show, comma-separated: tld, second_level, alt_root (default: tld,second_level; alt_root does not resolve in public DNS)").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(Pa);L.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(Da);L.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",`
265
+ domani search myapp --json # machine-readable output`).action(Wa);V.command("tlds").description("List the TLDs Domani sells, with pricing").option("--kind <kinds>","Kinds to show, comma-separated: tld, second_level, alt_root (default: tld,second_level; alt_root does not resolve in public DNS)").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(Ka);V.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(za);V.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",`
266
266
  Examples:
267
267
  domani suggest "cat sitting marketplace"
268
268
  domani suggest "AI code editor" --style creative --tlds ai,dev
269
- domani suggest "meditation app" --lang japanese --count 5`).action(Na);L.command("buy [domains...]").description("Purchase one or more domains").option("--max-price <usd>","Ceiling for the total charge (default: the price shown)").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",`
269
+ domani suggest "meditation app" --lang japanese --count 5`).action(Ya);V.command("buy [domains...]").description("Purchase one or more domains").option("--max-price <usd>","Ceiling for the total charge (default: the price shown)").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",`
270
270
  Examples:
271
271
  domani buy myapp.dev # buy one domain
272
272
  domani buy myapp.dev myapp.com myapp.ai # buy multiple
273
273
  domani buy myapp.dev --dry-run # preview without buying
274
274
  domani buy myapp.dev --yes # skip confirmation
275
275
  domani buy myapp.dev --yes --max-price 15 # never pay more than $15
276
- domani buy myapp.dev --json # machine-readable output`).action(_r);L.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("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--years <n>","Registration years (1-10, default 1)").option("--max-price <usd>","Ceiling for the domain charge (default: the listed price)").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",`
276
+ domani buy myapp.dev --json # machine-readable output`).action(Cr);V.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("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--years <n>","Registration years (1-10, default 1)").option("--max-price <usd>","Ceiling for the domain charge (default: the listed price)").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",`
277
277
  Examples:
278
278
  domani provision myagent.run # domain + hi@ mailbox
279
279
  domani provision myagent.run --slug hey --name "My Agent" # custom mailbox
280
280
  DOMANI_SENDER_AUTH="Bearer secret" domani provision myagent.run --webhook https://me.dev/inbox --authorization-env DOMANI_SENDER_AUTH
281
- domani provision myagent.run --dry-run # preview`).action(Ra);L.command("adopt <domain>").description("Inspect an existing domain and plan the safest connection or transfer").option("--json","Output the complete machine-readable plan as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
281
+ domani provision myagent.run --dry-run # preview`).action(Ja);V.command("adopt <domain>").description("Inspect an existing domain and plan the safest connection or transfer").option("--json","Output the complete machine-readable plan as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
282
282
  Examples:
283
283
  domani adopt myapp.com
284
- domani adopt myapp.com --json`).action(Ma);L.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("--watch","If not eligible: poll until the lock lifts and continue, or register a server watch (email + webhook) for a dated wait").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",`
284
+ domani adopt myapp.com --json`).action(Qa);V.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("--watch","If not eligible: poll until the lock lifts and continue, or register a server watch (email + webhook) for a dated wait").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",`
285
285
  Examples:
286
286
  domani transfer myapp.com --auth-code ABC123XYZ
287
287
  domani transfer myapp.com --auth-code ABC123XYZ --dry-run
288
288
  domani transfer myapp.com --auth-code ABC123XYZ --yes
289
- domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(qa);L.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--max-price <usd>","Ceiling for the renewal charge (default: the price shown)").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",`
289
+ domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(Za);V.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--max-price <usd>","Ceiling for the renewal charge (default: the price shown)").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",`
290
290
  Examples:
291
291
  domani renew myapp.dev # renew one year at the price shown
292
292
  domani renew myapp.dev --years 3 --dry-run # preview the total without renewing
293
- domani renew myapp.dev --yes --max-price 40 # never pay more than $40`).action(Fa);L.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",`
293
+ domani renew myapp.dev --yes --max-price 40 # never pay more than $40`).action(ed);V.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",`
294
294
  Examples:
295
295
  domani import myapp.com # start import (shows TXT record to add)
296
- domani import myapp.com --verify # verify TXT record and complete import`).action(La);L.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",`
296
+ domani import myapp.com --verify # verify TXT record and complete import`).action(td);V.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",`
297
297
  Examples:
298
298
  domani sell myapp.dev --price 5000 # list for $5,000
299
299
  domani sell myapp.dev --price 5000 --description "Great brand name"
@@ -301,7 +301,7 @@ Examples:
301
301
  domani sell external.com --verify # verify TXT record
302
302
  domani sell myapp.dev --status # check listing status
303
303
  domani sell myapp.dev --cancel # remove from sale
304
- domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(Qa);L.command("route [action] [id]").description("Manage short-lived HTTP routes").option("--hostname <hostname>","Public hostname; omitted only when token policy can auto-assign").option("--upstream <url>","HTTP or HTTPS upstream origin").option("--domain <domain>","Filter routes by owned domain").option("--status <status>","Filter: active, expired, deleted, suspended, all").option("--limit <n>","Routes per page for list (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--expires-in <seconds>","Lease duration in seconds (60-86400)").option("--host-header <mode>","Host header mode: public or upstream").option("--upstream-verification <mode>","Verification mode: none or signed_headers").option("--upstream-authorization-env <name>","Read a write-only upstream Authorization value from this environment variable").option("--upstream-api-key-env <name>","Read a write-only upstream X-Api-Key value from this environment variable").option("--clear-upstream-headers","Clear stored write-only upstream authentication headers").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
304
+ domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(fd);V.command("route [action] [id]").description("Manage short-lived HTTP routes").option("--hostname <hostname>","Public hostname; omitted only when token policy can auto-assign").option("--upstream <url>","HTTP or HTTPS upstream origin").option("--domain <domain>","Filter routes by owned domain").option("--status <status>","Filter: active, expired, deleted, suspended, all").option("--limit <n>","Routes per page for list (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--expires-in <seconds>","Lease duration in seconds (60-86400)").option("--host-header <mode>","Host header mode: public or upstream").option("--upstream-verification <mode>","Verification mode: none or signed_headers").option("--upstream-authorization-env <name>","Read a write-only upstream Authorization value from this environment variable").option("--upstream-api-key-env <name>","Read a write-only upstream X-Api-Key value from this environment variable").option("--clear-upstream-headers","Clear stored write-only upstream authentication headers").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
305
305
  Examples:
306
306
  domani route create --hostname preview.example.com --upstream http://bore.pub:45255
307
307
  domani route list --domain example.com --status active
@@ -309,7 +309,7 @@ Examples:
309
309
  domani route refresh route_123 --expires-in 3600
310
310
  domani route rotate-verification route_123
311
311
  domani route rotate-headers route_123 --upstream-authorization-env SPRITES_AUTH
312
- domani route delete route_123`).action(Rd);L.command("assistant [action] [id]").description(`${Et.mailProductName} assistant: Today decisions, settings, consent, history import, activity (private preview)`).option("--enable","Show Today decisions and prepare drafts on demand (for set)").option("--disable","Stop surfacing decisions; shadow analysis may continue (for set)").option("--shadow","Analyze mail without surfacing decisions (for set)").option("--no-shadow","Stop shadow analysis (for set)").option("--pause","Pause every kind of processing (for set)").option("--resume","Resume processing (for set)").option("--mailboxes <ids>","Comma-separated owned mailbox IDs to process (for set, preview)").option("--none","Disable every mailbox; cancels a running import (for set)").option("--days <n>","History window in days (for set, preview; default 30)").option("--attachment-vision <mode>","on or off: let the model read images in attachments (for set)").option("--consent","Record explicit AI consent (required for preview)").option("--option <id>","Decision option to choose (for choose)").option("--decision <id>","Decision ID (for choose)").option("--decision-version <n>","Decision version (for choose)").option("--item-version <n>","Work item version fence (for choose, instruct, snooze, ignore, take-over, correct)").option("--scope <scope>","With ignore: also mute the sender, sender_domain or situation (default item)").option("--text <text>","Instruction or corrected value (for instruct, correct)").option("--until <iso>","Snooze until this ISO 8601 date-time (for snooze)").option("--field <name>","Analysis field to correct (for correct)").option("--limit <n>","Number of activity entries (for activity)").option("--out <file>","Write the export to a file instead of stdout (for export)").option("--correspondent <email>","The person you are about to answer (for brief)").option("--mailbox <address>","Restrict the correspondent brief to one mailbox (for brief)").option("--category <kind>","Only one kind of matter: invoice, meeting_request, newsletter... (for today)").option("--tag <name>","Only the matters carrying this tag (for today)").option("--add <tags>","Tags to put on the matter, comma separated (for tag)").option("--remove <tags>","Tags to take off the matter, comma separated (for tag)").option("--yes","Confirm deletion of derived data (for delete)").option("--plan <id>","Action plan to approve or reject (for approve, reject)").option("--ttl <seconds>","How long to hold the task lease, 30 to 3600 (for lease)").option("--effects <json>","JSON array of effects to ask for (for effects)").option("--question <text>","The question for the owner (for escalate)").option("--options <json>","JSON array of { key, label, outcome } the owner may pick (for escalate)").option("--outcome <outcome>","done, blocked or handed_back (for report)").option("--summary <text>","What was done and how it ended (for report)").option("--claims <json>","JSON array of { kind, ref } reconciled with the receipts (for report)").option("--evidence <refs>","Comma-separated evidence refs (for escalate, report)").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
312
+ domani route delete route_123`).action(Jd);V.command("assistant [action] [id]").description(`${Pt.mailProductName} assistant: Today decisions, settings, consent, history import, activity (private preview)`).option("--enable","Show Today decisions and prepare drafts on demand (for set)").option("--disable","Stop surfacing decisions; shadow analysis may continue (for set)").option("--shadow","Analyze mail without surfacing decisions (for set)").option("--no-shadow","Stop shadow analysis (for set)").option("--pause","Pause every kind of processing (for set)").option("--resume","Resume processing (for set)").option("--mailboxes <ids>","Comma-separated owned mailbox IDs to process (for set, preview)").option("--none","Disable every mailbox; cancels a running import (for set)").option("--days <n>","History window in days (for set, preview; default 30)").option("--attachment-vision <mode>","on or off: let the model read images in attachments (for set)").option("--consent","Record explicit AI consent (required for preview)").option("--option <id>","Decision option to choose (for choose)").option("--decision <id>","Decision ID (for choose)").option("--decision-version <n>","Decision version (for choose)").option("--item-version <n>","Work item version fence (for choose, instruct, snooze, ignore, take-over, correct)").option("--scope <scope>","With ignore: also mute the sender, sender_domain or situation (default item)").option("--text <text>","Instruction or corrected value (for instruct, correct)").option("--until <iso>","Snooze until this ISO 8601 date-time (for snooze)").option("--field <name>","Analysis field to correct (for correct)").option("--limit <n>","Number of activity entries (for activity)").option("--out <file>","Write the export to a file instead of stdout (for export)").option("--correspondent <email>","The person you are about to answer (for brief)").option("--mailbox <address>","Restrict the correspondent brief to one mailbox (for brief)").option("--category <kind>","Only one kind of matter: invoice, meeting_request, newsletter... (for today)").option("--tag <name>","Only the matters carrying this tag (for today)").option("--add <tags>","Tags to put on the matter, comma separated (for tag)").option("--remove <tags>","Tags to take off the matter, comma separated (for tag)").option("--yes","Confirm deletion of derived data (for delete)").option("--plan <id>","Action plan to approve or reject (for approve, reject)").option("--ttl <seconds>","How long to hold the task lease, 30 to 3600 (for lease)").option("--effects <json>","JSON array of effects to ask for (for effects)").option("--question <text>","The question for the owner (for escalate)").option("--options <json>","JSON array of { key, label, outcome } the owner may pick (for escalate)").option("--outcome <outcome>","done, blocked or handed_back (for report)").option("--summary <text>","What was done and how it ended (for report)").option("--claims <json>","JSON array of { kind, ref } reconciled with the receipts (for report)").option("--evidence <refs>","Comma-separated evidence refs (for escalate, report)").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
313
313
  Actions:
314
314
  today Now, Needs you, Waiting, Upcoming, Handled (--category keeps one kind, --tag one tag)
315
315
  settings Opt-in state, consent, and mailbox scope
@@ -357,21 +357,21 @@ Examples:
357
357
  This command never sends mail. Choosing an option prepares an exact draft; review it
358
358
  with "assistant plan" and send it through the normal reply endpoint
359
359
  (POST /api/emails/{address}/messages/{id}/reply with assistant_plan_id) or from the app.
360
- Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(Dd);L.command("binding [action] <domain> [id]").description("Manage HTTP edge hostname bindings and certificates").option("--hostname <hostname>","Exact hostname, wildcard, or apex").option("--browser-mode <mode>","stateless, dedicated_site, or trusted_same_site").option("--expected-zone-version <version>","Zone version returned by binding plan").option("--acknowledgements <values>","Comma-separated acknowledgement identifiers").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
360
+ Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(zd);V.command("binding [action] <domain> [id]").description("Manage HTTP edge hostname bindings and certificates").option("--hostname <hostname>","Exact hostname, wildcard, or apex").option("--browser-mode <mode>","stateless, dedicated_site, or trusted_same_site").option("--expected-zone-version <version>","Zone version returned by binding plan").option("--acknowledgements <values>","Comma-separated acknowledgement identifiers").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
361
361
  Examples:
362
362
  domani binding list example.com
363
363
  domani binding plan example.com --hostname '*.example.com' --browser-mode stateless
364
364
  domani binding create example.com --hostname '*.example.com' --expected-zone-version <version>
365
- domani binding verify example.com binding_123`).action((e,t,n,i)=>Md(t,e,n,i));L.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
365
+ domani binding verify example.com binding_123`).action((e,t,n,i)=>Qd(t,e,n,i));V.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
366
366
  Examples:
367
367
  domani list # list all domains
368
368
  domani domains # alias for list
369
- domani list --json --fields domain,expires_at`).action(Ta);L.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(wr);L.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",`
369
+ domani list --json --fields domain,expires_at`).action(Ba);V.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(xr);V.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",`
370
370
  Examples:
371
371
  domani connect --list # list providers
372
372
  domani connect myapp.dev vercel # connect to Vercel
373
373
  domani connect myapp.dev --provider google-workspace # connect Google Workspace
374
- domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(lr);L.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
374
+ domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(mr);V.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
375
375
  Examples:
376
376
  domani email list # list all mailboxes
377
377
  domani email create --domain myapp.dev --slug hi # create hi@myapp.dev
@@ -381,6 +381,12 @@ Examples:
381
381
  domani email drafts hi@myapp.dev # messages being composed from this address
382
382
  domani email draft DRAFT_ID --from hi@myapp.dev # one draft
383
383
  domani email archive hi@myapp.dev --message-ids m1,m2
384
+ domani email spam MSG --from hi@myapp.dev # to Spam, block the sender account-wide, offer domain and campaign
385
+ domani email not-spam MSG --from hi@myapp.dev # back to the Inbox, allow the sender account-wide
386
+ domani email sender-rules # learned rules: blocks and allows, who and when
387
+ domani email sender-rule-add --action block --match domain --value secure.net
388
+ domani email sender-rule-add --action block --match campaign --from hi@myapp.dev --message-id MSG
389
+ domani email sender-rule-remove RULE_ID # remove a rule and put back what it moved
384
390
  domani email send --from hi@myapp.dev --to bob@x.com --subject "Hello" --text "Hi Bob"
385
391
  domani email send --from hi@myapp.dev --to bob@x.com --subject "Hi" --text "..." --send-at 2026-09-03T09:00:00Z
386
392
  domani email send --from hi@myapp.dev --to bob@x.com --text "Sure" --in-reply-to "<msg@x.com>" # quotes the original by default
@@ -400,7 +406,7 @@ Examples:
400
406
  domani email thread THREAD --from hi@myapp.dev # one conversation, oldest first
401
407
  domani email label --from hi@myapp.dev --message-ids m1 --add billing,urgent
402
408
  domani email facts MSG --from hi@myapp.dev # what the assistant established
403
- domani email extract MSG --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}'`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--query <text>","Search text (for search; or pass it as the argument; --mode hybrid|semantic|keyword picks the ranking)").option("--since <iso>","Only mail or threads after this time (for search, threads, inbox)").option("--until <iso>","Only mail before this time (for search, inbox)").option("--label <labels>","Comma-separated labels, any of (for search, threads, inbox)").option("--kind <kinds>","Comma-separated mail kinds, any of: person, update, newsletter, promotion, code, report (for inbox)").option("--add <labels>","Labels to add (for label)").option("--remove <labels>","Labels to remove (for label; --set <labels> replaces every label)").option("--schema <json>","JSON schema of the fields to extract, inline or @file (for extract)").option("--instructions <text>","Guidance for the extraction (for extract)").option("--thread-id <id>","Thread ID (for thread; or pass it as the argument)").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("--send-at <iso>","Schedule the send (ISO 8601, 30s to 30 days out); trash the message to cancel").option("--message-id <id>","Message ID (for escalate/remind)").option("--reason <text>","Why the human is needed (for escalate)").option("--at <iso>","Reminder time, ISO 8601 (for remind)").option("--clear","Clear the escalation flag, reminder, or tone notes").option("--q <query>","Filter contacts by address or name").option("--order <order>","Contacts order: recent (default) or created (stable, for a full sync with --cursor)").option("--name <name>","Contact display name (for contact-add)").option("--notes <text>","Contact notes (for contact-add)").option("--set <text>","Tone notes to set on the mailbox (for tone)").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("--no-quote","With --in-reply-to, skip quoting the original message under the reply (on by default, in the local locale and time zone)").option("--url <url>","Webhook URL (for webhook)").option("--events <list>","Comma-separated webhook events: email.received plus delivery verdicts on outbound mail (email.delivered, email.bounced, email.failed, email.suppressed, email.complained, email.delayed); omit to keep the current subscription").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers (requires --url)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--folder <folder>","System folder: inbox, archive, sent, spam, trash").option("--view <view>","Virtual view: starred, all, or needs_human").option("--message-ids <ids>","Comma-separated message IDs for lifecycle actions").option("--mailbox-ids <ids>","Comma-separated mailbox IDs for shared inbox work").option("--workspace <id>","Create the mailbox inside this workspace (owner-only)").option("--thread-key <key>","Stable email thread key").option("--thread-aliases <keys>","Comma-separated legacy thread keys returned by the inbox").option("--status <status>","Workflow status: open, waiting, or closed").option("--assigned <filter>","Assignment filter: mine, unassigned, or all").option("--assignee-type <type>","Assignee type: member, token, or agent").option("--assignee-id <id>","Assignee ID").option("--conversation-id <id>","Conversation state ID").option("--note <text>","Private note text").option("--if-version <number>","Conversation version for compare-and-set updates").option("--idempotency-key <key>","Stable retry key for mailbox lifecycle actions").option("--client-id <id>","Stable opaque ID for this app installation or agent process").option("--lease-id <id>","Compose lease returned by a presence heartbeat").option("--mode <mode>","Presence mode: viewing or composing").option("--no-acquire-lease","Advertise composing presence without acquiring the primary lease").option("--limit <n>","Limit results").option("--cursor <cursor>","Opaque pagination or synchronization cursor").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(Ln);L.command("workspace [action]").description("Manage shared workspaces, members, and mailbox access").option("--id <id>","Workspace ID").option("--name <name>","Workspace name").option("--email <email>","Collaborator email").option("--role <role>","Workspace role: admin or member").option("--mailboxes <ids>","Comma-separated mailbox IDs").option("--mailbox-role <role>","Mailbox role: viewer, responder, or manager").option("--token <token>","Invitation token").option("--membership-id <id>","Target workspace membership ID").option("--invitation-id <id>","Pending workspace invitation ID").option("--transfer-id <id>","Pending ownership transfer ID").option("--mailbox-id <id>","Mailbox ID to adopt into the workspace").option("--subject <type:id>","Access subject: human:id, agent:id, token:id, service:id, or group:id").option("--resource <type:id>","Access resource: mailbox:id or collection:id").option("--profile <profile>","Access profile: viewer, responder, manager, draft_only, or mail_client").option("--principals <principals>","Comma-separated group principals as type:id").option("--group-id <id>","Existing access group ID to replace").option("--collection-id <id>","Existing mailbox collection ID to replace").option("--grant-id <id>","Canonical access grant ID").option("--apply","Apply an access plan; the default is dry-run").option("--expected-version <n>","Expected grant version for conflict-safe reconciliation").option("--ownership-disposition <mode>","Offer ownership: unchanged or claim").option("--creator-disposition <mode>","After ownership claim: stay, stay_admin, or leave").option("--billing-disposition <mode>","Billing after offer: unchanged, sponsor, or transfer").option("--plan <plan>",`${Et.mailProductName} plan: mail_solo, mail_team, or mail_business`).option("--no-open","Do not open checkout in a browser").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
409
+ domani email extract MSG --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}'`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--query <text>","Search text (for search; or pass it as the argument; --mode hybrid|semantic|keyword picks the ranking)").option("--since <iso>","Only mail or threads after this time (for search, threads, inbox)").option("--until <iso>","Only mail before this time (for search, inbox)").option("--label <labels>","Comma-separated labels, any of (for search, threads, inbox)").option("--kind <kinds>","Comma-separated mail kinds, any of: person, update, newsletter, promotion, code, report (for inbox)").option("--add <labels>","Labels to add (for label)").option("--remove <labels>","Labels to remove (for label; --set <labels> replaces every label)").option("--schema <json>","JSON schema of the fields to extract, inline or @file (for extract)").option("--instructions <text>","Guidance for the extraction (for extract)").option("--thread-id <id>","Thread ID (for thread; or pass it as the argument)").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("--send-at <iso>","Schedule the send (ISO 8601, 30s to 30 days out); trash the message to cancel").option("--message-id <id>","Message ID (for escalate, remind, spam, not-spam, sender-rule-add)").option("--reason <text>","Why the human is needed (for escalate)").option("--at <iso>","Reminder time, ISO 8601 (for remind)").option("--clear","Clear the escalation flag, reminder, or tone notes").option("--q <query>","Filter contacts by address or name").option("--order <order>","Contacts order: recent (default) or created (stable, for a full sync with --cursor)").option("--name <name>","Contact display name (for contact-add)").option("--notes <text>","Contact notes (for contact-add)").option("--set <text>","Tone notes to set on the mailbox (for tone)").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("--no-quote","With --in-reply-to, skip quoting the original message under the reply (on by default, in the local locale and time zone)").option("--url <url>","Webhook URL (for webhook)").option("--events <list>","Comma-separated webhook events: email.received plus delivery verdicts on outbound mail (email.delivered, email.bounced, email.failed, email.suppressed, email.complained, email.delayed); omit to keep the current subscription").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers (requires --url)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--folder <folder>","System folder: inbox, archive, sent, spam, trash").option("--view <view>","Virtual view: starred, all, or needs_human").option("--message-ids <ids>","Comma-separated message IDs for lifecycle actions").option("--mailbox-ids <ids>","Comma-separated mailbox IDs for shared inbox work").option("--workspace <id>","Create the mailbox inside this workspace (owner-only)").option("--thread-key <key>","Stable email thread key").option("--thread-aliases <keys>","Comma-separated legacy thread keys returned by the inbox").option("--status <status>","Workflow status: open, waiting, or closed").option("--assigned <filter>","Assignment filter: mine, unassigned, or all").option("--assignee-type <type>","Assignee type: member, token, or agent").option("--assignee-id <id>","Assignee ID").option("--conversation-id <id>","Conversation state ID").option("--note <text>","Private note text").option("--if-version <number>","Conversation version for compare-and-set updates").option("--idempotency-key <key>","Stable retry key for mailbox lifecycle actions").option("--confirm","Block a sender you know, or a shared domain (for spam, sender-rule-add)").option("--action <action>","Sender rule: block or allow (for sender-rules, sender-rule-add)").option("--match <match>","Sender rule match: address, domain or campaign (for sender-rule-add)").option("--value <value>","Sender rule address or domain (for sender-rule-add)").option("--keep-moved","Leave the mail a removed rule moved where it is (for sender-rule-remove)").option("--client-id <id>","Stable opaque ID for this app installation or agent process").option("--lease-id <id>","Compose lease returned by a presence heartbeat").option("--mode <mode>","Presence mode: viewing or composing").option("--no-acquire-lease","Advertise composing presence without acquiring the primary lease").option("--limit <n>","Limit results").option("--cursor <cursor>","Opaque pagination or synchronization cursor").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(Wn);V.command("workspace [action]").description("Manage shared workspaces, members, and mailbox access").option("--id <id>","Workspace ID").option("--name <name>","Workspace name").option("--email <email>","Collaborator email").option("--role <role>","Workspace role: admin or member").option("--mailboxes <ids>","Comma-separated mailbox IDs").option("--mailbox-role <role>","Mailbox role: viewer, responder, or manager").option("--token <token>","Invitation token").option("--membership-id <id>","Target workspace membership ID").option("--invitation-id <id>","Pending workspace invitation ID").option("--transfer-id <id>","Pending ownership transfer ID").option("--mailbox-id <id>","Mailbox ID to adopt into the workspace").option("--subject <type:id>","Access subject: human:id, agent:id, token:id, service:id, or group:id").option("--resource <type:id>","Access resource: mailbox:id or collection:id").option("--profile <profile>","Access profile: viewer, responder, manager, draft_only, or mail_client").option("--principals <principals>","Comma-separated group principals as type:id").option("--group-id <id>","Existing access group ID to replace").option("--collection-id <id>","Existing mailbox collection ID to replace").option("--grant-id <id>","Canonical access grant ID").option("--apply","Apply an access plan; the default is dry-run").option("--expected-version <n>","Expected grant version for conflict-safe reconciliation").option("--ownership-disposition <mode>","Offer ownership: unchanged or claim").option("--creator-disposition <mode>","After ownership claim: stay, stay_admin, or leave").option("--billing-disposition <mode>","Billing after offer: unchanged, sponsor, or transfer").option("--plan <plan>",`${Pt.mailProductName} plan: mail_solo, mail_team, or mail_business`).option("--no-open","Do not open checkout in a browser").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
404
410
  Examples:
405
411
  domani workspace list
406
412
  domani workspace create --name Acme
@@ -417,7 +423,7 @@ Examples:
417
423
  domani workspace transfer --id ws_123 --membership-id mem_123
418
424
  domani workspace accept-ownership --token <ownership-token>
419
425
  domani workspace adopt-mailbox --id ws_123 --mailbox-id mb_123
420
- domani workspace checkout --id ws_123 --plan mail_team`).action(Od);L.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/add/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",`
426
+ domani workspace checkout --id ws_123 --plan mail_team`).action(Ld);V.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/add/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",`
421
427
  Examples:
422
428
  domani dns myapp.dev get # list all records
423
429
  domani dns myapp.dev set --type A --name @ --value 76.76.21.21 # replace the @ A records with this one
@@ -425,21 +431,21 @@ Examples:
425
431
  domani dns myapp.dev set --type CNAME --name www --value cname.vercel-dns.com
426
432
  domani dns myapp.dev delete --type A --name @ # delete every @ A record
427
433
  domani dns myapp.dev snapshot # export DNS as JSON
428
- domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(yr);L.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(gd);L.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",`
434
+ domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(kr);V.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(Ad);V.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",`
429
435
  Examples:
430
436
  domani settings myapp.dev # view current settings
431
437
  domani settings myapp.dev --auto-renew on # enable auto-renew
432
438
  domani settings myapp.dev --whois-privacy on # enable WHOIS privacy
433
- domani settings myapp.dev --security-lock off # unlock for transfer`).action(Ha);L.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(Ja);L.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(Ba);L.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
439
+ domani settings myapp.dev --security-lock off # unlock for transfer`).action(sd);V.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(rd);V.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(od);V.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
434
440
  Examples:
435
441
  domani contact # view current contact info
436
442
  domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
437
- --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(Ga);L.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",`
443
+ --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(ad);V.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",`
438
444
  Examples:
439
445
  domani parking myapp.dev # view parking status
440
446
  domani parking myapp.dev enable # enable parking page
441
447
  domani parking myapp.dev disable # disable parking page
442
- domani parking myapp.dev price 500 # set for-sale price to $500`).action(Ya);L.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(Xa);L.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
448
+ domani parking myapp.dev price 500 # set for-sale price to $500`).action(cd);V.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(ud);V.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
443
449
  Examples:
444
450
  domani webhooks list
445
451
  domani webhooks create --url https://example.com/hook --events domain.purchased,domain.expiring
@@ -449,13 +455,13 @@ Examples:
449
455
  domani webhooks delete --webhook-id wh_abc
450
456
  domani webhooks deliveries --webhook-id wh_abc
451
457
  domani webhooks replay --webhook-id wh_abc --delivery-id del_abc --idempotency-key incident-2026-07-25
452
- 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("--delivery-id <id>","Webhook delivery ID (for replay)").option("--idempotency-key <key>","Stable idempotency key (for replay)").option("--active <on|off>","Enable or disable webhook").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers").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(Za);L.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("--limit <n>","Deals per page (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
458
+ 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("--delivery-id <id>","Webhook delivery ID (for replay)").option("--idempotency-key <key>","Stable idempotency key (for replay)").option("--active <on|off>","Enable or disable webhook").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers").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(md);V.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("--limit <n>","Deals per page (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
453
459
  Examples:
454
460
  domani deals # list all your deals
455
461
  domani deals --role seller --status active # your active sales
456
462
  domani deals --cursor <next_cursor> # next page
457
463
  domani deals deal_abc123 # view specific deal
458
- domani deals --json # machine-readable output`).action(ed);L.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",`
464
+ domani deals --json # machine-readable output`).action(pd);V.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",`
459
465
  Actions:
460
466
  request <domain> ask domani to acquire a taken domain (commission-only)
461
467
  list (default) list your acquisition requests
@@ -466,25 +472,25 @@ Examples:
466
472
  domani broker request dream.com --max-budget 5000
467
473
  domani broker # list your requests
468
474
  domani broker status brq_abc123
469
- domani broker cancel brq_abc123`).action((e,t,n)=>id(e,t,n));L.command("follow <domain>").description("Follow a taken domain for free: an alert in the app and by email at each step until it drops").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",`
475
+ domani broker cancel brq_abc123`).action((e,t,n)=>yd(e,t,n));V.command("follow <domain>").description("Follow a taken domain for free: an alert in the app and by email at each step until it drops").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",`
470
476
  Steps that raise an alert: expiring within 30 days, expired, redemption,
471
477
  pending delete (drops in about 5 days), available again, listed for sale.
472
478
  The step the name is at when you follow it raises none. Up to 50 names.
473
479
 
474
480
  Examples:
475
481
  domani follow taken.com # follow it
476
- domani follow taken.com --json # where it stands, as JSON`).action(ad);L.command("unfollow <domain>").description("Stop following a domain (a backorder on it is not affected)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(dd);L.command("watchlist").alias("following").description("List the domains you follow, with where each one stands").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
482
+ domani follow taken.com --json # where it stands, as JSON`).action($d);V.command("unfollow <domain>").description("Stop following a domain (a backorder on it is not affected)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(kd);V.command("watchlist").alias("following").description("List the domains you follow, with where each one stands").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
477
483
  Examples:
478
484
  domani watchlist # the names you follow
479
- domani watchlist --json --fields watches # machine-readable output`).action(ld);L.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("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
485
+ domani watchlist --json --fields watches # machine-readable output`).action(_d);V.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("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
480
486
  Examples:
481
487
  domani notifications --unread # what is new
482
- domani notifications --cursor <next_cursor> # next page`).action(ud);L.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("--no-quote","With --in-reply-to, skip quoting the original message under the reply (on by default)").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((e,t)=>Ln("send",e,t));L.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((e,t)=>Ln("inbox",e,t));L.command("agents [action] [slug]").description("Agent identities: give an agent its own API key, list or revoke its keys").addHelpText("after",`
488
+ domani notifications --cursor <next_cursor> # next page`).action(jd);V.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("--no-quote","With --in-reply-to, skip quoting the original message under the reply (on by default)").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((e,t)=>Wn("send",e,t));V.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((e,t)=>Wn("inbox",e,t));V.command("agents [action] [slug]").description("Agent identities: give an agent its own API key, list or revoke its keys").addHelpText("after",`
483
489
  Examples:
484
490
  domani agents list # your agent identities
485
491
  domani agents token dave --name "Dave on the pod" # mint a confined key for dave.domani.run
486
492
  domani agents tokens dave # the keys of dave
487
- domani agents revoke-token dave --token-id tok_1 # revoke one`).option("--name <name>","Key name (for token)").option("--mailboxes <ids>","Comma-separated mailbox IDs the key is confined to (for token)").option("--token-id <id>","Token ID (for revoke-token)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,n)=>Nd(e,t,n));L.command("mailbox [action] [target]").description("Connected inboxes: connect Gmail or any inbox by forwarding, read the connection, import older mail, disconnect").addHelpText("after",`
493
+ domani agents revoke-token dave --token-id tok_1 # revoke one`).option("--name <name>","Key name (for token)").option("--mailboxes <ids>","Comma-separated mailbox IDs the key is confined to (for token)").option("--token-id <id>","Token ID (for revoke-token)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,n)=>Yd(e,t,n));V.command("mailbox [action] [target]").description("Connected inboxes: connect Gmail or any inbox by forwarding, read the connection, import older mail, disconnect").addHelpText("after",`
488
494
  Examples:
489
495
  domani mailbox providers # which providers this server can connect
490
496
  domani mailbox connect gmail # the last 24 hours, then new mail as it arrives
@@ -494,8 +500,8 @@ Examples:
494
500
  domani mailbox verify me@outlook.com # send a probe through the rule
495
501
  domani mailbox connector someone@gmail.com # status, import progress, the Gmail confirmation code
496
502
  domani mailbox import someone@gmail.com --since 2026-01-01 # widen the import
497
- domani mailbox disconnect someone@gmail.com # remove your copies and the credential`).option("--address <address>","The inbox to connect by forwarding (for connect forwarding)").option("--since <date>","Import the mail received after this ISO date").option("--window <window>","A preset instead of --since: 24h (default), 7d, 30d, 1y").option("--workspace <id>","Workspace the mailbox belongs to (for connect)").option("--no-open","Do not open the browser (for connect)").option("--wait","Wait until the inbox is connected (for connect)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,n)=>Ud(e,t,n));L.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(kd);L.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").option("--yes","Perform the update even in JSON/non-interactive mode").action(bd);L.command("uninstall").description("Remove domani CLI and config from this machine").action($d);(async()=>{let e=ao();await L.parseAsync();let t=await e,n=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
498
- ${$t.default.red("!")} CLI v${Ie} is no longer supported. Run ${$t.default.bold(n)} to upgrade to v${t.update}
503
+ domani mailbox disconnect someone@gmail.com # remove your copies and the credential`).option("--address <address>","The inbox to connect by forwarding (for connect forwarding)").option("--since <date>","Import the mail received after this ISO date").option("--window <window>","A preset instead of --since: 24h (default), 7d, 30d, 1y").option("--workspace <id>","Workspace the mailbox belongs to (for connect)").option("--no-open","Do not open the browser (for connect)").option("--wait","Wait until the inbox is connected (for connect)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,n)=>Xd(e,t,n));V.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(Ud);V.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").option("--yes","Perform the update even in JSON/non-interactive mode").action(Td);V.command("uninstall").description("Remove domani CLI and config from this machine").action(Dd);(async()=>{let e=fo();await V.parseAsync();let t=await e,n=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
504
+ ${kt.default.red("!")} CLI v${Ae} is no longer supported. Run ${kt.default.bold(n)} to upgrade to v${t.update}
499
505
  `),process.exit(1)):t?.update&&console.error(`
500
- ${$t.default.yellow("!")} Update available: ${$t.default.dim(Ie)} ${$t.default.dim("\u2192")} ${$t.default.green(t.update)} Run ${$t.default.bold(n)}
506
+ ${kt.default.yellow("!")} Update available: ${kt.default.dim(Ae)} ${kt.default.dim("\u2192")} ${kt.default.green(t.update)} Run ${kt.default.bold(n)}
501
507
  `)})();