domani-cli 0.4.59 → 0.4.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/domani.cjs +153 -141
- package/package.json +1 -1
package/dist/domani.cjs
CHANGED
|
@@ -1,124 +1,124 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}displayWidth(t){return
|
|
2
|
+
"use strict";var Ta=Object.create;var bs=Object.defineProperty;var Pa=Object.getOwnPropertyDescriptor;var Da=Object.getOwnPropertyNames;var Na=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var Ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Bt=(e,t)=>{for(var i in t)bs(e,i,{get:t[i],enumerable:!0})},qa=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Da(t))!Ua.call(e,n)&&n!==i&&bs(e,n,{get:()=>t[n],enumerable:!(s=Pa(t,n))||s.enumerable});return e};var D=(e,t,i)=>(i=e!=null?Ta(Na(e)):{},qa(t||!e||!e.__esModule?bs(i,"default",{value:e,enumerable:!0}):i,e));var ri=ft(vs=>{var Si=class extends Error{constructor(t,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=t,this.nestedError=void 0}},ws=class extends Si{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};vs.CommanderError=Si;vs.InvalidArgumentError=ws});var Ci=ft(ks=>{var{InvalidArgumentError:Fa}=ri(),$s=class{constructor(t,i){switch(this.description=i||"",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,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}default(t,i){return this.defaultValue=t,this.defaultValueDescription=i,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new Fa(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ma(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}ks.Argument=$s;ks.humanReadableArgName=Ma});var js=ft(xs=>{var{humanReadableArgName:La}=Ci(),_s=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 i=t.commands.filter(n=>!n._hidden),s=t._getHelpCommand();return s&&!s._hidden&&i.push(s),this.sortSubcommands&&i.sort((n,r)=>n.name().localeCompare(r.name())),i}compareOptions(t,i){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(t).localeCompare(s(i))}visibleOptions(t){let i=t.options.filter(n=>!n.hidden),s=t._getHelpOption();if(s&&!s.hidden){let n=s.short&&t._findOption(s.short),r=s.long&&t._findOption(s.long);!n&&!r?i.push(s):s.long&&!r?i.push(t.createOption(s.long,s.description)):s.short&&!n&&i.push(t.createOption(s.short,s.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let i=[];for(let s=t.parent;s;s=s.parent){let n=s.options.filter(r=>!r.hidden);i.push(...n)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(i=>{i.description=i.description||t._argsDescription[i.name()]||""}),t.registeredArguments.find(i=>i.description)?t.registeredArguments:[]}subcommandTerm(t){let i=t.registeredArguments.map(s=>La(s)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,i){return i.visibleCommands(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleSubcommandTerm(i.subcommandTerm(n)))),0)}longestOptionTermLength(t,i){return i.visibleOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,i){return i.visibleGlobalOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestArgumentTermLength(t,i){return i.visibleArguments(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleArgumentTerm(i.argumentTerm(n)))),0)}commandUsage(t){let i=t._name;t._aliases[0]&&(i=i+"|"+t._aliases[0]);let s="";for(let n=t.parent;n;n=n.parent)s=n.name()+" "+s;return s+i+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let i=[];return t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&i.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&i.push(`env: ${t.envVar}`),i.length>0?`${t.description} (${i.join(", ")})`:t.description}argumentDescription(t){let i=[];if(t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),i.length>0){let s=`(${i.join(", ")})`;return t.description?`${t.description} ${s}`:s}return t.description}formatHelp(t,i){let s=i.padWidth(t,i),n=i.helpWidth??80;function r(g,b){return i.formatItem(g,s,b,i)}let o=[`${i.styleTitle("Usage:")} ${i.styleUsage(i.commandUsage(t))}`,""],a=i.commandDescription(t);a.length>0&&(o=o.concat([i.boxWrap(i.styleCommandDescription(a),n),""]));let l=i.visibleArguments(t).map(g=>r(i.styleArgumentTerm(i.argumentTerm(g)),i.styleArgumentDescription(i.argumentDescription(g))));l.length>0&&(o=o.concat([i.styleTitle("Arguments:"),...l,""]));let f=i.visibleOptions(t).map(g=>r(i.styleOptionTerm(i.optionTerm(g)),i.styleOptionDescription(i.optionDescription(g))));if(f.length>0&&(o=o.concat([i.styleTitle("Options:"),...f,""])),i.showGlobalOptions){let g=i.visibleGlobalOptions(t).map(b=>r(i.styleOptionTerm(i.optionTerm(b)),i.styleOptionDescription(i.optionDescription(b))));g.length>0&&(o=o.concat([i.styleTitle("Global Options:"),...g,""]))}let m=i.visibleCommands(t).map(g=>r(i.styleSubcommandTerm(i.subcommandTerm(g)),i.styleSubcommandDescription(i.subcommandDescription(g))));return m.length>0&&(o=o.concat([i.styleTitle("Commands:"),...m,""])),o.join(`
|
|
3
|
+
`)}displayWidth(t){return Hn(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i==="[command]"?this.styleSubcommandText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleCommandText(i)).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(i=>i==="[options]"?this.styleOptionText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleSubcommandText(i)).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,i){return Math.max(i.longestOptionTermLength(t,i),i.longestGlobalOptionTermLength(t,i),i.longestSubcommandTermLength(t,i),i.longestArgumentTermLength(t,i))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,i,s,n){let o=" ".repeat(2);if(!s)return o+t;let a=t.padEnd(i+t.length-n.displayWidth(t)),l=2,m=(this.helpWidth??80)-i-l-2,g;return m<this.minWidthToWrap||n.preformatted(s)?g=s:g=n.boxWrap(s,m).replace(/\n/g,`
|
|
4
4
|
`+" ".repeat(i+l)),o+a+" ".repeat(l)+g.replace(/\n/g,`
|
|
5
|
-
${o}`)}boxWrap(t,i){if(i<this.minWidthToWrap)return t;let s=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return s.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],f=this.displayWidth(l[0]);a.forEach(m=>{let g=this.displayWidth(m);if(f+g<=i){l.push(m),f+=g;return}r.push(l.join(""));let
|
|
6
|
-
`)}};function
|
|
5
|
+
${o}`)}boxWrap(t,i){if(i<this.minWidthToWrap)return t;let s=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return s.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],f=this.displayWidth(l[0]);a.forEach(m=>{let g=this.displayWidth(m);if(f+g<=i){l.push(m),f+=g;return}r.push(l.join(""));let b=m.trimStart();l=[b],f=this.displayWidth(b)}),r.push(l.join(""))}),r.join(`
|
|
6
|
+
`)}};function Hn(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}xs.Help=_s;xs.stripColor=Hn});var Is=ft(Os=>{var{InvalidArgumentError:Va}=ri(),Ss=class{constructor(t,i){this.flags=t,this.description=i||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let s=Wa(t);this.short=s.shortFlag,this.long=s.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,i){return this.defaultValue=t,this.defaultValueDescription=i,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let i=t;return typeof t=="string"&&(i={[t]:!0}),this.implied=Object.assign(this.implied||{},i),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,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new Va(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Jn(this.name().replace(/^no-/,"")):Jn(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Cs=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(i=>{i.negate?this.negativeOptions.set(i.attributeName(),i):this.positiveOptions.set(i.attributeName(),i)}),this.negativeOptions.forEach((i,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(t,i){let s=i.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,r=n!==void 0?n:!1;return i.negate===(r===t)}};function Jn(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function Wa(e){let t,i,s=/^-[^-]$/,n=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(s.test(r[0])&&(t=r.shift()),n.test(r[0])&&(i=r.shift()),!t&&s.test(r[0])&&(t=r.shift()),!t&&n.test(r[0])&&(t=i,i=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')`):s.test(o)?new Error(`${a}
|
|
10
10
|
- too many short flags`):n.test(o)?new Error(`${a}
|
|
11
11
|
- too many long flags`):new Error(`${a}
|
|
12
|
-
- unrecognised flag format`)}if(t===void 0&&i===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}
|
|
12
|
+
- unrecognised flag format`)}if(t===void 0&&i===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}Os.Option=Ss;Os.DualOptions=Cs});var Gn=ft(Bn=>{function Ha(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let s=0;s<=e.length;s++)i[s]=[s];for(let s=0;s<=t.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++){let r=1;e[n-1]===t[s-1]?r=0:r=1,i[n][s]=Math.min(i[n-1][s]+1,i[n][s-1]+1,i[n-1][s-1]+r),n>1&&s>1&&e[n-1]===t[s-2]&&e[n-2]===t[s-1]&&(i[n][s]=Math.min(i[n][s],i[n-2][s-2]+1))}return i[e.length][t.length]}function Ja(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");i&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let s=[],n=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=Ha(e,o),l=Math.max(e.length,o.length);(l-a)/l>r&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),i&&(s=s.map(o=>`--${o}`)),s.length>1?`
|
|
13
13
|
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
14
|
-
(Did you mean ${s[0]}?)`:""}
|
|
15
|
-
- specify the name in Command constructor or using .name()`);return i=i||{},i.isDefault&&(this._defaultCommandName=t._name),(i.noHelp||i.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,i){return new
|
|
16
|
-
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(i):this._lifeCycleHooks[t]=[i],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=i=>{if(i.code!=="commander.executeSubCommandAsync")throw i},this}_exit(t,i,s){this._exitCallback&&this._exitCallback(new
|
|
17
|
-
- already used by option '${i.flags}'`)}this.options.push(t)}_registerCommand(t){let i=n=>[n.name()].concat(n.aliases()),s=i(t).find(n=>this._findCommand(n));if(s){let n=i(this._findCommand(s)).join("|"),r=i(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let i=t.name(),s=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(s,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(s,t.defaultValue,"default");let n=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let l=this.getOptionValue(s);r!==null&&t.parseArg?r=this._callParseArg(t,r,l,o):r!==null&&t.variadic&&(r=t._concatValue(r,l)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+i,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+i,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(t,i,s,n,r){if(typeof i=="object"&&i instanceof
|
|
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,i,s){if(
|
|
14
|
+
(Did you mean ${s[0]}?)`:""}Bn.suggestSimilar=Ja});var Xn=ft(Ps=>{var Ba=require("node:events").EventEmitter,Rs=require("node:child_process"),pt=require("node:path"),Oi=require("node:fs"),ne=require("node:process"),{Argument:Ga,humanReadableArgName:Ka}=Ci(),{CommanderError:As}=ri(),{Help:za,stripColor:Ya}=js(),{Option:Kn,DualOptions:Xa}=Is(),{suggestSimilar:zn}=Gn(),Es=class e extends Ba{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:i=>ne.stdout.write(i),writeErr:i=>ne.stderr.write(i),outputError:(i,s)=>s(i),getOutHelpWidth:()=>ne.stdout.isTTY?ne.stdout.columns:void 0,getErrHelpWidth:()=>ne.stderr.isTTY?ne.stderr.columns:void 0,getOutHasColors:()=>Ts()??(ne.stdout.isTTY&&ne.stdout.hasColors?.()),getErrHasColors:()=>Ts()??(ne.stderr.isTTY&&ne.stderr.hasColors?.()),stripColor:i=>Ya(i)},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 i=this;i;i=i.parent)t.push(i);return t}command(t,i,s){let n=i,r=s;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),r.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(t){return new e(t)}createHelp(){return Object.assign(new za,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,i){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 i=i||{},i.isDefault&&(this._defaultCommandName=t._name),(i.noHelp||i.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,i){return new Ga(t,i)}argument(t,i,s,n){let r=this.createArgument(t,i);return typeof s=="function"?r.default(n).argParser(s):r.default(s),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(i=>{this.argument(i)}),this}addArgument(t){let i=this.registeredArguments.slice(-1)[0];if(i&&i.variadic)throw new Error(`only the last argument can be variadic '${i.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,i){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,s,n]=t.match(/([^ ]+) *(.*)/),r=i??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,i){return typeof t!="object"?(this.helpCommand(t,i),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,i){let s=["preSubcommand","preAction","postAction"];if(!s.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
16
|
+
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(i):this._lifeCycleHooks[t]=[i],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=i=>{if(i.code!=="commander.executeSubCommandAsync")throw i},this}_exit(t,i,s){this._exitCallback&&this._exitCallback(new As(t,i,s)),ne.exit(t)}action(t){let i=s=>{let n=this.registeredArguments.length,r=s.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=i,this}createOption(t,i){return new Kn(t,i)}_callParseArg(t,i,s,n){try{return t.parseArg(i,s)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${n} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(t){let i=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(i){let s=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 '${s}'
|
|
17
|
+
- already used by option '${i.flags}'`)}this.options.push(t)}_registerCommand(t){let i=n=>[n.name()].concat(n.aliases()),s=i(t).find(n=>this._findCommand(n));if(s){let n=i(this._findCommand(s)).join("|"),r=i(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let i=t.name(),s=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(s,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(s,t.defaultValue,"default");let n=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let l=this.getOptionValue(s);r!==null&&t.parseArg?r=this._callParseArg(t,r,l,o):r!==null&&t.variadic&&(r=t._concatValue(r,l)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+i,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+i,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(t,i,s,n,r){if(typeof i=="object"&&i instanceof Kn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(i,s);if(o.makeOptionMandatory(!!t.mandatory),typeof n=="function")o.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,f)=>{let m=a.exec(l);return m?m[0]:f},o.default(r).argParser(n)}else o.default(n);return this.addOption(o)}option(t,i,s,n){return this._optionEx({},t,i,s,n)}requiredOption(t,i,s,n){return this._optionEx({mandatory:!0},t,i,s,n)}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,i){return this.setOptionValueWithSource(t,i,void 0)}setOptionValueWithSource(t,i,s){return this._storeOptionsAsProperties?this[t]=i:this._optionValues[t]=i,this._optionValueSources[t]=s,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let i;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(t)!==void 0&&(i=s.getOptionValueSource(t))}),i}_prepareUserArgs(t,i){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(i=i||{},t===void 0&&i.from===void 0){ne.versions?.electron&&(i.from="electron");let n=ne.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(i.from="eval")}t===void 0&&(t=ne.argv),this.rawArgs=t.slice();let s;switch(i.from){case void 0:case"node":this._scriptPath=t[1],s=t.slice(2);break;case"electron":ne.defaultApp?(this._scriptPath=t[1],s=t.slice(2)):s=t.slice(1);break;case"user":s=t.slice(0);break;case"eval":s=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${i.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return this._parseCommand([],s),this}async parseAsync(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return await this._parseCommand([],s),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,i,s){if(Oi.existsSync(t))return;let n=i?`searched for local subcommand relative to directory '${i}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${t}' does not exist
|
|
19
19
|
- if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
20
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${n}`;throw new Error(r)}_executeSubCommand(t,i){i=i.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(m,g){let
|
|
21
|
+
- ${n}`;throw new Error(r)}_executeSubCommand(t,i){i=i.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(m,g){let b=pt.resolve(m,g);if(Oi.existsSync(b))return b;if(n.includes(pt.extname(g)))return;let k=n.find($=>Oi.existsSync(`${b}${$}`));if(k)return`${b}${k}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let m;try{m=Oi.realpathSync(this._scriptPath)}catch{m=this._scriptPath}a=pt.resolve(pt.dirname(m),a)}if(a){let m=r(a,o);if(!m&&!t._executableFile&&this._scriptPath){let g=pt.basename(this._scriptPath,pt.extname(this._scriptPath));g!==this._name&&(m=r(a,`${g}-${t._name}`))}o=m||o}s=n.includes(pt.extname(o));let l;ne.platform!=="win32"?s?(i.unshift(o),i=Yn(ne.execArgv).concat(i),l=Rs.spawn(ne.argv[0],i,{stdio:"inherit"})):l=Rs.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=Yn(ne.execArgv).concat(i),l=Rs.spawn(ne.execPath,i,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(g=>{ne.on(g,()=>{l.killed===!1&&l.exitCode===null&&l.kill(g)})});let f=this._exitCallback;l.on("close",m=>{m=m??1,f?f(new As(m,"commander.executeSubCommandAsync","(close)")):ne.exit(m)}),l.on("error",m=>{if(m.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(m.code==="EACCES")throw new Error(`'${o}' not executable`);if(!f)ne.exit(1);else{let g=new As(1,"commander.executeSubCommandAsync","(error)");g.nestedError=m,f(g)}}),this.runningCommand=l}_dispatchSubcommand(t,i,s){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,i.concat(s));else return n._parseCommand(i,s)}),r}_dispatchHelpCommand(t){t||this.help();let i=this._findCommand(t);return i&&!i._executableHandler&&i.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,i)=>{t.required&&this.args[i]==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=(s,n,r)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,r,a)}return o};this._checkNumberOfArguments();let i=[];this.registeredArguments.forEach((s,n)=>{let r=s.defaultValue;s.variadic?n<this.args.length?(r=this.args.slice(n),s.parseArg&&(r=r.reduce((o,a)=>t(s,a,o),s.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],s.parseArg&&(r=t(s,r,s.defaultValue))),i[n]=r}),this.processedArgs=i}_chainOrCall(t,i){return t&&t.then&&typeof t.then=="function"?t.then(()=>i()):i()}_chainOrCallHooks(t,i){let s=t,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[i]!==void 0).forEach(r=>{r._lifeCycleHooks[i].forEach(o=>{n.push({hookedCommand:r,callback:o})})}),i==="postAction"&&n.reverse(),n.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(t,i,s){let n=t;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{n=this._chainOrCall(n,()=>r(this,i))}),n}_parseCommand(t,i){let s=this.parseOptions(i);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(s.operands),i=s.unknown,this.args=t.concat(i),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),i);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(i),this._dispatchSubcommand(this._defaultCommandName,t,i);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,t,i)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,t,i);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,i);this.listenerCount("command:*")?this.emit("command:*",t,i):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(i=>i._name===t||i._aliases.includes(t))}_findOption(t){return this.options.find(i=>i.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(i=>{i.mandatory&&t.getOptionValue(i.attributeName())===void 0&&t.missingMandatoryOptionValue(i)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=t.find(r=>s.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let i=[],s=[],n=i,r=t.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;r.length;){let l=r.shift();if(l==="--"){n===s&&n.push(l),n.push(...r);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let f=this._findOption(l);if(f){if(f.required){let m=r.shift();m===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,m)}else if(f.optional){let m=null;r.length>0&&!o(r[0])&&(m=r.shift()),this.emit(`option:${f.name()}`,m)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let f=this._findOption(`-${l[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,l.slice(2)):(this.emit(`option:${f.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let f=l.indexOf("="),m=this._findOption(l.slice(0,f));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,l.slice(f+1));continue}}if(o(l)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&i.length===0&&s.length===0){if(this._findCommand(l)){i.push(l),r.length>0&&s.push(...r);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){i.push(l),r.length>0&&i.push(...r);break}else if(this._defaultCommandName){s.push(l),r.length>0&&s.push(...r);break}}if(this._passThroughOptions){n.push(l),r.length>0&&n.push(...r);break}n.push(l)}return{operands:i,unknown:s}}opts(){if(this._storeOptionsAsProperties){let t={},i=this.options.length;for(let s=0;s<i;s++){let n=this.options[s].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,i)=>Object.assign(t,i.opts()),{})}error(t,i){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 s=i||{},n=s.exitCode||1,r=s.code||"commander.error";this._exit(n,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in ne.env){let i=t.attributeName();(this.getOptionValue(i)===void 0||["default","config","env"].includes(this.getOptionValueSource(i)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,ne.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new
|
|
25
|
-
`),this._exit(0,"commander.version",t)}),this}description(t,i){return t===void 0&&i===void 0?this._description:(this._description=t,i&&(this._argsDescription=i),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let i=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(i=this.commands[this.commands.length-1]),t===i._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(t);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return i._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(i=>this.alias(i)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let i=this.registeredArguments.map(s=>
|
|
24
|
+
`),this.outputHelp({error:!0}));let s=i||{},n=s.exitCode||1,r=s.code||"commander.error";this._exit(n,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in ne.env){let i=t.attributeName();(this.getOptionValue(i)===void 0||["default","config","env"].includes(this.getOptionValueSource(i)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,ne.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new Xa(this.options),i=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&i(s.attributeName())&&t.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!i(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(t){let i=`error: missing required argument '${t}'`;this.error(i,{code:"commander.missingArgument"})}optionMissingArgument(t){let i=`error: option '${t.flags}' argument missing`;this.error(i,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let i=`error: required option '${t.flags}' not specified`;this.error(i,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,i){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),f=this.options.find(g=>g.negate&&a===g.attributeName()),m=this.options.find(g=>!g.negate&&a===g.attributeName());return f&&(f.presetArg===void 0&&l===!1||f.presetArg!==void 0&&l===f.presetArg)?f:m||o},n=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${n(t)} cannot be used with ${n(i)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let i="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);n=n.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);i=zn(t,n)}let s=`error: unknown option '${t}'${i}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let i=this.registeredArguments.length,s=i===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${i} argument${s} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],i="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),i=zn(t,n)}let s=`error: unknown command '${t}'${i}`;this.error(s,{code:"commander.unknownCommand"})}version(t,i,s){if(t===void 0)return this._version;this._version=t,i=i||"-V, --version",s=s||"output the version number";let n=this.createOption(i,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
25
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,i){return t===void 0&&i===void 0?this._description:(this._description=t,i&&(this._argsDescription=i),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let i=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(i=this.commands[this.commands.length-1]),t===i._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(t);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return i._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(i=>this.alias(i)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let i=this.registeredArguments.map(s=>Ka(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?i:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=pt.basename(t,pt.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let i=this.createHelp(),s=this._getOutputContext(t);i.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let n=i.formatHelp(this,i);return s.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let i=!!t.error,s,n,r;return i?(s=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:i,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:n,helpWidth:r}}outputHelp(t){let i;typeof t=="function"&&(i=t,t=void 0);let s=this._getOutputContext(t),n={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:s.error});if(i&&(r=i(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(t,i){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",i=i??"display help for command",this._helpOption=this.createOption(t,i),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 i=Number(ne.exitCode??0);i===0&&t&&typeof t!="function"&&t.error&&(i=1),this._exit(i,"commander.help","(outputHelp)")}addHelpText(t,i){let s=["beforeAll","before","after","afterAll"];if(!s.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${s.join("', '")}'`);let n=`${t}Help`;return this.on(n,r=>{let o;typeof i=="function"?o=i({error:r.error,command:r.command}):o=i,o&&r.write(`${o}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(t){let i=this._getHelpOption();i&&t.find(n=>i.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
28
|
-
`).ok),t&&(
|
|
27
|
+
`)}),this}_outputHelpIfRequested(t){let i=this._getHelpOption();i&&t.find(n=>i.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Yn(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let i,s="127.0.0.1",n="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?i=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(i=r[1],/^\d+$/.test(r[3])?n=r[3]:s=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(i=r[1],s=r[3],n=r[4]),i&&n!=="0"?`${i}=${s}:${parseInt(n)+1}`:t})}function Ts(){if(ne.env.NO_COLOR||ne.env.FORCE_COLOR==="0"||ne.env.FORCE_COLOR==="false")return!1;if(ne.env.FORCE_COLOR||ne.env.CLICOLOR_FORCE!==void 0)return!0}Ps.Command=Es;Ps.useColor=Ts});var tr=ft(Ye=>{var{Argument:Zn}=Ci(),{Command:Ds}=Xn(),{CommanderError:Za,InvalidArgumentError:Qn}=ri(),{Help:Qa}=js(),{Option:er}=Is();Ye.program=new Ds;Ye.createCommand=e=>new Ds(e);Ye.createOption=(e,t)=>new er(e,t);Ye.createArgument=(e,t)=>new Zn(e,t);Ye.Command=Ds;Ye.Option=er;Ye.Argument=Zn;Ye.Help=Qa;Ye.CommanderError=Za;Ye.InvalidArgumentError=Qn;Ye.InvalidOptionArgumentError=Qn});var M=ft((qu,Ns)=>{var Ri=process||{},nr=Ri.argv||[],Ii=Ri.env||{},el=!(Ii.NO_COLOR||nr.includes("--no-color"))&&(!!Ii.FORCE_COLOR||nr.includes("--color")||Ri.platform==="win32"||(Ri.stdout||{}).isTTY&&Ii.TERM!=="dumb"||!!Ii.CI),tl=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+il(n,t,i,r)+t:e+n+t},il=(e,t,i,s)=>{let n="",r=0;do n+=e.substring(r,s)+i,r=s+t.length,s=e.indexOf(t,r);while(~s);return n+e.substring(r)},rr=(e=el)=>{let t=e?tl:()=>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")}};Ns.exports=rr();Ns.exports.createColors=rr});var Gt,oi,ai=Ae(()=>{"use strict";Gt="domani.run",oi=`https://${Gt}`});function It(e,t,i){try{let s=(0,or.spawnSync)(e,t,{encoding:"utf-8",input:i,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:s.status===0,stdout:(s.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function ar(){return process.platform==="darwin"?!0:process.platform==="linux"?It("secret-tool",["--help"]).ok:!1}function lr(e={}){if(e.refresh&&(Kt=void 0),Kt!==void 0)return Kt??void 0;let t;if(process.platform==="darwin"){let i=It("security",["find-generic-password","-s",zt,"-a",Yt,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=It("secret-tool",["lookup","service",zt,"account",Yt]);i.ok&&i.stdout&&(t=i.stdout)}return Kt=t??null,t}function dr(e){let t=!1;return process.platform==="darwin"?t=It("security",["add-generic-password","-U","-s",zt,"-a",Yt,"-w",e]).ok:process.platform==="linux"&&(t=It("secret-tool",["store","--label=domani CLI token","service",zt,"account",Yt],e+`
|
|
28
|
+
`).ok),t&&(Kt=e),t}function cr(){process.platform==="darwin"?It("security",["delete-generic-password","-s",zt,"-a",Yt]):process.platform==="linux"&&It("secret-tool",["clear","service",zt,"account",Yt]),Kt=null}var or,zt,Yt,Kt,ur=Ae(()=>{"use strict";or=require("child_process"),zt="domani-cli",Yt="default"});function pr(e){fr=e}function ht(){try{let e=_t.default.readFileSync(Us,"utf-8");return JSON.parse(e)}catch{return{}}}function Xt(e){e.token&&ar()&&dr(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),_t.default.mkdirSync(Ti,{recursive:!0,mode:448}),_t.default.writeFileSync(Us,JSON.stringify(e,null,2),{mode:384})}function gr(){cr();try{_t.default.unlinkSync(Us)}catch{}}function Ve(){return fr||ht().api_url||oi}function We(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=ht();if(t.token)return t.token;if(t.token_in_keychain)return lr({refresh:e.refreshKeychain})}function nl(){try{let e=_t.default.readFileSync(hr,"utf-8");return JSON.parse(e)}catch{return null}}function rl(e){try{_t.default.mkdirSync(Ti,{recursive:!0,mode:448}),_t.default.writeFileSync(hr,JSON.stringify(e),{mode:384})}catch{}}function Ai(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function yr(){let e=nl();if(e&&Date.now()-e.checkedAt<sl)return Ai(e.version,xe)>0?{update:e.version,forced:Ai(xe,e.min)<0}:null;try{let t=Ve(),i=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)return null;let s=await i.json();if(rl({version:s.version,min:s.min,checkedAt:Date.now()}),Ai(s.version,xe)>0)return{update:s.version,forced:Ai(xe,s.min)<0}}catch{}return null}var _t,Ei,mr,Ti,Us,fr,hr,sl,qs,xe,gt=Ae(()=>{"use strict";_t=D(require("fs"),1),Ei=D(require("path"),1),mr=D(require("os"),1);ai();ur();Ti=process.env.DOMANI_CONFIG_DIR||Ei.default.join(mr.default.homedir(),".domani"),Us=Ei.default.join(Ti,"config.json");hr=Ei.default.join(Ti,"version-check.json"),sl=1440*60*1e3;qs=process.stdout.isTTY??!1,xe="0.4.60"});var Ms=ft((Hu,br)=>{"use strict";var Fs={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let i="";return e<0?i+=`\x1B[${-e}D`:e>0&&(i+=`\x1B[${e}C`),t<0?i+=`\x1B[${-t}A`:t>0&&(i+=`\x1B[${t}B`),i},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"},ol={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},al={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 i=0;i<e;i++)t+=this.line+(i<e-1?Fs.up():"");return e&&(t+=Fs.left),t}};br.exports={cursor:Fs,scroll:ol,erase:al,beep:"\x07"}});function yt(e,t,i){if(!i.some(o=>!o.disabled))return e;let s=e+t,n=Math.max(i.length-1,0),r=s<0?n:s>n?0:s;return i[r].disabled?yt(r,t<0?-1:1,i):r}function Js(e,t,i){return String(e).normalize().replaceAll(`\r
|
|
29
29
|
`,`
|
|
30
30
|
`).split(`
|
|
31
|
-
`).map(s=>
|
|
32
|
-
`)}function
|
|
31
|
+
`).map(s=>wl(s,t,i)).join(`
|
|
32
|
+
`)}function Cr(e){if(e.aliases!==void 0){let t=e.aliases;for(let i in t){if(!Object.hasOwn(t,i))continue;let s=t[i];ue.actions.has(s)&&(ue.aliases.has(i)||ue.aliases.set(i,s))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(ue.messages.cancel=t.cancel),t.error!==void 0&&(ue.messages.error=t.error)}e.withGuide!==void 0&&(ue.withGuide=e.withGuide!==!1)}function zs(e,t){if(typeof e=="string")return ue.aliases.get(e)===t;for(let i of e)if(i!==void 0&&zs(i,t))return!0;return!1}function $l(e,t){if(e===t)return;let i=e.split(`
|
|
33
33
|
`),s=t.split(`
|
|
34
|
-
`),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}function
|
|
34
|
+
`),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}function de(e){return e===Bs}function Ui(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function Or({input:e=Rt.stdin,output:t=Rt.stdout,overwrite:i=!0,hideCursor:s=!0}={}){let n=jt.createInterface({input:e,output:t,prompt:"",tabSize:1});jt.emitKeypressEvents(e,n),e instanceof Hs.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let f=String(o);if(zs([f,a,l],"cancel")){s&&t.write(Ee.cursor.show),process.exit(0);return}if(!i)return;jt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{jt.clearLine(t,1,()=>{e.once("keypress",r)})})};return s&&t.write(Ee.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),s&&t.write(Ee.cursor.show),e instanceof Hs.ReadStream&&e.isTTY&&!kl&&e.setRawMode(!1),n.terminal=!1,n.close()}}function ot(e,t,i,s=i){let n=At(e??Rt.stdout);return Js(t,n-i.length,{hard:!0,trim:!1}).split(`
|
|
35
35
|
`).map((r,o)=>`${o===0?s:i}${r}`).join(`
|
|
36
|
-
`)}function
|
|
37
|
-
`),m=f[Symbol.iterator](),g=m.next(),
|
|
38
|
-
`?(r&&(s
|
|
39
|
-
`&&(n&&
|
|
40
|
-
`),
|
|
41
|
-
`).length-1;this.output.write(Ee.cursor.move(-999,t*-1))}render(){let t=
|
|
36
|
+
`)}function _l(e,t){if(e===void 0||t.length===0)return 0;let i=t.findIndex(s=>s.value===e);return i!==-1?i:0}function xl(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function jl(e,t){if(t)return e?t:t[0]}var xt,Rt,jt,kr,Ee,Hs,ll,dl,cl,Ls,Pi,Di,Vs,Ni,ul,ml,_r,fl,li,Hi,xr,pl,Gs,jr,hl,Sr,Ks,wr,gl,vr,$r,yl,Ws,bl,wl,vl,ue,kl,Bs,At,Ys,rt,di,qi,Fi,Mi,Ir,Li,Vi,Wi,Xs=Ae(()=>{xt=D(M(),1),Rt=require("node:process"),jt=D(require("node:readline"),1),kr=D(require("node:readline"),1),Ee=D(Ms(),1),Hs=require("node:tty");ll=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,dl=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,cl=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,Ls=/[\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,Di=/\t{1,1000}/y,Vs=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"),Ni=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ul=new RegExp("\\p{M}+","gu"),ml={limit:1/0,ellipsis:""},_r=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?_r(n,ml,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,k=i.wideWidth??2,$=0,h=0,x=e.length,j=0,O=!1,A=x,V=Math.max(0,s-r),H=0,te=0,P=0,T=0;e:for(;;){if(te>H||h>=x&&h>$){let U=e.slice(H,te)||e.slice($,h);j=0;for(let Q of U.replaceAll(ul,"")){let X=Q.codePointAt(0)||0;if(dl(X)?T=g:cl(X)?T=k:f!==b&&ll(X)?T=f:T=b,P+T>V&&(A=Math.min(A,Math.max(H,$)+j)),P+T>s){O=!0;break e}j+=Q.length,P+=T}H=te=0}if(h>=x)break;if(Ni.lastIndex=h,Ni.test(e)){if(j=Ni.lastIndex-h,T=j*b,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/b))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Ni.lastIndex;continue}if(Ls.lastIndex=h,Ls.test(e)){if(P+o>V&&(A=Math.min(A,h)),P+o>s){O=!0;break}P+=o,H=$,te=h,h=$=Ls.lastIndex;continue}if(Pi.lastIndex=h,Pi.test(e)){if(j=Pi.lastIndex-h,T=j*a,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/a))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Pi.lastIndex;continue}if(Di.lastIndex=h,Di.test(e)){if(j=Di.lastIndex-h,T=j*l,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/l))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Di.lastIndex;continue}if(Vs.lastIndex=h,Vs.test(e)){if(P+m>V&&(A=Math.min(A,h)),P+m>s){O=!0;break}P+=m,H=$,te=h,h=$=Vs.lastIndex;continue}h+=1}return{width:O?V:P,index:O?A:x,truncated:O,ellipsed:O&&s>=r}},fl={limit:1/0,ellipsis:"",ellipsisWidth:0},li=(e,t={})=>_r(e,fl,t).width,Hi="\x1B",xr="\x9B",pl=39,Gs="\x07",jr="[",hl="]",Sr="m",Ks=`${hl}8;;`,wr=new RegExp(`(?:\\${jr}(?<code>\\d+)m|\\${Ks}(?<uri>.*)${Gs})`,"y"),gl=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},vr=e=>`${Hi}${jr}${e}${Sr}`,$r=e=>`${Hi}${Ks}${e}${Gs}`,yl=e=>e.map(t=>li(t)),Ws=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:li(o),l=s.next(),f=s.next(),m=0;for(;!l.done;){let g=l.value,b=li(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Hi||g===xr)&&(n=!0,r=t.startsWith(Ks,m+1)),n?r?g===Gs&&(n=!1,r=!1):g===Sr&&(n=!1):(a+=b,a===i&&!f.done&&(e.push(""),a=0)),l=f,f=s.next(),m+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},bl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(li(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},wl=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=yl(o),l=[""];for(let[$,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let x=li(l.at(-1)??"");if($!==0&&(x>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),x=0),(x>0||i.trim===!1)&&(l[l.length-1]+=" ",x++)),i.hard&&a[$]>t){let j=t-x,O=1+Math.floor((a[$]-j-1)/t);Math.floor((a[$]-1)/t)<O&&l.push(""),Ws(l,h,t);continue}if(x+a[$]>t&&x>0&&a[$]>0){if(i.wordWrap===!1&&x<t){Ws(l,h,t);continue}l.push("")}if(x+a[$]>t&&i.wordWrap===!1){Ws(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map($=>bl($)));let f=l.join(`
|
|
37
|
+
`),m=f[Symbol.iterator](),g=m.next(),b=m.next(),k=0;for(;!g.done;){let $=g.value,h=b.value;if(s+=$,$===Hi||$===xr){wr.lastIndex=k+1;let j=wr.exec(f)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);n=O===pl?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let x=n?gl(n):void 0;h===`
|
|
38
|
+
`?(r&&(s+=$r("")),n&&x&&(s+=vr(x))):$===`
|
|
39
|
+
`&&(n&&x&&(s+=vr(n)),r&&(s+=$r(r))),k+=$.length,g=b,b=m.next()}return s};vl=["up","down","left","right","space","enter","cancel"],ue={actions:new Set(vl),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};kl=globalThis.process.platform.startsWith("win"),Bs=Symbol("clack:cancel");At=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ys=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;rt=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,i=!0){let{input:s=Rt.stdin,output:n=Rt.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=i,this._abortSignal=o,this.input=s,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(t,i){let s=this._subscribers.get(t)??[];s.push(i),this._subscribers.set(t,s)}on(t,i){this.setSubscriber(t,{cb:i})}once(t,i){this.setSubscriber(t,{cb:i,once:!0})}emit(t,...i){let s=this._subscribers.get(t)??[],n=[];for(let r of s)r.cb(...i),r.once&&n.push(()=>s.splice(s.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Bs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=kr.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),Ui(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ee.cursor.show),this.output.off("resize",this.render),Ui(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Ee.cursor.show),this.output.off("resize",this.render),Ui(this.input,!1),t(Bs)})})}_isActionKey(t,i){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,i){this.userInput=t??"",this.emit("userInput",this.userInput),i&&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,i){if(this._track&&i.name!=="return"&&(i.name&&this._isActionKey(t,i)&&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"),i?.name&&(!this._track&&ue.aliases.has(i.name)&&this.emit("cursor",ue.aliases.get(i.name)),ue.actions.has(i.name)&&this.emit("cursor",i.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),i),i?.name==="return"){if(this.opts.validate){let s=this.opts.validate(this.value);s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}zs([t,i?.name,i?.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
|
+
`),Ui(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Js(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
41
|
+
`).length-1;this.output.write(Ee.cursor.move(-999,t*-1))}render(){let t=Js(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Ee.cursor.hide);else{let i=$l(this._prevFrame,t),s=Ys(this.output);if(this.restoreCursor(),i){let n=Math.max(0,i.numLinesAfter-s),r=Math.max(0,i.numLinesBefore-s),o=i.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=t;return}if(i.lines.length===1){this.output.write(Ee.cursor.move(0,o-r)),this.output.write(Ee.erase.lines(1));let a=t.split(`
|
|
42
42
|
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(Ee.cursor.move(0,a.length-o-1));return}else if(i.lines.length>1){if(n<r)o=n;else{let l=o-r;l>0&&this.output.write(Ee.cursor.move(0,l))}this.output.write(Ee.erase.down());let a=t.split(`
|
|
43
43
|
`).slice(o);this.output.write(a.join(`
|
|
44
|
-
`)),this._prevFrame=t;return}}this.output.write(Ee.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};
|
|
44
|
+
`)),this._prevFrame=t;return}}this.output.write(Ee.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};di=class extends rt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#s;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return xt.default.inverse(xt.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[i,...s]=this.userInput.slice(this._cursor);return`${t}${xt.default.inverse(i)}${s.join("")}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(t){super(t),this.#t=t.options;let i=this.options;this.filteredOptions=[...i],this.multiple=t.multiple===!0,this.#s=t.filter??xl;let s;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?s=t.initialValue:s=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(s=[this.options[0].value]),s)for(let n of s){let r=i.findIndex(o=>o.value===n);r!==-1&&(this.toggleSelected(n),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(n,r)=>this.#n(n,r)),this.on("userInput",n=>this.#r(n))}_isActionKey(t,i){return t===" "||this.multiple&&this.isNavigating&&i.name==="space"&&t!==void 0&&t!==""}#n(t,i){let s=i.name==="up",n=i.name==="down",r=i.name==="return";s||n?(this.#e=yt(this.#e,s?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=jl(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(i.name==="tab"||this.isNavigating&&i.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(i=>i!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let i=this.options;t?this.filteredOptions=i.filter(r=>this.#s(t,r)):this.filteredOptions=[...i];let s=_l(this.focusedValue,this.filteredOptions);this.#e=yt(s,0,this.filteredOptions);let n=this.filteredOptions[this.#e];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},qi=class extends rt{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",i=>{this.output.write(Ee.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},Fi=class extends rt{options;cursor=0;#e;getGroupItems(t){return this.options.filter(i=>i.group===t)}isGroupSelected(t){let i=this.getGroupItems(t),s=this.value;return s===void 0?!1:i.every(n=>s.includes(n.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let i=t.value,s=this.getGroupItems(i);this.isGroupSelected(i)?this.value=this.value.filter(n=>s.findIndex(r=>r.value===n)===-1):this.value=[...this.value,...s.map(n=>n.value)],this.value=Array.from(new Set(this.value))}else{let i=this.value.includes(t.value);this.value=i?this.value.filter(s=>s!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:i}=t;this.#e=t.selectableGroups!==!1,this.options=Object.entries(i).flatMap(([s,n])=>[{value:s,group:!0,label:s},...n.map(r=>({...r,group:s}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),this.#e?0:1),this.on("cursor",s=>{switch(s){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Mi=class extends rt{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,i=this.value!==void 0&&this.value.length===t.length;this.value=i?[]:t.map(s=>s.value)}toggleInvert(){let t=this.value;if(!t)return;let i=this._enabledOptions.filter(s=>!t.includes(s.value));this.value=i.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter(i=>i!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let i=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),0);this.cursor=this.options[i].disabled?yt(i,1,this.options):i,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=yt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=yt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Ir=class extends rt{_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}${xt.default.inverse(xt.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${xt.default.inverse(s[0])}${s.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},Li=class extends rt{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 i=this.options.findIndex(({value:n})=>n===t.initialValue),s=i===-1?0:i;this.cursor=this.options[s].disabled?yt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=yt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=yt(this.cursor,1,this.options);break}this.changeValue()})}},Vi=class extends rt{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let i=t.caseSensitive===!0,s=this.options.map(({value:[n]})=>i?n:n?.toLowerCase());this.cursor=Math.max(s.indexOf(t.initialValue),0),this.on("key",(n,r)=>{if(!n)return;let o=i&&r.shift?n.toUpperCase():n;if(!s.includes(o))return;let a=this.options.find(({value:[l]})=>i?l===o:l?.toLowerCase()===n);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},Wi=class extends rt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let i=t.slice(0,this.cursor),[s,...n]=t.slice(this.cursor);return`${i}${xt.default.inverse(s)}${n.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var gn={};Bt(gn,{S_BAR:()=>E,S_BAR_END:()=>je,S_BAR_END_RIGHT:()=>Mr,S_BAR_H:()=>Zi,S_BAR_START:()=>rn,S_BAR_START_RIGHT:()=>Fr,S_CHECKBOX_ACTIVE:()=>Xi,S_CHECKBOX_INACTIVE:()=>Qt,S_CHECKBOX_SELECTED:()=>Tt,S_CONNECT_LEFT:()=>Vr,S_CORNER_BOTTOM_LEFT:()=>ln,S_CORNER_BOTTOM_RIGHT:()=>an,S_CORNER_TOP_LEFT:()=>Wr,S_CORNER_TOP_RIGHT:()=>on,S_ERROR:()=>mn,S_INFO:()=>dn,S_PASSWORD_MASK:()=>Lr,S_RADIO_ACTIVE:()=>mi,S_RADIO_INACTIVE:()=>Dt,S_STEP_ACTIVE:()=>qr,S_STEP_CANCEL:()=>sn,S_STEP_ERROR:()=>nn,S_STEP_SUBMIT:()=>Nt,S_SUCCESS:()=>cn,S_WARN:()=>un,autocomplete:()=>zr,autocompleteMultiselect:()=>Ll,box:()=>Jl,cancel:()=>Kl,confirm:()=>Xe,group:()=>Bl,groupMultiselect:()=>Gl,intro:()=>zl,isCI:()=>tn,isCancel:()=>de,isTTY:()=>Ur,limitOptions:()=>ti,log:()=>Je,multiselect:()=>Xl,note:()=>ed,outro:()=>Yl,password:()=>td,path:()=>id,progress:()=>nd,select:()=>tt,selectKey:()=>rd,settings:()=>ue,spinner:()=>fi,stream:()=>Et,symbol:()=>et,symbolBar:()=>fn,taskLog:()=>ld,tasks:()=>od,text:()=>Te,unicode:()=>Yi,unicodeOr:()=>oe,updateSettings:()=>Cr});function Sl(){return He.default.platform!=="win32"?He.default.env.TERM!=="linux":!!He.default.env.CI||!!He.default.env.WT_SESSION||!!He.default.env.TERMINUS_SUBLIME||He.default.env.ConEmuTask==="{cmd::Cmder}"||He.default.env.TERM_PROGRAM==="Terminus-Sublime"||He.default.env.TERM_PROGRAM==="vscode"||He.default.env.TERM==="xterm-256color"||He.default.env.TERM==="alacritty"||He.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function ei(e,t,i){return String(e).normalize().replaceAll(`\r
|
|
45
45
|
`,`
|
|
46
46
|
`).split(`
|
|
47
|
-
`).map(s=>
|
|
48
|
-
`)}function Ir(e){return e.label??String(e.value??"")}function Hr(e,t){if(!e)return!0;let i=(t.label??String(t.value??"")).toLowerCase(),s=(t.hint??"").toLowerCase(),n=String(t.value).toLowerCase(),r=e.toLowerCase();return i.includes(r)||s.includes(r)||n.includes(r)}function Dl(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function Rr(e,t,i,s){let n=i,r=i;return s==="center"?n=Math.floor((t-e)/2):s==="right"&&(n=t-e-i),r=t-n-e,[n,r]}function Ql({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=ui(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),f=k=>{switch(k){case"initial":case"active":return p.default.magenta;case"error":case"cancel":return p.default.red;case"submit":return p.default.green;default:return p.default.magenta}},m=(k,$)=>{let h=Math.floor(r/a*l);return`${f(k)(Ar[e].repeat(h))}${p.default.dim(Ar[e].repeat(l-h))} ${$}`},g=(k="")=>{o=k,n.start(m("initial",k))},y=(k=1,$)=>{r=Math.min(a,k+r),n.message(m("active",$??o)),o=$??o};return{start:g,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:y,isCancelled:n.isCancelled,message:k=>y(0,k)}}var p,We,Tt,di,Yt,Gi,Ki,Xs,Tr,oe,Pr,Zs,Qs,Dt,en,E,je,Dr,Nr,ci,Pt,zi,Et,Xt,Ur,Yi,tn,qr,sn,nn,Fr,rn,on,an,ln,et,dn,kl,_l,xl,Ks,Wi,Hi,zs,Ji,jl,Sl,Mr,Cl,De,Xi,Lr,Ol,cn,Vr,Il,Wr,un,Sr,Rl,Cr,Or,Al,Ys,El,Tl,Pl,Qt,Jr,Nl,Ul,ql,Fl,Ml,Ye,Ll,Vl,He,Wl,Hl,Jl,li,Bl,Gl,Kl,zl,Yl,Xl,Zl,ui,Ar,Bi,tt,ed,Er,At,td,id,sd,Te,Ne=Ae(()=>{Gs();Gs();p=D(M(),1),We=D(require("node:process"),1),Tt=require("node:fs"),di=require("node:path"),Yt=D(Ns(),1),Gi=require("node:util");Ki=$l(),Xs=()=>process.env.CI==="true",Tr=e=>e.isTTY===!0,oe=(e,t)=>Ki?e:t,Pr=oe("\u25C6","*"),Zs=oe("\u25A0","x"),Qs=oe("\u25B2","x"),Dt=oe("\u25C7","o"),en=oe("\u250C","T"),E=oe("\u2502","|"),je=oe("\u2514","\u2014"),Dr=oe("\u2510","T"),Nr=oe("\u2518","\u2014"),ci=oe("\u25CF",">"),Pt=oe("\u25CB"," "),zi=oe("\u25FB","[\u2022]"),Et=oe("\u25FC","[+]"),Xt=oe("\u25FB","[ ]"),Ur=oe("\u25AA","\u2022"),Yi=oe("\u2500","-"),tn=oe("\u256E","+"),qr=oe("\u251C","+"),sn=oe("\u256F","+"),nn=oe("\u2570","+"),Fr=oe("\u256D","+"),rn=oe("\u25CF","\u2022"),on=oe("\u25C6","*"),an=oe("\u25B2","!"),ln=oe("\u25A0","x"),et=e=>{switch(e){case"initial":case"active":return p.default.cyan(Pr);case"cancel":return p.default.red(Zs);case"error":return p.default.yellow(Qs);case"submit":return p.default.green(Dt)}},dn=e=>{switch(e){case"initial":case"active":return p.default.cyan(E);case"cancel":return p.default.red(E);case"error":return p.default.yellow(E);case"submit":return p.default.green(E)}},kl=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,xl=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,Ks=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Wi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Hi=/\t{1,1000}/y,zs=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,jl=new RegExp("\\p{M}+","gu"),Sl={limit:1/0,ellipsis:""},Mr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Mr(n,Sl,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,g=i.fullWidthWidth??2,y=i.regularWidth??1,k=i.wideWidth??2,$=0,h=0,_=e.length,j=0,O=!1,A=_,L=Math.max(0,s-r),H=0,te=0,P=0,T=0;e:for(;;){if(te>H||h>=_&&h>$){let U=e.slice(H,te)||e.slice($,h);j=0;for(let Q of U.replaceAll(jl,"")){let Y=Q.codePointAt(0)||0;if(_l(Y)?T=g:xl(Y)?T=k:f!==y&&kl(Y)?T=f:T=y,P+T>L&&(A=Math.min(A,Math.max(H,$)+j)),P+T>s){O=!0;break e}j+=Q.length,P+=T}H=te=0}if(h>=_)break;if(Ji.lastIndex=h,Ji.test(e)){if(j=Ji.lastIndex-h,T=j*y,P+T>L&&(A=Math.min(A,h+Math.floor((L-P)/y))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Ji.lastIndex;continue}if(Ks.lastIndex=h,Ks.test(e)){if(P+o>L&&(A=Math.min(A,h)),P+o>s){O=!0;break}P+=o,H=$,te=h,h=$=Ks.lastIndex;continue}if(Wi.lastIndex=h,Wi.test(e)){if(j=Wi.lastIndex-h,T=j*a,P+T>L&&(A=Math.min(A,h+Math.floor((L-P)/a))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Wi.lastIndex;continue}if(Hi.lastIndex=h,Hi.test(e)){if(j=Hi.lastIndex-h,T=j*l,P+T>L&&(A=Math.min(A,h+Math.floor((L-P)/l))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Hi.lastIndex;continue}if(zs.lastIndex=h,zs.test(e)){if(P+m>L&&(A=Math.min(A,h)),P+m>s){O=!0;break}P+=m,H=$,te=h,h=$=zs.lastIndex;continue}h+=1}return{width:O?L:P,index:O?A:_,truncated:O,ellipsed:O&&s>=r}},Cl={limit:1/0,ellipsis:"",ellipsisWidth:0},De=(e,t={})=>Mr(e,Cl,t).width,Xi="\x1B",Lr="\x9B",Ol=39,cn="\x07",Vr="[",Il="]",Wr="m",un=`${Il}8;;`,Sr=new RegExp(`(?:\\${Vr}(?<code>\\d+)m|\\${un}(?<uri>.*)${cn})`,"y"),Rl=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},Cr=e=>`${Xi}${Vr}${e}${Wr}`,Or=e=>`${Xi}${un}${e}${cn}`,Al=e=>e.map(t=>De(t)),Ys=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:De(o),l=s.next(),f=s.next(),m=0;for(;!l.done;){let g=l.value,y=De(g);a+y<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Xi||g===Lr)&&(n=!0,r=t.startsWith(un,m+1)),n?r?g===cn&&(n=!1,r=!1):g===Wr&&(n=!1):(a+=y,a===i&&!f.done&&(e.push(""),a=0)),l=f,f=s.next(),m+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},El=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(De(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Tl=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Al(o),l=[""];for(let[$,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=De(l.at(-1)??"");if($!==0&&(_>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),_=0),(_>0||i.trim===!1)&&(l[l.length-1]+=" ",_++)),i.hard&&a[$]>t){let j=t-_,O=1+Math.floor((a[$]-j-1)/t);Math.floor((a[$]-1)/t)<O&&l.push(""),Ys(l,h,t);continue}if(_+a[$]>t&&_>0&&a[$]>0){if(i.wordWrap===!1&&_<t){Ys(l,h,t);continue}l.push("")}if(_+a[$]>t&&i.wordWrap===!1){Ys(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map($=>El($)));let f=l.join(`
|
|
49
|
-
`),m=f[Symbol.iterator](),g=m.next(),
|
|
50
|
-
`?(r&&(s+=
|
|
51
|
-
`&&(n&&
|
|
52
|
-
`);O.push(T),A+=T.length}if(A>
|
|
47
|
+
`).map(s=>ql(s,t,i)).join(`
|
|
48
|
+
`)}function Tr(e){return e.label??String(e.value??"")}function Kr(e,t){if(!e)return!0;let i=(t.label??String(t.value??"")).toLowerCase(),s=(t.hint??"").toLowerCase(),n=String(t.value).toLowerCase(),r=e.toLowerCase();return i.includes(r)||s.includes(r)||n.includes(r)}function Ml(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function Pr(e,t,i,s){let n=i,r=i;return s==="center"?n=Math.floor((t-e)/2):s==="right"&&(n=t-e-i),r=t-n-e,[n,r]}function nd({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=fi(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),f=k=>{switch(k){case"initial":case"active":return p.default.magenta;case"error":case"cancel":return p.default.red;case"submit":return p.default.green;default:return p.default.magenta}},m=(k,$)=>{let h=Math.floor(r/a*l);return`${f(k)(Dr[e].repeat(h))}${p.default.dim(Dr[e].repeat(l-h))} ${$}`},g=(k="")=>{o=k,n.start(m("initial",k))},b=(k=1,$)=>{r=Math.min(a,k+r),n.message(m("active",$??o)),o=$??o};return{start:g,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:b,isCancelled:n.isCancelled,message:k=>b(0,k)}}var p,He,Pt,ui,Zt,zi,Yi,tn,Ur,oe,qr,sn,nn,Nt,rn,E,je,Fr,Mr,mi,Dt,Xi,Tt,Qt,Lr,Zi,on,Vr,an,ln,Wr,dn,cn,un,mn,et,fn,Cl,Ol,Il,Zs,Ji,Bi,Qs,Gi,Rl,Al,Hr,El,Ne,Qi,Jr,Tl,pn,Br,Pl,Gr,hn,Rr,Dl,Ar,Er,Nl,en,Ul,ql,Fl,ti,zr,Ll,Vl,Wl,Hl,Jl,Xe,Bl,Gl,Je,Kl,zl,Yl,ci,Xl,Zl,Ql,ed,td,id,sd,fi,Dr,Ki,tt,rd,Nr,Et,od,ad,ld,Te,Ue=Ae(()=>{Xs();Xs();p=D(M(),1),He=D(require("node:process"),1),Pt=require("node:fs"),ui=require("node:path"),Zt=D(Ms(),1),zi=require("node:util");Yi=Sl(),tn=()=>process.env.CI==="true",Ur=e=>e.isTTY===!0,oe=(e,t)=>Yi?e:t,qr=oe("\u25C6","*"),sn=oe("\u25A0","x"),nn=oe("\u25B2","x"),Nt=oe("\u25C7","o"),rn=oe("\u250C","T"),E=oe("\u2502","|"),je=oe("\u2514","\u2014"),Fr=oe("\u2510","T"),Mr=oe("\u2518","\u2014"),mi=oe("\u25CF",">"),Dt=oe("\u25CB"," "),Xi=oe("\u25FB","[\u2022]"),Tt=oe("\u25FC","[+]"),Qt=oe("\u25FB","[ ]"),Lr=oe("\u25AA","\u2022"),Zi=oe("\u2500","-"),on=oe("\u256E","+"),Vr=oe("\u251C","+"),an=oe("\u256F","+"),ln=oe("\u2570","+"),Wr=oe("\u256D","+"),dn=oe("\u25CF","\u2022"),cn=oe("\u25C6","*"),un=oe("\u25B2","!"),mn=oe("\u25A0","x"),et=e=>{switch(e){case"initial":case"active":return p.default.cyan(qr);case"cancel":return p.default.red(sn);case"error":return p.default.yellow(nn);case"submit":return p.default.green(Nt)}},fn=e=>{switch(e){case"initial":case"active":return p.default.cyan(E);case"cancel":return p.default.red(E);case"error":return p.default.yellow(E);case"submit":return p.default.green(E)}},Cl=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,Ol=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Il=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,Zs=/[\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,Bi=/\t{1,1000}/y,Qs=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,Rl=new RegExp("\\p{M}+","gu"),Al={limit:1/0,ellipsis:""},Hr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Hr(n,Al,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,k=i.wideWidth??2,$=0,h=0,x=e.length,j=0,O=!1,A=x,V=Math.max(0,s-r),H=0,te=0,P=0,T=0;e:for(;;){if(te>H||h>=x&&h>$){let U=e.slice(H,te)||e.slice($,h);j=0;for(let Q of U.replaceAll(Rl,"")){let X=Q.codePointAt(0)||0;if(Ol(X)?T=g:Il(X)?T=k:f!==b&&Cl(X)?T=f:T=b,P+T>V&&(A=Math.min(A,Math.max(H,$)+j)),P+T>s){O=!0;break e}j+=Q.length,P+=T}H=te=0}if(h>=x)break;if(Gi.lastIndex=h,Gi.test(e)){if(j=Gi.lastIndex-h,T=j*b,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/b))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Gi.lastIndex;continue}if(Zs.lastIndex=h,Zs.test(e)){if(P+o>V&&(A=Math.min(A,h)),P+o>s){O=!0;break}P+=o,H=$,te=h,h=$=Zs.lastIndex;continue}if(Ji.lastIndex=h,Ji.test(e)){if(j=Ji.lastIndex-h,T=j*a,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/a))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Ji.lastIndex;continue}if(Bi.lastIndex=h,Bi.test(e)){if(j=Bi.lastIndex-h,T=j*l,P+T>V&&(A=Math.min(A,h+Math.floor((V-P)/l))),P+T>s){O=!0;break}P+=T,H=$,te=h,h=$=Bi.lastIndex;continue}if(Qs.lastIndex=h,Qs.test(e)){if(P+m>V&&(A=Math.min(A,h)),P+m>s){O=!0;break}P+=m,H=$,te=h,h=$=Qs.lastIndex;continue}h+=1}return{width:O?V:P,index:O?A:x,truncated:O,ellipsed:O&&s>=r}},El={limit:1/0,ellipsis:"",ellipsisWidth:0},Ne=(e,t={})=>Hr(e,El,t).width,Qi="\x1B",Jr="\x9B",Tl=39,pn="\x07",Br="[",Pl="]",Gr="m",hn=`${Pl}8;;`,Rr=new RegExp(`(?:\\${Br}(?<code>\\d+)m|\\${hn}(?<uri>.*)${pn})`,"y"),Dl=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},Ar=e=>`${Qi}${Br}${e}${Gr}`,Er=e=>`${Qi}${hn}${e}${pn}`,Nl=e=>e.map(t=>Ne(t)),en=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Ne(o),l=s.next(),f=s.next(),m=0;for(;!l.done;){let g=l.value,b=Ne(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Qi||g===Jr)&&(n=!0,r=t.startsWith(hn,m+1)),n?r?g===pn&&(n=!1,r=!1):g===Gr&&(n=!1):(a+=b,a===i&&!f.done&&(e.push(""),a=0)),l=f,f=s.next(),m+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Ul=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Ne(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},ql=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Nl(o),l=[""];for(let[$,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let x=Ne(l.at(-1)??"");if($!==0&&(x>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),x=0),(x>0||i.trim===!1)&&(l[l.length-1]+=" ",x++)),i.hard&&a[$]>t){let j=t-x,O=1+Math.floor((a[$]-j-1)/t);Math.floor((a[$]-1)/t)<O&&l.push(""),en(l,h,t);continue}if(x+a[$]>t&&x>0&&a[$]>0){if(i.wordWrap===!1&&x<t){en(l,h,t);continue}l.push("")}if(x+a[$]>t&&i.wordWrap===!1){en(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map($=>Ul($)));let f=l.join(`
|
|
49
|
+
`),m=f[Symbol.iterator](),g=m.next(),b=m.next(),k=0;for(;!g.done;){let $=g.value,h=b.value;if(s+=$,$===Qi||$===Jr){Rr.lastIndex=k+1;let j=Rr.exec(f)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);n=O===Tl?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let x=n?Dl(n):void 0;h===`
|
|
50
|
+
`?(r&&(s+=Er("")),n&&x&&(s+=Ar(x))):$===`
|
|
51
|
+
`&&(n&&x&&(s+=Ar(n)),r&&(s+=Er(r))),k+=$.length,g=b,b=m.next()}return s};Fl=(e,t,i,s,n)=>{let r=t,o=0;for(let a=i;a<s;a++){let l=e[a];if(r=r-l.length,o++,r<=n)break}return{lineCount:r,removals:o}},ti=e=>{let{cursor:t,options:i,style:s}=e,n=e.output??process.stdout,r=At(n),o=e.columnPadding??0,a=e.rowPadding??4,l=r-o,f=Ys(n),m=p.default.dim("..."),g=e.maxItems??Number.POSITIVE_INFINITY,b=Math.max(f-a,0),k=Math.max(Math.min(g,b),5),$=0;t>=k-3&&($=Math.max(Math.min(t-k+3,i.length-k),0));let h=k<i.length&&$>0,x=k<i.length&&$+k<i.length,j=Math.min($+k,i.length),O=[],A=0;h&&A++,x&&A++;let V=$+(h?1:0),H=j-(x?1:0);for(let P=V;P<H;P++){let T=ei(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
|
|
52
|
+
`);O.push(T),A+=T.length}if(A>b){let P=0,T=0,U=A,Q=t-V,X=(q,se)=>Fl(O,U,q,se,b);h?({lineCount:U,removals:P}=X(0,Q),U>b&&({lineCount:U,removals:T}=X(Q+1,O.length))):({lineCount:U,removals:T}=X(Q+1,O.length),U>b&&({lineCount:U,removals:P}=X(0,Q))),P>0&&(h=!0,O.splice(0,P)),T>0&&(x=!0,O.splice(O.length-T,T))}let te=[];h&&te.push(m);for(let P of O)for(let T of P)te.push(T);return x&&te.push(m),te};zr=e=>new di({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,i)=>Kr(t,i)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??ue.withGuide,i=t?[`${p.default.gray(E)}`,`${et(this.state)} ${e.message}`]:[`${et(this.state)} ${e.message}`],s=this.userInput,n=this.options,r=e.placeholder,o=s===""&&r!==void 0,a=(l,f)=>{let m=Tr(l),g=l.hint&&l.value===this.focusedValue?p.default.dim(` (${l.hint})`):"";switch(f){case"active":return`${p.default.green(mi)} ${m}${g}`;case"inactive":return`${p.default.dim(Dt)} ${p.default.dim(m)}`;case"disabled":return`${p.default.gray(Dt)} ${p.default.strikethrough(p.default.gray(m))}`}};switch(this.state){case"submit":{let l=Ml(this.selectedValues,n),f=l.length>0?` ${p.default.dim(l.map(Tr).join(", "))}`:"",m=t?p.default.gray(E):"";return`${i.join(`
|
|
53
53
|
`)}
|
|
54
54
|
${m}${f}`}case"cancel":{let l=s?` ${p.default.strikethrough(p.default.dim(s))}`:"",f=t?p.default.gray(E):"";return`${i.join(`
|
|
55
55
|
`)}
|
|
56
|
-
${f}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,f=t?`${l(E)} `:"",m=t?l(je):"",g="";if(this.isNavigating||o){let O=o?r:s;g=O!==""?` ${p.default.dim(O)}`:""}else g=` ${this.userInputWithCursor}`;let
|
|
57
|
-
`)}}}}).prompt(),
|
|
56
|
+
${f}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,f=t?`${l(E)} `:"",m=t?l(je):"",g="";if(this.isNavigating||o){let O=o?r:s;g=O!==""?` ${p.default.dim(O)}`:""}else g=` ${this.userInputWithCursor}`;let b=this.filteredOptions.length!==n.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",k=this.filteredOptions.length===0&&s?[`${f}${p.default.yellow("No matches found")}`]:[],$=this.state==="error"?[`${f}${p.default.yellow(this.error)}`]:[];t&&i.push(`${f.trimEnd()}`),i.push(`${f}${p.default.dim("Search:")}${g}${b}`,...k,...$);let h=[`${p.default.dim("\u2191/\u2193")} to select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],x=[`${f}${h.join(" \u2022 ")}`,m],j=this.filteredOptions.length===0?[]:ti({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:i.length+x.length,style:(O,A)=>a(O,O.disabled?"disabled":A?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...i,...j.map(O=>`${f}${O}`),...x].join(`
|
|
57
|
+
`)}}}}).prompt(),Ll=e=>{let t=(s,n,r,o)=>{let a=r.includes(s.value),l=s.label??String(s.value??""),f=s.hint&&o!==void 0&&s.value===o?p.default.dim(` (${s.hint})`):"",m=a?p.default.green(Tt):p.default.dim(Qt);return s.disabled?`${p.default.gray(Qt)} ${p.default.strikethrough(p.default.gray(l))}`:n?`${m} ${l}${f}`:`${m} ${p.default.dim(l)}`},i=new di({options:e.options,multiple:!0,filter:e.filter??((s,n)=>Kr(s,n)),validate:()=>{if(e.required&&i.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let s=`${p.default.gray(E)}
|
|
58
58
|
${et(this.state)} ${e.message}
|
|
59
|
-
`,n=this.userInput,r=e.placeholder,o=n===""&&r!==void 0,a=this.isNavigating||o?p.default.dim(o?r:n):this.userInputWithCursor,l=this.options,f=this.filteredOptions.length!==l.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${s}${p.default.gray(E)} ${p.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${s}${p.default.gray(E)} ${p.default.strikethrough(p.default.dim(n))}`;default:{let m=this.state==="error"?p.default.yellow:p.default.cyan,g=[`${p.default.dim("\u2191/\u2193")} to navigate`,`${p.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],
|
|
60
|
-
`),`${m(E)} ${p.default.dim("Search:")} ${a}${f}`,...
|
|
61
|
-
`)}}}});return i.prompt()},
|
|
62
|
-
`),Q=h+o*2;for(let q of U){let se=
|
|
59
|
+
`,n=this.userInput,r=e.placeholder,o=n===""&&r!==void 0,a=this.isNavigating||o?p.default.dim(o?r:n):this.userInputWithCursor,l=this.options,f=this.filteredOptions.length!==l.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${s}${p.default.gray(E)} ${p.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${s}${p.default.gray(E)} ${p.default.strikethrough(p.default.dim(n))}`;default:{let m=this.state==="error"?p.default.yellow:p.default.cyan,g=[`${p.default.dim("\u2191/\u2193")} to navigate`,`${p.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],b=this.filteredOptions.length===0&&n?[`${m(E)} ${p.default.yellow("No matches found")}`]:[],k=this.state==="error"?[`${m(E)} ${p.default.yellow(this.error)}`]:[],$=[...`${s}${m(E)}`.split(`
|
|
60
|
+
`),`${m(E)} ${p.default.dim("Search:")} ${a}${f}`,...b,...k],h=[`${m(E)} ${g.join(" \u2022 ")}`,`${m(je)}`],x=ti({cursor:this.cursor,options:this.filteredOptions,style:(j,O)=>t(j,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:$.length+h.length});return[...$,...x.map(j=>`${m(E)} ${j}`),...h].join(`
|
|
61
|
+
`)}}}});return i.prompt()},Vl=[Wr,on,ln,an],Wl=[rn,Fr,je,Mr];Hl=e=>e,Jl=(e="",t="",i)=>{let s=i?.output??process.stdout,n=At(s),r=2,o=i?.titlePadding??1,a=i?.contentPadding??2,l=i?.width===void 0||i.width==="auto"?1:Math.min(1,i.width),f=i?.withGuide??ue.withGuide?`${E} `:"",m=i?.formatBorder??Hl,g=(i?.rounded?Vl:Wl).map(m),b=m(Zi),k=m(E),$=Ne(f),h=Ne(t),x=n-$,j=Math.floor(n*l)-$;if(i?.width==="auto"){let U=e.split(`
|
|
62
|
+
`),Q=h+o*2;for(let q of U){let se=Ne(q)+a*2;se>Q&&(Q=se)}let X=Q+r;X<j&&(j=X)}j%2!==0&&(j<x?j++:j--);let O=j-r,A=O-o*2,V=h>A?`${t.slice(0,A-3)}...`:t,[H,te]=Pr(Ne(V),O,o,i?.titleAlign),P=ei(e,O-a*2,{hard:!0,trim:!1});s.write(`${f}${g[0]}${b.repeat(H)}${V}${b.repeat(te)}${g[1]}
|
|
63
63
|
`);let T=P.split(`
|
|
64
|
-
`);for(let U of T){let[Q,
|
|
65
|
-
`)}s.write(`${f}${g[2]}${
|
|
66
|
-
`)},
|
|
64
|
+
`);for(let U of T){let[Q,X]=Pr(Ne(U),O,a,i?.contentAlign);s.write(`${f}${k}${" ".repeat(Q)}${U}${" ".repeat(X)}${k}
|
|
65
|
+
`)}s.write(`${f}${g[2]}${b.repeat(O)}${g[3]}
|
|
66
|
+
`)},Xe=e=>{let t=e.active??"Yes",i=e.inactive??"No";return new qi({active:t,inactive:i,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let s=e.withGuide??ue.withGuide,n=`${s?`${p.default.gray(E)}
|
|
67
67
|
`:""}${et(this.state)} ${e.message}
|
|
68
68
|
`,r=this.value?t:i;switch(this.state){case"submit":{let o=s?`${p.default.gray(E)} `:"";return`${n}${o}${p.default.dim(r)}`}case"cancel":{let o=s?`${p.default.gray(E)} `:"";return`${n}${o}${p.default.strikethrough(p.default.dim(r))}${s?`
|
|
69
|
-
${p.default.gray(E)}`:""}`}default:{let o=s?`${p.default.cyan(E)} `:"",a=s?p.default.cyan(je):"";return`${n}${o}${this.value?`${p.default.green(
|
|
69
|
+
${p.default.gray(E)}`:""}`}default:{let o=s?`${p.default.cyan(E)} `:"",a=s?p.default.cyan(je):"";return`${n}${o}${this.value?`${p.default.green(mi)} ${t}`:`${p.default.dim(Dt)} ${p.default.dim(t)}`}${e.vertical?s?`
|
|
70
70
|
${p.default.cyan(E)} `:`
|
|
71
|
-
`:` ${p.default.dim("/")} `}${this.value?`${p.default.dim(
|
|
71
|
+
`:` ${p.default.dim("/")} `}${this.value?`${p.default.dim(Dt)} ${p.default.dim(i)}`:`${p.default.green(mi)} ${i}`}
|
|
72
72
|
${a}
|
|
73
|
-
`}}}}).prompt()},
|
|
74
|
-
${p.default.cyan(E)}`;k=`${h.repeat(i-1)}${h} `}if(o==="active")return`${k}${p.default.dim(
|
|
73
|
+
`}}}}).prompt()},Bl=async(e,t)=>{let i={},s=Object.keys(e);for(let n of s){let r=e[n],o=await r({results:i})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&de(o)){i[n]="canceled",t.onCancel({results:i});continue}i[n]=o}return i},Gl=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,s=(r,o,a=[])=>{let l=r.label??String(r.value),f=typeof r.group=="string",m=f&&(a[a.indexOf(r)+1]??{group:!0}),g=f&&m&&m.group===!0,b=f?t?`${g?je:E} `:" ":"",k="";if(i>0&&!f){let h=`
|
|
74
|
+
${p.default.cyan(E)}`;k=`${h.repeat(i-1)}${h} `}if(o==="active")return`${k}${p.default.dim(b)}${p.default.cyan(Xi)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${k}${b}${p.default.cyan(Xi)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${k}${b}${p.default.green(Tt)} ${p.default.dim(l)}`;if(o==="selected"){let h=f||t?p.default.green(Tt):"";return`${k}${p.default.dim(b)}${h} ${p.default.dim(l)}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${p.default.strikethrough(p.default.dim(l))}`;if(o==="active-selected")return`${k}${p.default.dim(b)}${p.default.green(Tt)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${p.default.dim(l)}`;let $=f||t?p.default.dim(Qt):"";return`${k}${p.default.dim(b)}${$} ${p.default.dim(l)}`},n=e.required??!0;return new Fi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(n&&(r===void 0||r.length===0))return`Please select at least one option.
|
|
75
75
|
${p.default.reset(p.default.dim(`Press ${p.default.gray(p.default.bgWhite(p.default.inverse(" space ")))} to select, ${p.default.gray(p.default.bgWhite(p.default.inverse(" enter ")))} to submit`))}`},render(){let r=`${p.default.gray(E)}
|
|
76
76
|
${et(this.state)} ${e.message}
|
|
77
77
|
`,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>o.includes(f)).map(f=>s(f,"submitted")),l=a.length===0?"":` ${a.join(p.default.dim(", "))}`;return`${r}${p.default.gray(E)}${l}`}case"cancel":{let a=this.options.filter(({value:l})=>o.includes(l)).map(l=>s(l,"cancelled")).join(p.default.dim(", "));return`${r}${p.default.gray(E)} ${a.trim()?`${a}
|
|
78
78
|
${p.default.gray(E)}`:""}`}case"error":{let a=this.error.split(`
|
|
79
79
|
`).map((l,f)=>f===0?`${p.default.yellow(je)} ${p.default.yellow(l)}`:` ${l}`).join(`
|
|
80
|
-
`);return`${r}${p.default.yellow(E)} ${this.options.map((l,f,m)=>{let g=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),
|
|
80
|
+
`);return`${r}${p.default.yellow(E)} ${this.options.map((l,f,m)=>{let g=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),b=f===this.cursor;return!b&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?s(l,g?"group-active-selected":"group-active",m):b&&g?s(l,"active-selected",m):g?s(l,"selected",m):s(l,b?"active":"inactive",m)}).join(`
|
|
81
81
|
${p.default.yellow(E)} `)}
|
|
82
82
|
${a}
|
|
83
|
-
`}default:{let a=this.options.map((f,m,g)=>{let
|
|
83
|
+
`}default:{let a=this.options.map((f,m,g)=>{let b=o.includes(f.value)||f.group===!0&&this.isGroupSelected(`${f.value}`),k=m===this.cursor,$=!k&&typeof f.group=="string"&&this.options[this.cursor].value===f.group,h="";return $?h=s(f,b?"group-active-selected":"group-active",g):k&&b?h=s(f,"active-selected",g):b?h=s(f,"selected",g):h=s(f,k?"active":"inactive",g),`${m!==0&&!h.startsWith(`
|
|
84
84
|
`)?" ":""}${h}`}).join(`
|
|
85
85
|
${p.default.cyan(E)}`),l=a.startsWith(`
|
|
86
86
|
`)?"":" ";return`${r}${p.default.cyan(E)}${l}${a}
|
|
87
87
|
${p.default.cyan(je)}
|
|
88
|
-
`}}}}).prompt()},
|
|
89
|
-
`);if(g.length>0){let[
|
|
88
|
+
`}}}}).prompt()},Je={message:(e=[],{symbol:t=p.default.gray(E),secondarySymbol:i=p.default.gray(E),output:s=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??ue.withGuide,l=a?i:"",f=a?`${t} `:"",m=a?`${i} `:"";for(let b=0;b<n;b++)o.push(l);let g=Array.isArray(e)?e:e.split(`
|
|
89
|
+
`);if(g.length>0){let[b,...k]=g;b.length>0?o.push(`${f}${b}`):o.push(a?t:"");for(let $ of k)$.length>0?o.push(`${m}${$}`):o.push(a?i:"")}s.write(`${o.join(`
|
|
90
90
|
`)}
|
|
91
|
-
`)},info:(e,t)=>{
|
|
91
|
+
`)},info:(e,t)=>{Je.message(e,{...t,symbol:p.default.blue(dn)})},success:(e,t)=>{Je.message(e,{...t,symbol:p.default.green(cn)})},step:(e,t)=>{Je.message(e,{...t,symbol:p.default.green(Nt)})},warn:(e,t)=>{Je.message(e,{...t,symbol:p.default.yellow(un)})},warning:(e,t)=>{Je.warn(e,t)},error:(e,t)=>{Je.message(e,{...t,symbol:p.default.red(mn)})}},Kl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(je)} ${p.default.red(e)}
|
|
92
92
|
|
|
93
|
-
`)},
|
|
94
|
-
`)},
|
|
93
|
+
`)},zl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(rn)} ${e}
|
|
94
|
+
`)},Yl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(E)}
|
|
95
95
|
${p.default.gray(je)} ${e}
|
|
96
96
|
|
|
97
|
-
`)},
|
|
97
|
+
`)},ci=(e,t)=>e.split(`
|
|
98
98
|
`).map(i=>t(i)).join(`
|
|
99
|
-
`),
|
|
100
|
-
${p.default.reset(p.default.dim(`Press ${p.default.gray(p.default.bgWhite(p.default.inverse(" space ")))} to select, ${p.default.gray(p.default.bgWhite(p.default.inverse(" enter ")))} to submit`))}`},render(){let s=ot(e.output,e.message,`${
|
|
99
|
+
`),Xl=e=>{let t=(s,n)=>{let r=s.label??String(s.value);return n==="disabled"?`${p.default.gray(Qt)} ${ci(r,o=>p.default.strikethrough(p.default.gray(o)))}${s.hint?` ${p.default.dim(`(${s.hint??"disabled"})`)}`:""}`:n==="active"?`${p.default.cyan(Xi)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="selected"?`${p.default.green(Tt)} ${ci(r,p.default.dim)}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="cancelled"?`${ci(r,o=>p.default.strikethrough(p.default.dim(o)))}`:n==="active-selected"?`${p.default.green(Tt)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="submitted"?`${ci(r,p.default.dim)}`:`${p.default.dim(Qt)} ${ci(r,p.default.dim)}`},i=e.required??!0;return new Mi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:i,cursorAt:e.cursorAt,validate(s){if(i&&(s===void 0||s.length===0))return`Please select at least one option.
|
|
100
|
+
${p.default.reset(p.default.dim(`Press ${p.default.gray(p.default.bgWhite(p.default.inverse(" space ")))} to select, ${p.default.gray(p.default.bgWhite(p.default.inverse(" enter ")))} to submit`))}`},render(){let s=ot(e.output,e.message,`${fn(this.state)} `,`${et(this.state)} `),n=`${p.default.gray(E)}
|
|
101
101
|
${s}
|
|
102
102
|
`,r=this.value??[],o=(a,l)=>{if(a.disabled)return t(a,"disabled");let f=r.includes(a.value);return l&&f?t(a,"active-selected"):f?t(a,"selected"):t(a,l?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"submitted")).join(p.default.dim(", "))||p.default.dim("none"),l=ot(e.output,a,`${p.default.gray(E)} `);return`${n}${l}`}case"cancel":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"cancelled")).join(p.default.dim(", "));if(a.trim()==="")return`${n}${p.default.gray(E)}`;let l=ot(e.output,a,`${p.default.gray(E)} `);return`${n}${l}
|
|
103
103
|
${p.default.gray(E)}`}case"error":{let a=`${p.default.yellow(E)} `,l=this.error.split(`
|
|
104
|
-
`).map((g,
|
|
104
|
+
`).map((g,b)=>b===0?`${p.default.yellow(je)} ${p.default.yellow(g)}`:` ${g}`).join(`
|
|
105
105
|
`),f=n.split(`
|
|
106
106
|
`).length,m=l.split(`
|
|
107
|
-
`).length+1;return`${n}${a}${
|
|
107
|
+
`).length+1;return`${n}${a}${ti({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:o}).join(`
|
|
108
108
|
${a}`)}
|
|
109
109
|
${l}
|
|
110
110
|
`}default:{let a=`${p.default.cyan(E)} `,l=n.split(`
|
|
111
|
-
`).length;return`${n}${a}${
|
|
111
|
+
`).length;return`${n}${a}${ti({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+2,style:o}).join(`
|
|
112
112
|
${a}`)}
|
|
113
113
|
${p.default.cyan(je)}
|
|
114
|
-
`}}}}).prompt()},
|
|
115
|
-
`),r=n.reduce((l,f)=>Math.max(
|
|
116
|
-
`).map(r),""],a=
|
|
114
|
+
`}}}}).prompt()},Zl=e=>p.default.dim(e),Ql=(e,t,i)=>{let s={hard:!0,trim:!1},n=ei(e,t,s).split(`
|
|
115
|
+
`),r=n.reduce((l,f)=>Math.max(Ne(f),l),0),o=n.map(i).reduce((l,f)=>Math.max(Ne(f),l),0),a=t-(o-r);return ei(e,a,s)},ed=(e="",t="",i)=>{let s=i?.output??He.default.stdout,n=i?.withGuide??ue.withGuide,r=i?.format??Zl,o=["",...Ql(e,At(s)-6,r).split(`
|
|
116
|
+
`).map(r),""],a=Ne(t),l=Math.max(o.reduce((b,k)=>{let $=Ne(k);return $>b?$:b},0),a)+2,f=o.map(b=>`${p.default.gray(E)} ${b}${" ".repeat(l-Ne(b))}${p.default.gray(E)}`).join(`
|
|
117
117
|
`),m=n?`${p.default.gray(E)}
|
|
118
|
-
`:"",g=n?
|
|
118
|
+
`:"",g=n?Vr:ln;s.write(`${m}${p.default.green(Nt)} ${p.default.reset(t)} ${p.default.gray(Zi.repeat(Math.max(l-a-1,1))+on)}
|
|
119
119
|
${f}
|
|
120
|
-
${p.default.gray(g+
|
|
121
|
-
`)},
|
|
120
|
+
${p.default.gray(g+Zi.repeat(l+2)+an)}
|
|
121
|
+
`)},td=e=>new Ir({validate:e.validate,mask:e.mask??Lr,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??ue.withGuide,i=`${t?`${p.default.gray(E)}
|
|
122
122
|
`:""}${et(this.state)} ${e.message}
|
|
123
123
|
`,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=t?`${p.default.yellow(E)} `:"",o=t?`${p.default.yellow(je)} `:"",a=n??"";return e.clearOnError&&this.clear(),`${i.trim()}
|
|
124
124
|
${r}${a}
|
|
@@ -126,47 +126,47 @@ ${o}${p.default.yellow(this.error)}
|
|
|
126
126
|
`}case"submit":{let r=t?`${p.default.gray(E)} `:"",o=n?p.default.dim(n):"";return`${i}${r}${o}`}case"cancel":{let r=t?`${p.default.gray(E)} `:"",o=n?p.default.strikethrough(p.default.dim(n)):"";return`${i}${r}${o}${n&&t?`
|
|
127
127
|
${p.default.gray(E)}`:""}`}default:{let r=t?`${p.default.cyan(E)} `:"",o=t?p.default.cyan(je):"";return`${i}${r}${s}
|
|
128
128
|
${o}
|
|
129
|
-
`}}}}).prompt(),
|
|
130
|
-
`);let F=
|
|
131
|
-
`);F.length>1&&i.write(
|
|
132
|
-
`);let
|
|
133
|
-
`):i.write(`${
|
|
134
|
-
`)),P(),m()};return{start:q,stop:(F="")=>se(F,0),message:(F="")=>{$=U(F??$)},cancel:(F="")=>se(F,1),error:(F="")=>se(F,2),clear:()=>se("",0,!0),get isCancelled(){return k}}},
|
|
129
|
+
`}}}}).prompt(),id=e=>{let t=e.validate;return zr({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(i){if(!Array.isArray(i)){if(!i)return"Please select a path";if(t)return t(i)}},options(){let i=this.userInput;if(i==="")return[];try{let s;return(0,Pt.existsSync)(i)?(0,Pt.lstatSync)(i).isDirectory()?s=i:s=(0,ui.dirname)(i):s=(0,ui.dirname)(i),(0,Pt.readdirSync)(s).map(n=>{let r=(0,ui.join)(s,n),o=(0,Pt.lstatSync)(r);return{name:n,path:r,isDirectory:o.isDirectory()}}).filter(({path:n,isDirectory:r})=>n.startsWith(i)&&(e.directory||!r)).map(n=>({value:n.path}))}catch{return[]}}})},sd=p.default.magenta,fi=({indicator:e="dots",onCancel:t,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=Yi?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Yi?80:120,signal:a,...l}={})=>{let f=tn(),m,g,b=!1,k=!1,$="",h,x=performance.now(),j=At(i),O=l?.styleFrame??sd,A=F=>{let Z=F>1?n??ue.messages.error:s??ue.messages.cancel;k=F===1,b&&(se(Z,F),k&&typeof t=="function"&&t())},V=()=>A(2),H=()=>A(1),te=()=>{process.on("uncaughtExceptionMonitor",V),process.on("unhandledRejection",V),process.on("SIGINT",H),process.on("SIGTERM",H),process.on("exit",A),a&&a.addEventListener("abort",H)},P=()=>{process.removeListener("uncaughtExceptionMonitor",V),process.removeListener("unhandledRejection",V),process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H),process.removeListener("exit",A),a&&a.removeEventListener("abort",H)},T=()=>{if(h===void 0)return;f&&i.write(`
|
|
130
|
+
`);let F=ei(h,j,{hard:!0,trim:!1}).split(`
|
|
131
|
+
`);F.length>1&&i.write(Zt.cursor.up(F.length-1)),i.write(Zt.cursor.to(0)),i.write(Zt.erase.down())},U=F=>F.replace(/\.+$/,""),Q=F=>{let Z=(performance.now()-F)/1e3,ee=Math.floor(Z/60),z=Math.floor(Z%60);return ee>0?`[${ee}m ${z}s]`:`[${z}s]`},X=l.withGuide??ue.withGuide,q=(F="")=>{b=!0,m=Or({output:i}),$=U(F),x=performance.now(),X&&i.write(`${p.default.gray(E)}
|
|
132
|
+
`);let Z=0,ee=0;te(),g=setInterval(()=>{if(f&&$===h)return;T(),h=$;let z=O(r[Z]),Re;if(f)Re=`${z} ${$}...`;else if(e==="timer")Re=`${z} ${$} ${Q(x)}`;else{let ce=".".repeat(Math.floor(ee)).slice(0,3);Re=`${z} ${$}${ce}`}let ze=ei(Re,j,{hard:!0,trim:!1});i.write(ze),Z=Z+1<r.length?Z+1:0,ee=ee<4?ee+.125:0},o)},se=(F="",Z=0,ee=!1)=>{if(!b)return;b=!1,clearInterval(g),T();let z=Z===0?p.default.green(Nt):Z===1?p.default.red(sn):p.default.red(nn);$=F??$,ee||(e==="timer"?i.write(`${z} ${$} ${Q(x)}
|
|
133
|
+
`):i.write(`${z} ${$}
|
|
134
|
+
`)),P(),m()};return{start:q,stop:(F="")=>se(F,0),message:(F="")=>{$=U(F??$)},cancel:(F="")=>se(F,1),error:(F="")=>se(F,2),clear:()=>se("",0,!0),get isCancelled(){return k}}},Dr={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Ki=(e,t)=>e.includes(`
|
|
135
135
|
`)?e.split(`
|
|
136
136
|
`).map(i=>t(i)).join(`
|
|
137
|
-
`):t(e),tt=e=>{let t=(i,s)=>{let n=i.label??String(i.value);switch(s){case"disabled":return`${p.default.gray(
|
|
137
|
+
`):t(e),tt=e=>{let t=(i,s)=>{let n=i.label??String(i.value);switch(s){case"disabled":return`${p.default.gray(Dt)} ${Ki(n,p.default.gray)}${i.hint?` ${p.default.dim(`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Ki(n,p.default.dim)}`;case"active":return`${p.default.green(mi)} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`;case"cancelled":return`${Ki(n,r=>p.default.strikethrough(p.default.dim(r)))}`;default:return`${p.default.dim(Dt)} ${Ki(n,p.default.dim)}`}};return new Li({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??ue.withGuide,s=`${et(this.state)} `,n=`${fn(this.state)} `,r=ot(e.output,e.message,n,s),o=`${i?`${p.default.gray(E)}
|
|
138
138
|
`:""}${r}
|
|
139
139
|
`;switch(this.state){case"submit":{let a=i?`${p.default.gray(E)} `:"",l=ot(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${l}`}case"cancel":{let a=i?`${p.default.gray(E)} `:"",l=ot(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${l}${i?`
|
|
140
140
|
${p.default.gray(E)}`:""}`}default:{let a=i?`${p.default.cyan(E)} `:"",l=i?p.default.cyan(je):"",f=o.split(`
|
|
141
|
-
`).length,m=i?2:1;return`${o}${a}${
|
|
141
|
+
`).length,m=i?2:1;return`${o}${a}${ti({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:(g,b)=>t(g,g.disabled?"disabled":b?"active":"inactive")}).join(`
|
|
142
142
|
${a}`)}
|
|
143
143
|
${l}
|
|
144
|
-
`}}}}).prompt()},
|
|
144
|
+
`}}}}).prompt()},rd=e=>{let t=(i,s="inactive")=>{let n=i.label??String(i.value);return s==="selected"?`${p.default.dim(n)}`:s==="cancelled"?`${p.default.strikethrough(p.default.dim(n))}`:s==="active"?`${p.default.bgCyan(p.default.gray(` ${i.value} `))} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`:`${p.default.gray(p.default.bgWhite(p.default.inverse(` ${i.value} `)))} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`};return new Vi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let i=e.withGuide??ue.withGuide,s=`${i?`${p.default.gray(E)}
|
|
145
145
|
`:""}${et(this.state)} ${e.message}
|
|
146
146
|
`;switch(this.state){case"submit":{let n=i?`${p.default.gray(E)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=ot(e.output,t(r,"selected"),n);return`${s}${o}`}case"cancel":{let n=i?`${p.default.gray(E)} `:"",r=ot(e.output,t(this.options[0],"cancelled"),n);return`${s}${r}${i?`
|
|
147
147
|
${p.default.gray(E)}`:""}`}default:{let n=i?`${p.default.cyan(E)} `:"",r=i?p.default.cyan(je):"",o=this.options.map((a,l)=>ot(e.output,t(a,l===this.cursor?"active":"inactive"),n)).join(`
|
|
148
148
|
`);return`${s}${o}
|
|
149
149
|
${r}
|
|
150
|
-
`}}}}).prompt()},
|
|
150
|
+
`}}}}).prompt()},Nr=`${p.default.gray(E)} `,Et={message:async(e,{symbol:t=p.default.gray(E)}={})=>{process.stdout.write(`${p.default.gray(E)}
|
|
151
151
|
${t} `);let i=3;for await(let s of e){s=s.replace(/\n/g,`
|
|
152
|
-
${
|
|
153
|
-
`)&&(i=3+(0,
|
|
154
|
-
`))).length);let n=(0,
|
|
155
|
-
${
|
|
156
|
-
`)},info:e=>
|
|
157
|
-
`),t.write(`${p.default.green(
|
|
158
|
-
`);for(let
|
|
159
|
-
`);let l=[{value:"",full:""}],f=!1,m=
|
|
152
|
+
${Nr}`),s.includes(`
|
|
153
|
+
`)&&(i=3+(0,zi.stripVTControlCharacters)(s.slice(s.lastIndexOf(`
|
|
154
|
+
`))).length);let n=(0,zi.stripVTControlCharacters)(s).length;i+n<process.stdout.columns?(i+=n,process.stdout.write(s)):(process.stdout.write(`
|
|
155
|
+
${Nr}${s.trimStart()}`),i=3+(0,zi.stripVTControlCharacters)(s.trimStart()).length)}process.stdout.write(`
|
|
156
|
+
`)},info:e=>Et.message(e,{symbol:p.default.blue(dn)}),success:e=>Et.message(e,{symbol:p.default.green(cn)}),step:e=>Et.message(e,{symbol:p.default.green(Nt)}),warn:e=>Et.message(e,{symbol:p.default.yellow(un)}),warning:e=>Et.warn(e),error:e=>Et.message(e,{symbol:p.default.red(mn)})},od=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let s=fi(t);s.start(i.title);let n=await i.task(s.message);s.stop(n||i.title)}},ad=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),ld=e=>{let t=e.output??process.stdout,i=At(t),s=p.default.gray(E),n=e.spacing??1,r=3,o=e.retainLog===!0,a=!tn()&&Ur(t);t.write(`${s}
|
|
157
|
+
`),t.write(`${p.default.green(Nt)} ${e.title}
|
|
158
|
+
`);for(let x=0;x<n;x++)t.write(`${s}
|
|
159
|
+
`);let l=[{value:"",full:""}],f=!1,m=x=>{if(l.length===0)return;let j=0;x&&(j+=n+2);for(let O of l){let{value:A,result:V}=O,H=V?.message??A;if(H.length===0)continue;V===void 0&&O.header!==void 0&&O.header!==""&&(H+=`
|
|
160
160
|
${O.header}`);let te=H.split(`
|
|
161
|
-
`).reduce((P,T)=>T===""?P+1:P+Math.ceil((T.length+r)/i),0);j+=te}j>0&&(j+=1,t.write(
|
|
162
|
-
${
|
|
163
|
-
`).map(p.default.bold),{output:t,secondarySymbol:s,symbol:s,spacing:0}),
|
|
164
|
-
`).map(p.default.dim),{output:t,secondarySymbol:s,symbol:s,spacing:j??n})},
|
|
165
|
-
`),
|
|
166
|
-
`),
|
|
161
|
+
`).reduce((P,T)=>T===""?P+1:P+Math.ceil((T.length+r)/i),0);j+=te}j>0&&(j+=1,t.write(Zt.erase.lines(j)))},g=(x,j,O)=>{let A=O?`${x.full}
|
|
162
|
+
${x.value}`:x.value;x.header!==void 0&&x.header!==""&&Je.message(x.header.split(`
|
|
163
|
+
`).map(p.default.bold),{output:t,secondarySymbol:s,symbol:s,spacing:0}),Je.message(A.split(`
|
|
164
|
+
`).map(p.default.dim),{output:t,secondarySymbol:s,symbol:s,spacing:j??n})},b=()=>{for(let x of l){let{header:j,value:O,full:A}=x;(j===void 0||j.length===0)&&O.length===0||g(x,void 0,o===!0&&A.length>0)}},k=(x,j,O)=>{if(m(!1),(O?.raw!==!0||!f)&&x.value!==""&&(x.value+=`
|
|
165
|
+
`),x.value+=ad(j),f=O?.raw===!0,e.limit!==void 0){let A=x.value.split(`
|
|
166
|
+
`),V=A.length-e.limit;if(V>0){let H=A.splice(0,V);o&&(x.full+=(x.full===""?"":`
|
|
167
167
|
`)+H.join(`
|
|
168
|
-
`))}
|
|
169
|
-
`)}a&&$()},$=()=>{for(let
|
|
168
|
+
`))}x.value=A.join(`
|
|
169
|
+
`)}a&&$()},$=()=>{for(let x of l)x.result?x.result.status==="error"?Je.error(x.result.message,{output:t,secondarySymbol:s,spacing:0}):Je.success(x.result.message,{output:t,secondarySymbol:s,spacing:0}):x.value!==""&&g(x,0)},h=(x,j)=>{m(!1),x.result=j,a&&$()};return{message(x,j){k(l[0],x,j)},group(x){let j={header:x,value:"",full:""};return l.push(j),{message(O,A){k(j,O,A)},error(O){h(j,{status:"error",message:O})},success(O){h(j,{status:"success",message:O})}}},error(x,j){m(!0),Je.error(x,{output:t,secondarySymbol:s,spacing:1}),j?.showLog!==!1&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(x,j){m(!0),Je.success(x,{output:t,secondarySymbol:s,spacing:1}),j?.showLog===!0&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Te=e=>new Wi({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??ue.withGuide,i=`${`${t?`${p.default.gray(E)}
|
|
170
170
|
`:""}${et(this.state)} `}${e.message}
|
|
171
171
|
`,s=e.placeholder?p.default.inverse(e.placeholder[0])+p.default.dim(e.placeholder.slice(1)):p.default.inverse(p.default.hidden("_")),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${p.default.yellow(this.error)}`:"",a=t?`${p.default.yellow(E)} `:"",l=t?p.default.yellow(je):"";return`${i.trim()}
|
|
172
172
|
${a}${n}
|
|
@@ -174,47 +174,48 @@ ${l}${o}
|
|
|
174
174
|
`}case"submit":{let o=r?` ${p.default.dim(r)}`:"",a=t?p.default.gray(E):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${p.default.strikethrough(p.default.dim(r))}`:"",a=t?p.default.gray(E):"";return`${i}${a}${o}${r.trim()?`
|
|
175
175
|
${a}`:""}`}default:{let o=t?`${p.default.cyan(E)} `:"",a=t?p.default.cyan(je):"";return`${i}${o}${n}
|
|
176
176
|
${a}
|
|
177
|
-
`}}}}).prompt()});function
|
|
178
|
-
`)}else{for(let k of y)console.log(k);f=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",m)),g(),n&&(o=setInterval(()=>{r++,g()},80))},markDone(y,k){t[y].status="done",k!==void 0&&(t[y].icon=k),n&&g()},stop(){o&&clearInterval(o);for(let y of t)y.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",m))}}}var J,Kr,Se,b,v,rd,od,ld,Gr,V=Ae(()=>{"use strict";J=D(M(),1),Kr=require("child_process");Ne();Se=process.stdout.isTTY??!1;b={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},v={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};rd={start:()=>{},stop:()=>{},message:()=>{}};od=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;ld={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Gr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function Xr(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function Zr(e){return Xr(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(Xr)}async function Qr(){if(gn)return;let e=process.argv.includes("--json")||!Ps,t=Le(),i=Ve();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Zr(r)){gn=!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)),d(),console.log(` ${ve.default.dim("This feature requires a")} ${ve.default.bold("paid plan")} ${ve.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${ve.default.dim("Opening pricing page")} ${b.arrow} ${ve.default.cyan("domani.run/pricing")}`),Je(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),d();let s=C(!0);s.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Zr(o)){gn=!0,s.stop(`${b.success} Paid plan active! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No upgrade detected. Visit ${ve.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function eo(){if(hn||Ve()){hn=!0;return}(process.argv.includes("--json")||!Ps)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),d(),console.log(` ${ve.default.dim("You're not logged in.")} Starting authentication...`),d();let t=Le(),i=C(!0);i.start("Requesting auth code");let s;try{s=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{i.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Could not reach ${t}. Check your connection.`),process.exit(1)}if(!s.ok){i.stop("Failed");let o=`Server error (${s.status})`;try{let a=await s.json();o=a.error||a.message||o}catch{}console.error(` ${ve.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await s.json())}catch{i.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${b.success} Auth code ready`),d(),console.log(` ${ve.default.dim("Verification code:")} ${ve.default.bold(ve.default.cyan(n))}`),console.log(` ${ve.default.dim("Opening browser")} ${b.arrow} ${v.url(r)}`),Je(r),d(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(f=>setTimeout(f,5e3));let a=await fetch(`${t}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){zt({...ht(),token:l.token,email:l.email,api_url:t}),hn=!0,i.stop(`${b.success} Logged in as ${ve.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No approval received. Run ${ve.default.cyan("domani login")} to try again.`),process.exit(1)}var ve,hn,gn,yn=Ae(()=>{"use strict";ve=D(M(),1);gt();V();hn=!1,gn=!1});function so(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let i=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${i?` (got: "${i}")`:""}. 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={},i=!1){let s=Ve(),n=`${Le()}${e}`,r=await fetch(n,{...t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json","User-Agent":`domani-cli/${xe}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await Qr(),x(e,t,!0)}catch{}}return so(r)}async function we(e,t={}){let i=`${Le()}${e}`,s=Ve(),n=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${xe}`,...s?{Authorization:`Bearer ${s}`}:{},...t.headers}});return so(n)}var G=Ae(()=>{"use strict";gt();yn()});function St(){return{ok:!0}}function bt(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function oo(e){return md.test(e)?bt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):St()}function bd(e){return fd.test(e)?bt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):St()}function wd(e){return pd.test(e)?bt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):St()}function vd(e){return hd.test(e)?bt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):St()}function ao(e){if(!e)return bt("Domain name is required","validation_error");if(e.length>ro)return bt(`Domain name too long (${e.length} chars, max ${ro})`,"validation_error");for(let t of[oo,bd,wd,vd]){let i=t(e);if(!i.ok)return i}return gd.test(e)?St():bt(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function $d(e){if(!e)return bt("TLD is required","validation_error");let t=oo(e);return t.ok?yd.test(e)?St():bt(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function kd(e){for(let t of e){let i=ao(t);if(!i.ok)return i}return St()}function _d(e){for(let t of e){let i=$d(t);if(!i.ok)return i}return St()}function z(e,t){let i=ao(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function lo(e,t){let i=kd(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Qi(e,t){let i=_d(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var md,fd,pd,hd,gd,yd,ro,ge=Ae(()=>{"use strict";V();md=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,fd=/\.\.[/\\]/,pd=/[?#]/,hd=/%[0-9a-fA-F]{2}/,gd=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,yd=/^\.?[a-zA-Z]{2,63}$/,ro=253});async function fe(){Se||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"),i=await t.json();t.ok||(e.stop("Failed"),pn(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${wn.default.dim("No domains yet.")} Use: ${wn.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await tt({message:"Which domain?",options:s.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return le(n)&&process.exit(0),n}var wn,Ze=Ae(()=>{"use strict";G();Ne();wn=D(M(),1);V()});var uo={};Ht(uo,{connect:()=>vn});async function vn(e,t,i){e||(e=await fe()),z(e,i);let s;if(t&&!i.provider?t.includes(".")?s=t:i.provider=t:s=t,!s&&!i.provider&&!i.list&&i.dryRun)return B("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!s&&!i.provider&&!i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){w(o,i.fields);return}let a=[];for(let h of["hosting","email"]){let _=o.providers?.[h]||[];for(let j of _)a.push({value:`${h}:${j.name}`,label:j.name,hint:h})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await tt({message:"Choose a provider",options:a});le(l)&&process.exit(0);let[f,m]=l.split(":"),y=(o.providers?.[f]||[]).find(h=>h.name===m),k;if(y&&y.methods.length>1){let h=await tt({message:"Choose a method",options:y.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});le(h)&&process.exit(0),k=h}let $;if(f==="hosting"&&y?.requires_target){y.notes?.setup&&Xe(y.notes.setup);let h=await Te({message:"Target hostname or IP"});le(h)&&process.exit(0),$=h.trim()}return co(e,{target:$,provider:m,method:k,dryRun:i.dryRun,json:!1})}if(i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){w(o,i.fields);return}S(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){d(),console.log(` ${ue.default.bold(a.toUpperCase())}`);for(let f of l){let m=f.methods.map(g=>g.default?ue.default.green(`${g.name} (default)`):ue.default.dim(g.name)).join(ue.default.dim(", "));console.log(` ${ue.default.cyan(f.name.padEnd(20))} ${m}`)}}}d();return}return co(e,i)}async function co(e,t){let i={};if(t.target&&(i.target=t.target),t.provider&&(i.provider=t.provider),t.method&&(i.method=t.method),t.dryRun)return B("connect",{domain:e,...i},t.json,t.fields);let s=C(!t.json);s.start(`Connecting ${v.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(i)}),r=await n.json();n.ok||(s.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(s.stop(o?`${b.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${b.success} Connected to ${ue.default.cyan(r.provider)}`),t.json){w(r,t.fields);return}if(S(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),c("Provider",ue.default.cyan(r.provider)),c("Method",r.method),r.records?.length){let a=[8,22,40];d(),console.log(` ${ue.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((m,g)=>ue.default.dim(m.padEnd(a[g]))).join(" "),f=a.map(m=>ue.default.dim("\u2500".repeat(m))).join(" ");console.log(` ${l}`),console.log(` ${f}`);for(let m of r.records){let g=m.record,y=m.status!=="already_set";process.stdout.isTTY&&y&&await Ut(50);let $=[ue.default.yellow(g.type),g.name,ue.default.cyan(g.value)+(g.priority?ue.default.dim(` pri=${g.priority}`):"")].map((j,O)=>Zi(j,a[O])).join(" "),h=m.status==="already_set"?ue.default.dim("\u2713"):m.status==="updated"?ue.default.yellow("\u21BA"):m.status==="pending"?ue.default.yellow("\u2192"):b.success,_=m.status==="already_set"?ue.default.dim(" already set"):m.status==="updated"?ue.default.dim(" updated"):m.status==="pending"?ue.default.dim(" add this"):"";console.log(` ${h} ${$}${_}`)}}d(),r.next_steps?.length?(console.log(` ${ue.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${ue.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${ue.default.dim(r.hint)}`),r.docs&&console.log(` ${ue.default.dim("Docs:")} ${v.url(r.docs)}`),d()}var ue,$n=Ae(()=>{"use strict";G();ue=D(M(),1);Ne();V();ge();Ze()});function Ft(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 i={},s=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[n,r]of s){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);i[n]=o}return Object.keys(i).length>0?i:void 0}function Mt(e){return e?Object.keys(e):[]}var es=Ae(()=>{"use strict"});var vo={};Ht(vo,{email:()=>fi,parseRecipients:()=>ts,recipientField:()=>is});function Sd(e){return[R.default.yellow(e.type),e.name,R.default.cyan(e.value)+(e.priority?R.default.dim(` pri=${e.priority}`):"")]}function kn(e){return jd[e]||e}function ts(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function is(e){if(e.length!==0)return e.length===1?e[0]:e}function Cd(e,t){if(e&&e.includes("@")){let[i,s]=e.split("@",2);!t.slug&&i&&(t.slug=i),!t.domain&&s&&(t.domain=s)}}async function Qe(e){return e.domain?(z(e.domain,e),e.domain):fe()}async function fi(e,t,i){if(e&&e.includes(".")&&!xd.includes(e))return i.check?fo(e,!!i.json,i.fields):t?po(e,t,!!i.json,i.fields):bo(e,!!i.json,i.fields);if(Cd(t,i),i.body&&!i.text&&(i.text=i.body),i.title&&!i.subject&&(i.subject=i.title),i.from&&i.from.includes("@")){let[s,n]=i.from.split("@",2);!i.slug&&s&&(i.slug=s),!i.domain&&n&&(i.domain=n)}switch(e){case void 0:return mo(i);case"list":return mo(i);case"inbox":return zd(i);case"folders":return Yd(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return Xd(e,i);case"setup":return Ud(i);case"status":return qd(i);case"remove":return Fd(i);case"create":return Md(i);case"delete":return Ld(i);case"send":return Vd(i);case"webhook":return Zd(i);case"webhook-test":return Qd(i);case"forward":return ec(i);case"work":return Ed(i);case"triage":return Td(i);case"note":return Pd(i);case"notes":return Dd(i);case"activity":return Nd(i);case"changes":return Ad(i);case"coordination":return Od(i);case"presence":return Id(i);case"release-presence":return Rd(i);case"escalate":return Wd(i);case"remind":return Hd(i);case"contacts":return Jd(i);case"contact-add":return Bd(i);case"contact-remove":return Gd(i);case"tone":return Kd(i);case"check":return fo(i.domain||await fe(),!!i.json,i.fields);case"connect":return po(i.domain||await fe(),t||void 0,!!i.json,i.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:i.json,fields:i.fields})}}function _n(e){let t=e.mailboxIds?.split(",").map(i=>i.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 Od(e){let{mailboxId:t,threadKey:i}=_n(e),s=new URLSearchParams({mailbox_id:t,thread_key:i}),n=await x(`/api/email/collaboration/coordination?${s}`),r=await n.json();if(n.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return w(r,e.fields);S("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 Id(e){let{mailboxId:t,threadKey:i}=_n(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 s=e.mode||"viewing";["viewing","composing"].includes(s)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let n=await x("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,mode:s,acquire_lease:e.acquireLease!==!1})}),r=await n.json();if(n.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return w(r,e.fields);S("Conversation Presence"),c("Mode",s),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 Rd(e){let{mailboxId:t,threadKey:i}=_n(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 s=await x("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,lease_id:e.leaseId})}),n=await s.json();if(s.ok||u(n.error||"Could not release presence",{code:n.code||"api_error",json:e.json,fields:e.fields}),e.json)return w(n,e.fields);S("Conversation Presence"),c("Released",e.clientId),c("Remaining presence",String(n.presence?.length||0))}async function Ad(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 i=new URLSearchParams({mailbox_id:t});e.cursor&&i.set("cursor",e.cursor),e.limit&&i.set("limit",e.limit);let s=await x(`/api/email/changes?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return w(n,e.fields);if(S("Mailbox Changes"),n.requires_full_sync){c("Full sync","Required"),c("Baseline cursor",n.next_cursor),Xe("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}n.changes.length?Z(["Sequence","Type","Resource","Created"],n.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${R.default.dim("No changes since this cursor.")}`),c("Next cursor",n.next_cursor),n.has_more&&Xe("More changes are available; call again with the next cursor.")}async function Ed(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 i=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&i.set("status",e.status),e.assigned&&i.set("assigned",e.assigned),e.limit&&i.set("limit",e.limit);let s=await x(`/api/email/work-queue?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return w(n,e.fields);if(S("Shared Inbox Work"),!n.items.length)return console.log(` ${R.default.dim("No conversations match this queue.")}`);Z(["Thread","Status","Assignee","Subject"],n.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),n.partial&&Xe("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function Td(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,i=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(n=>n.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),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 w(s,e.fields);S("Conversation Updated"),c("Status",s.status),c("Assignee",s.assignee?.label||"Unassigned"),c("Version",s.version)}async function Pd(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})}),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return w(i,e.fields);console.log(`${b.success} Private note added`)}async function Dd(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`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return w(i,e.fields);if(S("Private Notes"),!i.notes.length)return console.log(` ${R.default.dim("No private notes yet.")}`);Z(["Author","Created","Note"],i.notes.map(s=>[s.author.label,s.created_at,s.body]),[28,24,64])}async function Nd(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`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return w(i,e.fields);if(S("Conversation Activity"),!i.activity.length)return console.log(` ${R.default.dim("No activity yet.")}`);Z(["Type","Actor","Created"],i.activity.map(s=>[s.type,s.actor.label,s.created_at]),[36,32,24])}async function Ud(e){let t=await Qe(e);if(e.dryRun)return B("email_setup",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Setting up email on ${v.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),e.json){w(n,e.fields);return}if(n.records?.length){d(),S(`Email DNS Records ${v.domain(t)}`);let r=n.records.map(o=>[R.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?R.default.green(o.status):R.default.yellow(o.status)]);Z(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&Xe(n.hint),I("Check status:",`domani email status --domain ${t}`),d()}async function qd(e){let t=await Qe(e),i=C(!e.json);i.start(`Checking email status for ${v.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Status loaded`),e.json){w(n,e.fields);return}if(S(`Email ${v.domain(t)}`),c("Enabled",n.enabled?R.default.green("yes"):R.default.dim("no")),n.enabled&&(c("Verified",n.verified?R.default.green("yes"):R.default.yellow("pending")),c("Mailboxes",String(n.mailbox_count))),d(),!n.enabled)I("Set up email:",`domani email setup --domain ${t}`),d();else if(!n.verified&&n.records?.length){console.log(` ${R.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${R.default.yellow(r.type)} ${r.name} ${R.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function Fd(e){let t=await Qe(e);if(e.dryRun)return B("email_remove",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Removing email from ${v.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Email disabled`),e.json){w(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${R.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function mo(e){let t=C(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",s=await x(`/api/emails${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.mailboxes||[];if(t.stop(`${b.success} ${r.length} mailbox(es)`),e.json){w(n,e.fields);return}if(r.length===0){d(),console.log(` ${R.default.dim("No mailboxes.")}`),d(),I("Create one:","domani email create hello@example.com"),d();return}d(),S("Mailboxes");let o=r.map(a=>[R.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):R.default.dim("-"),R.default.dim(new Date(a.created_at).toLocaleDateString())]);Z(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function Md(e){let t=await Qe(e);if(e.dryRun)return B("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let i=e.slug;if(!i&&!e.json){let f=await Te({message:`Email handle for @${t}:`,placeholder:"hello"});le(f)&&process.exit(0),i=f}i||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let s=`${i}@${t}`,n=C(!e.json);n.start("Creating mailbox");let r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){n.stop("");let f=o.txt_record,m=o.email_records||[],g=[{type:"TXT",name:f?.name||"@",value:f?.value||"",note:"ownership proof"},...m];d(),console.log(" Add these records at your DNS provider:"),d();for(let j of g){let O=j.priority!==void 0?` ${R.default.dim(`priority: ${j.priority}`)}`:"",A=j.note?` ${R.default.dim(`(${j.note})`)}`:"";console.log(` ${R.default.yellow(j.type)} ${R.default.bold(j.name)}${O}${A}`),console.log(` ${R.default.dim("\u2192")} ${R.default.cyan(j.value)}`),d()}Xe("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let y=g.map(j=>({cells:[R.default.yellow(j.type),j.name,j.note?R.default.dim(`(${j.note})`):""],status:"pending"})),k=qt(["Type","Name",""],y,[6,24,16]);k.start();let $=0;for(;r.status===202&&$<60;)await Ut(15e3),$++,r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(k.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(k.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${s}`,code:"timeout",json:e.json,fields:e.fields})),k.markDone(0);let h=j=>`${j.type}:${j.name}`,_=new Map;g.slice(1).forEach((j,O)=>_.set(h(j),O+1));for(let j=0;j<60;j++){await Ut(15e3);let O=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),A=await O.json();if(O.ok&&A.records){for(let L of A.records)if(L.status==="verified"||L.status==="created"){let H=_.get(h(L));H!==void 0&&k.markDone(H)}}if(O.ok&&A.verified)break}k.stop(),d()}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(`${b.success} ${R.default.cyan(o.address)} created`),e.json){w(o,e.fields);return}let a=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),l=await a.json();d(),a.ok&&l.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${ni}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${ni}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function Ld(e){let t=await Qe(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 B("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=C(!e.json);i.start(`Deleting ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),n=await x(`/api/emails/${s}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Mailbox deleted`),e.json){w(r,e.fields);return}console.log(` ${R.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function Vd(e){let t=await Qe(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 B("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=C(!e.json);i.start(`Sending from ${e.slug}@${t}`);let s={to:is(ts(e.to))},n=is(ts(e.cc)),r=is(ts(e.bcc));n&&(s.cc=n),r&&(s.bcc=r),e.subject&&(s.subject=e.subject),e.text&&(s.text=e.text),e.inReplyTo&&(s.in_reply_to=e.inReplyTo),e.references&&(s.references=e.references),e.sendAt&&(s.send_at=e.sendAt);let o=encodeURIComponent(`${e.slug}@${t}`),a=await x(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(s)}),l=await a.json();if(!a.ok){i.stop("Failed");let m=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${R.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;u(l.error||l.message,{hint:m,status:a.status,json:e.json,fields:e.fields})}let f=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(l.status==="scheduled"?`${b.success} Scheduled for ${R.default.cyan(e.sendAt||"")} to ${R.default.cyan(f)} ${R.default.dim("(trash the message before then to cancel)")}`:`${b.success} Sent to ${R.default.cyan(f)}`),e.json){w(l,e.fields);return}}function xn(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 go(e,t,i,s,n){let r=C(!i.json);r.start(s);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:i.json,fields:i.fields})),r.stop(n(a)),i.json&&w(a,i.fields)}async function Wd(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:i}=xn(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let s={};e.reason&&(s.reason=e.reason),e.clear&&(s.clear=!0),await go(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/escalate`,s,e,e.clear?"Clearing escalation":"Flagging for a human",n=>n.needs_human?`${b.success} Flagged for a human ${R.default.dim("(conversation held, email.escalated fired)")}`:`${b.success} Escalation cleared`)}async function Hd(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:i}=xn(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 s={};e.at&&(s.remind_at=e.at),e.note&&(s.note=e.note),e.clear&&(s.clear=!0),await go(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/remind`,s,e,e.clear?"Clearing reminder":"Setting follow-up reminder",n=>n.remind_at?`${b.success} Reminder set for ${R.default.cyan(String(n.remind_at))} ${R.default.dim("(fires only if still unanswered)")}`:`${b.success} Reminder cleared`)}async function Jd(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=await x(`/api/contacts${t.size?`?${t}`:""}`),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){w(s,e.fields);return}let n=s.contacts||[];if(n.length===0){console.log(R.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let r of n){let o=r.name?` ${R.default.dim(r.name)}`:"",a=r.notes?` ${R.default.dim("-")} ${r.notes}`:"";console.log(`${R.default.cyan(r.address)}${o} ${R.default.dim(`(${r.message_count} msg${r.message_count!==1?"s":""}, last ${r.last_direction||"-"})`)}${a}`)}s.next_cursor&&console.log(R.default.dim(`More: --cursor ${s.next_cursor}`))}function yo(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 Bd(e){let i=yo(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),s={address:i};e.name!==void 0&&(s.name=e.name),e.notes!==void 0&&(s.notes=e.notes);let n=await x("/api/contacts",{method:"POST",body:JSON.stringify(s)}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){w(r,e.fields);return}console.log(`${b.success} Contact ${R.default.cyan(i)} saved.`)}async function Gd(e){let i=yo(e,"Usage: domani email contact-remove ada@example.com"),s=await x(`/api/contacts/${encodeURIComponent(i)}`,{method:"DELETE"}),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json){w(n,e.fields);return}console.log(n.deleted?`${b.success} Contact ${R.default.cyan(i)} deleted.`:R.default.dim(`No contact ${i}.`))}async function Kd(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:i}=xn(e,t),s=encodeURIComponent(i);if(e.set===void 0&&!e.clear){let o=await x(`/api/emails/${s}`),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){w({address:i,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:R.default.dim(`No tone notes on ${i}. Set them with --set.`));return}let n=await x(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){w(r,e.fields);return}console.log(e.clear?`${b.success} Tone notes cleared on ${R.default.cyan(i)}.`:`${b.success} Tone notes set on ${R.default.cyan(i)}.`)}async function zd(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams;e.direction&&i.set("direction",e.direction),e.folder&&i.set("folder",e.folder),e.view&&i.set("view",e.view),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i}`:"",n=C(!e.json);n.start(`Loading messages for ${e.slug}@${t}`);let r=encodeURIComponent(`${e.slug}@${t}`),o=await x(`/api/emails/${r}/messages${s}`),a=await o.json();o.ok||(n.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}));let l=a.messages||[];if(e.json){n.stop(`${b.success} ${l.length} message(s)`),w(a,e.fields);return}if(l.length===0){n.stop(`${R.default.dim("No messages")}`);return}let f=l.length>1?"s":"";n.stop(`${b.success} ${R.default.cyan(`${e.slug}@${t}`)} ${R.default.dim("\xB7 "+l.length+" message"+f)}`);for(let m of l){let g=m.direction==="in"?R.default.green("in "):R.default.dim("out"),y=m.direction==="in"?m.from:m.to,k=m.subject||"(no subject)",$=R.default.dim(new Date(m.created_at).toLocaleString()),h=k;if(m.text){let _=m.text.replace(/\s+/g," ").trim(),j=_.length>60?_.slice(0,60)+"\u2026":_;h=`${k} ${R.default.dim("- "+j)}`}console.log(` ${g} ${y.padEnd(30)} ${h} ${$}`)}a.next_cursor&&console.log(` ${R.default.dim("\u2026 more available, use --limit to paginate")}`)}async function Yd(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=encodeURIComponent(`${e.slug}@${t}`),s=await x(`/api/emails/${i}/folders`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return w(n,e.fields);S(`Folders for ${e.slug}@${t}`);for(let r of n.folders||[])c(r.id,`${r.total} total, ${r.unread} unread`);for(let r of n.views||[])c(r.id,`${r.total} total, ${r.unread} unread`)}async function Xd(e,t){let i=await Qe(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 s=(t.messageIds||"").split(",").map(m=>m.trim()).filter(Boolean);s.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let n={message_ids:s,idempotency_key:t.idempotencyKey||(0,ho.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(n,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(n.action="restore"),(e==="read"||e==="unread")&&Object.assign(n,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(n,{action:"star",starred:e==="star"}),t.dryRun)return B("email_messages_action",{address:`${t.slug}@${i}`,...n},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await x(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(n)}),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 w(a,t.fields);let l=(a.results||[]).filter(m=>m.ok).length,f=(a.results||[]).length-l;console.log(`${b.success} ${l} updated${f?R.default.yellow(`, ${f} 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 Zd(e){let t=await Qe(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 i=`${e.slug}@${t}`,s=encodeURIComponent(i),n;try{n=Ft(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&&n!==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 B("email_webhook",{address:i,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...n!==void 0?{header_names:Mt(n)}:{}},e.json,e.fields);let o=C(!e.json);if(e.url){o.start(`Setting webhook for ${i}`);let a=await x(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...n!==void 0?{headers:n}:{},...r!==void 0?{events:r}:{}})}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${b.success} Webhook set`),e.json){w(l,e.fields);return}S(`Mailbox ${l.address}`),c("Webhook",v.url(l.webhook_url)),c("Events",l.events?.join(", ")||R.default.dim("email.received")),c("Auth headers",l.header_names?.join(", ")||R.default.dim("none")),c("Signing secret",R.default.dim(l.signing_secret)),d()}else{o.start(`Removing webhook for ${i}`);let a=await x(`/api/emails/${s}/webhook`,{method:"DELETE"}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${b.success} Webhook removed`),e.json){w(l,e.fields);return}S(`Mailbox ${l.address}`),c("Webhook",R.default.dim("none")),d()}}async function Qd(e){let t=await Qe(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 i=`${e.slug}@${t}`;if(e.dryRun)return B("email_webhook_test",{address:i},e.json,e.fields);let s=C(!e.json);s.start(`Testing webhook for ${i}`);let n=await x(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await n.json();if((!n.ok||!r.success)&&(s.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:n.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Test delivered`),e.json)return w(r,e.fields);S(`Mailbox ${i}`),c("Delivery",R.default.green("successful")),typeof r.status=="number"&&c("Endpoint",`HTTP ${r.status}`),d()}async function ec(e){let t=await Qe(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 B("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=C(!e.json),s=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:s})}),o=await r.json();if(r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),i.stop(`${b.success} Forward ${s?"set":"removed"}`),e.json){w(o,e.fields);return}S(`Mailbox ${o.address}`),c("Forward to",o.forward_to?R.default.cyan(o.forward_to):R.default.dim("none")),d()}async function fo(e,t,i){let s=C(!t);s.start(`Checking email health for ${v.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Email health checked"),t){w(r,i);return}if(S(`Email Health ${v.domain(r.domain)}`),r.provider?c("Provider",R.default.cyan(kn(r.provider))):c("Provider",R.default.dim("unknown")),r.mx.configured?c("MX",`${b.success} ${R.default.green("propagated")} ${R.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${b.error} ${R.default.red("not configured")}`),r.spf.configured?c("SPF",`${b.success} ${R.default.green(r.spf.value)}`):c("SPF",`${b.error} ${R.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${b.success} ${R.default.green(o)}`)}else c("DMARC",`${b.error} ${R.default.red("missing")}`);r.dkim.configured?c("DKIM",`${b.success} ${R.default.green("found")} ${R.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${b.warning} ${R.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(Xe("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),d()):(I("Set up email:",`domani email ${e} google`),d())}async function po(e,t,i,s){return t?wo(e,t,i,s):bo(e,i,s)}async function bo(e,t,i){let s=C(!t);s.start("Loading email providers");let n=await x(`/api/domains/${encodeURIComponent(e)}/connect`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:i});let a=await tt({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:kn(l.name)}))});return le(a)&&process.exit(0),wo(e,a,t,i)}async function wo(e,t,i,s){if(i){let f=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),m=await f.json();f.ok||u(m.error||m.message,{hint:m.hint,status:f.status,json:i,fields:s}),w(m,s);return}let n=await x(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let f=await n.json();u(f.error||f.message,{hint:f.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=kn(a);if(S(`Email ${v.domain(e)}`),c("Provider",R.default.cyan(l)),o.length){d(),console.log(` ${R.default.bold("DNS Records")}`);let f=[8,24,40],m=qt(["Type","Name","Value"],o.map(j=>({cells:Sd(j),status:"pending"})),f);m.start();let g=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),y=await g.json();g.ok||(m.stop(),d(),u(y.error||y.message,{hint:y.hint,status:g.status,json:i,fields:s}));let k=y.records||[];for(let j=0;j<o.length;j++)k.find(A=>A.record.type===o[j].type&&A.record.name===o[j].name&&A.record.value===o[j].value)?.status==="already_set"||await Ut(60),m.markDone(j);await Ut(80),m.stop();let $=k.filter(j=>j.status==="created"||j.status==="updated").length,h=k.filter(j=>j.status==="already_set").length,_;h===k.length?_=`All ${h} records already set`:h>0?_=`${$} created, ${h} already set`:_=`${$} DNS records set`,d(),console.log(` ${b.success} ${R.default.green(`Email configured - ${_}`)}`)}else{let f=C(!0);f.start("Setting DNS records");let m=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await m.json();m.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:m.status,json:i,fields:s})),f.stop(`${b.success} Email configured via ${R.default.cyan(l)}`)}d(),I("Verify propagation:",`domani email ${e} --check`),d()}var R,ho,xd,jd,jn=Ae(()=>{"use strict";G();ri();R=D(M(),1);Ne();V();ge();Ze();ho=require("node:crypto");es();xd=["setup","status","remove","list","create","delete","send","inbox","folders","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"],jd={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var $o={};Ht($o,{dns:()=>Cn});async function Cn(e,t,i,s,n,r){e||(e=await fe()),z(e,r);let o=r?.json??!1,a=r?.type||i,l=r?.name||s,f=r?.value||n;if(!t||t==="get"){let m=C(!o);m.start(`Loading DNS for ${v.domain(e)}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json();if(g.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${y.records.length} record(s)`),o){w(y,r?.fields);return}if(y.records.length===0){d(),console.log(` ${Ce.default.dim(`No DNS records for ${e}`)}`),d(),I("Auto-configure DNS:",`domani connect ${e}`),d();return}let k=[8,24,40,8];S(`DNS ${v.domain(e)}`,k.reduce((h,_)=>h+_,0)+k.length-1);let $=y.records.map(h=>{let _=h.priority?Ce.default.dim(` pri=${h.priority}`):"";return[Ce.default.yellow(h.type),h.name,Ce.default.cyan(h.value)+_,Ce.default.dim(String(h.ttl))]});Z(["Type","Name","Value","TTL"],$,k),d();return}if(t==="set"){if((!a||!l||!f)&&u("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return B("dns_set",{domain:e,record:{type:a.toUpperCase(),name:l,value:f,ttl:3600}},o,r?.fields);let m=C(!o);m.start(`Setting ${Ce.default.yellow(a.toUpperCase())} record`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json(),$=(g.ok?y.records:[]).filter(j=>!(j.type===a.toUpperCase()&&j.name===l));$.push({type:a.toUpperCase(),name:l,value:f,ttl:3600});let h=await x(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:$})}),_=await h.json();h.ok||(m.stop("Failed"),u(_.error||_.message,{hint:_.hint,status:h.status,json:o,fields:r?.fields})),m.stop(`${b.success} ${Ce.default.yellow(a.toUpperCase())} ${l} ${b.arrow} ${Ce.default.cyan(f)}`),o?w(_,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="delete"){if((!a||!l)&&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 B("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let m=C(!o);m.start(`Deleting ${Ce.default.yellow(a.toUpperCase())} ${l}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),y=await g.json();g.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${b.success} Deleted ${Ce.default.yellow(a.toUpperCase())} ${l}`),o?w(y,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="snapshot"){if(r?.dryRun)return B("dns_snapshot",{domain:e},o,r?.fields);let m=C(!o);m.start(`Capturing DNS snapshot for ${v.domain(e)}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),y=await g.json();g.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields}));let k=y.records?.length??0;if(m.stop(`${b.success} Captured ${k} record(s)`),o){w(y,r?.fields);return}let $=`${e}.dns.json`,h=(0,Sn.resolve)(process.cwd(),$);(0,ss.writeFileSync)(h,JSON.stringify(y,null,2)+`
|
|
179
|
-
`),S("DNS Snapshot"),c("Domain",v.domain(y.domain)),c("Records",String(k)),c("Subdomains",String(y.subdomains?.length??0)),c("Sources",(y.sources||[]).join(", ")||"none"),c("Captured",y.capturedAt||y.captured_at||"now"),c("Saved to",Ce.default.cyan($)),d(),I("Restore from this snapshot:",`domani dns ${e} restore --file ${$}`),d();return}if(t==="restore"){if(r?.dryRun)return B("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let m=C(!o),g;if(r?.file){let $=(0,Sn.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 h=(0,ss.readFileSync)($,"utf-8"),_=JSON.parse(h);g=JSON.stringify({snapshot:_}),m.start(`Restoring DNS for ${v.domain(e)} from ${Ce.default.cyan(r.file)}`)}catch(h){u(`Failed to read snapshot file: ${h instanceof Error?h.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else m.start(`Restoring DNS for ${v.domain(e)} from server backup`);let y=await x(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),k=await y.json();if(y.ok||(m.stop("Failed"),u(k.error||k.message,{hint:k.hint,status:y.status,json:o,fields:r?.fields})),m.stop(`${b.success} Restored DNS`),o){w(k,r?.fields);return}if(S("DNS Restored"),c("Domain",v.domain(k.domain)),c("Applied",Ce.default.green(String(k.applied??0))),c("Skipped",Ce.default.dim(String(k.skipped??0))),k.errors?.length>0){c("Errors",Ce.default.red(String(k.errors.length)));for(let $ of k.errors)console.log(` ${Ce.default.red("\u2022")} ${$}`)}d(),I("Verify DNS records:",`domani dns ${e}`),d();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ce,ss,Sn,On=Ae(()=>{"use strict";G();Ce=D(M(),1);V();ge();Ze();ss=require("node:fs"),Sn=require("node:path")});var ko={};Ht(ko,{status:()=>In});function tc(e){return[it.default.yellow(e.type),e.name,it.default.cyan(e.value)+(e.priority?it.default.dim(` pri=${e.priority}`):"")]}function ic(e){if(S(`Status ${v.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,s=i!=null&&i<30?it.default.red:i!=null&&i<90?it.default.yellow:it.default.green;c("Expires",`${t} ${it.default.dim("(")}${s(`${i} days`)}${it.default.dim(")")}`)}}async function In(e,t){if(e||(e=await fe()),z(e,t),t.json){let g=await x(`/api/domains/${encodeURIComponent(e)}/status`),y=await g.json();g.ok||u(y.error||y.message,{hint:y.hint,status:g.status,json:t.json,fields:t.fields}),w(y,t.fields);return}let i=C(!0);i.start(`Checking ${v.domain(e)}`);let s;try{s=await x(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{i.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!s.ok){i.stop("Failed");try{let g=await s.json();u(g.error||g.message,{hint:g.hint,status:s.status,json:t.json,fields:t.fields})}catch{u(`Server error (${s.status})`,{status:s.status,json:t.json,fields:t.fields})}}let n=s.body;n||(i.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,l=[],f=!1,m="";try{for await(let g of n){o+=r.decode(g,{stream:!0});let y=o.split(`
|
|
180
|
-
`)
|
|
181
|
-
`);a=g.pop()??"";for(let y of g)if(y.startsWith("event: "))l=y.slice(7).trim();else if(y.startsWith("data: ")){let k=JSON.parse(y.slice(6));l==="checking"?s.message(`Checking ${v.domain(k.domain)}`):l==="payment"?s.message(`Charging ${v.price(k.total)}`):l==="registering"?s.message(`Registering ${v.domain(k.domain)}`):l==="registered"?r=k:l==="error"&&(s.stop("Purchase failed"),u(k.error,{hint:k.hint,fixUrl:k.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let f=r.expires?Ue.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${b.success} ${v.domain(r.domain)} is yours!${f}`),t.json){w(r,t.fields);return}Se?await An(r.domain):(I("Connect to a service:",`domani connect ${r.domain}`),I("Set up email:",`domani email setup ${r.domain}`),I("Configure DNS:",`domani dns ${r.domain}`),d())}async function nc(e,t){lo(e,t);let i=!!t.json,s=C(!i);s.start(`Checking ${e.length} domains`);let n=await Promise.all(e.map(async h=>{try{let _=await x(`/api/domains/search?q=${encodeURIComponent(h)}`),j=await _.json();return{domain:h,available:_.ok&&j.available,price:j.price}}catch{return{domain:h,available:!1,price:void 0}}})),r=n.filter(h=>h.available),o=n.filter(h=>!h.available);r.length===0&&(s.stop(`${b.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,_)=>h+(_.price||0),0);if(s.stop(`${b.success} ${r.length}/${e.length} available ${b.dot} ${v.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${b.error} ${v.domain(h.domain)} ${Ue.default.dim("not available")}`);if(t.dryRun)return B("buy_bulk",{domains:r.map(h=>({domain:h.domain,price:h.price})),unavailable:o.map(h=>h.domain),total_price:parseFloat(a.toFixed(2))},t.json,t.fields);if(!Nt(t)){let h=await Ye({message:`Purchase ${Ue.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${v.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${Ue.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[v.domain(h.domain),h.price?`${v.price(h.price.toFixed(2))}/yr`:""],status:"pending"})),f=qt(["Domain","Price"],l,[30,12],!i);f.start();let g=await(await x("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(h=>h.domain)})})).json(),y=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let _=r[h].domain.toLowerCase().trim();y.has(_)?f.markDone(h,b.success):f.markDone(h,b.error)}if(f.stop(),i){w(g,t.fields);return}d();let k=g.summary?.succeeded??0,$=g.summary?.failed??0;if(k>0&&console.log(` ${b.success} ${Ue.default.green(`${k} domain${k>1?"s":""} registered`)}`),$>0){console.log(` ${b.error} ${Ue.default.red(`${$} failed`)}`);for(let h of g.errors||[])console.log(` ${Ue.default.dim("\u2500")} ${v.domain(h.domain)}: ${Ue.default.dim(h.error)}${h.hint?` ${Ue.default.dim(`(${h.hint})`)}`:""}`)}if(d(),k>0&&Se){let h=(g.results||[]).filter(_=>_.success).map(_=>_.domain);if(h.length===1)await An(h[0]);else{let _=await tt({message:"Set up one of your new domains?",options:[...h.map(j=>({value:j,label:Ue.default.cyan(j)})),{value:"done",label:"Done"}]});!le(_)&&_!=="done"?(d(),await An(_)):d()}}else k>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),d())}async function En(e,t){let i=e.filter(Boolean);if(i.length===0){Se||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Te({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(le(s)||!s)&&process.exit(0),i=s.split(/\s+/).filter(Boolean)}return i.length===1?sc(i[0],t):nc(i,t)}var Ue,ei=Ae(()=>{"use strict";G();Ne();Ue=D(M(),1);V();ge()});var Zn=D(Xn(),1),{program:fu,createCommand:pu,createArgument:hu,createOption:gu,CommanderError:yu,InvalidArgumentError:bu,InvalidOptionArgumentError:wu,Command:Qn,Argument:vu,Option:$u,Help:ku}=Zn.default;var ut=D(M(),1);gt();yn();V();ri();gt();var at=D(M(),1);V();var cd=new Set(["cli","mcp","plugin","skill","api"]);function ud(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),i=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),s=!!(t?.length||i?.length||e.label||e.expiresIn),n=e.surface||"cli";if(!cd.has(n))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:s,body:{...t?.length?{scopes:t}:{},...i?.length?{mailboxes:i}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:n,intent:"programmatic_access"}}}async function to(e){let t=Le(),i=C(!e.json),s;try{s=ud(e)}catch(k){u(k instanceof Error?k.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=ht(),a=Ve();if(a&&!r){i.start("Checking session");try{let k=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(k.ok){let $=await k.json();i.stop(`Already logged in as ${at.default.bold($.email)}`),e.json&&w({status:"already_logged_in",email:$.email});return}}catch{}i.stop("Session expired, re-authenticating"),d()}i.start("Requesting auth code");let l=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!l.ok){i.stop("Failed to initiate login");try{let k=await l.json();u(k.error||k.message||`Server error (${l.status})`,{hint:k.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:f,auth_url:m,expires_in:g}=await l.json();if(i.stop("Auth code received"),e.json){w({status:"awaiting_approval",code:f,auth_url:m,expires_in:g});return}d(),console.log(` ${at.default.dim("Verification code:")} ${at.default.bold(at.default.cyan(f))}`),e.open!==!1?(console.log(` ${at.default.dim("Opening browser")} ${b.arrow} ${v.url(m)}`),Je(m)):console.log(` ${at.default.dim("Open this URL to approve:")} ${v.url(m)}`),d(),i.start("Waiting for approval");let y=120;for(let k=0;k<y;k++){await new Promise(_=>setTimeout(_,5e3));let $=await fetch(`${t}/api/auth/cli/poll?code=${f}`);!$.ok&&$.status!==202&&(i.stop("Login failed"),u(`Server error (${$.status})`,{code:"login_failed"}));let h=await $.json();if(h.status==="complete"){zt({...ht(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${at.default.bold(h.email)}`),d(),console.log(` ${at.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(` ${at.default.dim("A custom domain can wait until this loop works.")}`),d();return}h.error&&(i.stop("Login failed"),u(h.error||h.message,{hint:h.hint,code:"login_failed"}))}i.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}gt();var bn=D(M(),1);V();async function io(e){let t=ht();if(!t.token){e.json?w({status:"not_logged_in"}):console.log(` ${bn.default.dim("Not logged in.")}`);return}let{api_url:i}=t;mr(),i&&zt({api_url:i}),e.json?w({status:"logged_out",email:t.email||null}):console.log(` ${b.success} Logged out${t.email?` ${bn.default.dim(`(${t.email})`)}`:""}`)}G();var mi=D(M(),1);V();async function no(e){let[t,i]=await Promise.all([x("/api/me"),x("/api/me/activation")]),s=await t.json();t.ok||u(s.error||s.message,{hint:s.hint,status:t.status,json:e.json,fields:e.fields});let n=i.ok?await i.json():null;if(e.json){w({...s,activation:n},e.fields);return}if(S("Account"),c("Email",mi.default.bold(s.email)),c("Payment",s.has_payment_method?`${b.success} ${mi.default.green("active")}`:`${b.error} ${mi.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||mi.default.dim("-")),c("Created",new Date(s.created_at).toLocaleDateString()),n){c("Activation",n.status);let r=n.recommended_actions?.[0];r&&c("Next action",r.label)}d()}G();Ne();var N=D(M(),1);V();ge();var Be=10,ti=200,ns=["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"],rs=null;async function _o(){if(rs)return rs;try{let e=await we("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let i=(await e.json()).tlds.map(s=>s.tld);if(i.length>0){let s=new Set(ns),n=new Set(i),r=[...ns.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return rs=r,r}}}catch{}return rs=ns,ns}async function rc(e,t,i,s,n){let r=[],o=[],a=Be,l=0,f=!0,m=0,g=0,y=!1,k=!1,$=null,h="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],j=0,O=setInterval(()=>{k||!f||(j=(j+1)%_.length,T())},80);function A(){m>0&&(process.stdout.write(`\x1B[${m}A\x1B[0J`),m=0)}function L(){if(f)return[];let F=Be+g*Be;return r.length>a||s&&F<n.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function te(){let F=L();return Math.max(0,H().length+F.length-1)}let P=6;function T(){A();let F=[],X=H(),ee=!f&&X.length===0&&o.length>0,K=ee?o.slice(0,P):X,Re=K.reduce((de,ae)=>Math.max(de,ae.domain.length),0),Ke=L();for(let de=0;de<K.length;de++){let ae=K[de];if(ee)F.push(`${N.default.dim("\u2502")} ${N.default.dim("\u2715")} ${N.default.dim(ae.domain.padEnd(Re))} ${N.default.dim("taken")}`);else{let _e=de===l,mt=_e?N.default.green("\u25CF"):N.default.dim("\u25CB"),ie=ae.domain.padEnd(Re),nt=_e?N.default.bold(N.default.cyan(ie)):ie,kt=ae.for_sale?N.default.cyan(`$${ae.for_sale.price} (for sale)`):N.default.dim(`$${ae.price}/yr`);F.push(`${N.default.dim("\u2502")} ${mt} ${nt} ${kt}`)}}if(ee&&o.length>P&&F.push(`${N.default.dim("\u2502")} ${N.default.dim(`\u2026 and ${o.length-P} more taken`)}`),f){let de=h?N.default.dim(`checking ${h}\u2026`):N.default.dim("searching\u2026");F.push(`${N.default.dim("\u2502")} ${N.default.cyan(_[j])} ${de}`)}else{let de=Be+g*Be;s&&de>=n.length&&F.push(`${N.default.dim("\u2502")} ${N.default.dim(`All ${Math.min(de,n.length)} TLDs searched`)}`);for(let _e=0;_e<Ke.length;_e++){let nt=H().length+_e===l?N.default.green("\u25CF"):N.default.dim("\u25CB"),kt=Ke[_e]==="more"?N.default.dim("More \u2192"):Ke[_e]==="new"?N.default.dim("New search \u2192"):N.default.dim("Skip");F.push(`${N.default.dim("\u2502")} ${nt} ${kt}`)}F.push(N.default.dim("\u2514"))}process.stdout.write(F.join(`
|
|
177
|
+
`}}}}).prompt()});function dd(e){return!!(e.json||!Se)}function S(e,t=50){console.log(),console.log(` ${J.default.bold(e)}`),console.log(` ${J.default.dim("\u2500".repeat(t))}`)}function c(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${J.default.dim(e.padEnd(16))} ${t}`)}function d(){console.log()}function Pe(e){console.log(` ${J.default.dim(e)}`)}function R(e,t){console.log(` ${J.default.dim(e)} ${J.default.cyan(t)}`)}function Qr(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${J.default.underline(J.default.cyan(i))}\x1B]8;;\x1B\\`:J.default.dim(i)).join("")}function bn(e,t){console.error(` ${w.error} ${J.default.red(e)}`),t&&console.error(` ${Qr(t)}`)}function C(e=!0){return e?fi():cd}function eo(e){return e.replace(ud,"")}function es(e,t){let i=eo(e).length,s=Math.max(0,t-i);return e+" ".repeat(s)}function B(e,t,i){let s=i||e.map((o,a)=>{let l=t.reduce((f,m)=>Math.max(f,eo(m[a]||"").length),0);return Math.max(o.length,l)+2}),n=e.map((o,a)=>J.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>J.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of t){let a=o.map((l,f)=>es(l,s[f])).join(" ");console.log(` ${a}`)}}function md(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function yn(e){if(Array.isArray(e))return e.map(yn);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[md(i)]=yn(s);return t}return e}function y(e,t){let i=yn(e);if(!t){console.log(JSON.stringify(i,null,2));return}let s=t.split(",").map(n=>n.trim()).filter(Boolean);if(Array.isArray(i)){let n=i.map(r=>Yr(r,s));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?Yr(i,s):i,null,2))}function Yr(e,t){let i={};for(let s of t)s in e&&(i[s]=e[s]);if(Object.keys(i).length===0){for(let[s,n]of Object.entries(e))if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"){let r=n.map(o=>{let a={};for(let l of t)l in o&&(a[l]=o[l]);return a});Object.keys(r[0]).length>0&&(i[s]=r)}}return i}function Ut(e){return!!(e.yes||dd(e))}function G(e,t,i,s){if(i){y({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${J.default.yellow("\u25B8 DRY RUN")} ${J.default.dim("- no changes made")}`),console.log(` ${J.default.dim("Action:")} ${J.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${J.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${J.default.dim(n+":")} ${JSON.stringify(r)}`:` ${J.default.dim(n+":")} ${String(r)}`));console.log()}function pd(e,t,i){return t===401||t===403?"auth_required":t===402||i?"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 i=e||`Request failed${t?.status?` (${t.status})`:""}`,s=t?.code||pd(i,t?.status,t?.fixUrl),n=t?.fixCommand||fd[s];if(t?.json){let r={error:i,code:s};t.hint&&(r.hint=t.hint),n&&(r.fix_command=n),t.fixUrl&&(r.fix_url=t.fixUrl),y(r,t.fields)}else bn(i,t?.hint),n?console.error(` ${J.default.dim("Or run:")} ${J.default.cyan(n)}`):t?.fixUrl&&console.error(` ${Qr(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function Be(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Zr.execFile)(t,[e])}function qt(e){return new Promise(t=>setTimeout(t,e))}function Ft(e,t,i,s=!0){let n=process.stdout.isTTY??!1;if(!s)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function l(){let b=" "+e.map((h,x)=>J.default.dim(h.padEnd(i[x]))).join(" "),k=" "+i.map(h=>J.default.dim("\u2500".repeat(h))).join(" "),$=[b,k];for(let h of t){let x=h.status==="done"?h.icon??w.success:J.default.cyan(Xr[r%Xr.length]),j=h.cells.map((O,A)=>es(O,i[A])).join(" ");$.push(` ${x} ${j}`)}return $}let f=!1,m=()=>process.stdout.write("\x1B[?25h");function g(){let b=l();if(f&&n){process.stdout.write(`\x1B[${a}A`);for(let k of b)process.stdout.write(`\x1B[2K${k}
|
|
178
|
+
`)}else{for(let k of b)console.log(k);f=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",m)),g(),n&&(o=setInterval(()=>{r++,g()},80))},markDone(b,k){t[b].status="done",k!==void 0&&(t[b].icon=k),n&&g()},stop(){o&&clearInterval(o);for(let b of t)b.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",m))}}}var J,Zr,Se,w,v,cd,ud,fd,Xr,L=Ae(()=>{"use strict";J=D(M(),1),Zr=require("child_process");Ue();Se=process.stdout.isTTY??!1;w={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},v={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};cd={start:()=>{},stop:()=>{},message:()=>{}};ud=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;fd={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Xr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function to(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function io(e){return to(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(to)}async function so(){if(vn)return;let e=process.argv.includes("--json")||!qs,t=Ve(),i=We();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(io(r)){vn=!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)),d(),console.log(` ${ve.default.dim("This feature requires a")} ${ve.default.bold("paid plan")} ${ve.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${ve.default.dim("Opening pricing page")} ${w.arrow} ${ve.default.cyan("domani.run/pricing")}`),Be(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),d();let s=C(!0);s.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(io(o)){vn=!0,s.stop(`${w.success} Paid plan active! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No upgrade detected. Visit ${ve.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function no(){if(wn||We()){wn=!0;return}(process.argv.includes("--json")||!qs)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),d(),console.log(` ${ve.default.dim("You're not logged in.")} Starting authentication...`),d();let t=Ve(),i=C(!0);i.start("Requesting auth code");let s;try{s=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{i.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Could not reach ${t}. Check your connection.`),process.exit(1)}if(!s.ok){i.stop("Failed");let o=`Server error (${s.status})`;try{let a=await s.json();o=a.error||a.message||o}catch{}console.error(` ${ve.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await s.json())}catch{i.stop("Failed"),console.error(` ${ve.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${w.success} Auth code ready`),d(),console.log(` ${ve.default.dim("Verification code:")} ${ve.default.bold(ve.default.cyan(n))}`),console.log(` ${ve.default.dim("Opening browser")} ${w.arrow} ${v.url(r)}`),Be(r),d(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(f=>setTimeout(f,5e3));let a=await fetch(`${t}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){Xt({...ht(),token:l.token,email:l.email,api_url:t}),wn=!0,i.stop(`${w.success} Logged in as ${ve.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${ve.default.red("\u2717")} No approval received. Run ${ve.default.cyan("domani login")} to try again.`),process.exit(1)}var ve,wn,vn,$n=Ae(()=>{"use strict";ve=D(M(),1);gt();L();wn=!1,vn=!1});function ao(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let i=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${i?` (got: "${i}")`:""}. 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 _(e,t={},i=!1){let s=We(),n=`${Ve()}${e}`,r=await fetch(n,{...t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json","User-Agent":`domani-cli/${xe}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await so(),_(e,t,!0)}catch{}}return ao(r)}async function we(e,t={}){let i=`${Ve()}${e}`,s=We(),n=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${xe}`,...s?{Authorization:`Bearer ${s}`}:{},...t.headers}});return ao(n)}var K=Ae(()=>{"use strict";gt();$n()});function St(){return{ok:!0}}function bt(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function uo(e){return yd.test(e)?bt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):St()}function _d(e){return bd.test(e)?bt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):St()}function xd(e){return wd.test(e)?bt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):St()}function jd(e){return vd.test(e)?bt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):St()}function mo(e){if(!e)return bt("Domain name is required","validation_error");if(e.length>co)return bt(`Domain name too long (${e.length} chars, max ${co})`,"validation_error");for(let t of[uo,_d,xd,jd]){let i=t(e);if(!i.ok)return i}return $d.test(e)?St():bt(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Sd(e){if(!e)return bt("TLD is required","validation_error");let t=uo(e);return t.ok?kd.test(e)?St():bt(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function Cd(e){for(let t of e){let i=mo(t);if(!i.ok)return i}return St()}function Od(e){for(let t of e){let i=Sd(t);if(!i.ok)return i}return St()}function Y(e,t){let i=mo(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function fo(e,t){let i=Cd(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function ts(e,t){let i=Od(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var yd,bd,wd,vd,$d,kd,co,ye=Ae(()=>{"use strict";L();yd=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,bd=/\.\.[/\\]/,wd=/[?#]/,vd=/%[0-9a-fA-F]{2}/,$d=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,kd=/^\.?[a-zA-Z]{2,63}$/,co=253});async function pe(){Se||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 _("/api/domains"),i=await t.json();t.ok||(e.stop("Failed"),bn(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${_n.default.dim("No domains yet.")} Use: ${_n.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await tt({message:"Which domain?",options:s.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return de(n)&&process.exit(0),n}var _n,Ze=Ae(()=>{"use strict";K();Ue();_n=D(M(),1);L()});var ho={};Bt(ho,{connect:()=>xn});async function xn(e,t,i){e||(e=await pe()),Y(e,i);let s;if(t&&!i.provider?t.includes(".")?s=t:i.provider=t:s=t,!s&&!i.provider&&!i.list&&i.dryRun)return G("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!s&&!i.provider&&!i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){y(o,i.fields);return}let a=[];for(let h of["hosting","email"]){let x=o.providers?.[h]||[];for(let j of x)a.push({value:`${h}:${j.name}`,label:j.name,hint:h})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await tt({message:"Choose a provider",options:a});de(l)&&process.exit(0);let[f,m]=l.split(":"),b=(o.providers?.[f]||[]).find(h=>h.name===m),k;if(b&&b.methods.length>1){let h=await tt({message:"Choose a method",options:b.methods.map(x=>({value:x.name,label:x.name,hint:x.default?"default":void 0}))});de(h)&&process.exit(0),k=h}let $;if(f==="hosting"&&b?.requires_target){b.notes?.setup&&Pe(b.notes.setup);let h=await Te({message:"Target hostname or IP"});de(h)&&process.exit(0),$=h.trim()}return po(e,{target:$,provider:m,method:k,dryRun:i.dryRun,json:!1})}if(i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){y(o,i.fields);return}S(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){d(),console.log(` ${me.default.bold(a.toUpperCase())}`);for(let f of l){let m=f.methods.map(g=>g.default?me.default.green(`${g.name} (default)`):me.default.dim(g.name)).join(me.default.dim(", "));console.log(` ${me.default.cyan(f.name.padEnd(20))} ${m}`)}}}d();return}return po(e,i)}async function po(e,t){let i={};if(t.target&&(i.target=t.target),t.provider&&(i.provider=t.provider),t.method&&(i.method=t.method),t.dryRun)return G("connect",{domain:e,...i},t.json,t.fields);let s=C(!t.json);s.start(`Connecting ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(i)}),r=await n.json();n.ok||(s.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(s.stop(o?`${w.success} DNS instructions for ${me.default.cyan(r.provider)}`:`${w.success} Connected to ${me.default.cyan(r.provider)}`),t.json){y(r,t.fields);return}if(S(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),c("Provider",me.default.cyan(r.provider)),c("Method",r.method),r.records?.length){let a=[8,22,40];d(),console.log(` ${me.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((m,g)=>me.default.dim(m.padEnd(a[g]))).join(" "),f=a.map(m=>me.default.dim("\u2500".repeat(m))).join(" ");console.log(` ${l}`),console.log(` ${f}`);for(let m of r.records){let g=m.record,b=m.status!=="already_set";process.stdout.isTTY&&b&&await qt(50);let $=[me.default.yellow(g.type),g.name,me.default.cyan(g.value)+(g.priority?me.default.dim(` pri=${g.priority}`):"")].map((j,O)=>es(j,a[O])).join(" "),h=m.status==="already_set"?me.default.dim("\u2713"):m.status==="updated"?me.default.yellow("\u21BA"):m.status==="pending"?me.default.yellow("\u2192"):w.success,x=m.status==="already_set"?me.default.dim(" already set"):m.status==="updated"?me.default.dim(" updated"):m.status==="pending"?me.default.dim(" add this"):"";console.log(` ${h} ${$}${x}`)}}d(),r.next_steps?.length?(console.log(` ${me.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${me.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${me.default.dim(r.hint)}`),r.docs&&console.log(` ${me.default.dim("Docs:")} ${v.url(r.docs)}`),d()}var me,jn=Ae(()=>{"use strict";K();me=D(M(),1);Ue();L();ye();Ze()});function Mt(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 i={},s=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[n,r]of s){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);i[n]=o}return Object.keys(i).length>0?i:void 0}function Lt(e){return e?Object.keys(e):[]}var is=Ae(()=>{"use strict"});var xo={};Bt(xo,{email:()=>hi,parseRecipients:()=>ns,recipientField:()=>rs});function Ad(e){return[I.default.yellow(e.type),e.name,I.default.cyan(e.value)+(e.priority?I.default.dim(` pri=${e.priority}`):"")]}function Cn(e){return Rd[e]||e}function ns(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function rs(e){if(e.length!==0)return e.length===1?e[0]:e}function Ed(e,t){if(e&&e.includes("@")){let[i,s]=e.split("@",2);!t.slug&&i&&(t.slug=i),!t.domain&&s&&(t.domain=s)}}async function Qe(e){return e.domain?(Y(e.domain,e),e.domain):pe()}async function hi(e,t,i){if(e&&e.includes(".")&&!Id.includes(e))return i.check?yo(e,!!i.json,i.fields):t?bo(e,t,!!i.json,i.fields):ko(e,!!i.json,i.fields);if(Ed(t,i),i.body&&!i.text&&(i.text=i.body),i.title&&!i.subject&&(i.subject=i.title),i.from&&i.from.includes("@")){let[s,n]=i.from.split("@",2);!i.slug&&s&&(i.slug=s),!i.domain&&n&&(i.domain=n)}switch(e){case void 0:return go(i);case"list":return go(i);case"inbox":return oc(i);case"folders":return ac(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return lc(e,i);case"setup":return Kd(i);case"status":return zd(i);case"remove":return Yd(i);case"create":return Xd(i);case"delete":return Zd(i);case"send":return Qd(i);case"webhook":return dc(i);case"webhook-test":return cc(i);case"forward":return uc(i);case"work":return Wd(i);case"triage":return Hd(i);case"note":return Jd(i);case"notes":return Bd(i);case"activity":return Gd(i);case"changes":return Nd(i);case"search":return Ud(t,i);case"threads":return qd(i);case"thread":return Fd(t,i);case"label":return Md(i);case"facts":return Ld(t,i);case"extract":return Vd(t,i);case"coordination":return Td(i);case"presence":return Pd(i);case"release-presence":return Dd(i);case"escalate":return ec(i);case"remind":return tc(i);case"contacts":return ic(i);case"contact-add":return sc(i);case"contact-remove":return nc(i);case"tone":return rc(i);case"check":return yo(i.domain||await pe(),!!i.json,i.fields);case"connect":return bo(i.domain||await pe(),t||void 0,!!i.json,i.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:i.json,fields:i.fields})}}function On(e){let t=e.mailboxIds?.split(",").map(i=>i.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 Td(e){let{mailboxId:t,threadKey:i}=On(e),s=new URLSearchParams({mailbox_id:t,thread_key:i}),n=await _(`/api/email/collaboration/coordination?${s}`),r=await n.json();if(n.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return y(r,e.fields);S("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 Pd(e){let{mailboxId:t,threadKey:i}=On(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 s=e.mode||"viewing";["viewing","composing"].includes(s)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let n=await _("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,mode:s,acquire_lease:e.acquireLease!==!1})}),r=await n.json();if(n.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return y(r,e.fields);S("Conversation Presence"),c("Mode",s),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 Dd(e){let{mailboxId:t,threadKey:i}=On(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 s=await _("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,lease_id:e.leaseId})}),n=await s.json();if(s.ok||u(n.error||"Could not release presence",{code:n.code||"api_error",json:e.json,fields:e.fields}),e.json)return y(n,e.fields);S("Conversation Presence"),c("Released",e.clientId),c("Remaining presence",String(n.presence?.length||0))}async function Nd(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 i=new URLSearchParams({mailbox_id:t});e.cursor&&i.set("cursor",e.cursor),e.limit&&i.set("limit",e.limit);let s=await _(`/api/email/changes?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return y(n,e.fields);if(S("Mailbox Changes"),n.requires_full_sync){c("Full sync","Required"),c("Baseline cursor",n.next_cursor),Pe("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}n.changes.length?B(["Sequence","Type","Resource","Created"],n.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${I.default.dim("No changes since this cursor.")}`),c("Next cursor",n.next_cursor),n.has_more&&Pe("More changes are available; call again with the next cursor.")}function ss(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}async function Ud(e,t){let i=(t.query||(e&&!e.includes("@")?e:void 0)||"").trim();i||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 s=new URLSearchParams({q:i});t.mode&&s.set("mode",t.mode),t.limit&&s.set("limit",t.limit),t.slug&&t.domain&&s.set("mailbox",`${t.slug}@${t.domain}`),t.folder&&s.set("folder",t.folder),t.since&&s.set("since",t.since),t.until&&s.set("until",t.until),t.label&&s.set("label",t.label);let n=await _(`/api/emails/search?${s}`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);if(S(`Search: ${i}`),!r.results.length){console.log(` ${I.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]),Pe(`${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 qd(e){let{address:t}=Ct(e,"Usage: domani email threads --from hi@myapp.dev [--folder inbox] [--since <iso>] [--limit 25] [--cursor <cursor>] [--label billing]"),i=new URLSearchParams;e.folder&&i.set("folder",e.folder),e.since&&i.set("since",e.since),e.limit&&i.set("limit",e.limit),e.cursor&&i.set("cursor",e.cursor),e.label&&i.set("label",e.label);let s=await _(`/api/emails/${encodeURIComponent(t)}/threads${i.size?`?${i}`:""}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return y(n,e.fields);if(S(`Threads in ${t}`),!n.threads.length){console.log(` ${I.default.dim("No conversations here.")}`);return}B(["Messages","Unread","Subject","With","Last","Thread"],n.threads.map(r=>[String(r.message_count),String(r.unread_count),(r.subject||"").slice(0,40),r.participants.filter(o=>o!==t).join(", ").slice(0,30),r.last_message_at.slice(0,16),r.id]),[9,7,42,32,17,28]),n.next_cursor&&c("Next cursor",n.next_cursor)}async function Fd(e,t){let i=t.threadId||(e&&!e.includes("@")?e:void 0),{address:s}=Ct(t,"Usage: domani email thread <thread_id> --from hi@myapp.dev");i||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 n=await _(`/api/emails/${encodeURIComponent(s)}/threads/${encodeURIComponent(i)}`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);S(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
|
+
${I.default.bold(o.direction==="out"?"\u2192":"\u2190")} ${o.from} ${I.default.dim(o.created_at.slice(0,16))}${o.labels?.length?` ${I.default.dim(`[${o.labels.join(", ")}]`)}`:""} ${I.default.dim(o.id)}`),o.text&&console.log(` ${o.text.replace(/\s+/g," ").trim().slice(0,300)}`)}async function Md(e){let{address:t}=Ct(e,"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b"),i=ss(e.messageIds),s=ss(e.add),n=ss(e.remove),r=e.set===void 0?void 0:ss(e.set);(!i.length||!s.length&&!n.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:i,action:"label",idempotency_key:e.idempotencyKey||(0,Sn.randomUUID)()};s.length&&(o.add=s),n.length&&(o.remove=n),r!==void 0&&(o.set=r);let a=await _(`/api/emails/${encodeURIComponent(t)}/messages/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),l=await a.json();if(a.ok||u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields}),e.json)return y(l,e.fields);let f=l.results||[];S("Labels"),B(["Message","Result"],f.map(m=>[m.message_id,m.ok?m.changed?"updated":"unchanged":m.error?.message||"failed"]),[30,40])}async function Ld(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),{address:s}=Ct(t,"Usage: domani email facts <message_id> --from hi@myapp.dev");i||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 n=await _(`/api/emails/${encodeURIComponent(s)}/messages/${encodeURIComponent(i)}/facts`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);if(S("Facts"),!r.analysed){c("Analysed","no"),c("Reason",r.reason),Pe(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?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(` ${I.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 Vd(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),s=`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:n}=Ct(t,s);(!i||!t.schema)&&u("Message ID and --schema required",{hint:s,code:"validation_error",json:t.json,fields:t.fields});let r;try{let l=t.schema.startsWith("@")?(0,wo.readFileSync)(t.schema.slice(1),"utf8"):t.schema;r=JSON.parse(l)}catch(l){u("Schema must be JSON (inline or @file)",{hint:l instanceof Error?l.message:String(l),code:"validation_error",json:t.json,fields:t.fields})}let o=await _(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(i)}/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 y(a,t.fields);S("Extraction"),c("Confidence",String(a.confidence)),c("Cached",a.cached?"yes":"no"),c("Model",a.model);for(let[l,f]of Object.entries(a.data))c(l,f===null?I.default.dim("null"):typeof f=="object"?JSON.stringify(f):String(f));for(let l of a.evidence_quotes)console.log(` ${I.default.dim(`"${l.slice(0,120)}"`)}`)}async function Wd(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 i=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&i.set("status",e.status),e.assigned&&i.set("assigned",e.assigned),e.limit&&i.set("limit",e.limit);let s=await _(`/api/email/work-queue?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return y(n,e.fields);if(S("Shared Inbox Work"),!n.items.length)return console.log(` ${I.default.dim("No conversations match this queue.")}`);B(["Thread","Status","Assignee","Subject"],n.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),n.partial&&Pe("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function Hd(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,i=await _("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(n=>n.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),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 y(s,e.fields);S("Conversation Updated"),c("Status",s.status),c("Assignee",s.assignee?.label||"Unassigned"),c("Version",s.version)}async function Jd(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 _(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`,{method:"POST",body:JSON.stringify({body:e.note})}),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return y(i,e.fields);console.log(`${w.success} Private note added`)}async function Bd(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 _(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return y(i,e.fields);if(S("Private Notes"),!i.notes.length)return console.log(` ${I.default.dim("No private notes yet.")}`);B(["Author","Created","Note"],i.notes.map(s=>[s.author.label,s.created_at,s.body]),[28,24,64])}async function Gd(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 _(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/activity`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return y(i,e.fields);if(S("Conversation Activity"),!i.activity.length)return console.log(` ${I.default.dim("No activity yet.")}`);B(["Type","Actor","Created"],i.activity.map(s=>[s.type,s.actor.label,s.created_at]),[36,32,24])}async function Kd(e){let t=await Qe(e);if(e.dryRun)return G("email_setup",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Setting up email on ${v.domain(t)}`);let s=await _(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),e.json){y(n,e.fields);return}if(n.records?.length){d(),S(`Email DNS Records ${v.domain(t)}`);let r=n.records.map(o=>[I.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?I.default.green(o.status):I.default.yellow(o.status)]);B(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&Pe(n.hint),R("Check status:",`domani email status --domain ${t}`),d()}async function zd(e){let t=await Qe(e),i=C(!e.json);i.start(`Checking email status for ${v.domain(t)}`);let s=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Status loaded`),e.json){y(n,e.fields);return}if(S(`Email ${v.domain(t)}`),c("Enabled",n.enabled?I.default.green("yes"):I.default.dim("no")),n.enabled&&(c("Verified",n.verified?I.default.green("yes"):I.default.yellow("pending")),c("Mailboxes",String(n.mailbox_count))),d(),!n.enabled)R("Set up email:",`domani email setup --domain ${t}`),d();else if(!n.verified&&n.records?.length){console.log(` ${I.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${I.default.yellow(r.type)} ${r.name} ${I.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function Yd(e){let t=await Qe(e);if(e.dryRun)return G("email_remove",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Removing email from ${v.domain(t)}`);let s=await _(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Email disabled`),e.json){y(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${I.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function go(e){let t=C(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",s=await _(`/api/emails${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.mailboxes||[];if(t.stop(`${w.success} ${r.length} mailbox(es)`),e.json){y(n,e.fields);return}if(r.length===0){d(),console.log(` ${I.default.dim("No mailboxes.")}`),d(),R("Create one:","domani email create hello@example.com"),d();return}d(),S("Mailboxes");let o=r.map(a=>[I.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):I.default.dim("-"),I.default.dim(new Date(a.created_at).toLocaleDateString())]);B(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function Xd(e){let t=await Qe(e);if(e.dryRun)return G("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let i=e.slug;if(!i&&!e.json){let f=await Te({message:`Email handle for @${t}:`,placeholder:"hello"});de(f)&&process.exit(0),i=f}i||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let s=`${i}@${t}`,n=C(!e.json);n.start("Creating mailbox");let r=await _("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){n.stop("");let f=o.txt_record,m=o.email_records||[],g=[{type:"TXT",name:f?.name||"@",value:f?.value||"",note:"ownership proof"},...m];d(),console.log(" Add these records at your DNS provider:"),d();for(let j of g){let O=j.priority!==void 0?` ${I.default.dim(`priority: ${j.priority}`)}`:"",A=j.note?` ${I.default.dim(`(${j.note})`)}`:"";console.log(` ${I.default.yellow(j.type)} ${I.default.bold(j.name)}${O}${A}`),console.log(` ${I.default.dim("\u2192")} ${I.default.cyan(j.value)}`),d()}Pe("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let b=g.map(j=>({cells:[I.default.yellow(j.type),j.name,j.note?I.default.dim(`(${j.note})`):""],status:"pending"})),k=Ft(["Type","Name",""],b,[6,24,16]);k.start();let $=0;for(;r.status===202&&$<60;)await qt(15e3),$++,r=await _("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(k.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(k.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${s}`,code:"timeout",json:e.json,fields:e.fields})),k.markDone(0);let h=j=>`${j.type}:${j.name}`,x=new Map;g.slice(1).forEach((j,O)=>x.set(h(j),O+1));for(let j=0;j<60;j++){await qt(15e3);let O=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),A=await O.json();if(O.ok&&A.records){for(let V of A.records)if(V.status==="verified"||V.status==="created"){let H=x.get(h(V));H!==void 0&&k.markDone(H)}}if(O.ok&&A.verified)break}k.stop(),d()}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(`${w.success} ${I.default.cyan(o.address)} created`),e.json){y(o,e.fields);return}let a=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),l=await a.json();d(),a.ok&&l.verified?(R("Read inbox:",`domani email inbox ${o.address}`),R("Web inbox:",`${oi}/inbox?address=${encodeURIComponent(o.address)}`)):(R("Check propagation:",`domani email status --domain ${t}`),R("Web inbox:",`${oi}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function Zd(e){let t=await Qe(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 G("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=C(!e.json);i.start(`Deleting ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),n=await _(`/api/emails/${s}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Mailbox deleted`),e.json){y(r,e.fields);return}console.log(` ${I.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function Qd(e){let t=await Qe(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 G("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=C(!e.json);i.start(`Sending from ${e.slug}@${t}`);let s={to:rs(ns(e.to))},n=rs(ns(e.cc)),r=rs(ns(e.bcc));n&&(s.cc=n),r&&(s.bcc=r),e.subject&&(s.subject=e.subject),e.text&&(s.text=e.text),e.inReplyTo&&(s.in_reply_to=e.inReplyTo),e.references&&(s.references=e.references),e.sendAt&&(s.send_at=e.sendAt);let o=encodeURIComponent(`${e.slug}@${t}`),a=await _(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(s)}),l=await a.json();if(!a.ok){i.stop("Failed");let m=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${I.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;u(l.error||l.message,{hint:m,status:a.status,json:e.json,fields:e.fields})}let f=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(l.status==="scheduled"?`${w.success} Scheduled for ${I.default.cyan(e.sendAt||"")} to ${I.default.cyan(f)} ${I.default.dim("(trash the message before then to cancel)")}`:`${w.success} Sent to ${I.default.cyan(f)}`),e.json){y(l,e.fields);return}}function Ct(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 vo(e,t,i,s,n){let r=C(!i.json);r.start(s);let o=await _(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:i.json,fields:i.fields})),r.stop(n(a)),i.json&&y(a,i.fields)}async function ec(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:i}=Ct(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let s={};e.reason&&(s.reason=e.reason),e.clear&&(s.clear=!0),await vo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/escalate`,s,e,e.clear?"Clearing escalation":"Flagging for a human",n=>n.needs_human?`${w.success} Flagged for a human ${I.default.dim("(conversation held, email.escalated fired)")}`:`${w.success} Escalation cleared`)}async function tc(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:i}=Ct(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 s={};e.at&&(s.remind_at=e.at),e.note&&(s.note=e.note),e.clear&&(s.clear=!0),await vo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/remind`,s,e,e.clear?"Clearing reminder":"Setting follow-up reminder",n=>n.remind_at?`${w.success} Reminder set for ${I.default.cyan(String(n.remind_at))} ${I.default.dim("(fires only if still unanswered)")}`:`${w.success} Reminder cleared`)}async function ic(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=await _(`/api/contacts${t.size?`?${t}`:""}`),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){y(s,e.fields);return}let n=s.contacts||[];if(n.length===0){console.log(I.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let r of n){let o=r.name?` ${I.default.dim(r.name)}`:"",a=r.notes?` ${I.default.dim("-")} ${r.notes}`:"";console.log(`${I.default.cyan(r.address)}${o} ${I.default.dim(`(${r.message_count} msg${r.message_count!==1?"s":""}, last ${r.last_direction||"-"})`)}${a}`)}s.next_cursor&&console.log(I.default.dim(`More: --cursor ${s.next_cursor}`))}function $o(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 sc(e){let i=$o(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),s={address:i};e.name!==void 0&&(s.name=e.name),e.notes!==void 0&&(s.notes=e.notes);let n=await _("/api/contacts",{method:"POST",body:JSON.stringify(s)}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){y(r,e.fields);return}console.log(`${w.success} Contact ${I.default.cyan(i)} saved.`)}async function nc(e){let i=$o(e,"Usage: domani email contact-remove ada@example.com"),s=await _(`/api/contacts/${encodeURIComponent(i)}`,{method:"DELETE"}),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json){y(n,e.fields);return}console.log(n.deleted?`${w.success} Contact ${I.default.cyan(i)} deleted.`:I.default.dim(`No contact ${i}.`))}async function rc(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:i}=Ct(e,t),s=encodeURIComponent(i);if(e.set===void 0&&!e.clear){let o=await _(`/api/emails/${s}`),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){y({address:i,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:I.default.dim(`No tone notes on ${i}. Set them with --set.`));return}let n=await _(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){y(r,e.fields);return}console.log(e.clear?`${w.success} Tone notes cleared on ${I.default.cyan(i)}.`:`${w.success} Tone notes set on ${I.default.cyan(i)}.`)}async function oc(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams;e.direction&&i.set("direction",e.direction),e.folder&&i.set("folder",e.folder),e.view&&i.set("view",e.view),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i}`:"",n=C(!e.json);n.start(`Loading messages for ${e.slug}@${t}`);let r=encodeURIComponent(`${e.slug}@${t}`),o=await _(`/api/emails/${r}/messages${s}`),a=await o.json();o.ok||(n.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}));let l=a.messages||[];if(e.json){n.stop(`${w.success} ${l.length} message(s)`),y(a,e.fields);return}if(l.length===0){n.stop(`${I.default.dim("No messages")}`);return}let f=l.length>1?"s":"";n.stop(`${w.success} ${I.default.cyan(`${e.slug}@${t}`)} ${I.default.dim("\xB7 "+l.length+" message"+f)}`);for(let m of l){let g=m.direction==="in"?I.default.green("in "):I.default.dim("out"),b=m.direction==="in"?m.from:m.to,k=m.subject||"(no subject)",$=I.default.dim(new Date(m.created_at).toLocaleString()),h=k;if(m.text){let x=m.text.replace(/\s+/g," ").trim(),j=x.length>60?x.slice(0,60)+"\u2026":x;h=`${k} ${I.default.dim("- "+j)}`}console.log(` ${g} ${b.padEnd(30)} ${h} ${$}`)}a.next_cursor&&console.log(` ${I.default.dim("\u2026 more available, use --limit to paginate")}`)}async function ac(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=encodeURIComponent(`${e.slug}@${t}`),s=await _(`/api/emails/${i}/folders`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return y(n,e.fields);S(`Folders for ${e.slug}@${t}`);for(let r of n.folders||[])c(r.id,`${r.total} total, ${r.unread} unread`);for(let r of n.views||[])c(r.id,`${r.total} total, ${r.unread} unread`)}async function lc(e,t){let i=await Qe(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 s=(t.messageIds||"").split(",").map(m=>m.trim()).filter(Boolean);s.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let n={message_ids:s,idempotency_key:t.idempotencyKey||(0,Sn.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(n,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(n.action="restore"),(e==="read"||e==="unread")&&Object.assign(n,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(n,{action:"star",starred:e==="star"}),t.dryRun)return G("email_messages_action",{address:`${t.slug}@${i}`,...n},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await _(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(n)}),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 y(a,t.fields);let l=(a.results||[]).filter(m=>m.ok).length,f=(a.results||[]).length-l;console.log(`${w.success} ${l} updated${f?I.default.yellow(`, ${f} 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 dc(e){let t=await Qe(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 i=`${e.slug}@${t}`,s=encodeURIComponent(i),n;try{n=Mt(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&&n!==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 G("email_webhook",{address:i,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...n!==void 0?{header_names:Lt(n)}:{}},e.json,e.fields);let o=C(!e.json);if(e.url){o.start(`Setting webhook for ${i}`);let a=await _(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...n!==void 0?{headers:n}:{},...r!==void 0?{events:r}:{}})}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook set`),e.json){y(l,e.fields);return}S(`Mailbox ${l.address}`),c("Webhook",v.url(l.webhook_url)),c("Events",l.events?.join(", ")||I.default.dim("email.received")),c("Auth headers",l.header_names?.join(", ")||I.default.dim("none")),c("Signing secret",I.default.dim(l.signing_secret)),d()}else{o.start(`Removing webhook for ${i}`);let a=await _(`/api/emails/${s}/webhook`,{method:"DELETE"}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook removed`),e.json){y(l,e.fields);return}S(`Mailbox ${l.address}`),c("Webhook",I.default.dim("none")),d()}}async function cc(e){let t=await Qe(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 i=`${e.slug}@${t}`;if(e.dryRun)return G("email_webhook_test",{address:i},e.json,e.fields);let s=C(!e.json);s.start(`Testing webhook for ${i}`);let n=await _(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await n.json();if((!n.ok||!r.success)&&(s.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:n.status,json:e.json,fields:e.fields})),s.stop(`${w.success} Test delivered`),e.json)return y(r,e.fields);S(`Mailbox ${i}`),c("Delivery",I.default.green("successful")),typeof r.status=="number"&&c("Endpoint",`HTTP ${r.status}`),d()}async function uc(e){let t=await Qe(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 G("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=C(!e.json),s=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await _(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:s})}),o=await r.json();if(r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Forward ${s?"set":"removed"}`),e.json){y(o,e.fields);return}S(`Mailbox ${o.address}`),c("Forward to",o.forward_to?I.default.cyan(o.forward_to):I.default.dim("none")),d()}async function yo(e,t,i){let s=C(!t);s.start(`Checking email health for ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Email health checked"),t){y(r,i);return}if(S(`Email Health ${v.domain(r.domain)}`),r.provider?c("Provider",I.default.cyan(Cn(r.provider))):c("Provider",I.default.dim("unknown")),r.mx.configured?c("MX",`${w.success} ${I.default.green("propagated")} ${I.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${w.error} ${I.default.red("not configured")}`),r.spf.configured?c("SPF",`${w.success} ${I.default.green(r.spf.value)}`):c("SPF",`${w.error} ${I.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${w.success} ${I.default.green(o)}`)}else c("DMARC",`${w.error} ${I.default.red("missing")}`);r.dkim.configured?c("DKIM",`${w.success} ${I.default.green("found")} ${I.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${w.warning} ${I.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(Pe("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),d()):(R("Set up email:",`domani email ${e} google`),d())}async function bo(e,t,i,s){return t?_o(e,t,i,s):ko(e,i,s)}async function ko(e,t,i){let s=C(!t);s.start("Loading email providers");let n=await _(`/api/domains/${encodeURIComponent(e)}/connect`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:i});let a=await tt({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:Cn(l.name)}))});return de(a)&&process.exit(0),_o(e,a,t,i)}async function _o(e,t,i,s){if(i){let f=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),m=await f.json();f.ok||u(m.error||m.message,{hint:m.hint,status:f.status,json:i,fields:s}),y(m,s);return}let n=await _(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let f=await n.json();u(f.error||f.message,{hint:f.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=Cn(a);if(S(`Email ${v.domain(e)}`),c("Provider",I.default.cyan(l)),o.length){d(),console.log(` ${I.default.bold("DNS Records")}`);let f=[8,24,40],m=Ft(["Type","Name","Value"],o.map(j=>({cells:Ad(j),status:"pending"})),f);m.start();let g=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),b=await g.json();g.ok||(m.stop(),d(),u(b.error||b.message,{hint:b.hint,status:g.status,json:i,fields:s}));let k=b.records||[];for(let j=0;j<o.length;j++)k.find(A=>A.record.type===o[j].type&&A.record.name===o[j].name&&A.record.value===o[j].value)?.status==="already_set"||await qt(60),m.markDone(j);await qt(80),m.stop();let $=k.filter(j=>j.status==="created"||j.status==="updated").length,h=k.filter(j=>j.status==="already_set").length,x;h===k.length?x=`All ${h} records already set`:h>0?x=`${$} created, ${h} already set`:x=`${$} DNS records set`,d(),console.log(` ${w.success} ${I.default.green(`Email configured - ${x}`)}`)}else{let f=C(!0);f.start("Setting DNS records");let m=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await m.json();m.ok||(f.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:m.status,json:i,fields:s})),f.stop(`${w.success} Email configured via ${I.default.cyan(l)}`)}d(),R("Verify propagation:",`domani email ${e} --check`),d()}var I,Sn,wo,Id,Rd,In=Ae(()=>{"use strict";K();ai();I=D(M(),1);Ue();L();ye();Ze();Sn=require("node:crypto"),wo=require("node:fs");is();Id=["setup","status","remove","list","create","delete","send","inbox","folders","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"],Rd={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var jo={};Bt(jo,{dns:()=>An});async function An(e,t,i,s,n,r){e||(e=await pe()),Y(e,r);let o=r?.json??!1,a=r?.type||i,l=r?.name||s,f=r?.value||n;if(!t||t==="get"){let m=C(!o);m.start(`Loading DNS for ${v.domain(e)}`);let g=await _(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json();if(g.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${b.records.length} record(s)`),o){y(b,r?.fields);return}if(b.records.length===0){d(),console.log(` ${Ce.default.dim(`No DNS records for ${e}`)}`),d(),R("Auto-configure DNS:",`domani connect ${e}`),d();return}let k=[8,24,40,8];S(`DNS ${v.domain(e)}`,k.reduce((h,x)=>h+x,0)+k.length-1);let $=b.records.map(h=>{let x=h.priority?Ce.default.dim(` pri=${h.priority}`):"";return[Ce.default.yellow(h.type),h.name,Ce.default.cyan(h.value)+x,Ce.default.dim(String(h.ttl))]});B(["Type","Name","Value","TTL"],$,k),d();return}if(t==="set"){if((!a||!l||!f)&&u("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return G("dns_set",{domain:e,record:{type:a.toUpperCase(),name:l,value:f,ttl:3600}},o,r?.fields);let m=C(!o);m.start(`Setting ${Ce.default.yellow(a.toUpperCase())} record`);let g=await _(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json(),$=(g.ok?b.records:[]).filter(j=>!(j.type===a.toUpperCase()&&j.name===l));$.push({type:a.toUpperCase(),name:l,value:f,ttl:3600});let h=await _(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:$})}),x=await h.json();h.ok||(m.stop("Failed"),u(x.error||x.message,{hint:x.hint,status:h.status,json:o,fields:r?.fields})),m.stop(`${w.success} ${Ce.default.yellow(a.toUpperCase())} ${l} ${w.arrow} ${Ce.default.cyan(f)}`),o?y(x,r?.fields):(d(),R("Check propagation:",`domani status ${e}`),d());return}if(t==="delete"){if((!a||!l)&&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 G("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let m=C(!o);m.start(`Deleting ${Ce.default.yellow(a.toUpperCase())} ${l}`);let g=await _(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),b=await g.json();g.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${w.success} Deleted ${Ce.default.yellow(a.toUpperCase())} ${l}`),o?y(b,r?.fields):(d(),R("Check propagation:",`domani status ${e}`),d());return}if(t==="snapshot"){if(r?.dryRun)return G("dns_snapshot",{domain:e},o,r?.fields);let m=C(!o);m.start(`Capturing DNS snapshot for ${v.domain(e)}`);let g=await _(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),b=await g.json();g.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields}));let k=b.records?.length??0;if(m.stop(`${w.success} Captured ${k} record(s)`),o){y(b,r?.fields);return}let $=`${e}.dns.json`,h=(0,Rn.resolve)(process.cwd(),$);(0,os.writeFileSync)(h,JSON.stringify(b,null,2)+`
|
|
180
|
+
`),S("DNS Snapshot"),c("Domain",v.domain(b.domain)),c("Records",String(k)),c("Subdomains",String(b.subdomains?.length??0)),c("Sources",(b.sources||[]).join(", ")||"none"),c("Captured",b.capturedAt||b.captured_at||"now"),c("Saved to",Ce.default.cyan($)),d(),R("Restore from this snapshot:",`domani dns ${e} restore --file ${$}`),d();return}if(t==="restore"){if(r?.dryRun)return G("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let m=C(!o),g;if(r?.file){let $=(0,Rn.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 h=(0,os.readFileSync)($,"utf-8"),x=JSON.parse(h);g=JSON.stringify({snapshot:x}),m.start(`Restoring DNS for ${v.domain(e)} from ${Ce.default.cyan(r.file)}`)}catch(h){u(`Failed to read snapshot file: ${h instanceof Error?h.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else m.start(`Restoring DNS for ${v.domain(e)} from server backup`);let b=await _(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),k=await b.json();if(b.ok||(m.stop("Failed"),u(k.error||k.message,{hint:k.hint,status:b.status,json:o,fields:r?.fields})),m.stop(`${w.success} Restored DNS`),o){y(k,r?.fields);return}if(S("DNS Restored"),c("Domain",v.domain(k.domain)),c("Applied",Ce.default.green(String(k.applied??0))),c("Skipped",Ce.default.dim(String(k.skipped??0))),k.errors?.length>0){c("Errors",Ce.default.red(String(k.errors.length)));for(let $ of k.errors)console.log(` ${Ce.default.red("\u2022")} ${$}`)}d(),R("Verify DNS records:",`domani dns ${e}`),d();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ce,os,Rn,En=Ae(()=>{"use strict";K();Ce=D(M(),1);L();ye();Ze();os=require("node:fs"),Rn=require("node:path")});var So={};Bt(So,{status:()=>Tn});function mc(e){return[it.default.yellow(e.type),e.name,it.default.cyan(e.value)+(e.priority?it.default.dim(` pri=${e.priority}`):"")]}function fc(e){if(S(`Status ${v.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,s=i!=null&&i<30?it.default.red:i!=null&&i<90?it.default.yellow:it.default.green;c("Expires",`${t} ${it.default.dim("(")}${s(`${i} days`)}${it.default.dim(")")}`)}}async function Tn(e,t){if(e||(e=await pe()),Y(e,t),t.json){let g=await _(`/api/domains/${encodeURIComponent(e)}/status`),b=await g.json();g.ok||u(b.error||b.message,{hint:b.hint,status:g.status,json:t.json,fields:t.fields}),y(b,t.fields);return}let i=C(!0);i.start(`Checking ${v.domain(e)}`);let s;try{s=await _(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{i.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!s.ok){i.stop("Failed");try{let g=await s.json();u(g.error||g.message,{hint:g.hint,status:s.status,json:t.json,fields:t.fields})}catch{u(`Server error (${s.status})`,{status:s.status,json:t.json,fields:t.fields})}}let n=s.body;n||(i.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,l=[],f=!1,m="";try{for await(let g of n){o+=r.decode(g,{stream:!0});let b=o.split(`
|
|
181
|
+
`);o=b.pop()??"";for(let k of b)if(k.startsWith("event: "))m=k.slice(7);else if(k.startsWith("data: ")){let $=JSON.parse(k.slice(6));if(m==="info"&&(i.stop("Status retrieved"),f=!0,fc($)),m==="records")if(l=$,l.length>0){d(),console.log(` ${it.default.bold("DNS Records")}`);let h=[8,10,34];a=Ft(["Type","Name","Value"],l.map(x=>({cells:mc(x),status:"pending"})),h),a.start()}else d(),c("DNS",it.default.dim("no records")),R("Auto-configure DNS:",`domani connect ${e}`);if(m==="propagation"&&a){let{index:h,propagated:x}=$,j=x?w.success:`${w.warning}`;a.markDone(h,j)}m==="done"&&a&&a.stop(),m==="error"&&(f||i.stop("Failed"),a&&a.stop(),u($.message||"Status check failed"))}}}catch{f||i.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})}f||i.stop("Done"),d()}var it,Pn=Ae(()=>{"use strict";K();it=D(M(),1);L();ye();Ze()});var gi={};Bt(gi,{buy:()=>Nn});async function Dn(e){let t=await tt({message:`What's next for ${qe.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"){d();return}if(d(),t==="connect"){let{connect:i}=await Promise.resolve().then(()=>(jn(),ho));await i(e,void 0,{})}else if(t==="email"){let i=await Te({message:`Mailbox name for ${qe.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(de(i)||!i){d();return}d();let{email:s}=await Promise.resolve().then(()=>(In(),xo));await s("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(En(),jo));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(Pn(),So));await i(e,{})}}async function pc(e,t){Y(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let m=C(!t.json);m.start(`Checking ${v.domain(e)}`);let g=await _(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await g.json(),g.ok||(m.stop("Search failed"),u(i.error,{hint:i.hint,status:g.status,json:t.json,fields:t.fields})),i.available||(m.stop(`${w.error} ${v.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),m.stop(`${w.success} ${v.domain(e)} ${w.dot} available ${w.dot} ${v.price(i.price)}/yr`)}if(t.dryRun)return G("buy",{domain:e,available:!0,price:i.price,currency:i.currency||"USD"},t.json,t.fields);if(!Ut(t)){let m=await Xe({message:`Purchase ${qe.default.bold(e)} for ${v.price(i.price)}/yr?`});if(!m||typeof m=="symbol"){console.log(` ${qe.default.dim("Cancelled.")}`);return}}let s=C(!t.json);s.start("Purchasing");let n=await _("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e})});if(!n.ok||!n.body){s.stop("Purchase failed");let m=await n.json().catch(()=>({}));u(m.error||m.message,{hint:m.hint,fixUrl:m.setup_url||m.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})}let r={},o=new TextDecoder,a="",l="";for await(let m of n.body){a+=o.decode(m,{stream:!0});let g=a.split(`
|
|
182
|
+
`);a=g.pop()??"";for(let b of g)if(b.startsWith("event: "))l=b.slice(7).trim();else if(b.startsWith("data: ")){let k=JSON.parse(b.slice(6));l==="checking"?s.message(`Checking ${v.domain(k.domain)}`):l==="payment"?s.message(`Charging ${v.price(k.total)}`):l==="registering"?s.message(`Registering ${v.domain(k.domain)}`):l==="registered"?r=k:l==="error"&&(s.stop("Purchase failed"),u(k.error,{hint:k.hint,fixUrl:k.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let f=r.expires?qe.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${w.success} ${v.domain(r.domain)} is yours!${f}`),t.json){y(r,t.fields);return}Se?await Dn(r.domain):(R("Connect to a service:",`domani connect ${r.domain}`),R("Set up email:",`domani email setup ${r.domain}`),R("Configure DNS:",`domani dns ${r.domain}`),d())}async function hc(e,t){fo(e,t);let i=!!t.json,s=C(!i);s.start(`Checking ${e.length} domains`);let n=await Promise.all(e.map(async h=>{try{let x=await _(`/api/domains/search?q=${encodeURIComponent(h)}`),j=await x.json();return{domain:h,available:x.ok&&j.available,price:j.price}}catch{return{domain:h,available:!1,price:void 0}}})),r=n.filter(h=>h.available),o=n.filter(h=>!h.available);r.length===0&&(s.stop(`${w.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,x)=>h+(x.price||0),0);if(s.stop(`${w.success} ${r.length}/${e.length} available ${w.dot} ${v.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${w.error} ${v.domain(h.domain)} ${qe.default.dim("not available")}`);if(t.dryRun)return G("buy_bulk",{domains:r.map(h=>({domain:h.domain,price:h.price})),unavailable:o.map(h=>h.domain),total_price:parseFloat(a.toFixed(2))},t.json,t.fields);if(!Ut(t)){let h=await Xe({message:`Purchase ${qe.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${v.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${qe.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[v.domain(h.domain),h.price?`${v.price(h.price.toFixed(2))}/yr`:""],status:"pending"})),f=Ft(["Domain","Price"],l,[30,12],!i);f.start();let g=await(await _("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(h=>h.domain)})})).json(),b=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let x=r[h].domain.toLowerCase().trim();b.has(x)?f.markDone(h,w.success):f.markDone(h,w.error)}if(f.stop(),i){y(g,t.fields);return}d();let k=g.summary?.succeeded??0,$=g.summary?.failed??0;if(k>0&&console.log(` ${w.success} ${qe.default.green(`${k} domain${k>1?"s":""} registered`)}`),$>0){console.log(` ${w.error} ${qe.default.red(`${$} failed`)}`);for(let h of g.errors||[])console.log(` ${qe.default.dim("\u2500")} ${v.domain(h.domain)}: ${qe.default.dim(h.error)}${h.hint?` ${qe.default.dim(`(${h.hint})`)}`:""}`)}if(d(),k>0&&Se){let h=(g.results||[]).filter(x=>x.success).map(x=>x.domain);if(h.length===1)await Dn(h[0]);else{let x=await tt({message:"Set up one of your new domains?",options:[...h.map(j=>({value:j,label:qe.default.cyan(j)})),{value:"done",label:"Done"}]});!de(x)&&x!=="done"?(d(),await Dn(x)):d()}}else k>0&&(R("Connect to a service:","domani connect <domain>"),R("Set up email:","domani email setup <domain>"),d())}async function Nn(e,t){let i=e.filter(Boolean);if(i.length===0){Se||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Te({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(de(s)||!s)&&process.exit(0),i=s.split(/\s+/).filter(Boolean)}return i.length===1?pc(i[0],t):hc(i,t)}var qe,ii=Ae(()=>{"use strict";K();Ue();qe=D(M(),1);L();ye()});var ir=D(tr(),1),{program:Cu,createCommand:Ou,createArgument:Iu,createOption:Ru,CommanderError:Au,InvalidArgumentError:Eu,InvalidOptionArgumentError:Tu,Command:sr,Argument:Pu,Option:Du,Help:Nu}=ir.default;var ut=D(M(),1);gt();$n();L();ai();gt();var at=D(M(),1);L();var hd=new Set(["cli","mcp","plugin","skill","api"]);function gd(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),i=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),s=!!(t?.length||i?.length||e.label||e.expiresIn),n=e.surface||"cli";if(!hd.has(n))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:s,body:{...t?.length?{scopes:t}:{},...i?.length?{mailboxes:i}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:n,intent:"programmatic_access"}}}async function ro(e){let t=Ve(),i=C(!e.json),s;try{s=gd(e)}catch(k){u(k instanceof Error?k.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=ht(),a=We();if(a&&!r){i.start("Checking session");try{let k=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(k.ok){let $=await k.json();i.stop(`Already logged in as ${at.default.bold($.email)}`),e.json&&y({status:"already_logged_in",email:$.email});return}}catch{}i.stop("Session expired, re-authenticating"),d()}i.start("Requesting auth code");let l=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!l.ok){i.stop("Failed to initiate login");try{let k=await l.json();u(k.error||k.message||`Server error (${l.status})`,{hint:k.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:f,auth_url:m,expires_in:g}=await l.json();if(i.stop("Auth code received"),e.json){y({status:"awaiting_approval",code:f,auth_url:m,expires_in:g});return}d(),console.log(` ${at.default.dim("Verification code:")} ${at.default.bold(at.default.cyan(f))}`),e.open!==!1?(console.log(` ${at.default.dim("Opening browser")} ${w.arrow} ${v.url(m)}`),Be(m)):console.log(` ${at.default.dim("Open this URL to approve:")} ${v.url(m)}`),d(),i.start("Waiting for approval");let b=120;for(let k=0;k<b;k++){await new Promise(x=>setTimeout(x,5e3));let $=await fetch(`${t}/api/auth/cli/poll?code=${f}`);!$.ok&&$.status!==202&&(i.stop("Login failed"),u(`Server error (${$.status})`,{code:"login_failed"}));let h=await $.json();if(h.status==="complete"){Xt({...ht(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${at.default.bold(h.email)}`),d(),console.log(` ${at.default.bold("Get one real result:")}`),R("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),R("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),R("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${at.default.dim("A custom domain can wait until this loop works.")}`),d();return}h.error&&(i.stop("Login failed"),u(h.error||h.message,{hint:h.hint,code:"login_failed"}))}i.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}gt();var kn=D(M(),1);L();async function oo(e){let t=ht();if(!t.token){e.json?y({status:"not_logged_in"}):console.log(` ${kn.default.dim("Not logged in.")}`);return}let{api_url:i}=t;gr(),i&&Xt({api_url:i}),e.json?y({status:"logged_out",email:t.email||null}):console.log(` ${w.success} Logged out${t.email?` ${kn.default.dim(`(${t.email})`)}`:""}`)}K();var pi=D(M(),1);L();async function lo(e){let[t,i]=await Promise.all([_("/api/me"),_("/api/me/activation")]),s=await t.json();t.ok||u(s.error||s.message,{hint:s.hint,status:t.status,json:e.json,fields:e.fields});let n=i.ok?await i.json():null;if(e.json){y({...s,activation:n},e.fields);return}if(S("Account"),c("Email",pi.default.bold(s.email)),c("Payment",s.has_payment_method?`${w.success} ${pi.default.green("active")}`:`${w.error} ${pi.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||pi.default.dim("-")),c("Created",new Date(s.created_at).toLocaleDateString()),n){c("Activation",n.status);let r=n.recommended_actions?.[0];r&&c("Next action",r.label)}d()}K();Ue();var N=D(M(),1);L();ye();var Ge=10,si=200,as=["com","io","ai","dev","app","co","net","org","xyz","sh","me","cc","tech","run","cloud","so","gg","fm","tv","pro","one","inc","ltd","llc","biz","group","global","ventures","capital","fund","agency","store","shop","market","sale","deals","auction","trade","studio","design","art","space","style","fashion","luxury","brand","media","digital","site","online","live","show","world","zone","land","place","city","town","blog","news","social","chat","link","page","fun","lol","meme","wtf","tools","build","works","work","team","solutions","services","systems","network","software","music","video","photo","photos","game","games","club","stream","film","movie","pizza","coffee","beer","bar","pub","restaurant","cafe","kitchen","food","wine","health","care","clinic","dental","fitness","yoga","bio","life","lifestyle","finance","money","legal","law","cash","academy","university","education","training","courses","science","wiki","guide","us","uk","eu","ca","au","de","fr","it","es","nl","jp","sg","nz","mx","house","homes","realty","estate","garden","nyc","london","berlin","paris","guru","ninja","rocks","fail","party","vip","gold","black","pink","red","events","travel","sport","jobs","careers","consulting","energy","eco","green","support","help","info","new","now","today","day"],ls=null;async function Co(){if(ls)return ls;try{let e=await we("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let i=(await e.json()).tlds.map(s=>s.tld);if(i.length>0){let s=new Set(as),n=new Set(i),r=[...as.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return ls=r,r}}}catch{}return ls=as,as}async function gc(e,t,i,s,n){let r=[],o=[],a=Ge,l=0,f=!0,m=0,g=0,b=!1,k=!1,$=null,h="",x=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],j=0,O=setInterval(()=>{k||!f||(j=(j+1)%x.length,T())},80);function A(){m>0&&(process.stdout.write(`\x1B[${m}A\x1B[0J`),m=0)}function V(){if(f)return[];let F=Ge+g*Ge;return r.length>a||s&&F<n.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function te(){let F=V();return Math.max(0,H().length+F.length-1)}let P=6;function T(){A();let F=[],Z=H(),ee=!f&&Z.length===0&&o.length>0,z=ee?o.slice(0,P):Z,Re=z.reduce((ce,le)=>Math.max(ce,le.domain.length),0),ze=V();for(let ce=0;ce<z.length;ce++){let le=z[ce];if(ee)F.push(`${N.default.dim("\u2502")} ${N.default.dim("\u2715")} ${N.default.dim(le.domain.padEnd(Re))} ${N.default.dim("taken")}`);else{let _e=ce===l,mt=_e?N.default.green("\u25CF"):N.default.dim("\u25CB"),ie=le.domain.padEnd(Re),nt=_e?N.default.bold(N.default.cyan(ie)):ie,kt=le.for_sale?N.default.cyan(`$${le.for_sale.price} (for sale)`):N.default.dim(`$${le.price}/yr`);F.push(`${N.default.dim("\u2502")} ${mt} ${nt} ${kt}`)}}if(ee&&o.length>P&&F.push(`${N.default.dim("\u2502")} ${N.default.dim(`\u2026 and ${o.length-P} more taken`)}`),f){let ce=h?N.default.dim(`checking ${h}\u2026`):N.default.dim("searching\u2026");F.push(`${N.default.dim("\u2502")} ${N.default.cyan(x[j])} ${ce}`)}else{let ce=Ge+g*Ge;s&&ce>=n.length&&F.push(`${N.default.dim("\u2502")} ${N.default.dim(`All ${Math.min(ce,n.length)} TLDs searched`)}`);for(let _e=0;_e<ze.length;_e++){let nt=H().length+_e===l?N.default.green("\u25CF"):N.default.dim("\u25CB"),kt=ze[_e]==="more"?N.default.dim("More \u2192"):ze[_e]==="new"?N.default.dim("New search \u2192"):N.default.dim("Skip");F.push(`${N.default.dim("\u2502")} ${nt} ${kt}`)}F.push(N.default.dim("\u2514"))}process.stdout.write(F.join(`
|
|
182
183
|
`)+`
|
|
183
184
|
`),m=F.length}process.stdout.write(`${N.default.cyan("\u25C6")} Register a domain?
|
|
184
|
-
`),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let U=F=>{let
|
|
185
|
-
`);ee=
|
|
185
|
+
`),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let U=F=>{let Z=F.toString();if(Z==="\x1B[A")l=Math.max(0,l-1),T();else if(Z==="\x1B[B")l=Math.min(te(),l+1),T();else if(Z==="\r"){let ee=H();if(f&&ee.length===0)return;if(l<ee.length)$=ee[l]?.domain??null,k=!0;else{let Re=V()[l-ee.length];Re==="more"?(a+=Ge,r.length<a?b=!0:(l=Math.min(l,te()),T())):(Re==="new"&&($="__new__"),k=!0)}}else(Z===""||Z==="\x1B")&&(k=!0)};process.stdin.on("data",U),T();async function Q(F){let Z=new TextDecoder,ee="",z="";for await(let Re of F){if(k)break;ee+=Z.decode(Re,{stream:!0});let ze=ee.split(`
|
|
186
|
+
`);ee=ze.pop()??"";for(let ce of ze)if(ce.startsWith("event: "))z=ce.slice(7);else if(ce.startsWith("data: ")){let le=JSON.parse(ce.slice(6));if(z==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(le.message||le.error||"Search failed",{code:le.code||"error"})),z==="result"&&(h=le.domain),z==="result"&&(le.available||le.for_sale||i)){if(g===0){let _e=r.findIndex(mt=>mt.price>le.price);_e===-1?r.push(le):(r.splice(_e,0,le),_e<=l&&l++)}else r.push(le);T()}else if(z==="result"&&!le.available&&!le.error)o.length<8&&o.push(le);else if(z==="done"){f=!1,l=Math.min(l,te());let _e=Ge+g*Ge;r.length<a&&s&&_e<n.length&&(b=!0),b||T()}}}f=!1}for(await Q(e);!k;)if(await new Promise(F=>{let Z=setInterval(()=>{(k||b)&&(clearInterval(Z),F())},16)}),b&&!k){b=!1;let F=Ge+g*Ge,Z=n.slice(F,F+Ge);g++,f=!0,l=Math.min(l,Math.max(0,r.length-1)),T();let ee=new URLSearchParams;ee.set("domains",Z.map(z=>`${t}.${z}`).join(","));try{let z=await we(`/api/domains/search?${ee}`,{headers:{Accept:"text/event-stream"}});z.ok&&z.body?await Q(z.body):(f=!1,T())}catch{f=!1,T()}}clearInterval(O),process.stdin.removeListener("data",U),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),A();let X=$==="__new__",q=X?null:$,se=q?r.find(F=>F.domain===q)??null:null;return q?process.stdout.write(`${N.default.dim("\u25C7")} Register a domain?
|
|
186
187
|
${N.default.dim("\u2502")} ${N.default.bold(N.default.cyan(q))}
|
|
187
188
|
${N.default.dim("\u2514")}
|
|
188
189
|
`):process.stdout.write(`${N.default.dim("\u2514")}
|
|
189
|
-
`),{chosen:q,chosenResult:se,searchAgain:
|
|
190
|
-
`);se=nt.pop()??"";for(let kt of nt)kt.startsWith("event: ")?F=kt.slice(7):kt.startsWith("data: ")&&F==="result"&&
|
|
191
|
-
`);P=Q.pop()??"";for(let
|
|
192
|
-
`);k=
|
|
193
|
-
domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),
|
|
194
|
-
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 i=await x(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${b.success} Token revoked`),e.json){w(s,e.fields);return}console.log(` ${qe.default.dim("Any applications using this key will need a new one.")}`),d()}G();var Ie=D(M(),1);V();ge();Ze();async function qo(e,t){e||(e=await fe()),z(e,t);let i=t.autoRenew!==void 0,s=t.whoisPrivacy!==void 0,n=t.securityLock!==void 0;if(!i&&!s&&!n)return uc(e,t.json,t.fields);let r={};if(i){let f=Tn(t.autoRenew);f===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=f}if(s){let f=Tn(t.whoisPrivacy);f===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=f}if(n){let f=Tn(t.securityLock);f===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=f}if(t.dryRun)return B("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)}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${b.success} Settings updated`),t.json){w(l,t.fields);return}S("Settings Updated"),c("Domain",v.domain(l.domain)),l.auto_renew!==void 0&&c("Auto-renew",l.auto_renew?Ie.default.green("on"):Ie.default.dim("off")),l.whois_privacy!==void 0&&c("WHOIS privacy",l.whois_privacy?Ie.default.green("on"):Ie.default.dim("off")),l.security_lock!==void 0&&c("Security lock",l.security_lock?Ie.default.green("locked"):Ie.default.dim("unlocked")),l.hint&&c("",Ie.default.dim(l.hint)),d()}async function uc(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${b.success} ${v.domain(e)}`),t){w(r,i);return}S("Domain Settings"),c("Domain",v.domain(r.domain)),c("Status",r.status==="active"?Ie.default.green(r.status):Ie.default.yellow(r.status)),c("Auto-renew",r.auto_renew?Ie.default.green("on"):Ie.default.dim("off")),r.registrar&&(c("WHOIS privacy",r.registrar.whois_privacy?Ie.default.green("on"):Ie.default.dim("off")),c("Security lock",r.registrar.security_lock?Ie.default.green("locked"):Ie.default.dim("unlocked"))),c("Expires",new Date(r.expires_at).toLocaleDateString()+Ie.default.dim(` (${r.days_until_expiry} days)`)),d(),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}`),d()}function Tn(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}G();var Vt=D(M(),1);V();ge();Ze();async function Fo(e,t){e||(e=await fe()),z(e,t);let i=C(!t.json);i.start(`Getting auth code for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/auth-code`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${b.success} Auth code retrieved`),t.json){w(n,t.fields);return}if(S("Auth Code"),c("Domain",v.domain(n.domain)),c("Auth code",Vt.default.bold(Vt.default.green(n.auth_code))),n.was_unlocked&&c("",Vt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${Vt.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${Vt.default.dim("\u2192")} ${Vt.default.dim(r)}`)}d(),I("Check transfer status:",`domani transfer-away ${e}`),I("Re-lock domain:",`domani settings ${e} --security-lock on`),d()}G();var $t=D(M(),1);V();ge();Ze();var mc={none:$t.default.dim,pending:$t.default.yellow,approved:$t.default.yellow,completed:$t.default.green,rejected:$t.default.red,expired:$t.default.red};async function Mo(e,t){e||(e=await fe()),z(e,t);let i=C(!t.json);i.start(`Checking transfer status for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/transfer-away`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${b.success} ${v.domain(e)}`),t.json){w(n,t.fields);return}S("Transfer Away Status"),c("Domain",v.domain(n.domain));let r=mc[n.status]||$t.default.dim;c("Status",r(n.status)),n.gaining_registrar&&c("New registrar",n.gaining_registrar),n.request_date&&c("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(d(),console.log(` ${$t.default.dim(n.hint)}`)),d(),n.status==="none"?I("Get auth code to start:",`domani auth-code ${e}`):n.status==="pending"||n.status==="approved"?I("Check again later:",`domani transfer-away ${e}`):n.status==="completed"?I("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${e}`),d()}G();Ne();var as=D(M(),1);V();async function Lo(e,t){return e==="set"?pc(t):fc(t)}async function fc(e){let t=C(!e.json);t.start("Loading contact info");let i=await x("/api/me/contact"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${b.success} Contact info`),e.json){w(s,e.fields);return}if(S("Contact Info"),!s.has_contact){console.log(` ${b.warning} ${as.default.yellow("No contact info set.")} Run ${as.default.bold("domani contact set")} to add.`),d(),console.log(` ${as.default.dim("Contact info is required before purchasing domains.")}`),d();return}let n=s.contact;c("Name",`${n.first_name} ${n.last_name}`),n.org_name&&c("Organization",n.org_name),c("Address",n.address1),n.address2&&c("",n.address2),c("",`${n.city}, ${n.state} ${n.postal_code}`),c("Country",n.country),c("Phone",n.phone),c("Email",n.email),d()}async function pc(e){let t={},i=e.firstName||e.lastName||e.address1;if(!Se&&!i&&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}),i){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},f=a.filter(m=>!e[m]);f.length>0&&u(`Missing required flags: ${f.map(m=>`--${m.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[m,g]of Object.entries(l)){let y=e[m];y&&(t[g]=y)}}else{let a=await x("/api/me/contact"),f=(a.ok?await a.json():null)?.contact,m=[{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 g of m){let y=f?.[g.key]||"",k=await Te({message:g.message,placeholder:g.placeholder,defaultValue:y,validate:g.required?h=>h?.trim()?void 0:`${g.message} is required`:void 0});le(k)&&process.exit(0);let $=k.trim();$&&(t[g.key]=$)}}if(e.dryRun)return B("contact_set",t,e.json,e.fields);let s=C(!e.json);s.start("Saving contact info");let n=await x("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${b.success} Contact info saved`),e.json){w(r,e.fields);return}S("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),d(),I("Search for a domain:","domani search <name>"),d()}G();var Pe=D(M(),1);V();ge();Ze();async function Ho(e,t,i,s){if(e||(e=await fe()),z(e,s),!t)return hc(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?B("parking_enable",{domain:e},s.json,s.fields):Vo(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?B("parking_disable",{domain:e},s.json,s.fields):Vo(e,!1,s.json,s.fields);case"price":{i||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:s.json,fields:s.fields});let n=parseFloat(i);return(isNaN(n)||n<=0)&&u("Price must be a positive number",{hint:`Got: "${i}"`,code:"validation_error",json:s.json,fields:s.fields}),s.dryRun?B("parking_price",{domain:e,price:n},s.json,s.fields):Wo(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?B("parking_unlist",{domain:e},s.json,s.fields):Wo(e,null,s.json,s.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:s.json,fields:s.fields})}}async function hc(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${b.success} ${v.domain(e)}`),t){w({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}S("Parking"),c("Domain",v.domain(r.domain)),c("Parking",r.parking_enabled?Pe.default.green("enabled"):Pe.default.dim("disabled")),c("Listing",r.listing_price?`${v.price(r.listing_price)} ${Pe.default.dim("(for sale)")}`:Pe.default.dim("not listed")),d(),I("Enable parking:",`domani parking ${e} enable`),I("Set sale price:",`domani parking ${e} price 499`),I("View analytics:",`domani analytics ${e}`),d()}async function Vo(e,t,i,s){let n=C(!i);n.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(n.stop(`${b.warning} DNS records will be replaced`),i){w(o,s);return}console.log(`
|
|
195
|
-
${
|
|
196
|
-
${
|
|
197
|
-
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()),i;try{i=
|
|
190
|
+
`),{chosen:q,chosenResult:se,searchAgain:X,allTaken:r.length===0&&o.length>0,expanded:g>0}}async function Oo(e,t,i){if(!e){Se||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let U=await Te({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(de(U)||!U)&&process.exit(0),e=U}let s=t.map(U=>U.replace(/^\./,"")),n=i.tlds?.split(",").map(U=>U.trim())||[],r=[...new Set([...s,...n])];if(r.length>0&&ts(r,i),Y(e,i),e.includes(".")&&r.length===0){let U=C(!i.json);U.start(`Checking ${v.domain(e)}`);let[Q,X]=await Promise.all([we(`/api/domains/search?q=${encodeURIComponent(e)}`),we(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),q=await Q.json();if(Q.ok||(U.stop("Search failed"),u(q.error||q.message,{hint:q.hint,status:Q.status,json:i.json,fields:i.fields})),i.json){let se=q.domain.split(".")[0];y({name:se,results:[q],total:1,available:q.available?1:0},i.fields);return}if(q.available)if(U.stop(`${w.success} ${v.domain(q.domain)} ${w.dot} available ${w.dot} ${v.price(q.price)}/yr`),Se&&!i.json){let{buy:se}=await Promise.resolve().then(()=>(ii(),gi));await se([q.domain],{preChecked:{price:q.price,currency:q.currency}})}else d(),R("Register it:",`domani buy ${q.domain}`),d();else if(q.for_sale?.buyable)if(U.stop(`${w.info} ${v.domain(q.domain)} ${w.dot} ${N.default.cyan("for sale")} ${w.dot} ${v.price(q.for_sale.price)}`),Se&&!i.json){let{buy:se}=await Promise.resolve().then(()=>(ii(),gi));await se([q.domain],{preChecked:{price:q.for_sale.price,currency:q.for_sale.currency,marketplace:!0}})}else d(),R("Buy it:",`domani buy ${q.domain}`),d();else if(q.error)U.stop(`${N.default.dim("?")} ${v.domain(q.domain)} ${w.dot} ${N.default.dim("lookup failed")}`);else{let se;try{if(X?.ok){let Z=await X.json();Z?.title&&(se=Z.title)}}catch{}let F=se?` ${w.dot} ${N.default.dim(`"${se}"`)}`:"";U.stop(`${w.error} ${v.domain(q.domain)} ${w.dot} ${N.default.red("taken")}${F}`)}return}let o=e.split(".")[0];if(Se&&!i.json&&r.length>0){let U=new URLSearchParams;U.set("domains",r.map(ie=>`${o}.${ie}`).join(",")),i.maxPrice&&U.set("max_price",i.maxPrice);let Q=await we(`/api/domains/search?${U}`,{headers:{Accept:"text/event-stream"}});if(!Q.ok||!Q.body){u("Search failed",{json:i.json});return}let X=[],q=new TextDecoder,se="",F="",Z=C(!0);Z.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let ie of Q.body){se+=q.decode(ie,{stream:!0});let nt=se.split(`
|
|
191
|
+
`);se=nt.pop()??"";for(let kt of nt)kt.startsWith("event: ")?F=kt.slice(7):kt.startsWith("data: ")&&F==="result"&&X.push(JSON.parse(kt.slice(6)))}Z.stop("");let ee=Math.max(...r.map(ie=>`${o}.${ie}`.length))+2,z=X.filter(ie=>ie.available),Re=X.filter(ie=>!ie.available&&!ie.error),ze=X.filter(ie=>!ie.available&&ie.for_sale);for(let ie of[...z,...ze,...Re.filter(nt=>!nt.for_sale)])ie.available?console.log(` ${N.default.green("\u2713")} ${N.default.bold(N.default.white(ie.domain.padEnd(ee)))} ${N.default.green(v.price(ie.price)+"/yr")}`):ie.for_sale?console.log(` ${N.default.cyan("$")} ${N.default.bold(N.default.white(ie.domain.padEnd(ee)))} ${N.default.cyan(v.price(ie.for_sale.price))} ${N.default.dim("(for sale)")}`):console.log(` ${N.default.dim("\u2717")} ${N.default.dim(ie.domain.padEnd(ee))} ${N.default.dim("taken")}`);if(z.length===0){console.log(` ${N.default.dim("No domains available")}`),d();return}let{buy:ce}=await Promise.resolve().then(()=>(ii(),gi));if(z.length===1){await ce([z[0].domain],{preChecked:{price:z[0].price,currency:z[0].currency}});return}let{select:le,isCancel:_e}=await Promise.resolve().then(()=>(Ue(),gn)),mt=await le({message:"Register one?",options:[...z.map(ie=>({value:ie.domain,label:v.domain(ie.domain),hint:v.price(ie.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!_e(mt)&&mt!=="__skip__"){d();let ie=z.find(nt=>nt.domain===mt);await ce([mt],{preChecked:ie?{price:ie.price,currency:ie.currency}:void 0})}else d();return}if(Se&&!i.json){let U=await Co();for(i.expand&&U.length>si&&console.error(N.default.dim(` (--expand: checking the first ${si} of ${U.length} TLDs - server limit per request)`));;){let Q=i.expand?U.slice(0,si):U.slice(0,Ge),X=new URLSearchParams;X.set("domains",Q.map(le=>`${o}.${le}`).join(",")),i.maxPrice&&X.set("max_price",i.maxPrice);let q=C(!0);q.start(`Searching available domains for ${N.default.bold(o)}`);let se=await we(`/api/domains/search?${X}`,{headers:{Accept:"text/event-stream"}});if(!se.ok||!se.body){q.stop("Search failed");break}q.stop("");let F=!i.expand,{chosen:Z,chosenResult:ee,searchAgain:z}=await gc(se.body,o,i.all??!1,F,U);if(Z){d();let{buy:le}=await Promise.resolve().then(()=>(ii(),gi)),_e=ee?{price:ee.price,currency:ee.currency}:void 0;await le([Z],{preChecked:_e});return}if(!z)break;let{text:Re,isCancel:ze}=await Promise.resolve().then(()=>(Ue(),gn)),ce=await Re({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(ze(ce)||!ce)break;o=ce.split(".")[0]}d();return}let a=o,l=await Co(),f=r.length>0?r:i.expand?l.slice(0,si):l.slice(0,Ge);i.expand&&r.length===0&&l.length>si&&console.error(`(--expand: checking the first ${si} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let m=f.map(U=>`${a}.${U}`),g=new URLSearchParams;g.set("domains",m.join(",")),i.maxPrice&&g.set("max_price",i.maxPrice);let b=C(!i.json);b.start(`Searching available domains for ${N.default.bold(a)}`);let k=await we(`/api/domains/search?${g}`,{headers:{Accept:"text/event-stream"}});if(!k.ok){b.stop("Search failed");try{let U=await k.json();u(U.error||U.message||`Server error (${k.status})`,{hint:U.hint,status:k.status,json:i.json,fields:i.fields})}catch{u(`Server error (${k.status})`,{status:k.status,json:i.json,fields:i.fields})}}let $=k.body;$||(b.stop("Search failed"),u("Empty response",{code:"error",json:i.json,fields:i.fields}));let h=[],x=!1,j=0,O=i.all??!1;function A(){x||(x=!0,b.stop(`Checking TLDs for ${N.default.bold(a)}`),d())}function V(U){A(),U.available?console.log(` ${w.success} ${v.domain(U.domain).padEnd(37)} ${v.price(U.price)}${N.default.dim("/yr")}`):U.for_sale?console.log(` ${w.info} ${v.domain(U.domain).padEnd(37)} ${N.default.cyan(v.price(U.for_sale.price))} ${N.default.dim("(for sale)")}`):U.error||console.log(` ${w.error} ${N.default.dim(U.domain.padEnd(38))} ${N.default.red("taken")}`)}function H(){x||b.message(`Checking TLDs for ${N.default.bold(a)} ${N.default.dim(`(${j} checked)`)}`)}let te=new TextDecoder,P="",T="";for await(let U of $){P+=te.decode(U,{stream:!0});let Q=P.split(`
|
|
192
|
+
`);P=Q.pop()??"";for(let X of Q)if(X.startsWith("event: "))T=X.slice(7);else if(X.startsWith("data: ")){let q=JSON.parse(X.slice(6));if(T==="error")b.stop("Search failed"),u(q.message||q.error||"Search failed",{code:q.code||"error",json:i.json,fields:i.fields});else if(T==="result")j++,q.available||q.for_sale||O?(i.json||V(q),h.push(q)):i.json||H();else if(T==="done"){if(i.json){h.sort((ee,z)=>ee.price-z.price),y({name:a,results:h,total:q.total,available:q.available},i.fields);return}x&&console.log(` ${N.default.dim("\u2500".repeat(50))}`);let se=q.total-q.available,F=q.total>=5&&se/q.total>=.5,Z=`Checked ${q.total} TLDs \xB7 ${q.available} available${F?" \xB7 popular name":""}`;console.log(` ${N.default.dim(Z)}`),q.available===0&&!i.expand&&r.length===0&&(d(),R("Try more TLDs:",`domani search ${a} --expand`))}}}d()}ii();K();var yi=D(M(),1);L();ye();is();function Io(e,t,i=process.env){let s=Mt(t,i);if(s!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_headers:s}:{}},preview:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_header_names:Lt(s)}:{}}}}async function Ro(e,t){Y(e,t);let i={domain:e};t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name);let s;try{s=Io(t.webhook,t)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}if(Object.assign(i,s.request),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){let a={...i};delete a.webhook_headers,Object.assign(a,s.preview),G("POST /api/agents/provision",a,t.json,t.fields);return}let n=C(!t.json);n.start(`Provisioning ${v.domain(e)}`);let r=await _("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),o=await r.json();if(r.ok||(n.stop("Provisioning failed"),u(o.error||"Provisioning failed",{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${v.domain(e)} is ready`),t.json){y(o,t.fields);return}if(d(),S("Agent identity"),c("Domain",`${o.domain} (${o.domain_status})`),c("Mailbox",o.mailbox?yi.default.green(o.mailbox.address):yi.default.yellow("pending DNS")),c("Webhook",o.webhook?o.webhook.url:yi.default.dim("none")),o.webhook?.header_names.length&&c("Webhook auth",o.webhook.header_names.join(", ")),o.webhook?.secret&&c("Signing secret",o.webhook.secret),o.warnings?.length){d();for(let a of o.warnings)Pe(yi.default.yellow(a))}if(o.next_steps?.length){d(),S("Next");for(let a of o.next_steps)Pe(a)}d()}K();var wt=D(M(),1);L();async function Ao(e){let t=C(!e.json);t.start("Loading domains");let i=await _("/api/domains"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${s.domains.length} domain(s)`),e.json){y({...s,count:s.domains.length},e.fields);return}if(s.domains.length===0){d(),console.log(` ${wt.default.dim("No domains yet.")} Use: ${wt.default.cyan("domani buy <domain>")}`),d();return}let n=[30,12,12,14];S(`Your Domains (${s.domains.length})`,n.reduce((o,a)=>o+a,0)+n.length-1);let r=s.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),l=o.status==="active"?wt.default.green:o.status==="pending"?wt.default.yellow:wt.default.red,f=o.autoRenew?wt.default.green("on"):wt.default.dim("off");return[v.domain(o.domain),l(o.status),f,wt.default.dim(a)]});B(["Domain","Status","Auto-renew","Expires"],r,n),d()}En();K();var Vt=D(M(),1);L();async function Eo(e){let t=new URLSearchParams;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");let i=C(!e.json);i.start("Loading TLDs");let s=await we(`/api/tlds?${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${n.total} TLDs loaded`),e.json){y(n,e.fields);return}let r=n.tlds;if(r.length===0){d(),console.log(` ${Vt.default.dim("No TLDs match your filters.")}`),d();return}S("TLD Pricing");let o=r.map(a=>[Vt.default.bold(`.${a.tld}`),v.price(a.registration.toFixed(2))+Vt.default.dim("/yr"),Vt.default.dim("renew ")+v.price(a.renewal.toFixed(2))+Vt.default.dim("/yr")]);B(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Vt.default.dim(`${n.total} TLDs total`)}`),d()}K();var Oe=D(M(),1);L();ye();async function To(e,t){Y(e,t);let i=C(!t.json);i.start(`Looking up ${v.domain(e)}`);let[s,n]=await Promise.all([we(`/api/domains/whois?q=${encodeURIComponent(e)}`),we(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await s.json(),o=null;try{n?.ok&&(o=await n.json())}catch{}if(s.ok||(i.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("WHOIS data retrieved"),t.json){y({...r,...o?{og:o}:{}},t.fields);return}if(S(`WHOIS ${v.domain(r.domain)}`),!r.registered){c("Status",`${w.success} ${Oe.default.green("not registered")}`),d(),R("Register it:",`domani buy ${r.domain}`),d();return}if(c("Status",`${w.error} ${Oe.default.red("registered")}`),(o?.title||o?.description)&&(d(),console.log(` ${Oe.default.bold("Website preview")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),o.title&&c("Title",o.title),o.description&&c("Description",Oe.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),d()),r.registrar&&c("Registrar",r.registrar),r.created&&c("Created",r.created),r.expires&&c("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,f=l<30?Oe.default.red:l<90?Oe.default.yellow:Oe.default.green;c("Days left",f(String(l)))}r.updated&&c("Updated",r.updated),c("DNSSEC",r.dnssec?Oe.default.green("yes"):Oe.default.dim("no")),r.nameservers?.length>0&&c("Nameservers",r.nameservers.map(l=>Oe.default.cyan(l)).join(Oe.default.dim(", "))),r.status?.length>0&&c("Status codes",Oe.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(d(),console.log(` ${Oe.default.bold("Registrant")}`),console.log(` ${Oe.default.dim("\u2500".repeat(50))}`),a.name&&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",Oe.default.dim("redacted (WHOIS privacy)")),d()}K();Ue();var vt=D(M(),1);L();ye();async function Po(e,t){if(!e){Se||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let h=await Te({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(de(h)||!h)&&process.exit(0),e=h}let i=new URLSearchParams({prompt:e});if(t.count&&i.set("count",t.count),t.tlds&&i.set("tlds",t.tlds),t.tlds&&ts(t.tlds.split(",").map(h=>h.trim()),t),t.style&&i.set("style",t.style),t.lang&&i.set("lang",t.lang),t.json){let h=C(!1);h.start("Finding available domains");let x=t.timeout?parseInt(t.timeout,10)*1e3:6e4,j;try{j=await we(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(x)})}catch{h.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 j.json();j.ok||(h.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:j.status,json:t.json,fields:t.fields})),y(O,t.fields);return}let s=C(!0);s.start("Finding available domains");let n=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await we(`/api/domains/suggest?${i}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{s.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){s.stop("Failed");try{let h=await r.json();u(h.error||h.message||`Server error (${r.status})`,{hint:h.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(s.stop("Failed"),u("Empty response"));let a=[],l=[],f=!1,m=0;function g(){f||(f=!0,s.stop("Finding available domains"),d())}let b=new TextDecoder,k="",$="";for await(let h of o){k+=b.decode(h,{stream:!0});let x=k.split(`
|
|
193
|
+
`);k=x.pop()??"";for(let j of x)if(j.startsWith("event: "))$=j.slice(7);else if(j.startsWith("data: "))try{let O=JSON.parse(j.slice(6));if($==="result")m++,O.available?a.push(O):l.push(O),f||s.message(`Finding available domains ${vt.default.dim(`(${m} checked, ${a.length} available)`)}`);else if($==="iteration")f||s.message(`Finding available domains ${vt.default.dim(`(round ${O.n})`)}`);else if($==="done"){g();for(let A of a){let V=A.reason?` ${vt.default.dim(A.reason)}`:"";console.log(` ${w.success} ${v.domain(A.domain).padEnd(37)} ${v.price(A.price)}${vt.default.dim("/yr")}${V}`)}for(let A of l)console.log(` ${w.error} ${vt.default.dim(A.domain.padEnd(38))} ${vt.default.red("taken")}`);console.log(` ${vt.default.dim("\u2500".repeat(50))}`),console.log(` ${vt.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else $==="error"&&(f||s.stop("Failed"),u(O.message))}catch{}}a.length===0&&l.length===0&&(f||s.stop("No results"),u("Could not find available domains for this prompt.")),d(),a.length>0&&(R("Register one:",`domani buy ${a[0].domain}`),d())}jn();Pn();K();Ue();var lt=D(M(),1);L();ye();ai();async function Do(e){let t=e.maxConsecutiveFailures??10,i=0;for(let s=1;s<=e.maxAttempts;s++){let n=await e.fetchPlan().catch(()=>null);if(e.onTick?.(n,s),n!==null){if(i=0,e.isEligible(n))return{status:"eligible",plan:n}}else if(i++,i>=t)return{status:"unreachable",failures:i};s<e.maxAttempts&&await e.sleep(e.intervalMs)}return{status:"timeout",attempts:e.maxAttempts}}var bi=D(M(),1);L();function wi(e){if(e){d(),console.log(` ${bi.default.bold(`Exit path (${e.managed_via})`)}`),console.log(` ${bi.default.dim("Unlock:")} ${e.unlock}`),console.log(` ${bi.default.dim("Auth code:")} ${e.auth_code}`);for(let t of e.notes||[])console.log(` ${bi.default.yellow("!")} ${t}`)}}var yc=6e4,bc=1440;async function No(e,t){Y(e,t);let i=C(!t.json);i.start(`Planning safe adoption for ${v.domain(e)}`);let s=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Check failed"),u(n.error,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),n.options?.transfer?.eligible)i.stop(`${w.success} Eligible for transfer`);else{i.stop(`${w.error} Not eligible`);let a=n.options?.transfer;if(t.watch&&a?.eligible_at){let l=await _("/api/domains/transfer-watch",{method:"POST",body:JSON.stringify({domain:e})}),f=await l.json();if(l.ok||u(f.error||f.message,{hint:f.hint,status:l.status,json:t.json,fields:t.fields}),t.json){y(f,t.fields);return}S("Transfer Watch Registered"),c("Domain",v.domain(e)),c("Eligible from",f.eligible_at||a.eligible_at),f.hint&&(d(),console.log(` ${lt.default.dim(f.hint)}`)),d();return}if(t.watch){t.json||(console.log(` ${lt.default.dim(a?.reason||"Domain is not eligible for transfer yet.")}`),wi(a?.guidance),d());let l=C(!t.json);l.start(`Watching ${v.domain(e)} until it becomes transferable (every 60s, Ctrl+C to stop)`);let f=await Do({fetchPlan:async()=>{let m=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`);return m.ok?m.json():null},isEligible:m=>!!m.options?.transfer?.eligible,sleep:m=>new Promise(g=>setTimeout(g,m)),intervalMs:yc,maxAttempts:bc});f.status!=="eligible"&&(l.stop(`${w.error} Watch ended`),u(f.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:f.status==="timeout"?"watch_timeout":"watch_unreachable",json:t.json,fields:t.fields})),n=f.plan,l.stop(`${w.success} Now eligible for transfer`)}else{t.json||wi(a?.guidance);let l=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.",f=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:[l+f,...n.warnings?.length?[n.warnings.join(" ")]:[]].join(" "),code:"not_eligible",json:t.json,fields:t.fields})}}if(t.dryRun)return G("transfer",{domain:e,eligible:!0,price:n.options.transfer.price,currency:n.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:n.current.nameservers,dns_provider:n.current.dns_provider,dnssec_enabled:n.current.dnssec_enabled},t.json,t.fields);if(!Ut(t)){S("Transfer Safety Plan"),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",`${n.current.nameservers.length} preserved`),c("DNSSEC",n.current.dnssec_enabled?lt.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),d();let a=n.options.transfer.price!=null?` for ${v.price(n.options.transfer.price.toFixed(2))}`:"",l=await Xe({message:`Transfer ${lt.default.bold(e)} to ${Gt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${lt.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}),n.options?.transfer?.guidance&&console.log(` ${lt.default.dim("Where to get it:")} ${n.options.transfer.guidance.auth_code}`);let a=await Te({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});de(a)&&process.exit(0),t.authCode=a}i.start(`Initiating transfer for ${v.domain(e)}`);let r=await _("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:e,auth_code:t.authCode})}),o=await r.json();if(r.ok||(i.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})),i.stop(`${w.success} Transfer initiated`),t.json){y(o,t.fields);return}S("Transfer Initiated"),c("Domain",v.domain(o.domain)),c("Status",lt.default.yellow(o.status||"pending")),o.price&&c("Price",v.price(o.price)+lt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&c("Payment",o.payment_method),o.expires&&c("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(d(),console.log(` ${lt.default.dim(o.hint)}`)),d(),R("Check transfer progress:",`domani status ${o.domain}`),d()}K();var vi=D(M(),1);L();ye();async function Uo(e,t){Y(e,t);let i=C(!t.json);i.start(`Inspecting ${v.domain(e)}`);let s=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Inspection failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Adoption plan ready`),t.json){y(n,t.fields);return}if(S(`Adopt ${v.domain(n.domain)}`),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",n.current.nameservers.join(", ")||"None detected"),c("DNSSEC",n.current.dnssec_enabled?vi.default.yellow("Enabled"):"Not enabled"),c("Account",n.account_state),c("Recommended",vi.default.cyan(n.recommended_action)),d(),n.recommended_action==="connect"&&R("Connect free, without changing registrar or DNS:",`domani import ${n.domain}`),n.options.transfer.available){let r=n.options.transfer.price==null?"price unavailable":`$${n.options.transfer.price.toFixed(2)} ${n.options.transfer.currency}`;R(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${n.domain}`),!n.options.transfer.eligible&&n.options.transfer.reason&&(console.log(` ${vi.default.yellow("!")} ${n.options.transfer.reason}`),R("Wait for eligibility and transfer in one go:",`domani transfer ${n.domain} --watch`)),wi(n.options.transfer.guidance)}for(let r of n.warnings||[])console.log(` ${vi.default.yellow("!")} ${r}`);d()}K();Ue();var ds=D(M(),1);L();ye();Ze();async function qo(e,t){e||(e=await pe()),Y(e,t);let i=t.years?parseInt(t.years,10):1;if((isNaN(i)||i<1||i>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return G("renew",{domain:e,years:i},t.json,t.fields);if(!Ut(t)){let o=await Xe({message:`Renew ${ds.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${ds.default.dim("Cancelled.")}`);return}}let s=C(!t.json);s.start(`Renewing ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:i})}),r=await n.json();if(n.ok||(s.stop("Renewal failed"),u(r.error||r.message,{hint:r.hint,fixUrl:r.setup_url||r.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})),s.stop(`${w.success} Domain renewed`),t.json){y(r,t.fields);return}S("Renewal Complete"),c("Domain",v.domain(r.domain)),c("Years",String(r.renewed_years)),c("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&c("Price",v.price(r.price)+ds.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&c("Payment",r.payment_method),d(),R("Verify renewal:",`domani status ${r.domain}`),d()}K();var dt=D(M(),1);L();ye();async function Fo(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
|
|
194
|
+
domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t);let i=t.verify?"/api/domains/import/verify":"/api/domains/import",s=C(!t.json);s.start(t.verify?`Verifying ownership of ${v.domain(e)}`:`Initiating import for ${v.domain(e)}`);let n=await _(i,{method:"POST",body:JSON.stringify({domain:e})}),r=await n.json();if(n.ok||(s.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),t.json){s.stop(""),y(r,t.fields);return}t.verify?(s.stop(`${w.success} ${v.domain(e)} imported!`),S("Domain Imported"),c("Domain",v.domain(r.domain)),c("Status",dt.default.green(r.status||"active")),r.expires_at&&c("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&c("Registrar",r.registrar),d(),R("Check domain health:",`domani status ${r.domain}`),d()):(s.stop(`${w.success} Verification record ready`),S("Import Domain"),c("Domain",v.domain(r.domain)),c("Status",dt.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${dt.default.dim("Type:")} ${dt.default.bold("TXT")}`),console.log(` ${dt.default.dim("Name:")} ${dt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${dt.default.dim("Value:")} ${dt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${dt.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),R("Once the record is set, verify:",`domani import ${e} --verify`),d())}In();gt();L();function Mo(e){let t=We();if(t||(d(),u("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:e.json})),!e.reveal&&!e.json&&process.stdout.isTTY){let i=`${t.slice(0,12)}...${t.slice(-4)}`;console.log(i),console.log("Run 'domani token --reveal' to print the full key.");return}e.json?y({token:t}):console.log(t)}K();var Fe=D(M(),1);L();async function Lo(e,t){switch(e){case void 0:case"list":return wc(t.json,t.fields);case"create":return vc(t);case"revoke":return $c(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function wc(e,t){let i=C(!e);i.start("Loading tokens");let s=await _("/api/tokens"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${w.success} ${n.tokens.length} token(s)`),e){y(n,t);return}if(n.tokens.length===0){d(),console.log(` ${Fe.default.dim("No tokens.")}`),d(),R("Create one:",'domani tokens create --name "My App"'),d();return}d(),S("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=Fe.default.red("Expired"):o.expiresAt?a=Fe.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Fe.default.dim("No expiration");let l=o.scopes.includes("*")?Fe.default.dim("all"):Fe.default.dim(o.scopes.join(", "));return[Fe.default.dim(o.id),Fe.default.bold(o.name),o.agent_identity?Fe.default.dim(o.agent_identity.name||o.agent_identity.slug):Fe.default.dim("\u2014"),l,a]});B(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),d()}async function vc(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 i=C(!e.json);i.start("Creating token");let s=await _("/api/tokens",{method:"POST",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Token created`),e.json){y(n,e.fields);return}d(),S("Token Created"),c("ID",n.id),c("Name",n.name),c("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),n.agent_identity&&c("Agent",n.agent_identity.name||n.agent_identity.slug),c("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),d(),console.log(` ${Fe.default.yellow("!")} ${Fe.default.bold("Key:")} ${n.key}`),console.log(` ${Fe.default.dim("Save this key - it will not be shown again.")}`),d()}async function $c(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
|
|
195
|
+
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 i=await _(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Token revoked`),e.json){y(s,e.fields);return}console.log(` ${Fe.default.dim("Any applications using this key will need a new one.")}`),d()}K();var Ie=D(M(),1);L();ye();Ze();async function Vo(e,t){e||(e=await pe()),Y(e,t);let i=t.autoRenew!==void 0,s=t.whoisPrivacy!==void 0,n=t.securityLock!==void 0;if(!i&&!s&&!n)return kc(e,t.json,t.fields);let r={};if(i){let f=Un(t.autoRenew);f===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=f}if(s){let f=Un(t.whoisPrivacy);f===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=f}if(n){let f=Un(t.securityLock);f===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=f}if(t.dryRun)return G("settings_update",{domain:e,...r},t.json,t.fields);let o=C(!t.json);o.start(`Updating ${v.domain(e)}`);let a=await _(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${w.success} Settings updated`),t.json){y(l,t.fields);return}S("Settings Updated"),c("Domain",v.domain(l.domain)),l.auto_renew!==void 0&&c("Auto-renew",l.auto_renew?Ie.default.green("on"):Ie.default.dim("off")),l.whois_privacy!==void 0&&c("WHOIS privacy",l.whois_privacy?Ie.default.green("on"):Ie.default.dim("off")),l.security_lock!==void 0&&c("Security lock",l.security_lock?Ie.default.green("locked"):Ie.default.dim("unlocked")),l.hint&&c("",Ie.default.dim(l.hint)),d()}async function kc(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${w.success} ${v.domain(e)}`),t){y(r,i);return}S("Domain Settings"),c("Domain",v.domain(r.domain)),c("Status",r.status==="active"?Ie.default.green(r.status):Ie.default.yellow(r.status)),c("Auto-renew",r.auto_renew?Ie.default.green("on"):Ie.default.dim("off")),r.registrar&&(c("WHOIS privacy",r.registrar.whois_privacy?Ie.default.green("on"):Ie.default.dim("off")),c("Security lock",r.registrar.security_lock?Ie.default.green("locked"):Ie.default.dim("unlocked"))),c("Expires",new Date(r.expires_at).toLocaleDateString()+Ie.default.dim(` (${r.days_until_expiry} days)`)),d(),R("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),R("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),R("Toggle security lock:",`domani settings ${e} --security-lock off`),R("Get transfer auth code:",`domani auth-code ${e}`),d()}function Un(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}K();var Wt=D(M(),1);L();ye();Ze();async function Wo(e,t){e||(e=await pe()),Y(e,t);let i=C(!t.json);i.start(`Getting auth code for ${v.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/auth-code`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Auth code retrieved`),t.json){y(n,t.fields);return}if(S("Auth Code"),c("Domain",v.domain(n.domain)),c("Auth code",Wt.default.bold(Wt.default.green(n.auth_code))),n.was_unlocked&&c("",Wt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${Wt.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${Wt.default.dim("\u2192")} ${Wt.default.dim(r)}`)}d(),R("Check transfer status:",`domani transfer-away ${e}`),R("Re-lock domain:",`domani settings ${e} --security-lock on`),d()}K();var $t=D(M(),1);L();ye();Ze();var _c={none:$t.default.dim,pending:$t.default.yellow,approved:$t.default.yellow,completed:$t.default.green,rejected:$t.default.red,expired:$t.default.red};async function Ho(e,t){e||(e=await pe()),Y(e,t);let i=C(!t.json);i.start(`Checking transfer status for ${v.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/transfer-away`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} ${v.domain(e)}`),t.json){y(n,t.fields);return}S("Transfer Away Status"),c("Domain",v.domain(n.domain));let r=_c[n.status]||$t.default.dim;c("Status",r(n.status)),n.gaining_registrar&&c("New registrar",n.gaining_registrar),n.request_date&&c("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(d(),console.log(` ${$t.default.dim(n.hint)}`)),d(),n.status==="none"?R("Get auth code to start:",`domani auth-code ${e}`):n.status==="pending"||n.status==="approved"?R("Check again later:",`domani transfer-away ${e}`):n.status==="completed"?R("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&R("Retry with a new auth code:",`domani auth-code ${e}`),d()}K();Ue();var cs=D(M(),1);L();async function Jo(e,t){return e==="set"?jc(t):xc(t)}async function xc(e){let t=C(!e.json);t.start("Loading contact info");let i=await _("/api/me/contact"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Contact info`),e.json){y(s,e.fields);return}if(S("Contact Info"),!s.has_contact){console.log(` ${w.warning} ${cs.default.yellow("No contact info set.")} Run ${cs.default.bold("domani contact set")} to add.`),d(),console.log(` ${cs.default.dim("Contact info is required before purchasing domains.")}`),d();return}let n=s.contact;c("Name",`${n.first_name} ${n.last_name}`),n.org_name&&c("Organization",n.org_name),c("Address",n.address1),n.address2&&c("",n.address2),c("",`${n.city}, ${n.state} ${n.postal_code}`),c("Country",n.country),c("Phone",n.phone),c("Email",n.email),d()}async function jc(e){let t={},i=e.firstName||e.lastName||e.address1;if(!Se&&!i&&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}),i){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},f=a.filter(m=>!e[m]);f.length>0&&u(`Missing required flags: ${f.map(m=>`--${m.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[m,g]of Object.entries(l)){let b=e[m];b&&(t[g]=b)}}else{let a=await _("/api/me/contact"),f=(a.ok?await a.json():null)?.contact,m=[{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 g of m){let b=f?.[g.key]||"",k=await Te({message:g.message,placeholder:g.placeholder,defaultValue:b,validate:g.required?h=>h?.trim()?void 0:`${g.message} is required`:void 0});de(k)&&process.exit(0);let $=k.trim();$&&(t[g.key]=$)}}if(e.dryRun)return G("contact_set",t,e.json,e.fields);let s=C(!e.json);s.start("Saving contact info");let n=await _("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${w.success} Contact info saved`),e.json){y(r,e.fields);return}S("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),d(),R("Search for a domain:","domani search <name>"),d()}K();var De=D(M(),1);L();ye();Ze();async function Ko(e,t,i,s){if(e||(e=await pe()),Y(e,s),!t)return Sc(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?G("parking_enable",{domain:e},s.json,s.fields):Bo(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?G("parking_disable",{domain:e},s.json,s.fields):Bo(e,!1,s.json,s.fields);case"price":{i||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:s.json,fields:s.fields});let n=parseFloat(i);return(isNaN(n)||n<=0)&&u("Price must be a positive number",{hint:`Got: "${i}"`,code:"validation_error",json:s.json,fields:s.fields}),s.dryRun?G("parking_price",{domain:e,price:n},s.json,s.fields):Go(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?G("parking_unlist",{domain:e},s.json,s.fields):Go(e,null,s.json,s.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:s.json,fields:s.fields})}}async function Sc(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${w.success} ${v.domain(e)}`),t){y({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}S("Parking"),c("Domain",v.domain(r.domain)),c("Parking",r.parking_enabled?De.default.green("enabled"):De.default.dim("disabled")),c("Listing",r.listing_price?`${v.price(r.listing_price)} ${De.default.dim("(for sale)")}`:De.default.dim("not listed")),d(),R("Enable parking:",`domani parking ${e} enable`),R("Set sale price:",`domani parking ${e} price 499`),R("View analytics:",`domani analytics ${e}`),d()}async function Bo(e,t,i,s){let n=C(!i);n.start(`${t?"Enabling":"Disabling"} parking for ${v.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(n.stop(`${w.warning} DNS records will be replaced`),i){y(o,s);return}console.log(`
|
|
196
|
+
${De.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${De.default.dim(a.type)} ${a.name} ${De.default.dim("\u2192")} ${a.value}`);console.log(`
|
|
197
|
+
${De.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${De.default.dim("Or use the dashboard to confirm.")}`),d();return}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${w.success} Parking ${t?"enabled":"disabled"}`),i){y(o,s);return}S("Parking Updated"),c("Domain",v.domain(o.domain)),c("Parking",o.parking_enabled?De.default.green("enabled"):De.default.dim("disabled")),o.hint&&c("",De.default.dim(o.hint)),d()}async function Go(e,t,i,s){let n=C(!i);n.start(t!==null?`Setting price for ${v.domain(e)} to ${v.price(t)}`:`Removing listing for ${v.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${w.success} ${t!==null?"Price set":"Listing removed"}`),i){y(o,s);return}S("Listing Updated"),c("Domain",v.domain(o.domain)),c("Listing",o.listing_price?`${v.price(o.listing_price)} ${De.default.dim("(for sale)")}`:De.default.dim("not listed")),o.hint&&c("",De.default.dim(o.hint)),d()}K();var Ke=D(M(),1);L();ye();Ze();var Cc=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Oc(e){let t=Math.max(...e,1);return e.map(i=>Cc[Math.min(Math.round(i/t*8),8)]).join("")}async function zo(e,t){e||(e=await pe()),Y(e,t);let i=C(!t.json);i.start(`Loading analytics for ${v.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/analytics`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("Analytics loaded"),t.json){y(n,t.fields);return}if(d(),S(`Analytics: ${v.domain(e)}`),c("Views (7d)",Ke.default.cyan(n.views_7d.toLocaleString())),c("Views (30d)",Ke.default.cyan(n.views_30d.toLocaleString())),c("Inquiries",Ke.default.cyan(String(n.inquiries_30d))),c("Conversion",n.conversion_rate>0?Ke.default.green(`${n.conversion_rate}%`):Ke.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(f=>f.views),o=Oc(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${Ke.default.dim(a)} ${Ke.default.cyan(o)} ${Ke.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${Ke.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[Ke.default.dim(o.email),o.offer?v.price(o.offer):Ke.default.dim("-"),Ke.default.dim(new Date(o.date).toLocaleDateString())]);B(["Email","Offer","Date"],r,[30,12,14])}d(),R("Set a listing price:",`domani parking ${e} price <amount>`),R("Set up email:",`domani email setup ${e}`),R("Domain settings:",`domani settings ${e}`),d()}K();var he=D(M(),1);L();is();async function Yo(e,t){switch(e){case void 0:case"list":return Rc(t.json,t.fields);case"create":return Ac(t);case"update":return Ec(t);case"delete":return Tc(t);case"deliveries":return Pc(t);case"replay":return Ic(t);case"events":return Dc(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 Ic(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 i=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Webhook replay ${s.status}`),e.json)return y(s,e.fields);S("Webhook Replay Receipt"),c("Delivery",s.delivery_id),c("Original",s.original_delivery_id),c("Status",s.status),c("Attempts",s.attempts),c("Idempotent retry",s.idempotent_replay?"yes":"no"),d()}async function Rc(e,t){let i=C(!e);i.start("Loading webhooks");let s=await _("/api/webhooks"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${w.success} ${n.webhooks.length} webhook(s)`),e){y(n,t);return}if(n.webhooks.length===0){d(),console.log(` ${he.default.dim("No webhooks configured.")}`),d(),R("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),R("List events:","domani webhooks events"),d();return}d(),S("Webhooks");let r=n.webhooks.map(o=>[he.default.dim(o.id),v.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||he.default.dim("none"),o.active?he.default.green("active"):he.default.dim("paused")]);B(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),d()}async function Ac(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
|
|
198
|
+
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()),i;try{i=Mt(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 G("webhook_create",{url:e.url,events:t,header_names:Lt(i)},e.json,e.fields);let s=C(!e.json);s.start("Creating webhook");let n=await _("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...i!==void 0?{headers:i}:{}})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${w.success} Webhook created`),e.json){y(r,e.fields);return}d(),S("Webhook Created"),c("ID",r.id),c("URL",v.url(r.url)),c("Events",r.events.join(", ")),c("Auth headers",r.header_names?.join(", ")||he.default.dim("none")),c("Status",he.default.green("active")),d(),console.log(` ${he.default.yellow("!")} ${he.default.bold("Secret:")} ${r.secret}`),console.log(` ${he.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${he.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),d()}async function Ec(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=Mt(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 G("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:Lt(r)}:{}},e.json,e.fields)}let i=C(!e.json);i.start("Updating webhook");let s=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Webhook updated`),e.json){y(n,e.fields);return}S("Webhook Updated"),c("ID",n.id),c("URL",v.url(n.url)),c("Events",n.events.join(", ")),c("Auth headers",n.header_names?.join(", ")||he.default.dim("none")),c("Status",n.active?he.default.green("active"):he.default.dim("paused")),d()}async function Tc(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 G("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=C(!e.json);t.start("Deleting webhook");let i=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Webhook deleted`),e.json){y(s,e.fields);return}console.log(` ${he.default.dim("Pending deliveries have been cancelled.")}`),d()}async function Pc(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}`:"",i=C(!e.json);i.start("Loading deliveries");let s=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} ${n.deliveries.length} delivery(ies)`),e.json){y(n,e.fields);return}if(n.deliveries.length===0){d(),console.log(` ${he.default.dim("No deliveries yet.")}`),d();return}d(),S("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?he.default.green("delivered"):o.status==="failed"?he.default.red("failed"):he.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):he.default.dim("-"),String(o.attempts),he.default.dim(new Date(o.created_at).toLocaleString())]});B(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),d()}async function Dc(e,t){let i=C(!e);i.start("Loading event types");let s=await we("/api/webhooks/events"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${w.success} ${n.events.length} event type(s)`),e){y(n,t);return}d(),S("Webhook Event Types");let r=n.events.map(o=>[he.default.cyan(o.type),he.default.dim(o.description)]);B(["Event","Description"],r,[24,50]),d()}K();var $e=D(M(),1);L();ye();async function Xo(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
|
|
198
199
|
domani sell <domain> --verify
|
|
199
200
|
domani sell <domain> --status
|
|
200
|
-
domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),
|
|
201
|
+
domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t),t.status)return qc(e,t);if(t.verify)return Uc(e,t);if(t.cancel)return Fc(e,t);if(t.transferCode)return Mc(e,t.transferCode,t);if(t.price)return Nc(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
|
|
201
202
|
domani sell <domain> --verify
|
|
202
203
|
domani sell <domain> --status
|
|
203
204
|
domani sell <domain> --cancel
|
|
204
|
-
domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function
|
|
205
|
-
Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:i.json,fields:i.fields}));let l=a[0].id;s.message(`Submitting transfer code for deal ${$e.default.dim(l)}`);let f=await x(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),m=await f.json();if(f.ok||(s.stop("Failed"),u(m.error||m.message,{hint:m.hint,status:f.status,json:i.json,fields:i.fields})),i.json){s.stop(""),w(m,i.fields);return}s.stop(`${b.success} Transfer code submitted for ${v.domain(e)}`),S("Transfer Code Submitted"),c("Domain",v.domain(e)),c("Deal",$e.default.dim(l)),c("Status",$e.default.green(m.status||"code_submitted")),d(),I("Track the deal:",`domani deals ${l}`),d()}G();var ke=D(M(),1);V();async function Ko(e,t){return e?Ac(e,t):Rc(t)}async function Rc(e){let t=C(!e.json);t.start("Loading deals");let i=new URLSearchParams;e.role&&i.set("role",e.role),e.status&&i.set("status",e.status);let s=i.toString()?`?${i.toString()}`:"",n=await x(`/api/deals${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.deals||r.data||[];if(t.stop(`${b.success} ${o.length} deal(s)`),e.json){w(r,e.fields);return}if(o.length===0){d(),console.log(` ${ke.default.dim("No deals found.")}`),d(),I("List a domain for sale:","domani sell <domain> --price <amount>"),d();return}d(),S("Deals");let a=o.map(l=>{let f=l.status==="completed"?ke.default.green:l.status==="active"?ke.default.cyan:l.status==="cancelled"?ke.default.red:ke.default.yellow;return[v.domain(l.domain),v.price(l.price),f(l.status),ke.default.dim(l.role||"-"),ke.default.dim(new Date(l.created_at).toLocaleDateString())]});Z(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function Ac(e,t){let i=C(!t.json);i.start(`Loading deal ${ke.default.dim(e)}`);let s=await x(`/api/deals/${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${b.success} Deal loaded`),t.json){w(n,t.fields);return}let r=n.deal||n;S("Deal Details"),c("ID",ke.default.dim(r.id)),c("Domain",v.domain(r.domain)),c("Price",v.price(r.price));let o=r.status==="completed"?ke.default.green:r.status==="active"?ke.default.cyan:r.status==="cancelled"?ke.default.red:ke.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",ke.default.dim(r.buyer)),r.seller&&c("Seller",ke.default.dim(r.seller)),r.created_at&&c("Created",ke.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",ke.default.dim(new Date(r.updated_at).toLocaleDateString())),d();let a=r.events||[];if(a.length>0){S("Timeline");for(let l of a){let f=ke.default.dim(new Date(l.created_at).toLocaleString()),m=l.status==="completed"?b.success:l.status==="expired"||l.status==="refunded"?b.error:b.info;console.log(` ${m} ${f} ${l.detail||l.status}`)}d()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),d())}G();var Fe=D(M(),1);V();ge();async function Xo(e,t,i){switch(e){case void 0:case"list":case"ls":return Ec(i);case"request":case"acquire":case"new":return zo(t,i);case"status":case"get":return Yo(t,i);case"cancel":case"rm":return Tc(t,i);default:return e.includes(".")?zo(e,i):Yo(e,i)}}async function zo(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),z(e,{json:t.json});let i=C(!t.json);i.start(`Requesting acquisition of ${v.domain(e)}`);let s={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}),s.max_budget=a}let n=await x("/api/broker",{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${b.success} Acquisition requested`),t.json)return w(r,t.fields);S("Broker request"),c("Domain",v.domain(o.domain)),c("Status",Pn(o.status)),o.max_budget!=null&&c("Max budget",v.price(o.max_budget)),c("ID",Fe.default.dim(o.id)),d(),console.log(` ${Fe.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),d(),I("Check progress:",`domani broker status ${o.id}`),d()}async function Ec(e){let t=C(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",s=await x(`/api/broker${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.requests||n.data||[];if(t.stop(`${b.success} ${r.length} request(s)`),e.json)return w(n,e.fields);if(r.length===0){d(),console.log(` ${Fe.default.dim("No broker requests yet.")}`),d(),I("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),d();return}d(),S("Broker requests"),Z(["Domain","Status","Budget","ID"],r.map(o=>[v.domain(o.domain),Pn(o.status),o.max_budget!=null?v.price(o.max_budget):Fe.default.dim("-"),Fe.default.dim(o.id)])),d()}async function Yo(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=C(!t.json);i.start("Loading request");let s=await x(`/api/broker/${encodeURIComponent(e)}`),n=await s.json();s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields}));let r=n.request||n;if(i.stop(`${b.success} ${v.domain(r.domain)}`),t.json)return w(n,t.fields);S("Broker request"),c("Domain",v.domain(r.domain)),c("Status",Pn(r.status)),r.max_budget!=null&&c("Max budget",v.price(r.max_budget)),c("Contacted",r.contacted?Fe.default.green("yes"):Fe.default.dim("not yet")),r.failure_reason&&c("Reason",Fe.default.yellow(r.failure_reason)),c("ID",Fe.default.dim(r.id)),d(),r.negotiation_id?(console.log(` ${Fe.default.dim("The owner responded - an anonymous negotiation is open.")}`),d(),I("Review the offer:","domani deals"),d()):["sourcing","contacted","negotiating"].includes(r.status)&&(I("Cancel this request:",`domani broker cancel ${r.id}`),d())}async function Tc(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=C(!t.json);i.start("Cancelling request");let s=await x(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${b.success} Request cancelled`),t.json)return w(n,t.fields);d()}function Pn(e){return["completed","agreed"].includes(e)?Fe.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Fe.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Fe.default.dim(e):e}G();var ye=D(M(),1);V();async function Qo(e){return e.read?Dc(e):Pc(e)}async function Pc(e){let t=C(!e.json);t.start("Loading notifications");let i=new URLSearchParams;e.unread&&i.set("unread","true"),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i.toString()}`:"",n=await x(`/api/notifications${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(f=>!f.read).length;if(t.stop(`${b.success} ${o.length} notification(s)${a>0?` ${b.dot} ${ye.default.yellow(`${a} unread`)}`:""}`),e.json){w(r,e.fields);return}if(o.length===0){d(),console.log(` ${ye.default.dim("No notifications.")}`),d();return}d(),S("Notifications");let l=o.map(f=>{let m=f.read?ye.default.dim(b.dot):ye.default.cyan(b.info),g=Nc(f.type),y=f.read?ye.default.dim(f.title):ye.default.white(f.title),k=f.body?f.read?ye.default.dim(Zo(f.body,40)):ye.default.dim(Zo(f.body,40)):ye.default.dim("-"),$=ye.default.dim(new Date(f.created_at).toLocaleDateString());return[m,g,y,k,$]});Z(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${ye.default.dim("Mark all as read:")} ${ye.default.cyan("domani notifications --read")}`),d())}async function Dc(e){let t=C(!e.json);t.start("Marking all notifications as read");let i=await x("/api/notifications/read-all",{method:"POST"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),w(s,e.fields);return}let n=s.count??0;t.stop(`${b.success} ${n} notification(s) marked as read`),d()}function Nc(e){let t={deal:ye.default.cyan,sale:ye.default.green,purchase:ye.default.green,transfer:ye.default.yellow,expiry:ye.default.red,security:ye.default.red,billing:ye.default.yellow,email:ye.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||ye.default.dim)(e)}function Zo(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}G();var Ct=D(M(),1);V();async function ea(e){let t=e.limit?Number(e.limit):20,i=await x(`/api/billing/invoices?limit=${t}`),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){w({...s,count:s.invoices.length},e.fields);return}if(s.invoices.length===0){console.log(` ${Ct.default.dim("No invoices yet.")}`);return}S(`Invoices (${s.invoices.length})`),d();for(let n of s.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${b.success} ${Ct.default.bold(a)} ${Ct.default.green(r)} ${Ct.default.dim(o)}`),n.description&&console.log(` ${Ct.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${Ct.default.dim(n.hosted_invoice_url)}`)}d(),s.has_more&&(console.log(` ${Ct.default.dim(`Showing ${s.invoices.length} most recent. Use --limit to see more.`)}`),d())}G();var wi=D(M(),1);V();async function ta(e){let t=C(!e?.json);t.start("Setting up billing session");let i=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.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){w({url:s.url});return}d(),console.log(` ${wi.default.dim("Opening browser")} ${b.arrow} ${v.url(s.url)}`),d(),Je(s.url),console.log(` ${b.info} ${wi.default.dim("Complete payment setup in your browser.")}`),console.log(` ${wi.default.dim(" After setup, you can purchase domains with")} ${wi.default.cyan("domani buy")}`),d()}G();var Dn=D(M(),1);V();async function ia(e){let t=C(!e?.json);t.start("Creating upgrade session");let i=await x("/api/billing/subscribe",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="ALREADY_SUBSCRIBED"||s.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Ready"),e?.json){w({url:s.url},e?.fields);return}d(),console.log(` ${Dn.default.dim("Opening browser")} ${b.arrow} ${v.url(s.url)}`),d(),Je(s.url),console.log(` ${b.info} ${Dn.default.dim("Complete your plan upgrade in the browser.")}`),d()}G();var Nn=D(M(),1);V();async function sa(e){let t=C(!e?.json);t.start("Cancelling subscription");let i=await x("/api/billing/cancel",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="NOT_PAID"||s.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Done"),e?.json){w(s,e?.fields);return}d();let n=s.cancel_at?new Date(s.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${b.success} ${Nn.default.dim("Subscription cancelled.")} Access continues until ${Nn.default.cyan(n)}.`),d()}G();var st=D(M(),1);V();ge();Ze();async function na(e,t,i){e||(e=await fe()),z(e,i);let s=[];if(t?.length&&s.push(...t),i.set&&s.push(...i.set.split(",").map(n=>n.trim()).filter(Boolean)),s.length>0||i.reset){await qc(e,s,i);return}await Uc(e,i)}async function Uc(e,t){let i=C(!t.json);i.start(`Fetching nameservers for ${v.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${v.domain(e)}`),t.json){w(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${b.warning} ${st.default.yellow("No nameservers configured.")}`),console.log(` ${st.default.dim("DNS operations (parking, email, connect) will not work.")}`),d(),I("Set default nameservers:",`domani nameservers ${e} --reset`);else{S("Nameservers");for(let r of n.nameservers)console.log(` ${b.success} ${st.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(d(),console.log(` ${st.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(d(),c("Defaults",n.default_nameservers.map(r=>st.default.dim(r)).join(st.default.dim(", ")))),d()}async function qc(e,t,i){let s=C(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${v.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(s.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(s.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:i.json,fields:i.fields})),t=a.default_nameservers,s.stop(`Using defaults: ${t.map(l=>st.default.cyan(l)).join(st.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:i.json,fields:i.fields}),i.dryRun)return B("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);s.start(`Setting nameservers for ${v.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields})),s.stop(`${b.success} Nameservers updated`),i.json){w(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${b.success} ${st.default.cyan(o)}`);d(),console.log(` ${st.default.dim("Changes may take up to 48 hours to propagate.")}`),d(),I("Check propagation:",`domani status ${e}`),d()}var ra=require("crypto"),ls=D(require("fs"),1);gt();var vi=D(M(),1);V();function Fc(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function oa(e){let t=!!e?.json,i=C(!t);i.start("Checking for updates");let s=Le();try{let n=await fetch(`${s}/api/cli/version`);n.ok||(i.stop("Failed"),u("Could not check for updates"));let r=await n.json(),o=r.version,a=r.sha256;if(Fc(o,xe)<=0){i.stop(`${b.success} Already up to date (v${xe})`),t&&w({current:xe,latest:o,up_to_date:!0});return}if(t&&!e?.yes){i.stop(""),w({current:xe,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}i.stop(t?"":`New version available: ${vi.default.cyan(xe)} ${b.arrow} ${vi.default.green(o)}`);let l=C(!t);l.start("Downloading update");let f=`${s}/cli/domani.js`,m=await fetch(f);m.ok||(l.stop("Download failed"),u(`Failed to download from ${f}`));let g=await m.text();a&&(0,ra.createHash)("sha256").update(g).digest("hex")!==a&&(l.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let y=process.argv[1];y||(l.stop("Failed"),u("Could not determine binary path"));let k=ls.default.realpathSync(y),$=k+".tmp";if(ls.default.writeFileSync($,g,{mode:493}),ls.default.renameSync($,k),l.stop(`${b.success} Updated to v${o}`),t){w({updated:!0,from:xe,to:o});return}d(),console.log(` ${vi.default.dim("Restart your terminal or run")} domani --version ${vi.default.dim("to verify")}`),d()}catch(n){u(`Update failed: ${n instanceof Error?n.message:String(n)}`)}}var ds=D(require("fs"),1),aa=D(require("path"),1),la=D(require("os"),1);Ne();var $i=D(M(),1);V();async function da(){let e=process.argv[1],t=e?ds.default.realpathSync(e):null,i=aa.default.join(la.default.homedir(),".domani");if(d(),console.log(` ${$i.default.bold("This will remove:")}`),t&&console.log(` ${b.dot} CLI binary: ${$i.default.dim(t)}`),console.log(` ${b.dot} Config dir: ${$i.default.dim(i)}`),d(),await Ye({message:"Uninstall domani?"})!==!0){console.log(` ${$i.default.dim("Cancelled.")}`);return}ds.default.rmSync(i,{recursive:!0,force:!0}),t&&ds.default.unlinkSync(t),d(),console.log(` ${b.success} domani uninstalled.`),d()}G();var re=D(M(),1);V();async function ua(e,t){let i=t?.json,s=t?.fields,n=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=C(!i);r.start("Loading schema");let o=await we(n),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:s})),r.stop("Schema loaded"),i){w(a,s);return}e?Lc(e,a):Mc(a.commands)}function Mc(e){S("Commands");let t=Object.entries(e).map(([i,s])=>[re.default.bold(re.default.cyan(i)),s.description]);Z(["Command","Description"],t,[20,50]),d(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),d()}function Lc(e,t){if(S(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${v.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){d(),console.log(` ${re.default.bold("Arguments")}`);for(let[i,s]of Object.entries(t.arguments)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type}${s.variadic?", variadic":""})`);console.log(` ${re.default.cyan(i)}${n} ${r}`),s.description&&console.log(` ${re.default.dim(s.description)}`)}}if(t.options&&Object.keys(t.options).length>0){d(),console.log(` ${re.default.bold("Options")}`);for(let[i,s]of Object.entries(t.options)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type})`),o=s.choices?re.default.dim(` [${s.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${i}`)}${n} ${r}${o}`),console.log(` ${re.default.dim(s.description)}`)}}if(t.api)if(d(),console.log(` ${re.default.bold("API")}`),Vc(t.api))ca(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),ca(s,6);t.errors&&t.errors.length>0&&(d(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>re.default.dim(i)).join(re.default.dim(", "))}`)),d()}function Vc(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function ca(e,t=4){let i=" ".repeat(t);if(console.log(`${i}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[s,n]of Object.entries(e.parameters)){let r=n.required?re.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${i} ${re.default.cyan(s)}${r} ${a}`),n.description&&console.log(`${i} ${re.default.dim(n.description)}`)}}G();var Me=D(M(),1);Ne();V();async function ma(e){let t=C(!e.json);t.start("Loading payment method");let i=await x("/api/me"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),w(s.card?{has_payment_method:s.has_payment_method,card:s.card}:{has_payment_method:!1},e.fields);return}if(!s.has_payment_method||!s.card){t.stop("No payment method on file"),d(),console.log(` ${Me.default.dim("Add a card with")} ${Me.default.cyan("domani card add")}`),d();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=s.card,l=`${String(o).padStart(2,"0")}/${a}`,f=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),S("Payment method"),c("Card",`${Me.default.bold(f)} \u2022\u2022\u2022\u2022 ${Me.default.bold(r)}`),c("Expires",l),d(),console.log(` ${Me.default.dim("Update with")} ${Me.default.cyan("domani card add")}`),d()}async function fa(e){let t=C(!e?.json);t.start("Setting up payment session");let i=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){w({url:s.url},e?.fields);return}d(),console.log(` ${Me.default.dim("Opening browser")} ${b.arrow} ${v.url(s.url)}`),d(),Je(s.url),console.log(` ${b.info} ${Me.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Me.default.dim(" After setup, you can purchase domains with")} ${Me.default.cyan("domani buy")}`),d()}async function pa(e){if(!e?.yes&&!e?.json){let n=await Ye({message:"Remove your saved payment method?"});if(le(n)||!n){console.log(` ${Me.default.dim("Cancelled.")}`);return}}let t=C(!e?.json);t.start("Removing payment method");let i=await x("/api/billing/card",{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),t.stop(`${b.success} Payment method removed`),e?.json){w({removed:!0},e?.fields);return}d(),console.log(` ${Me.default.dim("Add a new card with")} ${Me.default.cyan("domani card add")}`),d()}var Un=D(M(),1);G();V();async function me(e,t,i,s){let n=C(!i.json);n.start(s);let r=await x(e,t),o=await r.json();return r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop(`${b.success} Done`),o}async function ha(e,t){if(!e||e==="list"){let i=await me("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return w(i,t.fields);if(d(),S("Workspaces"),!i.workspaces.length){console.log(` ${Un.default.dim("No workspaces yet.")}`),I("Create one:","domani workspace create --name Acme");return}Z(["ID","Name","Role","Mailboxes","Members"],i.workspaces.map(s=>[s.id,s.name,s.role,String(s.mailbox_count),String(s.member_count)]),[28,28,10,10,8]),d();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let i=await me("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return w(i,t.fields);d(),S("Workspace Created"),c("ID",i.id),c("Name",i.name),d();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return w(i,t.fields);d(),S(i.name),c("Role",i.role),c("Mailboxes",i.mailboxes.length),c("Members",i.members.length),d(),Z(["Email","Role","Mailbox grants"],i.members.map(s=>[s.email,s.role,String(s.mailbox_grants.length)]),[42,12,16]),d();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 me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return w(a,t.fields);d(),S("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),d();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[i,s]=t.subject.split(":",2),[n,r]=t.resource.split(":",2);(!s||!["human","agent","service","token","group"].includes(i))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(n))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:i==="group"?{type:"group",id:s}:{type:"principal",principal:{type:i,id:s}},resource:{type:n,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 w(o,t.fields);d(),S(t.apply?"Access Applied":"Access Plan"),c("Action",o.action),c("Changed",String(o.changed)),o.grant_id&&c("Grant",o.grant_id),d();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 i=(t.principals||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let[r,o]=n.split(":",2);return o||u(`Invalid principal: ${n}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:i})},t,"Syncing access group");if(t.json)return w(s,t.fields);d(),S("Access Group Synced"),c("ID",s.id),c("Principals",s.principal_count),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return w(i,t.fields);d(),S("Mailbox Collection Synced"),c("ID",i.id),c("Mailboxes",i.mailbox_count),d();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 i=(t.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>({resource:{type:"mailbox",id:n},profile:t.profile||"responder"})),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:i,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return w(s,t.fields);d(),S("Access Offered"),c("Email",s.email),c("Expires",s.expires_at),d();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 i=await me("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return w(i,t.fields);d(),S("Access Accepted"),c("Workspace",i.workspace_name),c("Ownership",i.ownership),d();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 i=await me(`/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 w(i,t.fields);d(),S("Access Revoked"),c("Grant",i.grant_id),c("Version",i.version),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return w(i,t.fields);d(),S("Workspace Renamed"),c("ID",i.id),c("Name",i.name),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return w(i,t.fields);d(),S("Invitation Sent"),c("Email",i.email),c("Role",i.role),c("Expires",i.expires_at),d();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return w(i,t.fields);d(),S("Workspace Joined"),c("Workspace",i.workspace_name),c("Role",i.role),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return w(i,t.fields);d(),S("Invitation Revoked"),c("Invitation",i.invitation_id),d();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 i=await me(`/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 w(i,t.fields);d(),S("Member Updated"),c("Membership",i.id),c("Role",i.role),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return w(i,t.fields);d(),S("Member Removed"),c("Membership",i.membership_id),d();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return w(i,t.fields);d(),S("Workspace Left"),c("Workspace",i.workspace_id),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return w(i,t.fields);d(),S("Ownership Transfer Requested"),c("To",i.to_email),c("Expires",i.expires_at),c("Billing",i.billing),d();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 i=await me("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return w(i,t.fields);d(),S("Ownership Transferred"),c("Workspace",i.workspace_id),c("Domains",i.domains_transferred),c("Mailboxes",i.mailboxes_transferred),c("Previous owner",i.previous_owner_role),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return w(i,t.fields);d(),S("Ownership Transfer Revoked"),c("Transfer",i.transfer_id),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return w(i,t.fields);d(),S(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),c("Address",i.address),c("Mailboxes",i.mailbox_ids?.length??1),d();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 i=await me(`/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 w(i,t.fields);d(),S("Mailbox Access Granted"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),c("Role",i.role),d();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 i=await me(`/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 w(i,t.fields);d(),S("Mailbox Access Revoked"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),d();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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return w(i,t.fields);d(),S("Workspace Checkout"),c("Plan",i.plan),c("URL",i.url),d(),i.url&&t.open!==!1&&(console.log(` ${Un.default.dim("Opening browser")} ${b.arrow} ${v.url(i.url)}`),Je(i.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 i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return w(i,t.fields);d(),S("Cancellation Scheduled"),c("Message",i.message),i.cancel_at&&c("Cancels",i.cancel_at),d();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 fs=D(M(),1);G();var cs=D(require("node:crypto"),1),ii=D(require("node:fs"),1),ga=D(require("node:os"),1),us=D(require("node:path"),1),Wc=process.env.DOMANI_CONFIG_DIR||us.default.join(ga.default.homedir(),".domani"),ya=us.default.join(Wc,"mutations");function Hc(e){return us.default.join(ya,`${cs.default.createHash("sha256").update(e).digest("hex")}.json`)}function ct(e,t,i){let s=Hc(e),n=cs.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!i)try{let o=JSON.parse(ii.default.readFileSync(s,"utf8"));if(o.key&&o.fingerprint===n)return{key:o.key,complete:()=>{try{ii.default.unlinkSync(s)}catch{}}}}catch{}let r=i||`cli-${cs.default.randomUUID()}`;return ii.default.mkdirSync(ya,{recursive:!0,mode:448}),ii.default.writeFileSync(s,JSON.stringify({key:r,fingerprint:n}),{mode:384}),{key:r,complete:()=>{try{ii.default.unlinkSync(s)}catch{}}}}V();function ba(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[i,s]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!s)continue;let n=process.env[s];n||u(`Environment variable ${s} is empty`,{code:"validation_error",json:e.json}),t[i]=n}return Object.keys(t).length?t:void 0}async function Wt(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}function ms(e,t){if(t.json)return w(e,t.fields);let i=e.http_route||e;d(),S("HTTP Route"),c("ID",i.id),c("URL",i.url),c("Upstream",i.upstream),c("Status",i.status),c("Expires",i.expires_at),c("Browser mode",i.browser_mode||"stateless"),i.upstream_verification?.secret&&(c("Verification secret",fs.default.yellow(i.upstream_verification.secret)),console.log(fs.default.dim(" Save this secret now. It will not be shown again after this receipt."))),d()}async function wa(e,t,i){if(!e||e==="list"){let s=new URLSearchParams;i.domain&&s.set("domain",i.domain),i.hostname&&s.set("hostname",i.hostname),i.status&&s.set("status",i.status);let n=await Wt(await x(`/api/http-routes${s.size?`?${s}`:""}`),i);if(i.json)return w(n,i.fields);d(),S("HTTP Routes");for(let r of n.http_routes)console.log(` ${fs.default.dim(r.id)} ${r.hostname} ${r.status} ${r.upstream}`);d();return}if(e==="create"){i.upstream||u("--upstream is required",{code:"validation_error",json:i.json});let s=ba(i),n={...i.hostname?{hostname:i.hostname}:{},upstream:i.upstream,...i.expiresIn?{expires_in:Number(i.expiresIn)}:{},...i.hostHeader?{host_header:i.hostHeader}:{},...i.upstreamVerification?{upstream_verification:i.upstreamVerification}:{},...s?{upstream_headers:s}:{}},r=ct(`route:create:${i.hostname||"auto"}`,n,i.idempotencyKey),o=C(!i.json);o.start("Creating HTTP route");let a=await Wt(await x("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(n)}),i);return r.complete(),o.stop(`${b.success} HTTP route created`),ms(a,i)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:i.json}),e==="get")return ms(await Wt(await x(`/api/http-routes/${encodeURIComponent(t)}`),i),i);if(e==="delete"){let s=await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(s.ok||await Wt(s,i),i.json)return w({deleted:!0,id:t},i.fields);console.log(`${b.success} HTTP route deleted`);return}if(e==="refresh"){i.expiresIn||u("--expires-in is required",{code:"validation_error",json:i.json});let s={expires_in:Number(i.expiresIn)},n=ct(`route:refresh:${t}`,s,i.idempotencyKey),r=await Wt(await x(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":n.key},body:JSON.stringify(s)}),i);return n.complete(),ms(r,i)}if(e==="rotate-verification"){let s=ct(`route:rotate-verification:${t}`,{},i.idempotencyKey),n=await Wt(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":s.key}}),i);return s.complete(),i.json?w(n,i.fields):ms(n,i)}if(e==="rotate-headers"){let s=ba(i);s||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:i.json});let n=ct(`route:rotate-headers:${t}`,{upstream_headers:s},i.idempotencyKey),r=await Wt(await x(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":n.key},body:JSON.stringify({upstream_headers:s})}),i);if(n.complete(),i.json)return w(r,i.fields);console.log(`${b.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:i.json})}var he=D(M(),1),ka=require("node:fs");G();V();var qn="mailzero-personal-ai.v1",be=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="AssistantUsageError"}},Jc={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct"},Bc=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","plan","activity","export","delete"];function va(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function ki(e,t,i){let s=Number(e);if(!Number.isInteger(s)||s<i)throw new be(`${t} must be an integer of at least ${i}`);return s}function Gc(e,t,i){let s=e||"today";switch(s){case"today":return{method:"GET",path:"/api/assistant/today"};case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let n={};if(i.enable&&i.disable)throw new be("Use either --enable or --disable");if(i.pause&&i.resume)throw new be("Use either --pause or --resume");if(i.enable&&(n.enabled=!0),i.disable&&(n.enabled=!1),i.shadow!==void 0&&(n.shadow_enabled=i.shadow),i.pause&&(n.paused=!0),i.resume&&(n.paused=!1),i.none?n.mailbox_ids=[]:i.mailboxes!==void 0&&(n.mailbox_ids=va(i.mailboxes)),i.days!==void 0&&(n.history_window_days=ki(i.days,"--days",1)),i.attachmentVision!==void 0){if(!["on","off"].includes(i.attachmentVision))throw new be("--attachment-vision must be on or off");n.attachment_vision=i.attachmentVision==="on"}if(!Object.keys(n).length)throw new be("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:n}}case"preview":{if(!i.consent)throw new be("--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 ${qn}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let n=va(i.mailboxes);if(!n.length)throw new be("--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:n,history_window_days:i.days===void 0?30:ki(i.days,"--days",1),consent:!0,consent_version:qn}}}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 be("Work item ID is required","Usage: domani assistant item <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}`};case"plan":if(!t)throw new be("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${i.limit!==void 0?`?limit=${ki(i.limit,"--limit",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!i.yes)throw new be("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"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":{if(!t)throw new be("Work item ID is required",`Usage: domani assistant ${s} <id> --item-version <work_item_version>`);if(i.itemVersion===void 0)throw new be("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let n=Jc[s],r={type:n,work_item_version:ki(i.itemVersion,"--item-version",1)};if(n==="ignore"&&i.scope){if(!["item","sender","sender_domain","situation"].includes(i.scope))throw new be("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=i.scope}if(n==="choose"){if(!i.option||!i.decision||i.decisionVersion===void 0)throw new be("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=i.decision,r.decision_version=ki(i.decisionVersion,"--decision-version",1),r.option_id=i.option}if(n==="instruct"){if(!i.text)throw new be("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=i.text}if(n==="snooze"){if(!i.until)throw new be("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=i.until}if(n==="correct"){if(!i.field||!i.text)throw new be("--field and --text are required","Name the analysis field to correct and the correct value");r.field=i.field,r.correction=i.text}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${n}:${t}`}}default:throw new be(`Unknown action: ${s}`,`Actions: ${Bc.join(", ")}`)}}async function Kc(e,t){let i=await e.json();if(e.ok)return i;i.code==="NOT_AVAILABLE"&&u("The Mailzero 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}),i.code==="INSUFFICIENT_SCOPE"&&u(i.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(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields})}function zc(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",i=e.recurrence?.count&&e.recurrence.count>1?he.default.dim(`x${e.recurrence.count}`):"";return[he.default.dim(e.id),t,`${(e.title||e.summary||"").slice(0,60)} ${i}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function Yc(e,t){if(t.json)return w(e,t.fields);d(),S("Today");let i=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],s=0;for(let[r,o]of i){let a=e.sections&&typeof e.sections=="object"?e.sections:e,l=Array.isArray(a[r])?a[r]:[];l.length&&(s+=l.length,console.log(` ${he.default.bold(o)} ${he.default.dim(`(${l.length})`)}`),Z(["ID","Who","Summary","Deadline"],l.map(zc)),d())}s||console.log(he.default.dim(" Nothing needs you right now."));let n=typeof e.as_of=="string"?e.as_of:void 0;n&&console.log(he.default.dim(` As of ${n}`)),d()}function $a(e,t){if(t.json)return w(e,t.fields);let i=e.work_item||e;if(d(),S("Work item"),c("ID",i.id),c("Version",String(i.version??"")),c("Status",i.status||""),c("Mailbox",i.mailbox?.name?`${i.mailbox.name} <${i.mailbox.address||""}>`:i.mailbox?.address||""),i.title&&c("Title",i.title),i.sender?.address&&c("From",`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>${i.sender.kind&&i.sender.kind!=="human"?` (${i.sender.kind})`:""}`),i.ask&&c("Ask",i.ask),i.recurrence?.count&&i.recurrence.count>1&&c("Recurrence",`${i.recurrence.count} messages since ${(i.recurrence.first_seen_at||"").slice(0,10)}`),c("Summary",i.summary||""),i.attention?.reason&&c("Why",i.attention.reason),i.attention?.deadline&&c("Deadline",i.attention.deadline),i.source?.event_id&&c("Source",`${i.source.type||"mail"} ${i.source.event_id}`),i.decision?.options?.length){d(),console.log(` ${he.default.bold("Decision")} ${he.default.dim(`${i.decision.id} v${i.decision.version??1}`)}`);for(let s of i.decision.options)console.log(` ${he.default.dim(s.id)} ${s.label}${s.recommended?he.default.green(" recommended"):""}`);console.log(he.default.dim(` Choose with: domani assistant choose ${i.id} --version ${i.version??1} --decision ${i.decision.id} --decision-version ${i.decision.version??1} --option <id>`))}i.plan?.id&&c("Plan",`${i.plan.id} (preview with: domani assistant plan ${i.plan.id})`),d()}function Xc(e,t){if(t.json)return w(e,t.fields);d(),S("Mailzero 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||qn})`),d();let i=new Set(e.mailbox_ids||[]),s=e.mailboxes||[];s.length&&Z(["ID","Address","AI"],s.map(n=>[he.default.dim(n.id),n.address,i.has(n.id)?he.default.green("on"):he.default.dim("off")])),d()}function Zc(e,t){if(t.json)return w(e,t.fields);let i=e.backfill;if(d(),S("History import"),!i){console.log(he.default.dim(" No import has run yet.")),d();return}c("Status",`${i.status} (${i.phase})`),c("Progress",`${i.processed}/${i.total}${i.percent===null||i.percent===void 0?"":` (${i.percent}%)`}`),c("Failed",String(i.failed??0)),c("Paused",i.paused?"yes":"no"),i.estimated_completion_at&&c("ETA",i.estimated_completion_at),i.can_close_app&&console.log(he.default.dim(" The import continues in the background.")),d()}function Qc(e,t){if(t.json)return w(e,t.fields);let i=e.action_plan||e.plan||e;d(),S("Action preview"),c("ID",i.id),c("Status",i.status||""),i.expires_at&&c("Expires",i.expires_at);for(let s of i.effects||[])d(),console.log(` ${he.default.bold(s.kind||"effect")} ${he.default.dim(`mailbox ${s.mailbox_id||""}`)}${s.reply_to_message_id?he.default.dim(` in reply to ${s.reply_to_message_id}`):""}`),s.body&&console.log(`
|
|
205
|
+
domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function Nc(e,t){let i=parseFloat(t.price);(isNaN(i)||i<=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 s=C(!t.json);s.start(`Listing ${v.domain(e)} for sale`);let n={domain:e,price:i};t.description&&(n.description=t.description);let r=await _("/api/domains/sell",{method:"POST",body:JSON.stringify(n)}),o=await r.json();if(r.ok||(s.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){s.stop(""),y(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(s.stop(`${w.success} Listed for sale`),S("Sell Domain"),c("Domain",v.domain(o.listing?.domain||e)),c("Price",v.price(i)),c("Status",$e.default.green("active")),d(),console.log(` ${$e.default.dim("Your listing is live on the marketplace.")}`),d()):(s.stop(`${w.success} Verification record ready`),S("Sell Domain"),c("Domain",v.domain(o.listing?.domain||e)),c("Price",v.price(i)),c("Status",$e.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${$e.default.dim("Type:")} ${$e.default.bold("TXT")}`),console.log(` ${$e.default.dim("Name:")} ${$e.default.bold(o.txt_record?.name||"@")}`),console.log(` ${$e.default.dim("Value:")} ${$e.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),d(),console.log(` ${$e.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),R("Once the record is set, verify:",`domani sell ${e} --verify`),d())}async function Uc(e,t){let i=C(!t.json);i.start(`Verifying ownership of ${v.domain(e)}`);let s=await _("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),n=await s.json();if(s.ok||(i.stop("Verification failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),y(n,t.fields);return}i.stop(`${w.success} ${v.domain(e)} is now listed for sale!`),S("Domain Listed"),c("Domain",v.domain(n.domain||e)),c("Status",$e.default.green(n.status||"active")),n.price&&c("Price",v.price(n.price)),d(),R("Check listing status:",`domani sell ${e} --status`),R("View your deals:","domani deals"),d()}async function qc(e,t){let i=C(!t.json);i.start(`Checking listing status for ${v.domain(e)}`);let s=await _(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Listing status loaded`),t.json){y(n,t.fields);return}let r=n.listing;if(S("Listing Status"),c("Domain",v.domain(n.domain||e)),r){let o=r.status;c("Status",o==="active"?$e.default.green(o):$e.default.yellow(o||"unknown")),r.price&&c("Price",v.price(r.price)),r.description&&c("Description",r.description),r.created_at&&c("Listed",$e.default.dim(new Date(r.created_at).toLocaleDateString()))}else c("Status",$e.default.dim("No listing found"));n.deal&&c("Deal",`${n.deal.status} ($${n.deal.price})`),d()}async function Fc(e,t){let i=C(!t.json);i.start(`Removing ${v.domain(e)} from sale`);let s=await _(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),y(n,t.fields);return}i.stop(`${w.success} ${v.domain(e)} removed from sale`),d()}async function Mc(e,t,i){let s=C(!i.json);s.start(`Looking up active deal for ${v.domain(e)}`);let n=await _(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields}));let a=(r.deals||r.data||[]).filter(g=>g.domain.toLowerCase()===e.toLowerCase());a.length===0&&(s.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
|
|
206
|
+
Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:i.json,fields:i.fields}));let l=a[0].id;s.message(`Submitting transfer code for deal ${$e.default.dim(l)}`);let f=await _(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),m=await f.json();if(f.ok||(s.stop("Failed"),u(m.error||m.message,{hint:m.hint,status:f.status,json:i.json,fields:i.fields})),i.json){s.stop(""),y(m,i.fields);return}s.stop(`${w.success} Transfer code submitted for ${v.domain(e)}`),S("Transfer Code Submitted"),c("Domain",v.domain(e)),c("Deal",$e.default.dim(l)),c("Status",$e.default.green(m.status||"code_submitted")),d(),R("Track the deal:",`domani deals ${l}`),d()}K();var ke=D(M(),1);L();async function Zo(e,t){return e?Vc(e,t):Lc(t)}async function Lc(e){let t=C(!e.json);t.start("Loading deals");let i=new URLSearchParams;e.role&&i.set("role",e.role),e.status&&i.set("status",e.status);let s=i.toString()?`?${i.toString()}`:"",n=await _(`/api/deals${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.deals||r.data||[];if(t.stop(`${w.success} ${o.length} deal(s)`),e.json){y(r,e.fields);return}if(o.length===0){d(),console.log(` ${ke.default.dim("No deals found.")}`),d(),R("List a domain for sale:","domani sell <domain> --price <amount>"),d();return}d(),S("Deals");let a=o.map(l=>{let f=l.status==="completed"?ke.default.green:l.status==="active"?ke.default.cyan:l.status==="cancelled"?ke.default.red:ke.default.yellow;return[v.domain(l.domain),v.price(l.price),f(l.status),ke.default.dim(l.role||"-"),ke.default.dim(new Date(l.created_at).toLocaleDateString())]});B(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function Vc(e,t){let i=C(!t.json);i.start(`Loading deal ${ke.default.dim(e)}`);let s=await _(`/api/deals/${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Deal loaded`),t.json){y(n,t.fields);return}let r=n.deal||n;S("Deal Details"),c("ID",ke.default.dim(r.id)),c("Domain",v.domain(r.domain)),c("Price",v.price(r.price));let o=r.status==="completed"?ke.default.green:r.status==="active"?ke.default.cyan:r.status==="cancelled"?ke.default.red:ke.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",ke.default.dim(r.buyer)),r.seller&&c("Seller",ke.default.dim(r.seller)),r.created_at&&c("Created",ke.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",ke.default.dim(new Date(r.updated_at).toLocaleDateString())),d();let a=r.events||[];if(a.length>0){S("Timeline");for(let l of a){let f=ke.default.dim(new Date(l.created_at).toLocaleString()),m=l.status==="completed"?w.success:l.status==="expired"||l.status==="refunded"?w.error:w.info;console.log(` ${m} ${f} ${l.detail||l.status}`)}d()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(R("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),d())}K();var Me=D(M(),1);L();ye();async function ta(e,t,i){switch(e){case void 0:case"list":case"ls":return Wc(i);case"request":case"acquire":case"new":return Qo(t,i);case"status":case"get":return ea(t,i);case"cancel":case"rm":return Hc(t,i);default:return e.includes(".")?Qo(e,i):ea(e,i)}}async function Qo(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 i=C(!t.json);i.start(`Requesting acquisition of ${v.domain(e)}`);let s={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}),s.max_budget=a}let n=await _("/api/broker",{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${w.success} Acquisition requested`),t.json)return y(r,t.fields);S("Broker request"),c("Domain",v.domain(o.domain)),c("Status",qn(o.status)),o.max_budget!=null&&c("Max budget",v.price(o.max_budget)),c("ID",Me.default.dim(o.id)),d(),console.log(` ${Me.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),d(),R("Check progress:",`domani broker status ${o.id}`),d()}async function Wc(e){let t=C(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",s=await _(`/api/broker${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.requests||n.data||[];if(t.stop(`${w.success} ${r.length} request(s)`),e.json)return y(n,e.fields);if(r.length===0){d(),console.log(` ${Me.default.dim("No broker requests yet.")}`),d(),R("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),d();return}d(),S("Broker requests"),B(["Domain","Status","Budget","ID"],r.map(o=>[v.domain(o.domain),qn(o.status),o.max_budget!=null?v.price(o.max_budget):Me.default.dim("-"),Me.default.dim(o.id)])),d()}async function ea(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=C(!t.json);i.start("Loading request");let s=await _(`/api/broker/${encodeURIComponent(e)}`),n=await s.json();s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields}));let r=n.request||n;if(i.stop(`${w.success} ${v.domain(r.domain)}`),t.json)return y(n,t.fields);S("Broker request"),c("Domain",v.domain(r.domain)),c("Status",qn(r.status)),r.max_budget!=null&&c("Max budget",v.price(r.max_budget)),c("Contacted",r.contacted?Me.default.green("yes"):Me.default.dim("not yet")),r.failure_reason&&c("Reason",Me.default.yellow(r.failure_reason)),c("ID",Me.default.dim(r.id)),d(),r.negotiation_id?(console.log(` ${Me.default.dim("The owner responded - an anonymous negotiation is open.")}`),d(),R("Review the offer:","domani deals"),d()):["sourcing","contacted","negotiating"].includes(r.status)&&(R("Cancel this request:",`domani broker cancel ${r.id}`),d())}async function Hc(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=C(!t.json);i.start("Cancelling request");let s=await _(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Request cancelled`),t.json)return y(n,t.fields);d()}function qn(e){return["completed","agreed"].includes(e)?Me.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Me.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Me.default.dim(e):e}K();var be=D(M(),1);L();async function sa(e){return e.read?Bc(e):Jc(e)}async function Jc(e){let t=C(!e.json);t.start("Loading notifications");let i=new URLSearchParams;e.unread&&i.set("unread","true"),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i.toString()}`:"",n=await _(`/api/notifications${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(f=>!f.read).length;if(t.stop(`${w.success} ${o.length} notification(s)${a>0?` ${w.dot} ${be.default.yellow(`${a} unread`)}`:""}`),e.json){y(r,e.fields);return}if(o.length===0){d(),console.log(` ${be.default.dim("No notifications.")}`),d();return}d(),S("Notifications");let l=o.map(f=>{let m=f.read?be.default.dim(w.dot):be.default.cyan(w.info),g=Gc(f.type),b=f.read?be.default.dim(f.title):be.default.white(f.title),k=f.body?f.read?be.default.dim(ia(f.body,40)):be.default.dim(ia(f.body,40)):be.default.dim("-"),$=be.default.dim(new Date(f.created_at).toLocaleDateString());return[m,g,b,k,$]});B(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${be.default.dim("Mark all as read:")} ${be.default.cyan("domani notifications --read")}`),d())}async function Bc(e){let t=C(!e.json);t.start("Marking all notifications as read");let i=await _("/api/notifications/read-all",{method:"POST"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),y(s,e.fields);return}let n=s.count??0;t.stop(`${w.success} ${n} notification(s) marked as read`),d()}function Gc(e){let t={deal:be.default.cyan,sale:be.default.green,purchase:be.default.green,transfer:be.default.yellow,expiry:be.default.red,security:be.default.red,billing:be.default.yellow,email:be.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||be.default.dim)(e)}function ia(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}K();var Ot=D(M(),1);L();async function na(e){let t=e.limit?Number(e.limit):20,i=await _(`/api/billing/invoices?limit=${t}`),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){y({...s,count:s.invoices.length},e.fields);return}if(s.invoices.length===0){console.log(` ${Ot.default.dim("No invoices yet.")}`);return}S(`Invoices (${s.invoices.length})`),d();for(let n of s.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${w.success} ${Ot.default.bold(a)} ${Ot.default.green(r)} ${Ot.default.dim(o)}`),n.description&&console.log(` ${Ot.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${Ot.default.dim(n.hosted_invoice_url)}`)}d(),s.has_more&&(console.log(` ${Ot.default.dim(`Showing ${s.invoices.length} most recent. Use --limit to see more.`)}`),d())}K();var $i=D(M(),1);L();async function ra(e){let t=C(!e?.json);t.start("Setting up billing session");let i=await _("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.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){y({url:s.url});return}d(),console.log(` ${$i.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),d(),Be(s.url),console.log(` ${w.info} ${$i.default.dim("Complete payment setup in your browser.")}`),console.log(` ${$i.default.dim(" After setup, you can purchase domains with")} ${$i.default.cyan("domani buy")}`),d()}K();var Fn=D(M(),1);L();async function oa(e){let t=C(!e?.json);t.start("Creating upgrade session");let i=await _("/api/billing/subscribe",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="ALREADY_SUBSCRIBED"||s.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Ready"),e?.json){y({url:s.url},e?.fields);return}d(),console.log(` ${Fn.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),d(),Be(s.url),console.log(` ${w.info} ${Fn.default.dim("Complete your plan upgrade in the browser.")}`),d()}K();var Mn=D(M(),1);L();async function aa(e){let t=C(!e?.json);t.start("Cancelling subscription");let i=await _("/api/billing/cancel",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="NOT_PAID"||s.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Done"),e?.json){y(s,e?.fields);return}d();let n=s.cancel_at?new Date(s.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${w.success} ${Mn.default.dim("Subscription cancelled.")} Access continues until ${Mn.default.cyan(n)}.`),d()}K();var st=D(M(),1);L();ye();Ze();async function la(e,t,i){e||(e=await pe()),Y(e,i);let s=[];if(t?.length&&s.push(...t),i.set&&s.push(...i.set.split(",").map(n=>n.trim()).filter(Boolean)),s.length>0||i.reset){await zc(e,s,i);return}await Kc(e,i)}async function Kc(e,t){let i=C(!t.json);i.start(`Fetching nameservers for ${v.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${v.domain(e)}`),t.json){y(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${w.warning} ${st.default.yellow("No nameservers configured.")}`),console.log(` ${st.default.dim("DNS operations (parking, email, connect) will not work.")}`),d(),R("Set default nameservers:",`domani nameservers ${e} --reset`);else{S("Nameservers");for(let r of n.nameservers)console.log(` ${w.success} ${st.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(d(),console.log(` ${st.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(d(),c("Defaults",n.default_nameservers.map(r=>st.default.dim(r)).join(st.default.dim(", ")))),d()}async function zc(e,t,i){let s=C(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${v.domain(e)}`);let o=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(s.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(s.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:i.json,fields:i.fields})),t=a.default_nameservers,s.stop(`Using defaults: ${t.map(l=>st.default.cyan(l)).join(st.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:i.json,fields:i.fields}),i.dryRun)return G("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);s.start(`Setting nameservers for ${v.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields})),s.stop(`${w.success} Nameservers updated`),i.json){y(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${w.success} ${st.default.cyan(o)}`);d(),console.log(` ${st.default.dim("Changes may take up to 48 hours to propagate.")}`),d(),R("Check propagation:",`domani status ${e}`),d()}var da=require("crypto"),us=D(require("fs"),1);gt();var ki=D(M(),1);L();function Yc(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function ca(e){let t=!!e?.json,i=C(!t);i.start("Checking for updates");let s=Ve();try{let n=await fetch(`${s}/api/cli/version`);n.ok||(i.stop("Failed"),u("Could not check for updates"));let r=await n.json(),o=r.version,a=r.sha256;if(Yc(o,xe)<=0){i.stop(`${w.success} Already up to date (v${xe})`),t&&y({current:xe,latest:o,up_to_date:!0});return}if(t&&!e?.yes){i.stop(""),y({current:xe,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}i.stop(t?"":`New version available: ${ki.default.cyan(xe)} ${w.arrow} ${ki.default.green(o)}`);let l=C(!t);l.start("Downloading update");let f=`${s}/cli/domani.js`,m=await fetch(f);m.ok||(l.stop("Download failed"),u(`Failed to download from ${f}`));let g=await m.text();a&&(0,da.createHash)("sha256").update(g).digest("hex")!==a&&(l.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let b=process.argv[1];b||(l.stop("Failed"),u("Could not determine binary path"));let k=us.default.realpathSync(b),$=k+".tmp";if(us.default.writeFileSync($,g,{mode:493}),us.default.renameSync($,k),l.stop(`${w.success} Updated to v${o}`),t){y({updated:!0,from:xe,to:o});return}d(),console.log(` ${ki.default.dim("Restart your terminal or run")} domani --version ${ki.default.dim("to verify")}`),d()}catch(n){u(`Update failed: ${n instanceof Error?n.message:String(n)}`)}}var ms=D(require("fs"),1),ua=D(require("path"),1),ma=D(require("os"),1);Ue();var _i=D(M(),1);L();async function fa(){let e=process.argv[1],t=e?ms.default.realpathSync(e):null,i=ua.default.join(ma.default.homedir(),".domani");if(d(),console.log(` ${_i.default.bold("This will remove:")}`),t&&console.log(` ${w.dot} CLI binary: ${_i.default.dim(t)}`),console.log(` ${w.dot} Config dir: ${_i.default.dim(i)}`),d(),await Xe({message:"Uninstall domani?"})!==!0){console.log(` ${_i.default.dim("Cancelled.")}`);return}ms.default.rmSync(i,{recursive:!0,force:!0}),t&&ms.default.unlinkSync(t),d(),console.log(` ${w.success} domani uninstalled.`),d()}K();var re=D(M(),1);L();async function ha(e,t){let i=t?.json,s=t?.fields,n=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=C(!i);r.start("Loading schema");let o=await we(n),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:s})),r.stop("Schema loaded"),i){y(a,s);return}e?Zc(e,a):Xc(a.commands)}function Xc(e){S("Commands");let t=Object.entries(e).map(([i,s])=>[re.default.bold(re.default.cyan(i)),s.description]);B(["Command","Description"],t,[20,50]),d(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),d()}function Zc(e,t){if(S(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${v.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){d(),console.log(` ${re.default.bold("Arguments")}`);for(let[i,s]of Object.entries(t.arguments)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type}${s.variadic?", variadic":""})`);console.log(` ${re.default.cyan(i)}${n} ${r}`),s.description&&console.log(` ${re.default.dim(s.description)}`)}}if(t.options&&Object.keys(t.options).length>0){d(),console.log(` ${re.default.bold("Options")}`);for(let[i,s]of Object.entries(t.options)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type})`),o=s.choices?re.default.dim(` [${s.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${i}`)}${n} ${r}${o}`),console.log(` ${re.default.dim(s.description)}`)}}if(t.api)if(d(),console.log(` ${re.default.bold("API")}`),Qc(t.api))pa(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),pa(s,6);t.errors&&t.errors.length>0&&(d(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>re.default.dim(i)).join(re.default.dim(", "))}`)),d()}function Qc(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function pa(e,t=4){let i=" ".repeat(t);if(console.log(`${i}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[s,n]of Object.entries(e.parameters)){let r=n.required?re.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${i} ${re.default.cyan(s)}${r} ${a}`),n.description&&console.log(`${i} ${re.default.dim(n.description)}`)}}K();var Le=D(M(),1);Ue();L();async function ga(e){let t=C(!e.json);t.start("Loading payment method");let i=await _("/api/me"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),y(s.card?{has_payment_method:s.has_payment_method,card:s.card}:{has_payment_method:!1},e.fields);return}if(!s.has_payment_method||!s.card){t.stop("No payment method on file"),d(),console.log(` ${Le.default.dim("Add a card with")} ${Le.default.cyan("domani card add")}`),d();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=s.card,l=`${String(o).padStart(2,"0")}/${a}`,f=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),S("Payment method"),c("Card",`${Le.default.bold(f)} \u2022\u2022\u2022\u2022 ${Le.default.bold(r)}`),c("Expires",l),d(),console.log(` ${Le.default.dim("Update with")} ${Le.default.cyan("domani card add")}`),d()}async function ya(e){let t=C(!e?.json);t.start("Setting up payment session");let i=await _("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){y({url:s.url},e?.fields);return}d(),console.log(` ${Le.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),d(),Be(s.url),console.log(` ${w.info} ${Le.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Le.default.dim(" After setup, you can purchase domains with")} ${Le.default.cyan("domani buy")}`),d()}async function ba(e){if(!e?.yes&&!e?.json){let n=await Xe({message:"Remove your saved payment method?"});if(de(n)||!n){console.log(` ${Le.default.dim("Cancelled.")}`);return}}let t=C(!e?.json);t.start("Removing payment method");let i=await _("/api/billing/card",{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),t.stop(`${w.success} Payment method removed`),e?.json){y({removed:!0},e?.fields);return}d(),console.log(` ${Le.default.dim("Add a new card with")} ${Le.default.cyan("domani card add")}`),d()}var Ln=D(M(),1);K();L();async function fe(e,t,i,s){let n=C(!i.json);n.start(s);let r=await _(e,t),o=await r.json();return r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop(`${w.success} Done`),o}async function wa(e,t){if(!e||e==="list"){let i=await fe("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return y(i,t.fields);if(d(),S("Workspaces"),!i.workspaces.length){console.log(` ${Ln.default.dim("No workspaces yet.")}`),R("Create one:","domani workspace create --name Acme");return}B(["ID","Name","Role","Mailboxes","Members"],i.workspaces.map(s=>[s.id,s.name,s.role,String(s.mailbox_count),String(s.member_count)]),[28,28,10,10,8]),d();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let i=await fe("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return y(i,t.fields);d(),S("Workspace Created"),c("ID",i.id),c("Name",i.name),d();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return y(i,t.fields);d(),S(i.name),c("Role",i.role),c("Mailboxes",i.mailboxes.length),c("Members",i.members.length),d(),B(["Email","Role","Mailbox grants"],i.members.map(s=>[s.email,s.role,String(s.mailbox_grants.length)]),[42,12,16]),d();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return y(a,t.fields);d(),S("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),d();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[i,s]=t.subject.split(":",2),[n,r]=t.resource.split(":",2);(!s||!["human","agent","service","token","group"].includes(i))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(n))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:i==="group"?{type:"group",id:s}:{type:"principal",principal:{type:i,id:s}},resource:{type:n,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 y(o,t.fields);d(),S(t.apply?"Access Applied":"Access Plan"),c("Action",o.action),c("Changed",String(o.changed)),o.grant_id&&c("Grant",o.grant_id),d();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 i=(t.principals||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let[r,o]=n.split(":",2);return o||u(`Invalid principal: ${n}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),s=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:i})},t,"Syncing access group");if(t.json)return y(s,t.fields);d(),S("Access Group Synced"),c("ID",s.id),c("Principals",s.principal_count),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return y(i,t.fields);d(),S("Mailbox Collection Synced"),c("ID",i.id),c("Mailboxes",i.mailbox_count),d();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 i=(t.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>({resource:{type:"mailbox",id:n},profile:t.profile||"responder"})),s=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:i,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return y(s,t.fields);d(),S("Access Offered"),c("Email",s.email),c("Expires",s.expires_at),d();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 i=await fe("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return y(i,t.fields);d(),S("Access Accepted"),c("Workspace",i.workspace_name),c("Ownership",i.ownership),d();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 i=await fe(`/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 y(i,t.fields);d(),S("Access Revoked"),c("Grant",i.grant_id),c("Version",i.version),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return y(i,t.fields);d(),S("Workspace Renamed"),c("ID",i.id),c("Name",i.name),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return y(i,t.fields);d(),S("Invitation Sent"),c("Email",i.email),c("Role",i.role),c("Expires",i.expires_at),d();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let i=await fe("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return y(i,t.fields);d(),S("Workspace Joined"),c("Workspace",i.workspace_name),c("Role",i.role),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return y(i,t.fields);d(),S("Invitation Revoked"),c("Invitation",i.invitation_id),d();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 i=await fe(`/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 y(i,t.fields);d(),S("Member Updated"),c("Membership",i.id),c("Role",i.role),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return y(i,t.fields);d(),S("Member Removed"),c("Membership",i.membership_id),d();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return y(i,t.fields);d(),S("Workspace Left"),c("Workspace",i.workspace_id),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return y(i,t.fields);d(),S("Ownership Transfer Requested"),c("To",i.to_email),c("Expires",i.expires_at),c("Billing",i.billing),d();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 i=await fe("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return y(i,t.fields);d(),S("Ownership Transferred"),c("Workspace",i.workspace_id),c("Domains",i.domains_transferred),c("Mailboxes",i.mailboxes_transferred),c("Previous owner",i.previous_owner_role),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return y(i,t.fields);d(),S("Ownership Transfer Revoked"),c("Transfer",i.transfer_id),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return y(i,t.fields);d(),S(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),c("Address",i.address),c("Mailboxes",i.mailbox_ids?.length??1),d();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 i=await fe(`/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 y(i,t.fields);d(),S("Mailbox Access Granted"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),c("Role",i.role),d();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 i=await fe(`/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 y(i,t.fields);d(),S("Mailbox Access Revoked"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),d();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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return y(i,t.fields);d(),S("Workspace Checkout"),c("Plan",i.plan),c("URL",i.url),d(),i.url&&t.open!==!1&&(console.log(` ${Ln.default.dim("Opening browser")} ${w.arrow} ${v.url(i.url)}`),Be(i.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 i=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return y(i,t.fields);d(),S("Cancellation Scheduled"),c("Message",i.message),i.cancel_at&&c("Cancels",i.cancel_at),d();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 gs=D(M(),1);K();var fs=D(require("node:crypto"),1),ni=D(require("node:fs"),1),va=D(require("node:os"),1),ps=D(require("node:path"),1),eu=process.env.DOMANI_CONFIG_DIR||ps.default.join(va.default.homedir(),".domani"),$a=ps.default.join(eu,"mutations");function tu(e){return ps.default.join($a,`${fs.default.createHash("sha256").update(e).digest("hex")}.json`)}function ct(e,t,i){let s=tu(e),n=fs.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!i)try{let o=JSON.parse(ni.default.readFileSync(s,"utf8"));if(o.key&&o.fingerprint===n)return{key:o.key,complete:()=>{try{ni.default.unlinkSync(s)}catch{}}}}catch{}let r=i||`cli-${fs.default.randomUUID()}`;return ni.default.mkdirSync($a,{recursive:!0,mode:448}),ni.default.writeFileSync(s,JSON.stringify({key:r,fingerprint:n}),{mode:384}),{key:r,complete:()=>{try{ni.default.unlinkSync(s)}catch{}}}}L();function ka(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[i,s]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!s)continue;let n=process.env[s];n||u(`Environment variable ${s} is empty`,{code:"validation_error",json:e.json}),t[i]=n}return Object.keys(t).length?t:void 0}async function Ht(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}function hs(e,t){if(t.json)return y(e,t.fields);let i=e.http_route||e;d(),S("HTTP Route"),c("ID",i.id),c("URL",i.url),c("Upstream",i.upstream),c("Status",i.status),c("Expires",i.expires_at),c("Browser mode",i.browser_mode||"stateless"),i.upstream_verification?.secret&&(c("Verification secret",gs.default.yellow(i.upstream_verification.secret)),console.log(gs.default.dim(" Save this secret now. It will not be shown again after this receipt."))),d()}async function _a(e,t,i){if(!e||e==="list"){let s=new URLSearchParams;i.domain&&s.set("domain",i.domain),i.hostname&&s.set("hostname",i.hostname),i.status&&s.set("status",i.status);let n=await Ht(await _(`/api/http-routes${s.size?`?${s}`:""}`),i);if(i.json)return y(n,i.fields);d(),S("HTTP Routes");for(let r of n.http_routes)console.log(` ${gs.default.dim(r.id)} ${r.hostname} ${r.status} ${r.upstream}`);d();return}if(e==="create"){i.upstream||u("--upstream is required",{code:"validation_error",json:i.json});let s=ka(i),n={...i.hostname?{hostname:i.hostname}:{},upstream:i.upstream,...i.expiresIn?{expires_in:Number(i.expiresIn)}:{},...i.hostHeader?{host_header:i.hostHeader}:{},...i.upstreamVerification?{upstream_verification:i.upstreamVerification}:{},...s?{upstream_headers:s}:{}},r=ct(`route:create:${i.hostname||"auto"}`,n,i.idempotencyKey),o=C(!i.json);o.start("Creating HTTP route");let a=await Ht(await _("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(n)}),i);return r.complete(),o.stop(`${w.success} HTTP route created`),hs(a,i)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:i.json}),e==="get")return hs(await Ht(await _(`/api/http-routes/${encodeURIComponent(t)}`),i),i);if(e==="delete"){let s=await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(s.ok||await Ht(s,i),i.json)return y({deleted:!0,id:t},i.fields);console.log(`${w.success} HTTP route deleted`);return}if(e==="refresh"){i.expiresIn||u("--expires-in is required",{code:"validation_error",json:i.json});let s={expires_in:Number(i.expiresIn)},n=ct(`route:refresh:${t}`,s,i.idempotencyKey),r=await Ht(await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":n.key},body:JSON.stringify(s)}),i);return n.complete(),hs(r,i)}if(e==="rotate-verification"){let s=ct(`route:rotate-verification:${t}`,{},i.idempotencyKey),n=await Ht(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":s.key}}),i);return s.complete(),i.json?y(n,i.fields):hs(n,i)}if(e==="rotate-headers"){let s=ka(i);s||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:i.json});let n=ct(`route:rotate-headers:${t}`,{upstream_headers:s},i.idempotencyKey),r=await Ht(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":n.key},body:JSON.stringify({upstream_headers:s})}),i);if(n.complete(),i.json)return y(r,i.fields);console.log(`${w.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:i.json})}var ae=D(M(),1),Sa=require("node:fs");K();L();var Vn="mailzero-personal-ai.v1",ge=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="AssistantUsageError"}},iu={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct"},su=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","plan","activity","export","delete","brief","facts"];function xa(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function xi(e,t,i){let s=Number(e);if(!Number.isInteger(s)||s<i)throw new ge(`${t} must be an integer of at least ${i}`);return s}function nu(e,t,i){let s=e||"today";switch(s){case"today":return{method:"GET",path:"/api/assistant/today"};case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let n={};if(i.enable&&i.disable)throw new ge("Use either --enable or --disable");if(i.pause&&i.resume)throw new ge("Use either --pause or --resume");if(i.enable&&(n.enabled=!0),i.disable&&(n.enabled=!1),i.shadow!==void 0&&(n.shadow_enabled=i.shadow),i.pause&&(n.paused=!0),i.resume&&(n.paused=!1),i.none?n.mailbox_ids=[]:i.mailboxes!==void 0&&(n.mailbox_ids=xa(i.mailboxes)),i.days!==void 0&&(n.history_window_days=xi(i.days,"--days",1)),i.attachmentVision!==void 0){if(!["on","off"].includes(i.attachmentVision))throw new ge("--attachment-vision must be on or off");n.attachment_vision=i.attachmentVision==="on"}if(!Object.keys(n).length)throw new ge("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:n}}case"preview":{if(!i.consent)throw new ge("--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 ${Vn}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let n=xa(i.mailboxes);if(!n.length)throw new ge("--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:n,history_window_days:i.days===void 0?30:xi(i.days,"--days",1),consent:!0,consent_version:Vn}}}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 ge("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(!i.correspondent)throw new ge("Work item ID or --correspondent is required","Usage: domani assistant brief <id> | domani assistant brief --correspondent ada@example.com [--mailbox hi@myapp.dev]");let n=new URLSearchParams({correspondent:i.correspondent});return i.mailbox&&n.set("mailbox",i.mailbox),{method:"GET",path:`/api/assistant/brief?${n}`}}case"facts":if(!t)throw new ge("Work item ID is required","Usage: domani assistant facts <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/facts`};case"plan":if(!t)throw new ge("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${i.limit!==void 0?`?limit=${xi(i.limit,"--limit",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!i.yes)throw new ge("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"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":{if(!t)throw new ge("Work item ID is required",`Usage: domani assistant ${s} <id> --item-version <work_item_version>`);if(i.itemVersion===void 0)throw new ge("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let n=iu[s],r={type:n,work_item_version:xi(i.itemVersion,"--item-version",1)};if(n==="ignore"&&i.scope){if(!["item","sender","sender_domain","situation"].includes(i.scope))throw new ge("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=i.scope}if(n==="choose"){if(!i.option||!i.decision||i.decisionVersion===void 0)throw new ge("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=i.decision,r.decision_version=xi(i.decisionVersion,"--decision-version",1),r.option_id=i.option}if(n==="instruct"){if(!i.text)throw new ge("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=i.text}if(n==="snooze"){if(!i.until)throw new ge("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=i.until}if(n==="correct"){if(!i.field||!i.text)throw new ge("--field and --text are required","Name the analysis field to correct and the correct value");r.field=i.field,r.correction=i.text}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${n}:${t}`}}default:throw new ge(`Unknown action: ${s}`,`Actions: ${su.join(", ")}`)}}async function ru(e,t){let i=await e.json();if(e.ok)return i;i.code==="NOT_AVAILABLE"&&u("The Mailzero 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}),i.code==="INSUFFICIENT_SCOPE"&&u(i.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(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields})}function ou(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",i=e.recurrence?.count&&e.recurrence.count>1?ae.default.dim(`x${e.recurrence.count}`):"";return[ae.default.dim(e.id),t,`${(e.title||e.summary||"").slice(0,60)} ${i}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function au(e,t){if(t.json)return y(e,t.fields);d(),S("Today");let i=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],s=0;for(let[r,o]of i){let a=e.sections&&typeof e.sections=="object"?e.sections:e,l=Array.isArray(a[r])?a[r]:[];l.length&&(s+=l.length,console.log(` ${ae.default.bold(o)} ${ae.default.dim(`(${l.length})`)}`),B(["ID","Who","Summary","Deadline"],l.map(ou)),d())}s||console.log(ae.default.dim(" Nothing needs you right now."));let n=typeof e.as_of=="string"?e.as_of:void 0;n&&console.log(ae.default.dim(` As of ${n}`)),d()}function lu(e,t){if(t.json)return y(e,t.fields);let i=e.brief??e;if(e.correspondent&&!e.brief){d(),S(`Brief for ${e.correspondent}`),console.log(` ${ae.default.dim("Nothing analysed from this person yet.")}`);for(let s of e.recent_mail||[])c(s.received_at.slice(0,10),`${s.subject||""} (${s.mailbox})`);return}d(),S(i.title||"Brief"),i.situation&&c("Status",`${i.situation.status||""}${i.situation.attention?.level?` \xB7 ${i.situation.attention.level}`:""}${i.situation.occurrences&&i.situation.occurrences>1?` \xB7 ${i.situation.occurrences} messages`:""}`),i.situation?.sender?.address&&c("With",`${i.situation.sender.name?`${i.situation.sender.name} `:""}<${i.situation.sender.address}>`),i.summary&&c("Summary",i.summary),i.ask&&c("Ask",i.ask);for(let s of i.story||[])c(s.occurred_at.slice(0,10),`${s.title}${s.analysed?"":ae.default.dim(" (not analysed)")}`);for(let s of i.facts||[])c("Fact",`${s.subject||""} ${s.predicate||""} ${s.value?.value??s.object??""}${s.value?.currency?` ${s.value.currency}`:""}`.trim());for(let s of i.awaiting||[])c(s.overdue?ae.default.red("Awaited"):"Awaited",`${s.who}: ${s.what} (since ${s.since.slice(0,10)})`);for(let s of i.commitments||[])c(s.overdue?ae.default.red("Promised"):"Promised",`${s.who}: ${s.what}`);for(let s of(i.settled||[]).slice(0,5))c("Settled",`${s.what} (${s.status}, ${s.at.slice(0,10)})`);i.decision?.question&&c("Decision",`${i.decision.question} ${(i.decision.options||[]).map(s=>`${s.recommended?"\u2605 ":""}${s.label}`).join(" / ")}`),i.suggested_next&&c("Next",`${i.suggested_next.action} ${ae.default.dim(`(${i.suggested_next.reason})`)}`),e.related&&e.related.length&&c("Also",`${e.related.length} other item(s) from this person`)}function ja(e,t){if(t.json)return y(e,t.fields);let i=e.work_item||e;if(d(),S("Work item"),c("ID",i.id),c("Version",String(i.version??"")),c("Status",i.status||""),c("Mailbox",i.mailbox?.name?`${i.mailbox.name} <${i.mailbox.address||""}>`:i.mailbox?.address||""),i.title&&c("Title",i.title),i.sender?.address&&c("From",`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>${i.sender.kind&&i.sender.kind!=="human"?` (${i.sender.kind})`:""}`),i.ask&&c("Ask",i.ask),i.recurrence?.count&&i.recurrence.count>1&&c("Recurrence",`${i.recurrence.count} messages since ${(i.recurrence.first_seen_at||"").slice(0,10)}`),c("Summary",i.summary||""),i.attention?.reason&&c("Why",i.attention.reason),i.attention?.deadline&&c("Deadline",i.attention.deadline),i.source?.event_id&&c("Source",`${i.source.type||"mail"} ${i.source.event_id}`),i.decision?.options?.length){d(),console.log(` ${ae.default.bold("Decision")} ${ae.default.dim(`${i.decision.id} v${i.decision.version??1}`)}`);for(let s of i.decision.options)console.log(` ${ae.default.dim(s.id)} ${s.label}${s.recommended?ae.default.green(" recommended"):""}`);console.log(ae.default.dim(` Choose with: domani assistant choose ${i.id} --version ${i.version??1} --decision ${i.decision.id} --decision-version ${i.decision.version??1} --option <id>`))}i.plan?.id&&c("Plan",`${i.plan.id} (preview with: domani assistant plan ${i.plan.id})`),d()}function du(e,t){if(t.json)return y(e,t.fields);d(),S("Mailzero 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||Vn})`),d();let i=new Set(e.mailbox_ids||[]),s=e.mailboxes||[];s.length&&B(["ID","Address","AI"],s.map(n=>[ae.default.dim(n.id),n.address,i.has(n.id)?ae.default.green("on"):ae.default.dim("off")])),d()}function cu(e,t){if(t.json)return y(e,t.fields);let i=e.backfill;if(d(),S("History import"),!i){console.log(ae.default.dim(" No import has run yet.")),d();return}c("Status",`${i.status} (${i.phase})`),c("Progress",`${i.processed}/${i.total}${i.percent===null||i.percent===void 0?"":` (${i.percent}%)`}`),c("Failed",String(i.failed??0)),c("Paused",i.paused?"yes":"no"),i.estimated_completion_at&&c("ETA",i.estimated_completion_at),i.can_close_app&&console.log(ae.default.dim(" The import continues in the background.")),d()}function uu(e,t){if(t.json)return y(e,t.fields);let i=e.action_plan||e.plan||e;d(),S("Action preview"),c("ID",i.id),c("Status",i.status||""),i.expires_at&&c("Expires",i.expires_at);for(let s of i.effects||[])d(),console.log(` ${ae.default.bold(s.kind||"effect")} ${ae.default.dim(`mailbox ${s.mailbox_id||""}`)}${s.reply_to_message_id?ae.default.dim(` in reply to ${s.reply_to_message_id}`):""}`),s.body&&console.log(`
|
|
206
207
|
${String(s.body).split(`
|
|
207
208
|
`).map(n=>` ${n}`).join(`
|
|
208
209
|
`)}
|
|
209
|
-
`);console.log(
|
|
210
|
-
`;if(i.out){if((0,
|
|
211
|
-
`);for await(let n of i){if(!n.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(n)}catch{process.stdout.write(`${JSON.stringify(
|
|
212
|
-
`);return}let a=await
|
|
210
|
+
`);console.log(ae.default.dim(` Nothing is sent by this command. Send through the reply endpoint with assistant_plan_id=${i.id} or from the app.`)),d()}function mu(e,t){if(t.json)return y(e,t.fields);let i=e.events||[];d(),S("Assistant activity"),i.length?B(["When","Kind","Action","Work item"],i.map(s=>[s.occurred_at||"",s.kind||"",s.action||s.type||"",ae.default.dim(s.work_item?.id||s.work_item_id||"")])):console.log(ae.default.dim(" No activity yet.")),d()}async function Ca(e,t,i){let s;try{s=nu(e,t,i)}catch(g){throw g instanceof ge&&u(g.message,{hint:g.hint,code:"validation_error",json:i.json}),g}let n=e||"today",r={},o;s.idempotency&&(o=ct(s.idempotency,s.body||{},i.idempotencyKey),r["Idempotency-Key"]=o.key,s.body&&s.path.endsWith("/interactions")&&(s.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"}[n]||(s.method!=="GET"?"Recording your decision":void 0),l=C(!i.json&&!!a);a&&l.start(a);let f=await _(s.path,{method:s.method,headers:r,...s.body?{body:JSON.stringify(s.body)}:{}}),m=await ru(f,i);switch(o?.complete(),a&&l.stop(`${w.success} Done`),n){case"today":return au(m,i);case"settings":return du(m,i);case"backfill":return cu(m,i);case"item":return ja(m,i);case"brief":return lu(m,i);case"facts":return y(m,i.fields);case"plan":return uu(m,i);case"activity":return mu(m,i);case"export":{let g=`${JSON.stringify(m,null,2)}
|
|
211
|
+
`;if(i.out){if((0,Sa.writeFileSync)(i.out,g,"utf8"),i.json)return y({exported:!0,path:i.out},i.fields);console.log(`${w.success} Derived assistant data exported to ${i.out}`);return}process.stdout.write(g);return}case"delete":if(i.json)return y(m,i.fields);console.log(`${w.success} Derived assistant data deleted. Source mail is untouched.`);return;default:if(i.json)return y(m,i.fields);if(n==="set"||n==="preview"||n==="retry"){n==="preview"&&console.log(ae.default.dim(` Import ${m.preview?.backfill_id||""} runs in the background. Follow it with: domani assistant backfill`)),n==="retry"&&console.log(` Requeued ${m.retried??m.requeued??0} messages`),n==="set"&&console.log(` enabled=${m.enabled?"yes":"no"} shadow=${m.shadow_enabled?"yes":"no"} paused=${m.paused?"yes":"no"} mailboxes=${(m.mailbox_ids||[]).length}`);return}return m.work_item?ja(m,i):y(m,i.fields)}}K();var ys=D(M(),1);L();var fu=["list","token","tokens","revoke-token"],Jt=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="AgentsUsageError"}};function pu(e,t,i){switch(e||"list"){case"list":return{method:"GET",path:"/api/agents/identity"};case"token":{if(!t)throw new Jt("Agent handle is required",'Usage: domani agents token <slug> [--name "Dave on the pod"] [--mailboxes mb_1,mb_2]');let s=(i.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean);return{method:"POST",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`,body:{...i.name?{name:i.name}:{},...s.length?{mailbox_ids:s}:{}}}}case"tokens":if(!t)throw new Jt("Agent handle is required","Usage: domani agents tokens <slug>");return{method:"GET",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`};case"revoke-token":if(!t||!i.tokenId)throw new Jt("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(i.tokenId)}`};default:throw new Jt(`Unknown action: ${e}`,`Actions: ${fu.join(", ")}`)}}async function Oa(e,t,i){let s;try{s=pu(e,t,i)}catch(o){if(o instanceof Jt)return u(o.message,{hint:o.hint,code:"validation_error",json:i.json,fields:i.fields});throw o}let n=await _(s.path,{method:s.method,...s.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(s.body)}:{}}),r=await n.json().catch(()=>({}));if(!n.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:n.status,json:i.json,fields:i.fields});if(i.json)return y(r,i.fields);switch(e||"list"){case"list":{let o=r.identities||r.items||[];if(S("Agent identities"),!o.length){console.log(` ${ys.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":{S("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(", ")),Pe("Shown once. The key sees only this agent's mailboxes and the items handed to it.");return}case"tokens":{let o=r.tokens||[];if(S("Agent API keys"),!o.length){console.log(` ${ys.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(`${ys.default.green("\u2713")} Token revoked`);return}}var Ia=D(M(),1);K();L();async function hu(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}async function Ra(e,t,i,s){let n=`/api/domains/${encodeURIComponent(e)}/hostname-bindings`,r;if(!t||t==="list")r=await _(n);else if(t==="plan")s.hostname||u("--hostname is required",{code:"validation_error",json:s.json}),r=await _(`${n}/plan`,{method:"POST",body:JSON.stringify({hostname:s.hostname,browser_mode:s.browserMode})});else if(t==="create"){s.hostname||u("--hostname is required",{code:"validation_error",json:s.json});let l={hostname:s.hostname,browser_mode:s.browserMode,expected_zone_version:s.expectedZoneVersion,acknowledgements:s.acknowledgements?.split(",").map(m=>m.trim())},f=ct(`binding:create:${e}:${s.hostname}`,l);r=await _(n,{method:"POST",headers:{"Idempotency-Key":f.key},body:JSON.stringify(l)}),r.ok&&f.complete()}else{i||u("Binding ID is required",{hint:`Usage: domani binding ${e} ${t} <id>`,code:"validation_error",json:s.json});let l=`${n}/${encodeURIComponent(i)}`;if(t==="get")r=await _(l);else if(t==="verify")r=await _(`${l}/verify`,{method:"POST"});else if(t==="delete")r=await _(l,{method:"DELETE"});else if(t==="update"){s.browserMode||u("--browser-mode is required",{code:"validation_error",json:s.json});let f={browser_mode:s.browserMode,acknowledgements:s.acknowledgements?.split(",").map(g=>g.trim())},m=ct(`binding:update:${e}:${i}`,f);r=await _(l,{method:"PATCH",headers:{"Idempotency-Key":m.key},body:JSON.stringify(f)}),r.ok&&m.complete()}else return u(`Unknown action: ${t}`,{hint:"Actions: list, plan, create, get, update, verify, delete",code:"validation_error",json:s.json})}if(r.status===204){if(s.json)return y({disabled:!0,id:i},s.fields);console.log("Hostname binding disabled");return}let o=await hu(r,s);if(s.json)return y(o,s.fields);d(),S(t==="plan"?"Hostname Binding Plan":"Hostname Bindings");let a=o.hostname_bindings||(o.hostname_binding?[o.hostname_binding]:[]);if(a.length)for(let l of a)console.log(` ${Ia.default.dim(l.id)} ${l.hostname_pattern} ${l.status} ${l.browser_mode}`);else console.log(JSON.stringify(o,null,2));d()}var Aa=D(require("node:readline"),1);gt();function gu(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function Wn(e,t,i,s){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...s?{data:s}:{}}}}function ji(e,t,i,s){let n=gu(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>Wn(r.id??null,t,i,s));if(n.length!==0)return Array.isArray(e)?n:n[0]}function yu(e){let t=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{t.push(JSON.parse(s))}catch{}}return t}async function bu(e,t={}){let i=t.fetchImpl??fetch,s=t.getAuthToken?t.getAuthToken():We(),n=(t.apiUrl??Ve()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};s&&(r.Authorization=`Bearer ${s}`);let o=()=>i(`${n}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(m){let g=m instanceof Error?m.message:"Unknown network error",b=ji(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:g});return b===void 0?[]:[b]}if(a.status===401){let m=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:We({refreshKeychain:!0});if(m&&m!==s){await a.body?.cancel(),s=m,r.Authorization=`Bearer ${s}`;try{a=await o()}catch(g){let b=g instanceof Error?g.message:"Unknown network error",k=ji(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:b});return k===void 0?[]:[k]}}}if(a.status===202||a.status===204)return[];let l=await a.text();if(a.status===401){let m=ji(e,-32001,"Domani authentication required",{code:"AUTH_REQUIRED",hint:"Run `npx -y domani-cli@latest login`, approve access in the browser, then retry. Never paste an API key into chat.",fix_command:"npx -y domani-cli@latest login"});return m===void 0?[]:[m]}if(!a.ok){let m=ji(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 m===void 0?[]:[m]}if(!l.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return yu(l);try{return[JSON.parse(l)]}catch{let m=ji(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return m===void 0?[]:[m]}}async function Ea(e={}){let t=e.stderr??process.stderr,i=Aa.default.createInterface({input:process.stdin,crlfDelay:1/0}),s=new Set;e.verbose&&t.write(`domani MCP bridge ready
|
|
212
|
+
`);for await(let n of i){if(!n.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(n)}catch{process.stdout.write(`${JSON.stringify(Wn(null,-32700,"Parse error"))}
|
|
213
|
+
`);return}let a=await bu(o,e);for(let l of a)process.stdout.write(`${JSON.stringify(l)}
|
|
213
214
|
`)})().catch(o=>{if(e.verbose){let a=o instanceof Error?o.message:String(o);t.write(`domani MCP bridge internal error: ${a}
|
|
214
|
-
`)}process.stdout.write(`${JSON.stringify(
|
|
215
|
-
`)});s.add(r),r.then(()=>s.delete(r))}await Promise.all(s)}process.stdin.setMaxListeners(50);var W=new
|
|
215
|
+
`)}process.stdout.write(`${JSON.stringify(Wn(null,-32603,"Domani MCP bridge internal error"))}
|
|
216
|
+
`)});s.add(r),r.then(()=>s.delete(r))}await Promise.all(s)}process.stdin.setMaxListeners(50);var W=new sr;W.name("domani").description(`Domain names for developers and AI agents - ${Gt}`).version(xe).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${ut.default.red("\u2717")} ${i}
|
|
216
217
|
`),/unknown option|missing required|expected argument/i.test(i)){let s=process.argv[2],n=s&&!s.startsWith("-")?`domani ${s} --help`:"domani --help";t(`${ut.default.dim(` Run \`${n}\` to see available options.`)}
|
|
217
|
-
`)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&
|
|
218
|
+
`)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&pr(i.apiUrl),process.stdout.isTTY||t.options.some(r=>r.long==="--json")&&t.setOptionValue("json",!0),["login","logout","search","suggest","tlds","whois","schema","update","uninstall","mcp"].includes(t.name())||await no()});W.command("login").description(`Log in to ${Gt} (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",`
|
|
218
219
|
Examples:
|
|
219
220
|
domani login # interactive login (opens browser)
|
|
220
221
|
domani login --scopes domains:read,search --label "Project agent" --expires-in 86400
|
|
@@ -223,54 +224,54 @@ Examples:
|
|
|
223
224
|
domani login --surface plugin # authenticate the Domani agent plugin
|
|
224
225
|
domani login --json # non-interactive (returns auth_url)
|
|
225
226
|
domani login --no-open # print login URL without opening browser
|
|
226
|
-
DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(
|
|
227
|
+
DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(ro);W.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(oo);W.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
|
|
227
228
|
Examples:
|
|
228
229
|
domani me # show account overview
|
|
229
230
|
domani me --json # machine-readable account info
|
|
230
|
-
domani me --json --fields email,plan # just email and plan`).action(
|
|
231
|
+
domani me --json --fields email,plan # just email and plan`).action(lo);W.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(na);W.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 ga(t);if(e==="add")return ya(t);if(e==="remove")return ba(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});W.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(oa);W.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(aa);W.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(ra);W.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(Mo);W.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
|
|
231
232
|
Examples:
|
|
232
233
|
domani login # authenticate once in your browser
|
|
233
234
|
domani mcp serve # stdio bridge for agent plugins
|
|
234
235
|
|
|
235
236
|
The bridge reads the API token from the OS keychain. It never prints the token
|
|
236
|
-
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
|
|
237
|
+
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 Ea({verbose:t.verbose})});W.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",`
|
|
237
238
|
Examples:
|
|
238
239
|
domani tokens list # list all tokens
|
|
239
240
|
domani tokens create --name "CI" --scopes "domains:read,search"
|
|
240
241
|
domani tokens create --name "Support agent" --agent-identity agent_abc123
|
|
241
|
-
domani tokens revoke --token-id tok_abc123`).action(
|
|
242
|
+
domani tokens revoke --token-id tok_abc123`).action(Lo);W.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",`
|
|
242
243
|
Examples:
|
|
243
244
|
domani search myapp # check popular TLDs
|
|
244
245
|
domani search myapp .io .fm .xyz # specific TLDs
|
|
245
246
|
domani search myapp --expand # check 30+ TLDs
|
|
246
247
|
domani search myapp --max-price 20 # only affordable options
|
|
247
|
-
domani search myapp --json # machine-readable output`).action(
|
|
248
|
+
domani search myapp --json # machine-readable output`).action(Oo);W.command("tlds").description("List all TLDs with pricing").option("--max-price <price>","Maximum registration price").option("--min-price <price>","Minimum registration price").option("--sort <field>","Sort by: price, tld, renewal (default: tld)").option("--search <term>","Filter TLDs by name").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Eo);W.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(To);W.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",`
|
|
248
249
|
Examples:
|
|
249
250
|
domani suggest "cat sitting marketplace"
|
|
250
251
|
domani suggest "AI code editor" --style creative --tlds ai,dev
|
|
251
|
-
domani suggest "meditation app" --lang japanese --count 5`).action(
|
|
252
|
+
domani suggest "meditation app" --lang japanese --count 5`).action(Po);W.command("buy [domains...]").description("Purchase one or more domains").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
|
|
252
253
|
Examples:
|
|
253
254
|
domani buy myapp.dev # buy one domain
|
|
254
255
|
domani buy myapp.dev myapp.com myapp.ai # buy multiple
|
|
255
256
|
domani buy myapp.dev --dry-run # preview without buying
|
|
256
257
|
domani buy myapp.dev --yes # skip confirmation
|
|
257
|
-
domani buy myapp.dev --json # machine-readable output`).action(
|
|
258
|
+
domani buy myapp.dev --json # machine-readable output`).action(Nn);W.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("--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",`
|
|
258
259
|
Examples:
|
|
259
260
|
domani provision myagent.run # domain + hi@ mailbox
|
|
260
261
|
domani provision myagent.run --slug hey --name "My Agent" # custom mailbox
|
|
261
262
|
DOMANI_SENDER_AUTH="Bearer secret" domani provision myagent.run --webhook https://me.dev/inbox --authorization-env DOMANI_SENDER_AUTH
|
|
262
|
-
domani provision myagent.run --dry-run # preview`).action(
|
|
263
|
+
domani provision myagent.run --dry-run # preview`).action(Ro);W.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",`
|
|
263
264
|
Examples:
|
|
264
265
|
domani adopt myapp.com
|
|
265
|
-
domani adopt myapp.com --json`).action(
|
|
266
|
+
domani adopt myapp.com --json`).action(Uo);W.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",`
|
|
266
267
|
Examples:
|
|
267
268
|
domani transfer myapp.com --auth-code ABC123XYZ
|
|
268
269
|
domani transfer myapp.com --auth-code ABC123XYZ --dry-run
|
|
269
270
|
domani transfer myapp.com --auth-code ABC123XYZ --yes
|
|
270
|
-
domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(
|
|
271
|
+
domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(No);W.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(qo);W.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",`
|
|
271
272
|
Examples:
|
|
272
273
|
domani import myapp.com # start import (shows TXT record to add)
|
|
273
|
-
domani import myapp.com --verify # verify TXT record and complete import`).action(
|
|
274
|
+
domani import myapp.com --verify # verify TXT record and complete import`).action(Fo);W.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",`
|
|
274
275
|
Examples:
|
|
275
276
|
domani sell myapp.dev --price 5000 # list for $5,000
|
|
276
277
|
domani sell myapp.dev --price 5000 --description "Great brand name"
|
|
@@ -278,14 +279,14 @@ Examples:
|
|
|
278
279
|
domani sell external.com --verify # verify TXT record
|
|
279
280
|
domani sell myapp.dev --status # check listing status
|
|
280
281
|
domani sell myapp.dev --cancel # remove from sale
|
|
281
|
-
domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(
|
|
282
|
+
domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(Xo);W.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("--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",`
|
|
282
283
|
Examples:
|
|
283
284
|
domani route create --hostname preview.example.com --upstream http://bore.pub:45255
|
|
284
285
|
domani route list --domain example.com --status active
|
|
285
286
|
domani route refresh route_123 --expires-in 3600
|
|
286
287
|
domani route rotate-verification route_123
|
|
287
288
|
domani route rotate-headers route_123 --upstream-authorization-env SPRITES_AUTH
|
|
288
|
-
domani route delete route_123`).action(
|
|
289
|
+
domani route delete route_123`).action(_a);W.command("assistant [action] [id]").description("Mailzero 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("--yes","Confirm deletion of derived data (for delete)").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",`
|
|
289
290
|
Actions:
|
|
290
291
|
today Now, Needs you, Waiting, Upcoming, Handled
|
|
291
292
|
settings Opt-in state, consent, and mailbox scope
|
|
@@ -314,21 +315,21 @@ Examples:
|
|
|
314
315
|
This command never sends mail. Choosing an option prepares an exact draft; review it
|
|
315
316
|
with "assistant plan" and send it through the normal reply endpoint
|
|
316
317
|
(POST /api/emails/{address}/messages/{id}/reply with assistant_plan_id) or from the app.
|
|
317
|
-
Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(
|
|
318
|
+
Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(Ca);W.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",`
|
|
318
319
|
Examples:
|
|
319
320
|
domani binding list example.com
|
|
320
321
|
domani binding plan example.com --hostname '*.example.com' --browser-mode stateless
|
|
321
322
|
domani binding create example.com --hostname '*.example.com' --expected-zone-version <version>
|
|
322
|
-
domani binding verify example.com binding_123`).action((e,t,i,s)=>
|
|
323
|
+
domani binding verify example.com binding_123`).action((e,t,i,s)=>Ra(t,e,i,s));W.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
|
|
323
324
|
Examples:
|
|
324
325
|
domani list # list all domains
|
|
325
326
|
domani domains # alias for list
|
|
326
|
-
domani list --json --fields domain,expires_at`).action(
|
|
327
|
+
domani list --json --fields domain,expires_at`).action(Ao);W.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(Tn);W.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",`
|
|
327
328
|
Examples:
|
|
328
329
|
domani connect --list # list providers
|
|
329
330
|
domani connect myapp.dev vercel # connect to Vercel
|
|
330
331
|
domani connect myapp.dev --provider google-workspace # connect Google Workspace
|
|
331
|
-
domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(
|
|
332
|
+
domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(xn);W.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
|
|
332
333
|
Examples:
|
|
333
334
|
domani email list # list all mailboxes
|
|
334
335
|
domani email create --domain myapp.dev --slug hi # create hi@myapp.dev
|
|
@@ -345,7 +346,13 @@ Examples:
|
|
|
345
346
|
domani email webhook-test hi@myapp.dev # one signed test; live inbound retries up to 3x
|
|
346
347
|
domani email setup myapp.dev # setup email for domain
|
|
347
348
|
domani email status myapp.dev # check email DNS health
|
|
348
|
-
domani email delete --domain myapp.dev --slug hi # delete mailbox
|
|
349
|
+
domani email delete --domain myapp.dev --slug hi # delete mailbox
|
|
350
|
+
domani email search "the invoice from tucows" # by meaning and by words, every mailbox
|
|
351
|
+
domani email threads --from hi@myapp.dev # conversations, newest activity first
|
|
352
|
+
domani email thread THREAD --from hi@myapp.dev # one conversation, oldest first
|
|
353
|
+
domani email label --from hi@myapp.dev --message-ids m1 --add billing,urgent
|
|
354
|
+
domani email facts MSG --from hi@myapp.dev # what the assistant established
|
|
355
|
+
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)").option("--until <iso>","Only mail before this time (for search)").option("--label <labels>","Comma-separated labels, any of (for search, threads, 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("--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("--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(hi);W.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>","Mailzero 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",`
|
|
349
356
|
Examples:
|
|
350
357
|
domani workspace list
|
|
351
358
|
domani workspace create --name Acme
|
|
@@ -362,28 +369,28 @@ Examples:
|
|
|
362
369
|
domani workspace transfer --id ws_123 --membership-id mem_123
|
|
363
370
|
domani workspace accept-ownership --token <ownership-token>
|
|
364
371
|
domani workspace adopt-mailbox --id ws_123 --mailbox-id mb_123
|
|
365
|
-
domani workspace checkout --id ws_123 --plan mail_team`).action(
|
|
372
|
+
domani workspace checkout --id ws_123 --plan mail_team`).action(wa);W.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/delete/snapshot/restore)").option("--type <type>","Record type: A, AAAA, CNAME, MX, TXT, NS, SRV").option("--name <name>","Record name (e.g. www, @, _dmarc)").option("--value <value>","Record value").option("--file <path>","Snapshot file path (for restore)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
|
|
366
373
|
Examples:
|
|
367
374
|
domani dns myapp.dev get # list all records
|
|
368
375
|
domani dns myapp.dev set --type A --name @ --value 76.76.21.21 # add A record
|
|
369
376
|
domani dns myapp.dev set --type CNAME --name www --value cname.vercel-dns.com
|
|
370
377
|
domani dns myapp.dev delete --type A --name @
|
|
371
378
|
domani dns myapp.dev snapshot # export DNS as JSON
|
|
372
|
-
domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(
|
|
379
|
+
domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(An);W.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(la);W.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",`
|
|
373
380
|
Examples:
|
|
374
381
|
domani settings myapp.dev # view current settings
|
|
375
382
|
domani settings myapp.dev --auto-renew on # enable auto-renew
|
|
376
383
|
domani settings myapp.dev --whois-privacy on # enable WHOIS privacy
|
|
377
|
-
domani settings myapp.dev --security-lock off # unlock for transfer`).action(
|
|
384
|
+
domani settings myapp.dev --security-lock off # unlock for transfer`).action(Vo);W.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(Wo);W.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(Ho);W.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
|
|
378
385
|
Examples:
|
|
379
386
|
domani contact # view current contact info
|
|
380
387
|
domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
|
|
381
|
-
--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(
|
|
388
|
+
--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(Jo);W.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",`
|
|
382
389
|
Examples:
|
|
383
390
|
domani parking myapp.dev # view parking status
|
|
384
391
|
domani parking myapp.dev enable # enable parking page
|
|
385
392
|
domani parking myapp.dev disable # disable parking page
|
|
386
|
-
domani parking myapp.dev price 500 # set for-sale price to $500`).action(
|
|
393
|
+
domani parking myapp.dev price 500 # set for-sale price to $500`).action(Ko);W.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(zo);W.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
|
|
387
394
|
Examples:
|
|
388
395
|
domani webhooks list
|
|
389
396
|
domani webhooks create --url https://example.com/hook --events domain.purchased,domain.expiring
|
|
@@ -393,12 +400,12 @@ Examples:
|
|
|
393
400
|
domani webhooks delete --webhook-id wh_abc
|
|
394
401
|
domani webhooks deliveries --webhook-id wh_abc
|
|
395
402
|
domani webhooks replay --webhook-id wh_abc --delivery-id del_abc --idempotency-key incident-2026-07-25
|
|
396
|
-
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(
|
|
403
|
+
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(Yo);W.command("deals [id]").description("List marketplace deals or view deal details").option("--role <role>","Filter by role: buyer or seller").option("--status <status>","Filter by status: active, completed, or all").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
|
|
397
404
|
Examples:
|
|
398
405
|
domani deals # list all your deals
|
|
399
406
|
domani deals --role seller --status active # your active sales
|
|
400
407
|
domani deals deal_abc123 # view specific deal
|
|
401
|
-
domani deals --json # machine-readable output`).action(
|
|
408
|
+
domani deals --json # machine-readable output`).action(Zo);W.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",`
|
|
402
409
|
Actions:
|
|
403
410
|
request <domain> ask domani to acquire a taken domain (commission-only)
|
|
404
411
|
list (default) list your acquisition requests
|
|
@@ -409,7 +416,12 @@ Examples:
|
|
|
409
416
|
domani broker request dream.com --max-budget 5000
|
|
410
417
|
domani broker # list your requests
|
|
411
418
|
domani broker status brq_abc123
|
|
412
|
-
domani broker cancel brq_abc123`).action((e,t,i)=>
|
|
419
|
+
domani broker cancel brq_abc123`).action((e,t,i)=>ta(e,t,i));W.command("notifications").alias("notifs").description("View notifications or mark all as read").option("--read","Mark all notifications as read").option("--unread","Show only unread notifications").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(sa);W.command("send [arg2]").description("Send an email - shortcut for: domani email send").option("--from <email>","Sender address user@domain").option("--to <email>","Recipient email address").option("--cc <emails>","CC recipients, comma-separated").option("--bcc <emails>","BCC recipients, comma-separated").option("--subject <s>","Email subject").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to").option("--references <message-ids>","Space-separated Message-ID chain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t)=>hi("send",e,t));W.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)=>hi("inbox",e,t));W.command("agents [action] [slug]").description("Agent identities: give an agent its own API key, list or revoke its keys").addHelpText("after",`
|
|
420
|
+
Examples:
|
|
421
|
+
domani agents list # your agent identities
|
|
422
|
+
domani agents token dave --name "Dave on the pod" # mint a confined key for dave.domani.run
|
|
423
|
+
domani agents tokens dave # the keys of dave
|
|
424
|
+
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,i)=>Oa(e,t,i));W.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(ha);W.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(ca);W.command("uninstall").description("Remove domani CLI and config from this machine").action(fa);(async()=>{let e=yr();await W.parseAsync();let t=await e,i=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
|
|
413
425
|
${ut.default.red("!")} CLI v${xe} is no longer supported. Run ${ut.default.bold(i)} to upgrade to v${t.update}
|
|
414
426
|
`),process.exit(1)):t?.update&&console.error(`
|
|
415
427
|
${ut.default.yellow("!")} Update available: ${ut.default.dim(xe)} ${ut.default.dim("\u2192")} ${ut.default.green(t.update)} Run ${ut.default.bold(i)}
|