mmx-cli 1.0.21 → 1.0.24

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/mmx.mjs CHANGED
@@ -1,309 +1,797 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as qi}from"node:module";var Ii=Object.create;var{getPrototypeOf:Ti,defineProperty:vt,getOwnPropertyNames:Mi}=Object;var Oi=Object.prototype.hasOwnProperty;function Pi(e){return this[e]}var Ni,Li,ze=(e,t,o)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?Ni??=new WeakMap:Li??=new WeakMap,s=i.get(e);if(s)return s}o=e!=null?Ii(Ti(e)):{};let r=t||!e||!e.__esModule?vt(o,"default",{value:e,enumerable:!0}):o;if(e&&typeof e==="object"||typeof e==="function"){for(let u of Mi(e))if(!Oi.call(r,u))vt(r,u,{get:Pi.bind(e,u),enumerable:!0})}if(n)i.set(e,r);return r};var vr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ui=(e)=>e;function Gi(e,t){this[e]=Ui.bind(null,t)}var $t=(e,t)=>{for(var o in t)vt(e,o,{get:t[o],enumerable:!0,configurable:!0,set:Gi.bind(t,o)})};var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var Be=qi(import.meta.url);var d;var S=C(()=>{d={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10}});var m;var R=C(()=>{S();m=class m extends Error{exitCode;hint;constructor(e,t=d.GENERAL,o){super(e);this.name="CLIError",this.exitCode=t,this.hint=o}toJSON(){return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{}}}}}});function zi(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.access_token!=="string"||!t.access_token)return;if(typeof t.refresh_token!=="string")return;if(typeof t.expires_at!=="string")return;let o={access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at};if(typeof t.region==="string"&&Ar.has(t.region))o.region=t.region;if(typeof t.resource_url==="string"&&t.resource_url.startsWith("http"))o.resource_url=t.resource_url;if(typeof t.account==="string"&&t.account.length>0)o.account=t.account;return o}function Sr(e){if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=e,o={};if(typeof t.api_key==="string")o.api_key=t.api_key;if(typeof t.region==="string"&&Ar.has(t.region))o.region=t.region;if(typeof t.base_url==="string"&&t.base_url.startsWith("http"))o.base_url=t.base_url;if(typeof t.output==="string"&&Ki.has(t.output))o.output=t.output;if(typeof t.timeout==="number"&&t.timeout>0)o.timeout=t.timeout;if(typeof t.proxy==="string"&&t.proxy.startsWith("http"))o.proxy=t.proxy;let n=zi(t.oauth);if(n)o.oauth=n;if(typeof t.default_text_model==="string"&&t.default_text_model.length>0)o.default_text_model=t.default_text_model;if(typeof t.default_speech_model==="string"&&t.default_speech_model.length>0)o.default_speech_model=t.default_speech_model;if(typeof t.default_video_model==="string"&&t.default_video_model.length>0)o.default_video_model=t.default_video_model;return o}var U,Le,Je,Ar,Ki;var re=C(()=>{U={global:"https://api.minimax.io",cn:"https://api.minimaxi.com"},Le={global:"https://platform.minimax.io",cn:"https://platform.minimaxi.com"},Je={global:"https://account.minimax.io",cn:"https://account.minimaxi.com"},Ar=new Set(["global","cn"]),Ki=new Set(["text","json"])});function w(e){return{name:e.name,description:e.description,usage:e.usage,options:e.options,examples:e.examples,apiDocs:e.apiDocs,execute:e.run}}var Ye;var T=C(()=>{Ye=[{flag:"--api-key <key>",description:"API key"},{flag:"--region <region>",description:"API region: global, cn"},{flag:"--base-url <url>",description:"API base URL"},{flag:"--output <format>",description:"Output format: text, json"},{flag:"--timeout <seconds>",description:"Request timeout",type:"number"},{flag:"--quiet",description:"Suppress non-essential output"},{flag:"--verbose",description:"Print HTTP request/response details"},{flag:"--no-color",description:"Disable ANSI colors"},{flag:"--dry-run",description:"Dry run mode"},{flag:"--non-interactive",description:"Disable interactive prompts"},{flag:"--help",description:"Show help"},{flag:"--version",description:"Print version"}]});import{homedir as Ji}from"os";import{join as kr}from"path";function Xe(){if(process.env.MMX_CONFIG_DIR)return process.env.MMX_CONFIG_DIR;return kr(Ji(),Yi)}function oe(){return kr(Xe(),"config.json")}async function Rr(){let e=Xe();await(await import("fs/promises")).mkdir(e,{recursive:!0,mode:448})}var Yi=".mmx";var Ie=()=>{};var Ir={};$t(Ir,{formatKeyValue:()=>Qe,formatTable:()=>Br,formatText:()=>St});function St(e){if(e===null||e===void 0)return"";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);if(Array.isArray(e)){if(e.length===0)return"(empty)";if(typeof e[0]==="object"&&e[0]!==null)return Br(e);return e.map(String).join(`
3
- `)}if(typeof e==="object")return Qe(e);return String(e)}function Qe(e,t=0){let o=" ".repeat(t),n=[];for(let[i,s]of Object.entries(e)){if(s===null||s===void 0)continue;if(Array.isArray(s)){n.push(`${o}${i}:`);for(let r of s)if(typeof r==="object"&&r!==null)n.push(`${o} - ${Qe(r,t+4).trimStart()}`);else n.push(`${o} - ${String(r)}`)}else if(typeof s==="object")n.push(`${o}${i}:`),n.push(Qe(s,t+2));else n.push(`${o}${i}: ${String(s)}`)}return n.join(`
4
- `)}function Br(e){if(e.length===0)return"(empty)";let t=Object.keys(e[0]),o=t.map((r)=>Math.max(r.length,...e.map((u)=>String(u[r]??"").length))),n=t.map((r,u)=>r.toUpperCase().padEnd(o[u])).join(" "),i=o.map((r)=>"-".repeat(r)).join(" "),s=e.map((r)=>t.map((u,a)=>String(r[u]??"").padEnd(o[a])).join(" "));return[n,i,...s].join(`
5
- `)}function Tr(e){return JSON.stringify(e,null,2)}function _(e){if(e==="json"||e==="text")return e;if(!process.stdout.isTTY)return"json";return"text"}function F(e,t){switch(t){case"json":return Tr(e);case"text":return St(e)}}function le(e,t){if(!e.dryRun)return!1;return console.log(F({request:t},_(e.output))),!0}var N=()=>{};import{copyFileSync as Xi,existsSync as Qi,readFileSync as Zi,renameSync as es,unlinkSync as ts,writeFileSync as rs}from"fs";function os(e){return e instanceof Error&&"code"in e&&e.code==="EXDEV"}function ns(e,t,o={rename:es,copy:Xi,unlink:ts}){try{o.rename(e,t)}catch(n){if(!os(n))throw n;o.copy(e,t),o.unlink(e)}}function P(){let e=oe();if(!Qi(e))return{};try{return Sr(JSON.parse(Zi(e,"utf-8")))}catch(t){let o=t;if(o instanceof SyntaxError||o.message.includes("JSON"))process.stderr.write(`Warning: config file is corrupted. Run 'mmx config set' to reset.
6
- `);return{}}}async function K(e,t){await Rr();let o=oe(),n=o+".tmp";rs(n,JSON.stringify(e,null,2)+`
7
- `,{mode:384}),ns(n,o,t)}function kt(e){let t=P(),o=e.apiKey||void 0,n=t.api_key,i=e.region||process.env.MINIMAX_REGION||void 0;if(i&&!(i in U))throw new m(`Invalid region "${i}". Valid values: ${Object.keys(U).join(", ")}`,d.USAGE);let s=t.region,r=i||s||"global",u=o||n,a=!i&&(!s||u!==void 0&&u!==t.api_key),l=e.baseUrl||process.env.MINIMAX_BASE_URL||t.base_url||t.oauth?.resource_url||U[r]||U.global,p=_(e.output||process.env.MINIMAX_OUTPUT||t.output),f=process.env.MINIMAX_TIMEOUT?Number(process.env.MINIMAX_TIMEOUT):void 0,D=f!==void 0&&Number.isFinite(f)&&f>0?f:void 0,h=e.timeout??D??t.timeout??300;return{apiKey:o,fileApiKey:n,fileRegion:t.region,configPath:oe(),region:r,baseUrl:l,output:p,timeout:h,defaultTextModel:t.default_text_model,defaultSpeechModel:t.default_speech_model,defaultVideoModel:t.default_video_model,verbose:e.verbose||process.env.MINIMAX_VERBOSE==="1",quiet:e.quiet||!1,noColor:e.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,yes:e.yes||!1,dryRun:e.dryRun||!1,nonInteractive:e.nonInteractive||!1,async:e.async||!1,needsRegionDetection:a}}var se=C(()=>{re();Ie();N();R();S()});function G(e){if(e?.nonInteractive===!0)return!1;if(process.env.CI)return!1;return process.stdout.isTTY===!0&&process.stdin.isTTY===!0}var Bt=vr(function(Ic,Mr){var Rt={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let o="";if(e<0)o+=`\x1B[${-e}D`;else if(e>0)o+=`\x1B[${e}C`;if(t<0)o+=`\x1B[${-t}A`;else if(t>0)o+=`\x1B[${t}B`;return o},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"},is={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},ss={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 o=0;o<e;o++)t+=this.line+(o<e-1?Rt.up():"");if(e)t+=Rt.left;return t}};Mr.exports={cursor:Rt,scroll:is,erase:ss,beep:"\x07"}});var Tt=vr(function(Tc,It){var et=process||{},Or=et.argv||[],Ze=et.env||{},us=!(!!Ze.NO_COLOR||Or.includes("--no-color"))&&(!!Ze.FORCE_COLOR||Or.includes("--color")||et.platform==="win32"||(et.stdout||{}).isTTY&&Ze.TERM!=="dumb"||!!Ze.CI),as=(e,t,o=e)=>(n)=>{let i=""+n,s=i.indexOf(t,e.length);return~s?e+cs(i,t,o,s)+t:e+i+t},cs=(e,t,o,n)=>{let i="",s=0;do i+=e.substring(s,n)+o,s=n+t.length,n=e.indexOf(t,s);while(~n);return i+e.substring(s)},Pr=(e=us)=>{let t=e?as:()=>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")}};It.exports=Pr();It.exports.createColors=Pr});import{stdin as Xr,stdout as Qr}from"node:process";import*as me from"node:readline";import Nr from"node:readline";import{WriteStream as ls}from"node:tty";function ms({onlyFirst:e=!1}={}){let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}function Zr(e){if(typeof e!="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(ds,"")}function eo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ue(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Zr(e),e.length===0))return 0;e=e.replace(hs()," ");let o=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let s=i.codePointAt(0);if(s<=31||s>=127&&s<=159||s>=768&&s<=879)continue;switch(Ds.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=o;break;default:n+=1}}return n}function ys(){let e=new Map;for(let[t,o]of Object.entries(O)){for(let[n,i]of Object.entries(o))O[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},o[n]=O[n],e.set(i[0],i[1]);Object.defineProperty(O,t,{value:o,enumerable:!1})}return Object.defineProperty(O,"codes",{value:e,enumerable:!1}),O.color.close="\x1B[39m",O.bgColor.close="\x1B[49m",O.color.ansi=Lr(),O.color.ansi256=Ur(),O.color.ansi16m=Gr(),O.bgColor.ansi=Lr(Mt),O.bgColor.ansi256=Ur(Mt),O.bgColor.ansi16m=Gr(Mt),Object.defineProperties(O,{rgbToAnsi256:{value:(t,o,n)=>t===o&&o===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(o/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:(t)=>{let o=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!o)return[0,0,0];let[n]=o;n.length===3&&(n=[...n].map((s)=>s+s).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:(t)=>O.rgbToAnsi256(...O.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value:(t)=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let o,n,i;if(t>=232)o=((t-232)*10+8)/255,n=o,i=o;else{t-=16;let u=t%36;o=Math.floor(t/36)/5,n=Math.floor(u/6)/5,i=u%6/5}let s=Math.max(o,n,i)*2;if(s===0)return 30;let r=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(o));return s===2&&(r+=60),r},enumerable:!1},rgbToAnsi:{value:(t,o,n)=>O.ansi256ToAnsi(O.rgbToAnsi256(t,o,n)),enumerable:!1},hexToAnsi:{value:(t)=>O.ansi256ToAnsi(O.hexToAnsi256(t)),enumerable:!1}}),O}function jr(e,t,o){return String(e).normalize().replace(/\r\n/g,`
2
+ import{createRequire as xm}from"node:module";var dm=Object.create;var{getPrototypeOf:pm,defineProperty:Zr,getOwnPropertyNames:mm}=Object;var hm=Object.prototype.hasOwnProperty;function gm(e){return this[e]}var ym,bm,Ft=(e,t,n)=>{var i=e!=null&&typeof e==="object";if(i){var r=t?ym??=new WeakMap:bm??=new WeakMap,s=r.get(e);if(s)return s}n=e!=null?dm(pm(e)):{};let o=t||!e||!e.__esModule?Zr(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of mm(e))if(!hm.call(o,a))Zr(o,a,{get:gm.bind(e,a),enumerable:!0})}if(i)r.set(e,o);return o};var M=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var wm=(e)=>e;function vm(e,t){this[e]=wm.bind(null,t)}var ii=(e,t)=>{for(var n in t)Zr(e,n,{get:t[n],enumerable:!0,configurable:!0,set:vm.bind(t,n)})};var I=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ce=xm(import.meta.url);var x;var V=I(()=>{x={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10}});var v;var G=I(()=>{V();v=class v extends Error{exitCode;hint;constructor(e,t=x.GENERAL,n){super(e);this.name="CLIError",this.exitCode=t,this.hint=n}toJSON(){return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{}}}}}});function _m(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.access_token!=="string"||!t.access_token)return;if(typeof t.refresh_token!=="string")return;if(typeof t.expires_at!=="string")return;let n={access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at};if(typeof t.region==="string"&&Xa.has(t.region))n.region=t.region;if(typeof t.resource_url==="string"&&t.resource_url.startsWith("http"))n.resource_url=t.resource_url;if(typeof t.account==="string"&&t.account.length>0)n.account=t.account;return n}function Za(e){if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=e,n={};if(typeof t.api_key==="string")n.api_key=t.api_key;if(typeof t.region==="string"&&Xa.has(t.region))n.region=t.region;if(typeof t.base_url==="string"&&t.base_url.startsWith("http"))n.base_url=t.base_url;if(typeof t.output==="string"&&Em.has(t.output))n.output=t.output;if(typeof t.timeout==="number"&&t.timeout>0)n.timeout=t.timeout;if(typeof t.proxy==="string"&&t.proxy.startsWith("http"))n.proxy=t.proxy;let i=_m(t.oauth);if(i)n.oauth=i;if(typeof t.default_text_model==="string"&&t.default_text_model.length>0)n.default_text_model=t.default_text_model;if(typeof t.default_speech_model==="string"&&t.default_speech_model.length>0)n.default_speech_model=t.default_speech_model;if(typeof t.default_video_model==="string"&&t.default_video_model.length>0)n.default_video_model=t.default_video_model;return n}var Z,gt,si,Xa,Em;var Ae=I(()=>{Z={global:"https://api.minimax.io",cn:"https://api.minimaxi.com"},gt={global:"https://platform.minimax.io",cn:"https://platform.minimaxi.com"},si={global:"https://account.minimax.io",cn:"https://account.minimaxi.com"},Xa=new Set(["global","cn"]),Em=new Set(["text","json"])});function R(e){return{name:e.name,description:e.description,usage:e.usage,options:e.options,examples:e.examples,apiDocs:e.apiDocs,execute:e.run}}var fn;var J=I(()=>{fn=[{flag:"--api-key <key>",description:"API key"},{flag:"--region <region>",description:"API region: global, cn"},{flag:"--base-url <url>",description:"API base URL"},{flag:"--output <format>",description:"Output format: text, json"},{flag:"--timeout <seconds>",description:"Request timeout",type:"number"},{flag:"--quiet",description:"Suppress non-essential output"},{flag:"--verbose",description:"Print HTTP request/response details"},{flag:"--no-color",description:"Disable ANSI colors"},{flag:"--dry-run",description:"Dry run mode"},{flag:"--non-interactive",description:"Disable interactive prompts"},{flag:"--help",description:"Show help"},{flag:"--version",description:"Print version"}]});import{homedir as Tm}from"os";import{join as el}from"path";function oi(){if(process.env.MMX_CONFIG_DIR)return process.env.MMX_CONFIG_DIR;return el(Tm(),Im)}function Re(){return el(oi(),"config.json")}async function tl(){let e=oi();await(await import("fs/promises")).mkdir(e,{recursive:!0,mode:448})}var Im=".mmx";var Dt=()=>{};var il={};ii(il,{formatKeyValue:()=>ai,formatTable:()=>nl,formatText:()=>is});function is(e){if(e===null||e===void 0)return"";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);if(Array.isArray(e)){if(e.length===0)return"(empty)";if(typeof e[0]==="object"&&e[0]!==null)return nl(e);return e.map(String).join(`
3
+ `)}if(typeof e==="object")return ai(e);return String(e)}function ai(e,t=0){let n=" ".repeat(t),i=[];for(let[r,s]of Object.entries(e)){if(s===null||s===void 0)continue;if(Array.isArray(s)){i.push(`${n}${r}:`);for(let o of s)if(typeof o==="object"&&o!==null)i.push(`${n} - ${ai(o,t+4).trimStart()}`);else i.push(`${n} - ${String(o)}`)}else if(typeof s==="object")i.push(`${n}${r}:`),i.push(ai(s,t+2));else i.push(`${n}${r}: ${String(s)}`)}return i.join(`
4
+ `)}function nl(e){if(e.length===0)return"(empty)";let t=Object.keys(e[0]),n=t.map((o)=>Math.max(o.length,...e.map((a)=>String(a[o]??"").length))),i=t.map((o,a)=>o.toUpperCase().padEnd(n[a])).join(" "),r=n.map((o)=>"-".repeat(o)).join(" "),s=e.map((o)=>t.map((a,l)=>String(o[a]??"").padEnd(n[l])).join(" "));return[i,r,...s].join(`
5
+ `)}function rl(e){return JSON.stringify(e,null,2)}function F(e){if(e==="json"||e==="text")return e;if(!process.stdout.isTTY)return"json";return"text"}function N(e,t){switch(t){case"json":return rl(e);case"text":return is(e)}}function Je(e,t){if(!e.dryRun)return!1;return console.log(N({request:t},F(e.output))),!0}var z=()=>{};import{copyFileSync as Om,existsSync as Mm,readFileSync as Nm,renameSync as Cm,unlinkSync as Rm,writeFileSync as Lm}from"fs";function Pm(e){return e instanceof Error&&"code"in e&&e.code==="EXDEV"}function qm(e,t,n={rename:Cm,copy:Om,unlink:Rm}){try{n.rename(e,t)}catch(i){if(!Pm(i))throw i;n.copy(e,t),n.unlink(e)}}function Q(){let e=Re();if(!Mm(e))return{};try{return Za(JSON.parse(Nm(e,"utf-8")))}catch(t){let n=t;if(n instanceof SyntaxError||n.message.includes("JSON"))process.stderr.write(`Warning: config file is corrupted. Run 'mmx config set' to reset.
6
+ `);return{}}}async function pe(e,t){await tl();let n=Re(),i=n+".tmp";Lm(i,JSON.stringify(e,null,2)+`
7
+ `,{mode:384}),qm(i,n,t)}function rs(e){let t=Q(),n=e.apiKey||void 0,i=t.api_key,r=e.region||process.env.MINIMAX_REGION||void 0;if(r&&!(r in Z))throw new v(`Invalid region "${r}". Valid values: ${Object.keys(Z).join(", ")}`,x.USAGE);let s=t.region,o=r||s||"global",a=n||i,l=!r&&(!s||a!==void 0&&a!==t.api_key),c=e.baseUrl||process.env.MINIMAX_BASE_URL||t.base_url||t.oauth?.resource_url||Z[o]||Z.global,f=F(e.output||process.env.MINIMAX_OUTPUT||t.output),u=process.env.MINIMAX_TIMEOUT?Number(process.env.MINIMAX_TIMEOUT):void 0,d=u!==void 0&&Number.isFinite(u)&&u>0?u:void 0,g=e.timeout??d??t.timeout??300;return{apiKey:n,fileApiKey:i,fileRegion:t.region,configPath:Re(),region:o,baseUrl:c,output:f,timeout:g,defaultTextModel:t.default_text_model,defaultSpeechModel:t.default_speech_model,defaultVideoModel:t.default_video_model,verbose:e.verbose||process.env.MINIMAX_VERBOSE==="1",quiet:e.quiet||!1,noColor:e.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,yes:e.yes||!1,dryRun:e.dryRun||!1,nonInteractive:e.nonInteractive||!1,async:e.async||!1,needsRegionDetection:l}}var Be=I(()=>{Ae();Dt();z();G();V()});var dn=M(function(SA,ss){var ci=process||{},sl=ci.argv||[],li=ci.env||{},Fm=!(!!li.NO_COLOR||sl.includes("--no-color"))&&(!!li.FORCE_COLOR||sl.includes("--color")||ci.platform==="win32"||(ci.stdout||{}).isTTY&&li.TERM!=="dumb"||!!li.CI),Dm=(e,t,n=e)=>(i)=>{let r=""+i,s=r.indexOf(t,e.length);return~s?e+Um(r,t,n,s)+t:e+r+t},Um=(e,t,n,i)=>{let r="",s=0;do r+=e.substring(s,i)+n,s=i+t.length,i=e.indexOf(t,s);while(~i);return r+e.substring(s)},ol=(e=Fm)=>{let t=e?Dm:()=>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")}};ss.exports=ol();ss.exports.createColors=ol});function Y(e){if(e?.nonInteractive===!0)return!1;if(process.env.CI)return!1;return process.stdout.isTTY===!0&&process.stdin.isTTY===!0}var as=M(function(kA,al){var os={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},jm={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Bm={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?os.up():"");if(e)t+=os.left;return t}};al.exports={cursor:os,scroll:jm,erase:Bm,beep:"\x07"}});var yl={};ii(yl,{AutocompletePrompt:()=>hn,ConfirmPrompt:()=>gi,GroupMultiSelectPrompt:()=>yi,MultiSelectPrompt:()=>bi,PasswordPrompt:()=>ws,Prompt:()=>Le,SelectKeyPrompt:()=>vi,SelectPrompt:()=>wi,TextPrompt:()=>xi,block:()=>bs,getColumns:()=>Qe,getRows:()=>hi,isCancel:()=>mn,settings:()=>ee,updateSettings:()=>gs,wrapTextWithPrefix:()=>Ee});import{stdout as ps,stdin as dl}from"node:process";import*as ze from"node:readline";import Vm from"node:readline";import{ReadStream as ll}from"node:tty";function fs(e,t,n){return String(e).normalize().replaceAll(`\r
8
+ `,`
8
9
  `).split(`
9
- `).map((n)=>vs(n,t,o)).join(`
10
- `)}function As(e,t){if(e===t)return;let o=e.split(`
11
- `),n=t.split(`
12
- `),i=[];for(let s=0;s<Math.max(o.length,n.length);s++)o[s]!==n[s]&&i.push(s);return i}function ot(e){return e===no}function tt(e,t){e.isTTY&&e.setRawMode(t)}class de{constructor({render:e,input:t=Xr,output:o=Qr,...n},i=!0){X(this,"input"),X(this,"output"),X(this,"rl"),X(this,"opts"),X(this,"_track",!1),X(this,"_render"),X(this,"_cursor",0),X(this,"state","initial"),X(this,"value"),X(this,"error",""),X(this,"subscribers",new Map),X(this,"_prevFrame",""),this.opts=n,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=e.bind(this),this._track=i,this.input=t,this.output=o}prompt(){let e=new ls(0);return e._write=(t,o,n)=>{this._track&&(this.value=this.rl.line.replace(/\t/g,""),this._cursor=this.rl.cursor,this.emit("value",this.value)),n()},this.input.pipe(e),this.rl=Nr.createInterface({input:this.input,output:e,tabSize:2,prompt:"",escapeCodeTimeout:50}),Nr.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),tt(this.input,!0),this.output.on("resize",this.render),this.render(),new Promise((t,o)=>{this.once("submit",()=>{this.output.write(H.cursor.show),this.output.off("resize",this.render),tt(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(H.cursor.show),this.output.off("resize",this.render),tt(this.input,!1),t(no)})})}on(e,t){let o=this.subscribers.get(e)??[];o.push({cb:t}),this.subscribers.set(e,o)}once(e,t){let o=this.subscribers.get(e)??[];o.push({cb:t,once:!0}),this.subscribers.set(e,o)}emit(e,...t){let o=this.subscribers.get(e)??[],n=[];for(let i of o)i.cb(...t),i.once&&n.push(()=>o.splice(o.indexOf(i),1));for(let i of n)i()}unsubscribe(){this.subscribers.clear()}onKeypress(e,t){if(this.state==="error"&&(this.state="active"),t?.name&&!this._track&&Hr.has(t.name)&&this.emit("cursor",Hr.get(t.name)),t?.name&&Ss.has(t.name)&&this.emit("cursor",t.name),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),e==="\t"&&this.opts.placeholder&&(this.value||(this.rl.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),e&&this.emit("key",e.toLowerCase()),t?.name==="return"){if(this.opts.validate){let o=this.opts.validate(this.value);o&&(this.error=o,this.state="error",this.rl.write(this.value))}this.state!=="error"&&(this.state="submit")}e==="\x03"&&(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(`
13
- `),tt(this.input,!1),this.rl.close(),this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=jr(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
14
- `).length-1;this.output.write(H.cursor.move(-999,e*-1))}render(){let e=jr(this._render(this)??"",process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(H.cursor.hide);else{let t=As(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let o=t[0];this.output.write(H.cursor.move(0,o)),this.output.write(H.erase.lines(1));let n=e.split(`
15
- `);this.output.write(n[o]),this._prevFrame=e,this.output.write(H.cursor.move(0,n.length-o-1));return}else if(t&&t?.length>1){let o=t[0];this.output.write(H.cursor.move(0,o)),this.output.write(H.erase.down());let n=e.split(`
16
- `).slice(o);this.output.write(n.join(`
17
- `)),this._prevFrame=e;return}this.output.write(H.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function uo({input:e=Xr,output:t=Qr,overwrite:o=!0,hideCursor:n=!0}={}){let i=me.createInterface({input:e,output:t,prompt:"",tabSize:1});me.emitKeypressEvents(e,i),e.isTTY&&e.setRawMode(!0);let s=(r,{name:u})=>{if(String(r)==="\x03"){n&&t.write(H.cursor.show),process.exit(0);return}if(!o)return;me.moveCursor(t,u==="return"?0:-1,u==="return"?-1:0,()=>{me.clearLine(t,1,()=>{e.once("keypress",s)})})};return n&&t.write(H.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),n&&t.write(H.cursor.show),e.isTTY&&!Vs&&e.setRawMode(!1),i.terminal=!1,i.close()}}var H,Ce,ds,to,ps,Ds,fs=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},hs,Mt=10,Lr=(e=0)=>(t)=>`\x1B[${t+e}m`,Ur=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Gr=(e=0)=>(t,o,n)=>`\x1B[${38+e};2;${t};${o};${n}m`,O,gs,Cs,bs,rt,Es=39,Pt="\x07",ro="[",Fs="]",oo="m",Nt,qr=(e)=>`${rt.values().next().value}${ro}${e}${oo}`,Vr=(e)=>`${rt.values().next().value}${Nt}${e}${Pt}`,xs=(e)=>e.split(" ").map((t)=>Ue(t)),Ot=(e,t,o)=>{let n=[...t],i=!1,s=!1,r=Ue(Zr(e[e.length-1]));for(let[u,a]of n.entries()){let l=Ue(a);if(r+l<=o?e[e.length-1]+=a:(e.push(a),r=0),rt.has(a)&&(i=!0,s=n.slice(u+1).join("").startsWith(Nt)),i){s?a===Pt&&(i=!1,s=!1):a===oo&&(i=!1);continue}r+=l,r===o&&u<n.length-1&&(e.push(""),r=0)}!r&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},ws=(e)=>{let t=e.split(" "),o=t.length;for(;o>0&&!(Ue(t[o-1])>0);)o--;return o===t.length?e:t.slice(0,o).join(" ")+t.slice(o).join("")},vs=(e,t,o={})=>{if(o.trim!==!1&&e.trim()==="")return"";let n="",i,s,r=xs(e),u=[""];for(let[l,p]of e.split(" ").entries()){o.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let f=Ue(u[u.length-1]);if(l!==0&&(f>=t&&(o.wordWrap===!1||o.trim===!1)&&(u.push(""),f=0),(f>0||o.trim===!1)&&(u[u.length-1]+=" ",f++)),o.hard&&r[l]>t){let D=t-f,h=1+Math.floor((r[l]-D-1)/t);Math.floor((r[l]-1)/t)<h&&u.push(""),Ot(u,p,t);continue}if(f+r[l]>t&&f>0&&r[l]>0){if(o.wordWrap===!1&&f<t){Ot(u,p,t);continue}u.push("")}if(f+r[l]>t&&o.wordWrap===!1){Ot(u,p,t);continue}u[u.length-1]+=p}o.trim!==!1&&(u=u.map((l)=>ws(l)));let a=[...u.join(`
18
- `)];for(let[l,p]of a.entries()){if(n+=p,rt.has(p)){let{groups:D}=new RegExp(`(?:\\${ro}(?<code>\\d+)m|\\${Nt}(?<uri>.*)${Pt})`).exec(a.slice(l).join(""))||{groups:{}};if(D.code!==void 0){let h=Number.parseFloat(D.code);i=h===Es?void 0:h}else D.uri!==void 0&&(s=D.uri.length===0?void 0:D.uri)}let f=bs.codes.get(Number(i));a[l+1]===`
19
- `?(s&&(n+=Vr("")),i&&f&&(n+=qr(f))):p===`
20
- `&&(i&&f&&(n+=qr(i)),s&&(n+=Vr(s)))}return n},$s,_s=(e,t,o)=>(t in e)?$s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,X=(e,t,o)=>(_s(e,typeof t!="symbol"?t+"":t,o),o),no,Hr,Ss,Lt,ks,Rs=(e,t,o)=>(t in e)?ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,Wr=(e,t,o)=>(Rs(e,typeof t!="symbol"?t+"":t,o),o),Ut,Bs,Is=(e,t,o)=>(t in e)?Bs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,Kr=(e,t,o)=>(Is(e,typeof t!="symbol"?t+"":t,o),o),io,Ts,Ms=(e,t,o)=>(t in e)?Ts(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,zr=(e,t,o)=>(Ms(e,typeof t!="symbol"?t+"":t,o),o),Gt,Os,Ps=(e,t,o)=>(t in e)?Os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,Jr=(e,t,o)=>(Ps(e,typeof t!="symbol"?t+"":t,o),o),so,Ns,Ls=(e,t,o)=>(t in e)?Ns(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,Yr=(e,t,o)=>(Ls(e,typeof t!="symbol"?t+"":t,o),o),qt,Us,Gs=(e,t,o)=>(t in e)?Us(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,qs=(e,t,o)=>(Gs(e,typeof t!="symbol"?t+"":t,o),o),Vt,Vs;var jt=C(()=>{H=ze(Bt(),1),Ce=ze(Tt(),1);ds=ms();to={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(n){var i=n.charCodeAt(0),s=n.length==2?n.charCodeAt(1):0,r=i;return 55296<=i&&i<=56319&&56320<=s&&s<=57343&&(i&=1023,s&=1023,r=i<<10|s,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?"F":r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?"H":4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?"W":32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?"Na":r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?"A":"N"},t.characterLength=function(n){var i=this.eastAsianWidth(n);return i=="F"||i=="W"||i=="A"?2:1};function o(n){return n.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(n){for(var i=o(n),s=0,r=0;r<i.length;r++)s=s+this.characterLength(i[r]);return s},t.slice=function(n,i,s){textLen=t.length(n),i=i||0,s=s||1,i<0&&(i=textLen+i),s<0&&(s=textLen+s);for(var r="",u=0,a=o(n),l=0;l<a.length;l++){var p=a[l],f=t.length(p);if(u>=i-(f==2?1:0))if(u+f<=s)r+=p;else break;u+=f}return r}})(to);ps=to.exports,Ds=eo(ps),hs=eo(fs);O={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(O.modifier);gs=Object.keys(O.color),Cs=Object.keys(O.bgColor);[...gs,...Cs];bs=ys(),rt=new Set(["\x1B","›"]),Nt=`${Fs}8;;`;$s=Object.defineProperty;no=Symbol("clack:cancel");Hr=new Map([["k","up"],["j","down"],["h","left"],["l","right"]]),Ss=new Set(["up","down","left","right","space","enter"]);Lt=class Lt extends de{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(H.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};ks=Object.defineProperty;Ut=class Ut extends de{constructor(e){super(e,!1),Wr(this,"options"),Wr(this,"cursor",0);let{options:t}=e;this.options=Object.entries(t).flatMap(([o,n])=>[{value:o,group:!0,label:o},...n.map((i)=>({...i,group:o}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:o})=>o===e.cursorAt),0),this.on("cursor",(o)=>{switch(o){case"left":case"up":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;break;case"space":this.toggleValue();break}})}getGroupItems(e){return this.options.filter((t)=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every((t)=>this.value.includes(t.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,o=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((n)=>o.findIndex((i)=>i.value===n)===-1):this.value=[...this.value,...o.map((n)=>n.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(e.value);this.value=t?this.value.filter((o)=>o!==e.value):[...this.value,e.value]}}};Bs=Object.defineProperty,io=class extends de{constructor(e){super(e,!1),Kr(this,"options"),Kr(this,"cursor",0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on("key",(t)=>{t==="a"&&this.toggleAll()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":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;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){let e=this.value.length===this.options.length;this.value=e?[]:this.options.map((t)=>t.value)}toggleValue(){let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}},Ts=Object.defineProperty;Gt=class Gt extends de{constructor({mask:e,...t}){super(t),zr(this,"valueWithCursor",""),zr(this,"_mask","•"),this._mask=e??"•",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Ce.default.inverse(Ce.default.hidden("_"))}`;else{let o=this.masked.slice(0,this.cursor),n=this.masked.slice(this.cursor);this.valueWithCursor=`${o}${Ce.default.inverse(n[0])}${n.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};Os=Object.defineProperty,so=class extends de{constructor(e){super(e,!1),Jr(this,"options"),Jr(this,"cursor",0),this.options=e.options,this.cursor=this.options.findIndex(({value:t})=>t===e.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",(t)=>{switch(t){case"left":case"up":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;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}},Ns=Object.defineProperty;qt=class qt extends de{constructor(e){super(e,!1),Yr(this,"options"),Yr(this,"cursor",0),this.options=e.options;let t=this.options.map(({value:[o]})=>o?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on("key",(o)=>{if(!t.includes(o))return;let n=this.options.find(({value:[i]})=>i?.toLowerCase()===o);n&&(this.value=n.value,this.state="submit",this.emit("submit"))})}};Us=Object.defineProperty;Vt=class Vt extends de{constructor(e){super(e),qs(this,"valueWithCursor",""),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.valueWithCursor=this.value}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.value}${Ce.default.inverse(Ce.default.hidden("_"))}`;else{let t=this.value.slice(0,this.cursor),o=this.value.slice(this.cursor);this.valueWithCursor=`${t}${Ce.default.inverse(o[0])}${o.slice(1)}`}})}get cursor(){return this._cursor}};Vs=globalThis.process.platform.startsWith("win")});var Ee={};$t(Ee,{cancel:()=>cu,confirm:()=>ou,group:()=>Du,groupMultiselect:()=>uu,intro:()=>lu,isCancel:()=>ot,log:()=>ye,multiselect:()=>su,note:()=>au,outro:()=>mu,password:()=>ru,select:()=>nu,selectKey:()=>iu,spinner:()=>du,text:()=>tu});import ee from"node:process";function js(){return ee.platform!=="win32"?ee.env.TERM!=="linux":Boolean(ee.env.CI)||Boolean(ee.env.WT_SESSION)||Boolean(ee.env.TERMINUS_SUBLIME)||ee.env.ConEmuTask==="{cmd::Cmder}"||ee.env.TERM_PROGRAM==="Terminus-Sublime"||ee.env.TERM_PROGRAM==="vscode"||ee.env.TERM==="xterm-256color"||ee.env.TERM==="alacritty"||ee.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function pu(){let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(e,"g")}var c,Te,Wt,L=(e,t)=>Wt?e:t,Hs,co,lo,nt,Ws,b,z,Kt,zt,Jt,Ge,mo,Ks,ao,zs,Js,Ys,Xs,Qs,Zs,eu,be=(e)=>{switch(e){case"initial":case"active":return c.default.cyan(Hs);case"cancel":return c.default.red(co);case"error":return c.default.yellow(lo);case"submit":return c.default.green(nt)}},tu=(e)=>new Vt({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){let t=`${c.default.gray(b)}
21
- ${be(this.state)} ${e.message}
22
- `,o=e.placeholder?c.default.inverse(e.placeholder[0])+c.default.dim(e.placeholder.slice(1)):c.default.inverse(c.default.hidden("_")),n=this.value?this.valueWithCursor:o;switch(this.state){case"error":return`${t.trim()}
23
- ${c.default.yellow(b)} ${n}
24
- ${c.default.yellow(z)} ${c.default.yellow(this.error)}
25
- `;case"submit":return`${t}${c.default.gray(b)} ${c.default.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${c.default.gray(b)} ${c.default.strikethrough(c.default.dim(this.value??""))}${this.value?.trim()?`
26
- `+c.default.gray(b):""}`;default:return`${t}${c.default.cyan(b)} ${n}
27
- ${c.default.cyan(z)}
28
- `}}}).prompt(),ru=(e)=>new Gt({validate:e.validate,mask:e.mask??Ks,render(){let t=`${c.default.gray(b)}
29
- ${be(this.state)} ${e.message}
30
- `,o=this.valueWithCursor,n=this.masked;switch(this.state){case"error":return`${t.trim()}
31
- ${c.default.yellow(b)} ${n}
32
- ${c.default.yellow(z)} ${c.default.yellow(this.error)}
33
- `;case"submit":return`${t}${c.default.gray(b)} ${c.default.dim(n)}`;case"cancel":return`${t}${c.default.gray(b)} ${c.default.strikethrough(c.default.dim(n??""))}${n?`
34
- `+c.default.gray(b):""}`;default:return`${t}${c.default.cyan(b)} ${o}
35
- ${c.default.cyan(z)}
36
- `}}}).prompt(),ou=(e)=>{let t=e.active??"Yes",o=e.inactive??"No";return new Lt({active:t,inactive:o,initialValue:e.initialValue??!0,render(){let n=`${c.default.gray(b)}
37
- ${be(this.state)} ${e.message}
38
- `,i=this.value?t:o;switch(this.state){case"submit":return`${n}${c.default.gray(b)} ${c.default.dim(i)}`;case"cancel":return`${n}${c.default.gray(b)} ${c.default.strikethrough(c.default.dim(i))}
39
- ${c.default.gray(b)}`;default:return`${n}${c.default.cyan(b)} ${this.value?`${c.default.green(Kt)} ${t}`:`${c.default.dim(zt)} ${c.default.dim(t)}`} ${c.default.dim("/")} ${this.value?`${c.default.dim(zt)} ${c.default.dim(o)}`:`${c.default.green(Kt)} ${o}`}
40
- ${c.default.cyan(z)}
41
- `}}}).prompt()},nu=(e)=>{let t=(n,i)=>{let s=n.label??String(n.value);return i==="active"?`${c.default.green(Kt)} ${s} ${n.hint?c.default.dim(`(${n.hint})`):""}`:i==="selected"?`${c.default.dim(s)}`:i==="cancelled"?`${c.default.strikethrough(c.default.dim(s))}`:`${c.default.dim(zt)} ${c.default.dim(s)}`},o=0;return new so({options:e.options,initialValue:e.initialValue,render(){let n=`${c.default.gray(b)}
42
- ${be(this.state)} ${e.message}
43
- `;switch(this.state){case"submit":return`${n}${c.default.gray(b)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${c.default.gray(b)} ${t(this.options[this.cursor],"cancelled")}
44
- ${c.default.gray(b)}`;default:{let i=e.maxItems===void 0?1/0:Math.max(e.maxItems,5);this.cursor>=o+i-3?o=Math.max(Math.min(this.cursor-i+3,this.options.length-i),0):this.cursor<o+2&&(o=Math.max(this.cursor-2,0));let s=i<this.options.length&&o>0,r=i<this.options.length&&o+i<this.options.length;return`${n}${c.default.cyan(b)} ${this.options.slice(o,o+i).map((u,a,l)=>a===0&&s?c.default.dim("..."):a===l.length-1&&r?c.default.dim("..."):t(u,a+o===this.cursor?"active":"inactive")).join(`
45
- ${c.default.cyan(b)} `)}
46
- ${c.default.cyan(z)}
47
- `}}}}).prompt()},iu=(e)=>{let t=(o,n="inactive")=>{let i=o.label??String(o.value);return n==="selected"?`${c.default.dim(i)}`:n==="cancelled"?`${c.default.strikethrough(c.default.dim(i))}`:n==="active"?`${c.default.bgCyan(c.default.gray(` ${o.value} `))} ${i} ${o.hint?c.default.dim(`(${o.hint})`):""}`:`${c.default.gray(c.default.bgWhite(c.default.inverse(` ${o.value} `)))} ${i} ${o.hint?c.default.dim(`(${o.hint})`):""}`};return new qt({options:e.options,initialValue:e.initialValue,render(){let o=`${c.default.gray(b)}
48
- ${be(this.state)} ${e.message}
49
- `;switch(this.state){case"submit":return`${o}${c.default.gray(b)} ${t(this.options.find((n)=>n.value===this.value),"selected")}`;case"cancel":return`${o}${c.default.gray(b)} ${t(this.options[0],"cancelled")}
50
- ${c.default.gray(b)}`;default:return`${o}${c.default.cyan(b)} ${this.options.map((n,i)=>t(n,i===this.cursor?"active":"inactive")).join(`
51
- ${c.default.cyan(b)} `)}
52
- ${c.default.cyan(z)}
53
- `}}}).prompt()},su=(e)=>{let t=(o,n)=>{let i=o.label??String(o.value);return n==="active"?`${c.default.cyan(Jt)} ${i} ${o.hint?c.default.dim(`(${o.hint})`):""}`:n==="selected"?`${c.default.green(Ge)} ${c.default.dim(i)}`:n==="cancelled"?`${c.default.strikethrough(c.default.dim(i))}`:n==="active-selected"?`${c.default.green(Ge)} ${i} ${o.hint?c.default.dim(`(${o.hint})`):""}`:n==="submitted"?`${c.default.dim(i)}`:`${c.default.dim(mo)} ${c.default.dim(i)}`};return new io({options:e.options,initialValues:e.initialValues,required:e.required??!0,cursorAt:e.cursorAt,validate(o){if(this.required&&o.length===0)return`Please select at least one option.
54
- ${c.default.reset(c.default.dim(`Press ${c.default.gray(c.default.bgWhite(c.default.inverse(" space ")))} to select, ${c.default.gray(c.default.bgWhite(c.default.inverse(" enter ")))} to submit`))}`},render(){let o=`${c.default.gray(b)}
55
- ${be(this.state)} ${e.message}
56
- `;switch(this.state){case"submit":return`${o}${c.default.gray(b)} ${this.options.filter(({value:n})=>this.value.includes(n)).map((n)=>t(n,"submitted")).join(c.default.dim(", "))||c.default.dim("none")}`;case"cancel":{let n=this.options.filter(({value:i})=>this.value.includes(i)).map((i)=>t(i,"cancelled")).join(c.default.dim(", "));return`${o}${c.default.gray(b)} ${n.trim()?`${n}
57
- ${c.default.gray(b)}`:""}`}case"error":{let n=this.error.split(`
58
- `).map((i,s)=>s===0?`${c.default.yellow(z)} ${c.default.yellow(i)}`:` ${i}`).join(`
59
- `);return o+c.default.yellow(b)+" "+this.options.map((i,s)=>{let r=this.value.includes(i.value),u=s===this.cursor;return u&&r?t(i,"active-selected"):r?t(i,"selected"):t(i,u?"active":"inactive")}).join(`
60
- ${c.default.yellow(b)} `)+`
61
- `+n+`
62
- `}default:return`${o}${c.default.cyan(b)} ${this.options.map((n,i)=>{let s=this.value.includes(n.value),r=i===this.cursor;return r&&s?t(n,"active-selected"):s?t(n,"selected"):t(n,r?"active":"inactive")}).join(`
63
- ${c.default.cyan(b)} `)}
64
- ${c.default.cyan(z)}
65
- `}}}).prompt()},uu=(e)=>{let t=(o,n,i=[])=>{let s=o.label??String(o.value),r=typeof o.group=="string",u=r&&(i[i.indexOf(o)+1]??{group:!0}),a=r&&u.group===!0,l=r?`${a?z:b} `:"";return n==="active"?`${c.default.dim(l)}${c.default.cyan(Jt)} ${s} ${o.hint?c.default.dim(`(${o.hint})`):""}`:n==="group-active"?`${l}${c.default.cyan(Jt)} ${c.default.dim(s)}`:n==="group-active-selected"?`${l}${c.default.green(Ge)} ${c.default.dim(s)}`:n==="selected"?`${c.default.dim(l)}${c.default.green(Ge)} ${c.default.dim(s)}`:n==="cancelled"?`${c.default.strikethrough(c.default.dim(s))}`:n==="active-selected"?`${c.default.dim(l)}${c.default.green(Ge)} ${s} ${o.hint?c.default.dim(`(${o.hint})`):""}`:n==="submitted"?`${c.default.dim(s)}`:`${c.default.dim(l)}${c.default.dim(mo)} ${c.default.dim(s)}`};return new Ut({options:e.options,initialValues:e.initialValues,required:e.required??!0,cursorAt:e.cursorAt,validate(o){if(this.required&&o.length===0)return`Please select at least one option.
66
- ${c.default.reset(c.default.dim(`Press ${c.default.gray(c.default.bgWhite(c.default.inverse(" space ")))} to select, ${c.default.gray(c.default.bgWhite(c.default.inverse(" enter ")))} to submit`))}`},render(){let o=`${c.default.gray(b)}
67
- ${be(this.state)} ${e.message}
68
- `;switch(this.state){case"submit":return`${o}${c.default.gray(b)} ${this.options.filter(({value:n})=>this.value.includes(n)).map((n)=>t(n,"submitted")).join(c.default.dim(", "))}`;case"cancel":{let n=this.options.filter(({value:i})=>this.value.includes(i)).map((i)=>t(i,"cancelled")).join(c.default.dim(", "));return`${o}${c.default.gray(b)} ${n.trim()?`${n}
69
- ${c.default.gray(b)}`:""}`}case"error":{let n=this.error.split(`
70
- `).map((i,s)=>s===0?`${c.default.yellow(z)} ${c.default.yellow(i)}`:` ${i}`).join(`
71
- `);return`${o}${c.default.yellow(b)} ${this.options.map((i,s,r)=>{let u=this.value.includes(i.value)||i.group===!0&&this.isGroupSelected(`${i.value}`),a=s===this.cursor;return!a&&typeof i.group=="string"&&this.options[this.cursor].value===i.group?t(i,u?"group-active-selected":"group-active",r):a&&u?t(i,"active-selected",r):u?t(i,"selected",r):t(i,a?"active":"inactive",r)}).join(`
72
- ${c.default.yellow(b)} `)}
73
- ${n}
74
- `}default:return`${o}${c.default.cyan(b)} ${this.options.map((n,i,s)=>{let r=this.value.includes(n.value)||n.group===!0&&this.isGroupSelected(`${n.value}`),u=i===this.cursor;return!u&&typeof n.group=="string"&&this.options[this.cursor].value===n.group?t(n,r?"group-active-selected":"group-active",s):u&&r?t(n,"active-selected",s):r?t(n,"selected",s):t(n,u?"active":"inactive",s)}).join(`
75
- ${c.default.cyan(b)} `)}
76
- ${c.default.cyan(z)}
77
- `}}}).prompt()},Ht=(e)=>e.replace(pu(),""),au=(e="",t="")=>{let o=`
78
- ${e}
79
- `.split(`
80
- `),n=Ht(t).length,i=Math.max(o.reduce((r,u)=>(u=Ht(u),u.length>r?u.length:r),0),n)+2,s=o.map((r)=>`${c.default.gray(b)} ${c.default.dim(r)}${" ".repeat(i-Ht(r).length)}${c.default.gray(b)}`).join(`
81
- `);process.stdout.write(`${c.default.gray(b)}
82
- ${c.default.green(nt)} ${c.default.reset(t)} ${c.default.gray(ao.repeat(Math.max(i-n-1,1))+zs)}
83
- ${s}
84
- ${c.default.gray(Js+ao.repeat(i+2)+Ys)}
85
- `)},cu=(e="")=>{process.stdout.write(`${c.default.gray(z)} ${c.default.red(e)}
10
+ `).map((i)=>th(i,t,n)).join(`
11
+ `)}function gs(e){if(e.aliases!==void 0){let t=e.aliases;for(let n in t){if(!Object.hasOwn(t,n))continue;let i=t[n];ee.actions.has(i)&&(ee.aliases.has(n)||ee.aliases.set(n,i))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(ee.messages.cancel=t.cancel),t.error!==void 0&&(ee.messages.error=t.error)}e.withGuide!==void 0&&(ee.withGuide=e.withGuide!==!1)}function ys(e,t){if(typeof e=="string")return ee.aliases.get(e)===t;for(let n of e)if(n!==void 0&&ys(n,t))return!0;return!1}function ih(e,t){if(e===t)return;let n=e.split(`
12
+ `),i=t.split(`
13
+ `),r=Math.max(n.length,i.length),s=[];for(let o=0;o<r;o++)n[o]!==i[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:i.length,numLines:r}}function mn(e){return e===ds}function pi(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function bs({input:e=dl,output:t=ps,overwrite:n=!0,hideCursor:i=!0}={}){let r=ze.createInterface({input:e,output:t,prompt:"",tabSize:1});ze.emitKeypressEvents(e,r),e instanceof ll&&e.isTTY&&e.setRawMode(!0);let s=(o,{name:a,sequence:l})=>{let c=String(o);if(ys([c,a,l],"cancel")){i&&t.write(le.cursor.show),process.exit(0);return}if(!n)return;ze.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{ze.clearLine(t,1,()=>{e.once("keypress",s)})})};return i&&t.write(le.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),i&&t.write(le.cursor.show),e instanceof ll&&e.isTTY&&!rh&&e.setRawMode(!1),r.terminal=!1,r.close()}}function Ee(e,t,n,i=n){let r=Qe(e??ps);return fs(t,r-n.length,{hard:!0,trim:!1}).split(`
14
+ `).map((s,o)=>`${o===0?i:n}${s}`).join(`
15
+ `)}class Le{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=dl,output:i=ps,render:r,signal:s,...o}=e;this.opts=o,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=t,this._abortSignal=s,this.input=n,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],i=[];for(let r of n)r.cb(...t),r.once&&i.push(()=>n.splice(n.indexOf(r),1));for(let r of i)r()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(ds);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Vm.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),pi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(le.cursor.show),this.output.off("resize",this.render),pi(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(le.cursor.show),this.output.off("resize",this.render),pi(this.input,!1),e(ds)})})}_isActionKey(e,t){return e==="\t"}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&ee.aliases.has(t.name)&&this.emit("cursor",ee.aliases.get(t.name)),ee.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e?.toLowerCase(),t),t?.name==="return"){if(this.opts.validate){let n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ys([e,t?.name,t?.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(`
16
+ `),pi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=fs(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
17
+ `).length-1;this.output.write(le.cursor.move(-999,e*-1))}render(){let e=fs(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(le.cursor.hide);else{let t=ih(this._prevFrame,e),n=hi(this.output);if(this.restoreCursor(),t){let i=Math.max(0,t.numLinesAfter-n),r=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=i);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(le.cursor.move(0,s-r)),this.output.write(le.erase.lines(1));let o=e.split(`
18
+ `);this.output.write(o[s]),this._prevFrame=e,this.output.write(le.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(i<r)s=i;else{let a=s-r;a>0&&this.output.write(le.cursor.move(0,a))}this.output.write(le.erase.down());let o=e.split(`
19
+ `).slice(s);this.output.write(o.join(`
20
+ `)),this._prevFrame=e;return}}this.output.write(le.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function sh(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((i)=>i.value===e);return n!==-1?n:0}function oh(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function ah(e,t){if(t)return e?t:t[0]}function yt(e,t,n){let i=e+t,r=Math.max(n.length-1,0),s=i<0?r:i>r?0:i;return n[s].disabled?yt(s,t<0?-1:1,n):s}var Ye,le,Gm=(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,Km=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Wm=(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,ui,fi,cs,di,Hm,Jm,pl=(e,t={},n={})=>{let i=t.limit??1/0,r=t.ellipsis??"",s=t?.ellipsisWidth??(r?pl(r,Jm,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,f=n.emojiWidth??2,u=n.fullWidthWidth??2,d=n.regularWidth??1,g=n.wideWidth??2,h=0,p=0,m=e.length,b=0,w=!1,S=m,_=Math.max(0,i-s),E=0,A=0,k=0,T=0;e:for(;;){if(A>E||p>=m&&p>h){let C=e.slice(E,A)||e.slice(h,p);b=0;for(let P of C.replaceAll(Hm,"")){let L=P.codePointAt(0)||0;if(Km(L)?T=u:Wm(L)?T=g:c!==d&&Gm(L)?T=c:T=d,k+T>_&&(S=Math.min(S,Math.max(E,h)+b)),k+T>i){w=!0;break e}b+=P.length,k+=T}E=A=0}if(p>=m)break;if(di.lastIndex=p,di.test(e)){if(b=di.lastIndex-p,T=b*d,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/d))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=di.lastIndex;continue}if(ls.lastIndex=p,ls.test(e)){if(k+o>_&&(S=Math.min(S,p)),k+o>i){w=!0;break}k+=o,E=h,A=p,p=h=ls.lastIndex;continue}if(ui.lastIndex=p,ui.test(e)){if(b=ui.lastIndex-p,T=b*a,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/a))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=ui.lastIndex;continue}if(fi.lastIndex=p,fi.test(e)){if(b=fi.lastIndex-p,T=b*l,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/l))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=fi.lastIndex;continue}if(cs.lastIndex=p,cs.test(e)){if(k+f>_&&(S=Math.min(S,p)),k+f>i){w=!0;break}k+=f,E=h,A=p,p=h=cs.lastIndex;continue}p+=1}return{width:w?_:k,index:w?S:m,truncated:w,ellipsed:w&&i>=s}},Ym,pn=(e,t={})=>pl(e,Ym,t).width,mi="\x1B",ml="›",zm=39,ms="\x07",hl="[",Qm="]",gl="m",hs,cl,Xm=(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},ul=(e)=>`${mi}${hl}${e}${gl}`,fl=(e)=>`${mi}${hs}${e}${ms}`,Zm=(e)=>e.map((t)=>pn(t)),us=(e,t,n)=>{let i=t[Symbol.iterator](),r=!1,s=!1,o=e.at(-1),a=o===void 0?0:pn(o),l=i.next(),c=i.next(),f=0;for(;!l.done;){let u=l.value,d=pn(u);a+d<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===mi||u===ml)&&(r=!0,s=t.startsWith(hs,f+1)),r?s?u===ms&&(r=!1,s=!1):u===gl&&(r=!1):(a+=d,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=i.next(),f+=u.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},eh=(e)=>{let t=e.split(" "),n=t.length;for(;n>0&&!(pn(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},th=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",r,s,o=e.split(" "),a=Zm(o),l=[""];for(let[h,p]of o.entries()){n.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let m=pn(l.at(-1)??"");if(h!==0&&(m>=t&&(n.wordWrap===!1||n.trim===!1)&&(l.push(""),m=0),(m>0||n.trim===!1)&&(l[l.length-1]+=" ",m++)),n.hard&&a[h]>t){let b=t-m,w=1+Math.floor((a[h]-b-1)/t);Math.floor((a[h]-1)/t)<w&&l.push(""),us(l,p,t);continue}if(m+a[h]>t&&m>0&&a[h]>0){if(n.wordWrap===!1&&m<t){us(l,p,t);continue}l.push("")}if(m+a[h]>t&&n.wordWrap===!1){us(l,p,t);continue}l[l.length-1]+=p}n.trim!==!1&&(l=l.map((h)=>eh(h)));let c=l.join(`
21
+ `),f=c[Symbol.iterator](),u=f.next(),d=f.next(),g=0;for(;!u.done;){let h=u.value,p=d.value;if(i+=h,h===mi||h===ml){cl.lastIndex=g+1;let b=cl.exec(c)?.groups;if(b?.code!==void 0){let w=Number.parseFloat(b.code);r=w===zm?void 0:w}else b?.uri!==void 0&&(s=b.uri.length===0?void 0:b.uri)}let m=r?Xm(r):void 0;p===`
22
+ `?(s&&(i+=fl("")),r&&m&&(i+=ul(m))):h===`
23
+ `&&(r&&m&&(i+=ul(r)),s&&(i+=fl(s))),g+=h.length,u=d,d=f.next()}return i},nh,ee,rh,ds,Qe=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,hi=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20,hn,gi,yi,bi,ws,wi,vi,xi;var Si=I(()=>{Ye=Ft(dn(),1),le=Ft(as(),1),ls=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ui=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fi=/\t{1,1000}/y,cs=/[\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,di=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Hm=/\p{M}+/gu,Jm={limit:1/0,ellipsis:""},Ym={limit:1/0,ellipsis:"",ellipsisWidth:0},hs=`${Qm}8;;`,cl=new RegExp(`(?:\\${hl}(?<code>\\d+)m|\\${hs}(?<uri>.*)${ms})`,"y");nh=["up","down","left","right","space","enter","cancel"],ee={actions:new Set(nh),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};rh=globalThis.process.platform.startsWith("win"),ds=Symbol("clack:cancel");hn=class hn extends Le{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#n="";#t;#i;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return Ye.default.inverse(Ye.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this._cursor),[t,...n]=this.userInput.slice(this._cursor);return`${e}${Ye.default.inverse(t)}${n.join("")}`}get options(){return typeof this.#i=="function"?this.#i():this.#i}constructor(e){super(e),this.#i=e.options;let t=this.options;this.filteredOptions=[...t],this.multiple=e.multiple===!0,this.#t=e.filter??oh;let n;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?n=e.initialValue:n=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(n=[this.options[0].value]),n)for(let i of n){let r=t.findIndex((s)=>s.value===i);r!==-1&&(this.toggleSelected(i),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,r)=>this.#r(i,r)),this.on("userInput",(i)=>this.#s(i))}_isActionKey(e,t){return e==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&e!==void 0&&e!==""}#r(e,t){let n=t.name==="up",i=t.name==="down",r=t.name==="return";n||i?(this.#e=Math.max(0,Math.min(this.#e+(n?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=ah(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((t)=>t!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#s(e){if(e!==this.#n){this.#n=e;let t=this.options;e?this.filteredOptions=t.filter((n)=>this.#t(e,n)):this.filteredOptions=[...t],this.#e=sh(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};gi=class gi extends Le{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(le.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};yi=class yi extends Le{options;cursor=0;#e;getGroupItems(e){return this.options.filter((t)=>t.group===e)}isGroupSelected(e){let t=this.getGroupItems(e),n=this.value;return n===void 0?!1:t.every((i)=>n.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>n.findIndex((r)=>r.value===i)===-1):this.value=[...this.value,...n.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(e.value);this.value=t?this.value.filter((n)=>n!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:t}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([n,i])=>[{value:n,group:!0,label:n},...i.map((r)=>({...r,group:n}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),this.#e?0:1),this.on("cursor",(n)=>{switch(n){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(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 i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}};bi=class bi extends Le{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t].disabled?yt(t,1,this.options):t,this.on("key",(n)=>{n==="a"&&this.toggleAll(),n==="i"&&this.toggleInvert()}),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;case"space":this.toggleValue();break}})}};ws=class extends Le{_mask="•";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}${Ye.default.inverse(Ye.default.hidden("_"))}`;let t=this.masked,n=t.slice(0,this.cursor),i=t.slice(this.cursor);return`${n}${Ye.default.inverse(i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"•",this.on("userInput",(n)=>{this._setValue(n)})}};wi=class wi extends Le{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:i})=>i===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n].disabled?yt(n,1,this.options):n,this.changeValue(),this.on("cursor",(i)=>{switch(i){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 vi extends Le{options;cursor=0;constructor(e){super(e,!1),this.options=e.options;let t=e.caseSensitive===!0,n=this.options.map(({value:[i]})=>t?i:i?.toLowerCase());this.cursor=Math.max(n.indexOf(e.initialValue),0),this.on("key",(i,r)=>{if(!i)return;let s=t&&r.shift?i.toUpperCase():i;if(!n.includes(s))return;let o=this.options.find(({value:[a]})=>t?a===s:a?.toLowerCase()===i);o&&(this.value=o.value,this.state="submit",this.emit("submit"))})}};xi=class xi extends Le{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),[n,...i]=e.slice(this.cursor);return`${t}${Ye.default.inverse(n)}${i.join("")}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}});var _e={};ii(_e,{S_BAR:()=>O,S_BAR_END:()=>se,S_BAR_END_RIGHT:()=>Ol,S_BAR_H:()=>Ii,S_BAR_START:()=>_s,S_BAR_START_RIGHT:()=>Il,S_CHECKBOX_ACTIVE:()=>Ti,S_CHECKBOX_INACTIVE:()=>bn,S_CHECKBOX_SELECTED:()=>wt,S_CONNECT_LEFT:()=>Nl,S_CORNER_BOTTOM_LEFT:()=>Os,S_CORNER_BOTTOM_RIGHT:()=>Is,S_CORNER_TOP_LEFT:()=>Cl,S_CORNER_TOP_RIGHT:()=>Ts,S_ERROR:()=>Rs,S_INFO:()=>Ms,S_PASSWORD_MASK:()=>Ml,S_RADIO_ACTIVE:()=>yn,S_RADIO_INACTIVE:()=>jt,S_STEP_ACTIVE:()=>Tl,S_STEP_CANCEL:()=>As,S_STEP_ERROR:()=>Es,S_STEP_SUBMIT:()=>vt,S_SUCCESS:()=>Ns,S_WARN:()=>Cs,autocomplete:()=>Dl,autocompleteMultiselect:()=>Eh,box:()=>Oh,cancel:()=>Rh,confirm:()=>Mh,group:()=>Nh,groupMultiselect:()=>Ch,intro:()=>Lh,isCI:()=>ks,isCancel:()=>mn,isTTY:()=>_l,limitOptions:()=>Vt,log:()=>he,multiselect:()=>qh,note:()=>Uh,outro:()=>Ph,password:()=>jh,path:()=>Bh,progress:()=>Gh,select:()=>Kh,selectKey:()=>Wh,settings:()=>ee,spinner:()=>Fs,stream:()=>bt,symbol:()=>Pe,symbolBar:()=>Ls,taskLog:()=>Yh,tasks:()=>Hh,text:()=>zh,unicode:()=>_i,unicodeOr:()=>H,updateSettings:()=>gs});import ve from"node:process";import{readdirSync as lh,existsSync as ch,lstatSync as bl}from"node:fs";import{dirname as wl,join as uh}from"node:path";import{stripVTControlCharacters as vs}from"node:util";function fh(){return ve.platform!=="win32"?ve.env.TERM!=="linux":!!ve.env.CI||!!ve.env.WT_SESSION||!!ve.env.TERMINUS_SUBLIME||ve.env.ConEmuTask==="{cmd::Cmder}"||ve.env.TERM_PROGRAM==="Terminus-Sublime"||ve.env.TERM_PROGRAM==="vscode"||ve.env.TERM==="xterm-256color"||ve.env.TERM==="alacritty"||ve.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Bt(e,t,n){return String(e).normalize().replaceAll(`\r
24
+ `,`
25
+ `).split(`
26
+ `).map((i)=>$h(i,t,n)).join(`
27
+ `)}function $l(e){return e.label??String(e.value??"")}function Fl(e,t){if(!e)return!0;let n=(t.label??String(t.value??"")).toLowerCase(),i=(t.hint??"").toLowerCase(),r=String(t.value).toLowerCase(),s=e.toLowerCase();return n.includes(s)||i.includes(s)||r.includes(s)}function Ah(e,t){let n=[];for(let i of t)e.includes(i.value)&&n.push(i);return n}function kl(e,t,n,i){let r=n,s=n;return i==="center"?r=Math.floor((t-e)/2):i==="right"&&(r=t-e-n),s=t-r-e,[r,s]}function Gh({style:e="heavy",max:t=100,size:n=40,...i}={}){let r=Fs(i),s=0,o="",a=Math.max(1,t),l=Math.max(1,n),c=(g)=>{switch(g){case"initial":case"active":return y.default.magenta;case"error":case"cancel":return y.default.red;case"submit":return y.default.green;default:return y.default.magenta}},f=(g,h)=>{let p=Math.floor(s/a*l);return`${c(g)(Al[e].repeat(p))}${y.default.dim(Al[e].repeat(l-p))} ${h}`},u=(g="")=>{o=g,r.start(f("initial",g))},d=(g=1,h)=>{s=Math.min(a,g+s),r.message(f("active",h??o)),o=h??o};return{start:u,stop:r.stop,cancel:r.cancel,error:r.error,clear:r.clear,advance:d,isCancelled:r.isCancelled,message:(g)=>d(0,g)}}var y,Ut,_i,ks=()=>process.env.CI==="true",_l=(e)=>e.isTTY===!0,H=(e,t)=>_i?e:t,Tl,As,Es,vt,_s,O,se,Il,Ol,yn,jt,Ti,wt,bn,Ml,Ii,Ts,Nl,Is,Os,Cl,Ms,Ns,Cs,Rs,Pe=(e)=>{switch(e){case"initial":case"active":return y.default.cyan(Tl);case"cancel":return y.default.red(As);case"error":return y.default.yellow(Es);case"submit":return y.default.green(vt)}},Ls=(e)=>{switch(e){case"initial":case"active":return y.default.cyan(O);case"cancel":return y.default.red(O);case"error":return y.default.yellow(O);case"submit":return y.default.green(O)}},dh=(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,ph=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,mh=(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,xs,$i,ki,Ss,Ai,hh,gh,Rl=(e,t={},n={})=>{let i=t.limit??1/0,r=t.ellipsis??"",s=t?.ellipsisWidth??(r?Rl(r,gh,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.ambiguousWidth??1,f=n.emojiWidth??2,u=n.fullWidthWidth??2,d=n.regularWidth??1,g=n.wideWidth??2,h=0,p=0,m=e.length,b=0,w=!1,S=m,_=Math.max(0,i-s),E=0,A=0,k=0,T=0;e:for(;;){if(A>E||p>=m&&p>h){let C=e.slice(E,A)||e.slice(h,p);b=0;for(let P of C.replaceAll(hh,"")){let L=P.codePointAt(0)||0;if(ph(L)?T=u:mh(L)?T=g:c!==d&&dh(L)?T=c:T=d,k+T>_&&(S=Math.min(S,Math.max(E,h)+b)),k+T>i){w=!0;break e}b+=P.length,k+=T}E=A=0}if(p>=m)break;if(Ai.lastIndex=p,Ai.test(e)){if(b=Ai.lastIndex-p,T=b*d,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/d))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=Ai.lastIndex;continue}if(xs.lastIndex=p,xs.test(e)){if(k+o>_&&(S=Math.min(S,p)),k+o>i){w=!0;break}k+=o,E=h,A=p,p=h=xs.lastIndex;continue}if($i.lastIndex=p,$i.test(e)){if(b=$i.lastIndex-p,T=b*a,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/a))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=$i.lastIndex;continue}if(ki.lastIndex=p,ki.test(e)){if(b=ki.lastIndex-p,T=b*l,k+T>_&&(S=Math.min(S,p+Math.floor((_-k)/l))),k+T>i){w=!0;break}k+=T,E=h,A=p,p=h=ki.lastIndex;continue}if(Ss.lastIndex=p,Ss.test(e)){if(k+f>_&&(S=Math.min(S,p)),k+f>i){w=!0;break}k+=f,E=h,A=p,p=h=Ss.lastIndex;continue}p+=1}return{width:w?_:k,index:w?S:m,truncated:w,ellipsed:w&&i>=s}},yh,fe=(e,t={})=>Rl(e,yh,t).width,Oi="\x1B",Ll="›",bh=39,Ps="\x07",Pl="[",wh="]",ql="m",qs,vl,vh=(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},xl=(e)=>`${Oi}${Pl}${e}${ql}`,Sl=(e)=>`${Oi}${qs}${e}${Ps}`,xh=(e)=>e.map((t)=>fe(t)),$s=(e,t,n)=>{let i=t[Symbol.iterator](),r=!1,s=!1,o=e.at(-1),a=o===void 0?0:fe(o),l=i.next(),c=i.next(),f=0;for(;!l.done;){let u=l.value,d=fe(u);a+d<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===Oi||u===Ll)&&(r=!0,s=t.startsWith(qs,f+1)),r?s?u===Ps&&(r=!1,s=!1):u===ql&&(r=!1):(a+=d,a===n&&!c.done&&(e.push(""),a=0)),l=c,c=i.next(),f+=u.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Sh=(e)=>{let t=e.split(" "),n=t.length;for(;n>0&&!(fe(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},$h=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let i="",r,s,o=e.split(" "),a=xh(o),l=[""];for(let[h,p]of o.entries()){n.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let m=fe(l.at(-1)??"");if(h!==0&&(m>=t&&(n.wordWrap===!1||n.trim===!1)&&(l.push(""),m=0),(m>0||n.trim===!1)&&(l[l.length-1]+=" ",m++)),n.hard&&a[h]>t){let b=t-m,w=1+Math.floor((a[h]-b-1)/t);Math.floor((a[h]-1)/t)<w&&l.push(""),$s(l,p,t);continue}if(m+a[h]>t&&m>0&&a[h]>0){if(n.wordWrap===!1&&m<t){$s(l,p,t);continue}l.push("")}if(m+a[h]>t&&n.wordWrap===!1){$s(l,p,t);continue}l[l.length-1]+=p}n.trim!==!1&&(l=l.map((h)=>Sh(h)));let c=l.join(`
28
+ `),f=c[Symbol.iterator](),u=f.next(),d=f.next(),g=0;for(;!u.done;){let h=u.value,p=d.value;if(i+=h,h===Oi||h===Ll){vl.lastIndex=g+1;let b=vl.exec(c)?.groups;if(b?.code!==void 0){let w=Number.parseFloat(b.code);r=w===bh?void 0:w}else b?.uri!==void 0&&(s=b.uri.length===0?void 0:b.uri)}let m=r?vh(r):void 0;p===`
29
+ `?(s&&(i+=Sl("")),r&&m&&(i+=xl(m))):h===`
30
+ `&&(r&&m&&(i+=xl(r)),s&&(i+=Sl(s))),g+=h.length,u=d,d=f.next()}return i},kh=(e,t,n,i,r)=>{let s=t,o=0;for(let a=n;a<i;a++){let l=e[a];if(s=s-l.length,o++,s<=r)break}return{lineCount:s,removals:o}},Vt=(e)=>{let{cursor:t,options:n,style:i}=e,r=e.output??process.stdout,s=Qe(r),o=e.columnPadding??0,a=e.rowPadding??4,l=s-o,c=hi(r),f=y.default.dim("..."),u=e.maxItems??Number.POSITIVE_INFINITY,d=Math.max(c-a,0),g=Math.max(Math.min(u,d),5),h=0;t>=g-3&&(h=Math.max(Math.min(t-g+3,n.length-g),0));let p=g<n.length&&h>0,m=g<n.length&&h+g<n.length,b=Math.min(h+g,n.length),w=[],S=0;p&&S++,m&&S++;let _=h+(p?1:0),E=b-(m?1:0);for(let k=_;k<E;k++){let T=Bt(i(n[k],k===t),l,{hard:!0,trim:!1}).split(`
31
+ `);w.push(T),S+=T.length}if(S>d){let k=0,T=0,C=S,P=t-_,L=(D,U)=>kh(w,C,D,U,d);p?({lineCount:C,removals:k}=L(0,P),C>d&&({lineCount:C,removals:T}=L(P+1,w.length))):({lineCount:C,removals:T}=L(P+1,w.length),C>d&&({lineCount:C,removals:k}=L(0,P))),k>0&&(p=!0,w.splice(0,k)),T>0&&(m=!0,w.splice(w.length-T,T))}let A=[];p&&A.push(f);for(let k of w)for(let T of k)A.push(T);return m&&A.push(f),A},Dl=(e)=>new hn({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,n)=>Fl(t,n)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=[`${y.default.gray(O)}`,`${Pe(this.state)} ${e.message}`],n=this.userInput,i=this.options,r=e.placeholder,s=n===""&&r!==void 0;switch(this.state){case"submit":{let o=Ah(this.selectedValues,i),a=o.length>0?` ${y.default.dim(o.map($l).join(", "))}`:"";return`${t.join(`
32
+ `)}
33
+ ${y.default.gray(O)}${a}`}case"cancel":{let o=n?` ${y.default.strikethrough(y.default.dim(n))}`:"";return`${t.join(`
34
+ `)}
35
+ ${y.default.gray(O)}${o}`}default:{let o=`${(this.state==="error"?y.default.yellow:y.default.cyan)(O)} `,a=(this.state==="error"?y.default.yellow:y.default.cyan)(se),l="";if(this.isNavigating||s){let p=s?r:n;l=p!==""?` ${y.default.dim(p)}`:""}else l=` ${this.userInputWithCursor}`;let c=this.filteredOptions.length!==i.length?y.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",f=this.filteredOptions.length===0&&n?[`${o}${y.default.yellow("No matches found")}`]:[],u=this.state==="error"?[`${o}${y.default.yellow(this.error)}`]:[];t.push(`${o.trimEnd()}`,`${o}${y.default.dim("Search:")}${l}${c}`,...f,...u);let d=[`${y.default.dim("↑/↓")} to select`,`${y.default.dim("Enter:")} confirm`,`${y.default.dim("Type:")} to search`],g=[`${o}${y.default.dim(d.join(" • "))}`,`${a}`],h=this.filteredOptions.length===0?[]:Vt({cursor:this.cursor,options:this.filteredOptions,columnPadding:3,rowPadding:t.length+g.length,style:(p,m)=>{let b=$l(p),w=p.hint&&p.value===this.focusedValue?y.default.dim(` (${p.hint})`):"";return m?`${y.default.green(yn)} ${b}${w}`:`${y.default.dim(jt)} ${y.default.dim(b)}${w}`},maxItems:e.maxItems,output:e.output});return[...t,...h.map((p)=>`${o}${p}`),...g].join(`
36
+ `)}}}}).prompt(),Eh=(e)=>{let t=(i,r,s,o)=>{let a=s.includes(i.value),l=i.label??String(i.value??""),c=i.hint&&o!==void 0&&i.value===o?y.default.dim(` (${i.hint})`):"",f=a?y.default.green(wt):y.default.dim(bn);return r?`${f} ${l}${c}`:`${f} ${y.default.dim(l)}`},n=new hn({options:e.options,multiple:!0,filter:e.filter??((i,r)=>Fl(i,r)),validate:()=>{if(e.required&&n.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let i=`${y.default.gray(O)}
37
+ ${Pe(this.state)} ${e.message}
38
+ `,r=this.userInput,s=e.placeholder,o=r===""&&s!==void 0,a=this.isNavigating||o?y.default.dim(o?s:r):this.userInputWithCursor,l=this.options,c=this.filteredOptions.length!==l.length?y.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${i}${y.default.gray(O)} ${y.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${i}${y.default.gray(O)} ${y.default.strikethrough(y.default.dim(r))}`;default:{let f=this.state==="error"?y.default.yellow:y.default.cyan,u=[`${y.default.dim("↑/↓")} to navigate`,`${y.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${y.default.dim("Enter:")} confirm`,`${y.default.dim("Type:")} to search`],d=this.filteredOptions.length===0&&r?[`${f(O)} ${y.default.yellow("No matches found")}`]:[],g=this.state==="error"?[`${f(O)} ${y.default.yellow(this.error)}`]:[],h=[...`${i}${f(O)}`.split(`
39
+ `),`${f(O)} ${y.default.dim("Search:")} ${a}${c}`,...d,...g],p=[`${f(O)} ${y.default.dim(u.join(" • "))}`,`${f(se)}`],m=Vt({cursor:this.cursor,options:this.filteredOptions,style:(b,w)=>t(b,w,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:h.length+p.length});return[...h,...m.map((b)=>`${f(O)} ${b}`),...p].join(`
40
+ `)}}}});return n.prompt()},_h,Th,Ih=(e)=>e,Oh=(e="",t="",n)=>{let i=n?.output??process.stdout,r=Qe(i),o=n?.titlePadding??1,a=n?.contentPadding??2,l=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),c=(n?.withGuide??ee.withGuide)!==!1?`${O} `:"",f=n?.formatBorder??Ih,u=((n?.rounded)?_h:Th).map(f),d=f(Ii),g=f(O),h=fe(c),p=fe(t),m=r-h,b=Math.floor(r*l)-h;if(n?.width==="auto"){let C=e.split(`
41
+ `),P=p+o*2;for(let D of C){let U=fe(D)+a*2;U>P&&(P=U)}let L=P+2;L<b&&(b=L)}b%2!==0&&(b<m?b++:b--);let w=b-2,S=w-o*2,_=p>S?`${t.slice(0,S-3)}...`:t,[E,A]=kl(fe(_),w,o,n?.titleAlign),k=Bt(e,w-a*2,{hard:!0,trim:!1});i.write(`${c}${u[0]}${d.repeat(E)}${_}${d.repeat(A)}${u[1]}
42
+ `);let T=k.split(`
43
+ `);for(let C of T){let[P,L]=kl(fe(C),w,a,n?.contentAlign);i.write(`${c}${g}${" ".repeat(P)}${C}${" ".repeat(L)}${g}
44
+ `)}i.write(`${c}${u[2]}${d.repeat(w)}${u[3]}
45
+ `)},Mh=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new gi({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=`${y.default.gray(O)}
46
+ ${Pe(this.state)} ${e.message}
47
+ `,r=this.value?t:n;switch(this.state){case"submit":return`${i}${y.default.gray(O)} ${y.default.dim(r)}`;case"cancel":return`${i}${y.default.gray(O)} ${y.default.strikethrough(y.default.dim(r))}
48
+ ${y.default.gray(O)}`;default:return`${i}${y.default.cyan(O)} ${this.value?`${y.default.green(yn)} ${t}`:`${y.default.dim(jt)} ${y.default.dim(t)}`} ${y.default.dim("/")} ${this.value?`${y.default.dim(jt)} ${y.default.dim(n)}`:`${y.default.green(yn)} ${n}`}
49
+ ${y.default.cyan(se)}
50
+ `}}}).prompt()},Nh=async(e,t)=>{let n={},i=Object.keys(e);for(let r of i){let s=e[r],o=await s({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&mn(o)){n[r]="canceled",t.onCancel({results:n});continue}n[r]=o}return n},Ch=(e)=>{let{selectableGroups:t=!0,groupSpacing:n=0}=e,i=(s,o,a=[])=>{let l=s.label??String(s.value),c=typeof s.group=="string",f=c&&(a[a.indexOf(s)+1]??{group:!0}),u=c&&f&&f.group===!0,d=c?t?`${u?se:O} `:" ":"",g="";if(n>0&&!c){let p=`
51
+ ${y.default.cyan(O)}`;g=`${p.repeat(n-1)}${p} `}if(o==="active")return`${g}${y.default.dim(d)}${y.default.cyan(Ti)} ${l}${s.hint?` ${y.default.dim(`(${s.hint})`)}`:""}`;if(o==="group-active")return`${g}${d}${y.default.cyan(Ti)} ${y.default.dim(l)}`;if(o==="group-active-selected")return`${g}${d}${y.default.green(wt)} ${y.default.dim(l)}`;if(o==="selected"){let p=c||t?y.default.green(wt):"";return`${g}${y.default.dim(d)}${p} ${y.default.dim(l)}${s.hint?` ${y.default.dim(`(${s.hint})`)}`:""}`}if(o==="cancelled")return`${y.default.strikethrough(y.default.dim(l))}`;if(o==="active-selected")return`${g}${y.default.dim(d)}${y.default.green(wt)} ${l}${s.hint?` ${y.default.dim(`(${s.hint})`)}`:""}`;if(o==="submitted")return`${y.default.dim(l)}`;let h=c||t?y.default.dim(bn):"";return`${g}${y.default.dim(d)}${h} ${y.default.dim(l)}`},r=e.required??!0;return new yi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,selectableGroups:t,validate(s){if(r&&(s===void 0||s.length===0))return`Please select at least one option.
52
+ ${y.default.reset(y.default.dim(`Press ${y.default.gray(y.default.bgWhite(y.default.inverse(" space ")))} to select, ${y.default.gray(y.default.bgWhite(y.default.inverse(" enter ")))} to submit`))}`},render(){let s=`${y.default.gray(O)}
53
+ ${Pe(this.state)} ${e.message}
54
+ `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:c})=>o.includes(c)).map((c)=>i(c,"submitted")),l=a.length===0?"":` ${a.join(y.default.dim(", "))}`;return`${s}${y.default.gray(O)}${l}`}case"cancel":{let a=this.options.filter(({value:l})=>o.includes(l)).map((l)=>i(l,"cancelled")).join(y.default.dim(", "));return`${s}${y.default.gray(O)} ${a.trim()?`${a}
55
+ ${y.default.gray(O)}`:""}`}case"error":{let a=this.error.split(`
56
+ `).map((l,c)=>c===0?`${y.default.yellow(se)} ${y.default.yellow(l)}`:` ${l}`).join(`
57
+ `);return`${s}${y.default.yellow(O)} ${this.options.map((l,c,f)=>{let u=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),d=c===this.cursor;return!d&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?i(l,u?"group-active-selected":"group-active",f):d&&u?i(l,"active-selected",f):u?i(l,"selected",f):i(l,d?"active":"inactive",f)}).join(`
58
+ ${y.default.yellow(O)} `)}
59
+ ${a}
60
+ `}default:{let a=this.options.map((c,f,u)=>{let d=o.includes(c.value)||c.group===!0&&this.isGroupSelected(`${c.value}`),g=f===this.cursor,h=!g&&typeof c.group=="string"&&this.options[this.cursor].value===c.group,p="";return h?p=i(c,d?"group-active-selected":"group-active",u):g&&d?p=i(c,"active-selected",u):d?p=i(c,"selected",u):p=i(c,g?"active":"inactive",u),`${f!==0&&!p.startsWith(`
61
+ `)?" ":""}${p}`}).join(`
62
+ ${y.default.cyan(O)}`),l=a.startsWith(`
63
+ `)?"":" ";return`${s}${y.default.cyan(O)}${l}${a}
64
+ ${y.default.cyan(se)}
65
+ `}}}}).prompt()},he,Rh=(e="",t)=>{(t?.output??process.stdout).write(`${y.default.gray(se)} ${y.default.red(e)}
86
66
 
87
- `)},lu=(e="")=>{process.stdout.write(`${c.default.gray(Ws)} ${e}
88
- `)},mu=(e="")=>{process.stdout.write(`${c.default.gray(b)}
89
- ${c.default.gray(z)} ${e}
67
+ `)},Lh=(e="",t)=>{(t?.output??process.stdout).write(`${y.default.gray(_s)} ${e}
68
+ `)},Ph=(e="",t)=>{(t?.output??process.stdout).write(`${y.default.gray(O)}
69
+ ${y.default.gray(se)} ${e}
90
70
 
91
- `)},ye,du=()=>{let e=Wt?["◒","◐","◓","◑"]:["•","o","O","0"],t=Wt?80:120,o,n,i=!1,s="",r=(p="")=>{i=!0,o=uo(),s=p.replace(/\.+$/,""),process.stdout.write(`${c.default.gray(b)}
92
- `);let f=0,D=0;n=setInterval(()=>{let h=c.default.magenta(e[f]),E=".".repeat(Math.floor(D)).slice(0,3);process.stdout.write(Te.cursor.move(-999,0)),process.stdout.write(Te.erase.down(1)),process.stdout.write(`${h} ${s}${E}`),f=f+1<e.length?f+1:0,D=D<e.length?D+0.125:0},t)},u=(p="",f=0)=>{s=p??s,i=!1,clearInterval(n);let D=f===0?c.default.green(nt):f===1?c.default.red(co):c.default.red(lo);process.stdout.write(Te.cursor.move(-999,0)),process.stdout.write(Te.erase.down(1)),process.stdout.write(`${D} ${s}
93
- `),o()},a=(p="")=>{s=p??s},l=(p)=>{let f=p>1?"Something went wrong":"Canceled";i&&u(f,p)};return process.on("uncaughtExceptionMonitor",()=>l(2)),process.on("unhandledRejection",()=>l(2)),process.on("SIGINT",()=>l(1)),process.on("SIGTERM",()=>l(1)),process.on("exit",l),{start:r,stop:u,message:a}},Du=async(e,t)=>{let o={},n=Object.keys(e);for(let i of n){let s=e[i],r=await s({results:o})?.catch((u)=>{throw u});if(typeof t?.onCancel=="function"&&ot(r)){o[i]="canceled",t.onCancel({results:o});continue}o[i]=r}return o};var Fe=C(()=>{jt();jt();c=ze(Tt(),1),Te=ze(Bt(),1);Wt=js(),Hs=L("◆","*"),co=L("■","x"),lo=L("▲","x"),nt=L("◇","o"),Ws=L("┌","T"),b=L("│","|"),z=L("└","—"),Kt=L("●",">"),zt=L("○"," "),Jt=L("◻","[•]"),Ge=L("◼","[+]"),mo=L("◻","[ ]"),Ks=L("▪","•"),ao=L("─","-"),zs=L("╮","+"),Js=L("├","+"),Ys=L("╯","+"),Xs=L("●","•"),Qs=L("◆","*"),Zs=L("▲","!"),eu=L("■","x"),ye={message:(e="",{symbol:t=c.default.gray(b)}={})=>{let o=[`${c.default.gray(b)}`];if(e){let[n,...i]=e.split(`
94
- `);o.push(`${t} ${n}`,...i.map((s)=>`${c.default.gray(b)} ${s}`))}process.stdout.write(`${o.join(`
71
+ `)},gn=(e,t)=>e.split(`
72
+ `).map((n)=>t(n)).join(`
73
+ `),qh=(e)=>{let t=(i,r)=>{let s=i.label??String(i.value);return r==="disabled"?`${y.default.gray(bn)} ${gn(s,(o)=>y.default.strikethrough(y.default.gray(o)))}${i.hint?` ${y.default.dim(`(${i.hint??"disabled"})`)}`:""}`:r==="active"?`${y.default.cyan(Ti)} ${s}${i.hint?` ${y.default.dim(`(${i.hint})`)}`:""}`:r==="selected"?`${y.default.green(wt)} ${gn(s,y.default.dim)}${i.hint?` ${y.default.dim(`(${i.hint})`)}`:""}`:r==="cancelled"?`${gn(s,(o)=>y.default.strikethrough(y.default.dim(o)))}`:r==="active-selected"?`${y.default.green(wt)} ${s}${i.hint?` ${y.default.dim(`(${i.hint})`)}`:""}`:r==="submitted"?`${gn(s,y.default.dim)}`:`${y.default.dim(bn)} ${gn(s,y.default.dim)}`},n=e.required??!0;return new bi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
74
+ ${y.default.reset(y.default.dim(`Press ${y.default.gray(y.default.bgWhite(y.default.inverse(" space ")))} to select, ${y.default.gray(y.default.bgWhite(y.default.inverse(" enter ")))} to submit`))}`},render(){let i=Ee(e.output,e.message,`${Ls(this.state)} `,`${Pe(this.state)} `),r=`${y.default.gray(O)}
75
+ ${i}
76
+ `,s=this.value??[],o=(a,l)=>{if(a.disabled)return t(a,"disabled");let c=s.includes(a.value);return l&&c?t(a,"active-selected"):c?t(a,"selected"):t(a,l?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:c})=>s.includes(c)).map((c)=>t(c,"submitted")).join(y.default.dim(", "))||y.default.dim("none"),l=Ee(e.output,a,`${y.default.gray(O)} `);return`${r}${l}`}case"cancel":{let a=this.options.filter(({value:c})=>s.includes(c)).map((c)=>t(c,"cancelled")).join(y.default.dim(", "));if(a.trim()==="")return`${r}${y.default.gray(O)}`;let l=Ee(e.output,a,`${y.default.gray(O)} `);return`${r}${l}
77
+ ${y.default.gray(O)}`}case"error":{let a=`${y.default.yellow(O)} `,l=this.error.split(`
78
+ `).map((u,d)=>d===0?`${y.default.yellow(se)} ${y.default.yellow(u)}`:` ${u}`).join(`
79
+ `),c=r.split(`
80
+ `).length,f=l.split(`
81
+ `).length+1;return`${r}${a}${Vt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+f,style:o}).join(`
82
+ ${a}`)}
83
+ ${l}
84
+ `}default:{let a=`${y.default.cyan(O)} `,l=r.split(`
85
+ `).length;return`${r}${a}${Vt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+2,style:o}).join(`
86
+ ${a}`)}
87
+ ${y.default.cyan(se)}
88
+ `}}}}).prompt()},Fh=(e)=>y.default.dim(e),Dh=(e,t,n)=>{let i={hard:!0,trim:!1},r=Bt(e,t,i).split(`
89
+ `),s=r.reduce((l,c)=>Math.max(fe(c),l),0),o=r.map(n).reduce((l,c)=>Math.max(fe(c),l),0),a=t-(o-s);return Bt(e,a,i)},Uh=(e="",t="",n)=>{let i=n?.output??ve.stdout,r=(n?.withGuide??ee.withGuide)!==!1,s=n?.format??Fh,o=["",...Dh(e,Qe(i)-6,s).split(`
90
+ `).map(s),""],a=fe(t),l=Math.max(o.reduce((d,g)=>{let h=fe(g);return h>d?h:d},0),a)+2,c=o.map((d)=>`${y.default.gray(O)} ${d}${" ".repeat(l-fe(d))}${y.default.gray(O)}`).join(`
91
+ `),f=r?`${y.default.gray(O)}
92
+ `:"",u=r?Nl:Os;i.write(`${f}${y.default.green(vt)} ${y.default.reset(t)} ${y.default.gray(Ii.repeat(Math.max(l-a-1,1))+Ts)}
93
+ ${c}
94
+ ${y.default.gray(u+Ii.repeat(l+2)+Is)}
95
+ `)},jh=(e)=>new ws({validate:e.validate,mask:e.mask??Ml,signal:e.signal,input:e.input,output:e.output,render(){let t=`${y.default.gray(O)}
96
+ ${Pe(this.state)} ${e.message}
97
+ `,n=this.userInputWithCursor,i=this.masked;switch(this.state){case"error":{let r=i?` ${i}`:"";return e.clearOnError&&this.clear(),`${t.trim()}
98
+ ${y.default.yellow(O)}${r}
99
+ ${y.default.yellow(se)} ${y.default.yellow(this.error)}
100
+ `}case"submit":{let r=i?` ${y.default.dim(i)}`:"";return`${t}${y.default.gray(O)}${r}`}case"cancel":{let r=i?` ${y.default.strikethrough(y.default.dim(i))}`:"";return`${t}${y.default.gray(O)}${r}${i?`
101
+ ${y.default.gray(O)}`:""}`}default:return`${t}${y.default.cyan(O)} ${n}
102
+ ${y.default.cyan(se)}
103
+ `}}}).prompt(),Bh=(e)=>{let t=e.validate;return Dl({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(n){if(!Array.isArray(n)){if(!n)return"Please select a path";if(t)return t(n)}},options(){let n=this.userInput;if(n==="")return[];try{let i;return ch(n)?bl(n).isDirectory()?i=n:i=wl(n):i=wl(n),lh(i).map((r)=>{let s=uh(i,r),o=bl(s);return{name:r,path:s,isDirectory:o.isDirectory()}}).filter(({path:r,isDirectory:s})=>r.startsWith(n)&&(e.directory||!s)).map((r)=>({value:r.path}))}catch{return[]}}})},Vh,Fs=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:r,frames:s=_i?["◒","◐","◓","◑"]:["•","o","O","0"],delay:o=_i?80:120,signal:a,...l}={})=>{let c=ks(),f,u,d=!1,g=!1,h="",p,m=performance.now(),b=Qe(n),w=l?.styleFrame??Vh,S=(U)=>{let q=U>1?r??ee.messages.error:i??ee.messages.cancel;g=U===1,d&&(D(q,U),g&&typeof t=="function"&&t())},_=()=>S(2),E=()=>S(1),A=()=>{process.on("uncaughtExceptionMonitor",_),process.on("unhandledRejection",_),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",S),a&&a.addEventListener("abort",E)},k=()=>{process.removeListener("uncaughtExceptionMonitor",_),process.removeListener("unhandledRejection",_),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",S),a&&a.removeEventListener("abort",E)},T=()=>{if(p===void 0)return;c&&n.write(`
104
+ `);let U=Bt(p,b,{hard:!0,trim:!1}).split(`
105
+ `);U.length>1&&n.write(Ut.cursor.up(U.length-1)),n.write(Ut.cursor.to(0)),n.write(Ut.erase.down())},C=(U)=>U.replace(/\.+$/,""),P=(U)=>{let q=(performance.now()-U)/1000,W=Math.floor(q/60),we=Math.floor(q%60);return W>0?`[${W}m ${we}s]`:`[${we}s]`},L=(U="")=>{d=!0,f=bs({output:n}),h=C(U),m=performance.now(),n.write(`${y.default.gray(O)}
106
+ `);let q=0,W=0;A(),u=setInterval(()=>{if(c&&h===p)return;T(),p=h;let we=w(s[q]),je;if(c)je=`${we} ${h}...`;else if(e==="timer")je=`${we} ${h} ${P(m)}`;else{let fm=".".repeat(Math.floor(W)).slice(0,3);je=`${we} ${h}${fm}`}let um=Bt(je,b,{hard:!0,trim:!1});n.write(um),q=q+1<s.length?q+1:0,W=W<4?W+0.125:0},o)},D=(U="",q=0,W=!1)=>{if(!d)return;d=!1,clearInterval(u),T();let we=q===0?y.default.green(vt):q===1?y.default.red(As):y.default.red(Es);h=U??h,W||(e==="timer"?n.write(`${we} ${h} ${P(m)}
107
+ `):n.write(`${we} ${h}
108
+ `)),k(),f()};return{start:L,stop:(U="")=>D(U,0),message:(U="")=>{h=C(U??h)},cancel:(U="")=>D(U,1),error:(U="")=>D(U,2),clear:()=>D("",0,!0),get isCancelled(){return g}}},Al,Ei=(e,t)=>e.includes(`
109
+ `)?e.split(`
110
+ `).map((n)=>t(n)).join(`
111
+ `):t(e),Kh=(e)=>{let t=(n,i)=>{let r=n.label??String(n.value);switch(i){case"disabled":return`${y.default.gray(jt)} ${Ei(r,y.default.gray)}${n.hint?` ${y.default.dim(`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Ei(r,y.default.dim)}`;case"active":return`${y.default.green(yn)} ${r}${n.hint?` ${y.default.dim(`(${n.hint})`)}`:""}`;case"cancelled":return`${Ei(r,(s)=>y.default.strikethrough(y.default.dim(s)))}`;default:return`${y.default.dim(jt)} ${Ei(r,y.default.dim)}`}};return new wi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=`${Pe(this.state)} `,i=`${Ls(this.state)} `,r=Ee(e.output,e.message,i,n),s=`${y.default.gray(O)}
112
+ ${r}
113
+ `;switch(this.state){case"submit":{let o=`${y.default.gray(O)} `,a=Ee(e.output,t(this.options[this.cursor],"selected"),o);return`${s}${a}`}case"cancel":{let o=`${y.default.gray(O)} `,a=Ee(e.output,t(this.options[this.cursor],"cancelled"),o);return`${s}${a}
114
+ ${y.default.gray(O)}`}default:{let o=`${y.default.cyan(O)} `,a=s.split(`
115
+ `).length;return`${s}${o}${Vt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:o.length,rowPadding:a+2,style:(l,c)=>t(l,l.disabled?"disabled":c?"active":"inactive")}).join(`
116
+ ${o}`)}
117
+ ${y.default.cyan(se)}
118
+ `}}}}).prompt()},Wh=(e)=>{let t=(n,i="inactive")=>{let r=n.label??String(n.value);return i==="selected"?`${y.default.dim(r)}`:i==="cancelled"?`${y.default.strikethrough(y.default.dim(r))}`:i==="active"?`${y.default.bgCyan(y.default.gray(` ${n.value} `))} ${r}${n.hint?` ${y.default.dim(`(${n.hint})`)}`:""}`:`${y.default.gray(y.default.bgWhite(y.default.inverse(` ${n.value} `)))} ${r}${n.hint?` ${y.default.dim(`(${n.hint})`)}`:""}`};return new vi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let n=`${y.default.gray(O)}
119
+ ${Pe(this.state)} ${e.message}
120
+ `;switch(this.state){case"submit":{let i=`${y.default.gray(O)} `,r=this.options.find((o)=>o.value===this.value)??e.options[0],s=Ee(e.output,t(r,"selected"),i);return`${n}${s}`}case"cancel":{let i=`${y.default.gray(O)} `,r=Ee(e.output,t(this.options[0],"cancelled"),i);return`${n}${r}
121
+ ${y.default.gray(O)}`}default:{let i=`${y.default.cyan(O)} `,r=this.options.map((s,o)=>Ee(e.output,t(s,o===this.cursor?"active":"inactive"),i)).join(`
122
+ `);return`${n}${r}
123
+ ${y.default.cyan(se)}
124
+ `}}}}).prompt()},El,bt,Hh=async(e,t)=>{for(let n of e){if(n.enabled===!1)continue;let i=Fs(t);i.start(n.title);let r=await n.task(i.message);i.stop(r||n.title)}},Jh=(e)=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Yh=(e)=>{let t=e.output??process.stdout,n=Qe(t),i=y.default.gray(O),r=e.spacing??1,o=e.retainLog===!0,a=!ks()&&_l(t);t.write(`${i}
125
+ `),t.write(`${y.default.green(vt)} ${e.title}
126
+ `);for(let m=0;m<r;m++)t.write(`${i}
127
+ `);let l=[{value:"",full:""}],c=!1,f=(m)=>{if(l.length===0)return;let b=0;m&&(b+=r+2);for(let w of l){let{value:S,result:_}=w,E=_?.message??S;if(E.length===0)continue;_===void 0&&w.header!==void 0&&w.header!==""&&(E+=`
128
+ ${w.header}`);let A=E.split(`
129
+ `).reduce((k,T)=>T===""?k+1:k+Math.ceil((T.length+3)/n),0);b+=A}b>0&&(b+=1,t.write(Ut.erase.lines(b)))},u=(m,b,w)=>{let S=w?`${m.full}
130
+ ${m.value}`:m.value;m.header!==void 0&&m.header!==""&&he.message(m.header.split(`
131
+ `).map(y.default.bold),{output:t,secondarySymbol:i,symbol:i,spacing:0}),he.message(S.split(`
132
+ `).map(y.default.dim),{output:t,secondarySymbol:i,symbol:i,spacing:b??r})},d=()=>{for(let m of l){let{header:b,value:w,full:S}=m;(b===void 0||b.length===0)&&w.length===0||u(m,void 0,o===!0&&S.length>0)}},g=(m,b,w)=>{if(f(!1),(w?.raw!==!0||!c)&&m.value!==""&&(m.value+=`
133
+ `),m.value+=Jh(b),c=w?.raw===!0,e.limit!==void 0){let S=m.value.split(`
134
+ `),_=S.length-e.limit;if(_>0){let E=S.splice(0,_);o&&(m.full+=(m.full===""?"":`
135
+ `)+E.join(`
136
+ `))}m.value=S.join(`
137
+ `)}a&&h()},h=()=>{for(let m of l)m.result?m.result.status==="error"?he.error(m.result.message,{output:t,secondarySymbol:i,spacing:0}):he.success(m.result.message,{output:t,secondarySymbol:i,spacing:0}):m.value!==""&&u(m,0)},p=(m,b)=>{f(!1),m.result=b,a&&h()};return{message(m,b){g(l[0],m,b)},group(m){let b={header:m,value:"",full:""};return l.push(b),{message(w,S){g(b,w,S)},error(w){p(b,{status:"error",message:w})},success(w){p(b,{status:"success",message:w})}}},error(m,b){f(!0),he.error(m,{output:t,secondarySymbol:i,spacing:1}),b?.showLog!==!1&&d(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(m,b){f(!0),he.success(m,{output:t,secondarySymbol:i,spacing:1}),b?.showLog===!0&&d(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},zh=(e)=>new xi({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??ee.withGuide)!==!1,n=`${`${t?`${y.default.gray(O)}
138
+ `:""}${Pe(this.state)} `}${e.message}
139
+ `,i=e.placeholder?y.default.inverse(e.placeholder[0])+y.default.dim(e.placeholder.slice(1)):y.default.inverse(y.default.hidden("_")),r=this.userInput?this.userInputWithCursor:i,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${y.default.yellow(this.error)}`:"",a=t?`${y.default.yellow(O)} `:"",l=t?y.default.yellow(se):"";return`${n.trim()}
140
+ ${a}${r}
141
+ ${l}${o}
142
+ `}case"submit":{let o=s?` ${y.default.dim(s)}`:"",a=t?y.default.gray(O):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${y.default.strikethrough(y.default.dim(s))}`:"",a=t?y.default.gray(O):"";return`${n}${a}${o}${s.trim()?`
143
+ ${a}`:""}`}default:{let o=t?`${y.default.cyan(O)} `:"",a=t?y.default.cyan(se):"";return`${n}${o}${r}
144
+ ${a}
145
+ `}}}}).prompt();var Te=I(()=>{Si();Si();y=Ft(dn(),1),Ut=Ft(as(),1);_i=fh(),Tl=H("◆","*"),As=H("■","x"),Es=H("▲","x"),vt=H("◇","o"),_s=H("┌","T"),O=H("│","|"),se=H("└","—"),Il=H("┐","T"),Ol=H("┘","—"),yn=H("●",">"),jt=H("○"," "),Ti=H("◻","[•]"),wt=H("◼","[+]"),bn=H("◻","[ ]"),Ml=H("▪","•"),Ii=H("─","-"),Ts=H("╮","+"),Nl=H("├","+"),Is=H("╯","+"),Os=H("╰","+"),Cl=H("╭","+"),Ms=H("●","•"),Ns=H("◆","*"),Cs=H("▲","!"),Rs=H("■","x"),xs=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,$i=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ki=/\t{1,1000}/y,Ss=/[\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,Ai=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,hh=/\p{M}+/gu,gh={limit:1/0,ellipsis:""},yh={limit:1/0,ellipsis:"",ellipsisWidth:0},qs=`${wh}8;;`,vl=new RegExp(`(?:\\${Pl}(?<code>\\d+)m|\\${qs}(?<uri>.*)${Ps})`,"y");_h=[Cl,Ts,Os,Is],Th=[_s,Il,se,Ol];he={message:(e=[],{symbol:t=y.default.gray(O),secondarySymbol:n=y.default.gray(O),output:i=process.stdout,spacing:r=1,withGuide:s}={})=>{let o=[],a=(s??ee.withGuide)!==!1,l=a?n:"",c=a?`${t} `:"",f=a?`${n} `:"";for(let d=0;d<r;d++)o.push(l);let u=Array.isArray(e)?e:e.split(`
146
+ `);if(u.length>0){let[d,...g]=u;d.length>0?o.push(`${c}${d}`):o.push(a?t:"");for(let h of g)h.length>0?o.push(`${f}${h}`):o.push(a?n:"")}i.write(`${o.join(`
95
147
  `)}
96
- `)},info:(e)=>{ye.message(e,{symbol:c.default.blue(Xs)})},success:(e)=>{ye.message(e,{symbol:c.default.green(Qs)})},step:(e)=>{ye.message(e,{symbol:c.default.green(nt)})},warn:(e)=>{ye.message(e,{symbol:c.default.yellow(Zs)})},warning:(e)=>{ye.warn(e)},error:(e)=>{ye.message(e,{symbol:c.default.red(eu)})}}});async function te(e){if(!G())return;let{defaultValue:t,message:o}=e,i=await(await Promise.resolve().then(() => (Fe(),Ee))).text({message:o,default:t,placeholder:t});if(typeof i==="symbol")return;return i}async function po(e){if(!G())return;let{message:t}=e,n=await(await Promise.resolve().then(() => (Fe(),Ee))).confirm({message:t});if(typeof n==="symbol")return;return n}function xe(e,t){throw new m(`Missing required argument: --${e}
148
+ `)},info:(e,t)=>{he.message(e,{...t,symbol:y.default.blue(Ms)})},success:(e,t)=>{he.message(e,{...t,symbol:y.default.green(Ns)})},step:(e,t)=>{he.message(e,{...t,symbol:y.default.green(vt)})},warn:(e,t)=>{he.message(e,{...t,symbol:y.default.yellow(Cs)})},warning:(e,t)=>{he.warn(e,t)},error:(e,t)=>{he.message(e,{...t,symbol:y.default.red(Rs)})}},Vh=y.default.magenta,Al={light:H("─","-"),heavy:H("━","="),block:H("█","#")};El=`${y.default.gray(O)} `,bt={message:async(e,{symbol:t=y.default.gray(O)}={})=>{process.stdout.write(`${y.default.gray(O)}
149
+ ${t} `);let n=3;for await(let i of e){i=i.replace(/\n/g,`
150
+ ${El}`),i.includes(`
151
+ `)&&(n=3+vs(i.slice(i.lastIndexOf(`
152
+ `))).length);let r=vs(i).length;n+r<process.stdout.columns?(n+=r,process.stdout.write(i)):(process.stdout.write(`
153
+ ${El}${i.trimStart()}`),n=3+vs(i.trimStart()).length)}process.stdout.write(`
154
+ `)},info:(e)=>bt.message(e,{symbol:y.default.blue(Ms)}),success:(e)=>bt.message(e,{symbol:y.default.green(Ns)}),step:(e)=>bt.message(e,{symbol:y.default.green(vt)}),warn:(e)=>bt.message(e,{symbol:y.default.yellow(Cs)}),warning:(e)=>bt.warn(e),error:(e)=>bt.message(e,{symbol:y.default.red(Rs)})}});async function Ie(e){if(!Y())return;let{defaultValue:t,message:n}=e,r=await(await Promise.resolve().then(() => (Te(),_e))).text({message:n,default:t,placeholder:t});if(typeof r==="symbol")return;return r}function Qh(e){if(e.length<=Ul)return e;return`${e.slice(0,Ul)}.... (${e.length} chars)`}async function jl(e){if(!Y())return;let{TextPrompt:t}=await Promise.resolve().then(() => (Si(),yl)),n=await new t({render(){let i=Qh(this.userInput),r=ce.default.inverse(ce.default.hidden("_")),s=ce.default.gray("│");switch(this.state){case"submit":return`${s}
155
+ ${ce.default.green("◇")} ${e.message}
156
+ ${s} ${ce.default.dim(i)}`;case"cancel":return`${s}
157
+ ${ce.default.red("■")} ${e.message}
158
+ ${s} ${ce.default.strikethrough(ce.default.dim(i))}`;case"error":return`${s}
159
+ ${ce.default.yellow("▲")} ${e.message}
160
+ ${ce.default.yellow("│")} ${i}${r}
161
+ ${ce.default.yellow("└")} ${ce.default.yellow(this.error)}`;default:return`${s}
162
+ ${ce.default.cyan("◆")} ${e.message}
163
+ ${ce.default.cyan("│")} ${i}${r}
164
+ ${ce.default.cyan("└")}`}}}).prompt();if(typeof n==="symbol")return;return n}async function Bl(e,t){if(!Y())return t();let{spinner:n}=await Promise.resolve().then(() => (Te(),_e)),i=n();i.start(e.message);try{let r=await t();return i.stop(e.successMessage),r}catch(r){throw i.error(e.errorMessage),r}}async function Mi(e){if(!Y())return;let{message:t}=e,i=await(await Promise.resolve().then(() => (Te(),_e))).confirm({message:t});if(typeof i==="symbol")return;return i}async function Ds(e){if(!Y())return;(await Promise.resolve().then(() => (Te(),_e))).note(e.message,e.title)}async function Us(e){if(!Y())return;let n=await(await Promise.resolve().then(() => (Te(),_e))).select({message:e.message,options:e.choices,initialValue:e.initialValue});if(typeof n==="symbol")return;return n}async function Vl(e){if(!Y())return;let n=await(await Promise.resolve().then(() => (Te(),_e))).multiselect({message:e.message,options:e.choices,initialValues:e.initialValues,required:e.required});if(typeof n==="symbol")return;return n}function xt(e,t){throw new v(`Missing required argument: --${e}
97
165
  Hint: In non-interactive (CI / agent) environments all required flags must be provided.
98
- In an interactive terminal, run without --${e} and the CLI will prompt for it.`,d.USAGE,t)}async function it(e){if(e.value)return e.value;if(G({nonInteractive:e.nonInteractive})){let t=await te({message:e.message});if(!t)process.stderr.write(e.cancelMessage+`
99
- `),process.exit(1);return t}xe(e.flagName,e.usageHint)}var pe=C(()=>{R();S()});function J(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:"***"}async function fo(e){let t=Je[e],{randomBytes:o,createHash:n}=await import("crypto"),i=o(32).toString("base64url"),s=n("sha256").update(i).digest("base64url"),r=o(16).toString("base64url"),u=await fetch(`${t}/oauth2/device/code`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:Do,scope:hu.join(" "),code_challenge:s,code_challenge_method:"S256",state:r})});if(!u.ok){let f=await u.text().catch(()=>"");throw new m(`Failed to start device-code flow (HTTP ${u.status}).`,d.AUTH,f||`URL: ${t}/oauth2/device/code`)}let a=await u.json();if(a.state!==r)throw new m("OAuth state mismatch.",d.AUTH);Cu(a.verification_uri),process.stderr.write(`
100
- Opened: ${a.verification_uri}
101
- `),process.stderr.write(`Code: ${a.user_code}
102
- `),process.stderr.write(`Client: ${fu}
166
+ In an interactive terminal, run without --${e} and the CLI will prompt for it.`,x.USAGE,t)}async function Ni(e){if(e.value)return e.value;if(Y({nonInteractive:e.nonInteractive})){let t=await Ie({message:e.message});if(!t)process.stderr.write(e.cancelMessage+`
167
+ `),process.exit(1);return t}xt(e.flagName,e.usageHint)}var ce,Ul=30;var Ve=I(()=>{G();V();ce=Ft(dn(),1)});function ge(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:"***"}async function Kl(e){let t=si[e],{randomBytes:n,createHash:i}=await import("crypto"),r=n(32).toString("base64url"),s=i("sha256").update(r).digest("base64url"),o=n(16).toString("base64url"),a=await fetch(`${t}/oauth2/device/code`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:Gl,scope:Zh.join(" "),code_challenge:s,code_challenge_method:"S256",state:o})});if(!a.ok){let u=await a.text().catch(()=>"");throw new v(`Failed to start device-code flow (HTTP ${a.status}).`,x.AUTH,u||`URL: ${t}/oauth2/device/code`)}let l=await a.json();if(l.state!==o)throw new v("OAuth state mismatch.",x.AUTH);tg(l.verification_uri),process.stderr.write(`
168
+ Opened: ${l.verification_uri}
169
+ `),process.stderr.write(`Code: ${l.user_code}
170
+ `),process.stderr.write(`Client: ${Xh}
103
171
  `),process.stderr.write(`Waiting for authorization...
104
- `);let l=a.expired_in,p=a.interval||3000;while(Date.now()<l){await gu(p);let f=await fetch(`${t}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:Do,user_code:a.user_code,code_verifier:i})});if(!f.ok)throw new m(`Device-code authorization failed (HTTP ${f.status}).`,d.AUTH);let D=await f.json();if(D.status==="pending")continue;if(D.status==="success"&&D.access_token)return{access_token:D.access_token,refresh_token:D.refresh_token??"",expires_at:new Date(D.expired_in??Date.now()).toISOString(),region:e,resource_url:D.resource_url};throw new m(`Device-code authorization failed: ${D.status}`,d.AUTH)}throw new m("Device-code authorization timed out.",d.TIMEOUT)}function gu(e){return new Promise((t)=>setTimeout(t,e))}function Cu(e){let{execFile:t,spawn:o}=Be("child_process");if(process.platform==="darwin")t("open",[e]);else if(process.platform==="win32")o("cmd.exe",["/c","start","",e],{shell:!1,detached:!0});else t("xdg-open",[e])}var Do="659cf4c1-615c-45f6-a5f6-4bf15eb476e5",fu="MiniMax CLI",hu;var ho=C(()=>{re();R();S();hu=["openid","profile","coding_plan"]});async function Y(){return P().oauth??null}async function st(e){let t=P();t.oauth=e,await K(t)}async function go(){let e=P();if(!("oauth"in e))return;delete e.oauth,await K(e)}var De=C(()=>{se()});function ut(e){return`Looked for credentials in: ${e??oe()}
105
- ${yu}`}var yu;var Yt=C(()=>{Ie();yu=["Log in: mmx auth login","Pass per-call: --api-key sk-xxxxx","Or set env var: MMX_CONFIG_DIR=/path/to/.mmx"].join(`
106
- `)});function Me(e){return e.replace(/^https?:\/\//,"")}async function yo(e){if(e.apiKey||e.fileApiKey)return;if(await Y())return;let t=process.env.MINIMAX_API_KEY;if(t){if(!G({nonInteractive:e.nonInteractive}))return;if(await po({message:`Found MINIMAX_API_KEY in environment (${J(t)}). Save to config file?`}))await Co(e,t);return}if(!G({nonInteractive:e.nonInteractive}))throw new m("No credentials found.",d.AUTH,ut(e.configPath));let o=await Xt();if(o==="api-key"){let n=await te({message:"Enter your MiniMax API key:"});if(!n)throw new m("API key is required.",d.AUTH);await Co(e,n);return}await Qt(o==="oauth-cn"?"cn":"global")}async function Xt(){let{select:e,isCancel:t}=await Promise.resolve().then(() => (Fe(),Ee)),o=await e({message:"How would you like to authenticate?",options:bu.map((n)=>({value:n.value,label:n.label}))});if(t(o))throw new m("Authentication cancelled.",d.AUTH);return o}async function bo(){let{select:e,isCancel:t}=await Promise.resolve().then(() => (Fe(),Ee)),o=await e({message:"Select an OAuth region:",options:[{value:"global",label:`Global → ${Me(U.global)}`},{value:"cn",label:`China → ${Me(U.cn)}`}]});if(t(o))throw new m("Authentication cancelled.",d.AUTH);return o}async function Qt(e){let t=await fo(e),o=P();delete o.api_key,o.oauth=t,o.region=e,await K(o),process.stderr.write(`Logged in successfully.
172
+ `);let c=l.expired_in,f=l.interval||3000;while(Date.now()<c){await eg(f);let u=await fetch(`${t}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:Gl,user_code:l.user_code,code_verifier:r})});if(!u.ok)throw new v(`Device-code authorization failed (HTTP ${u.status}).`,x.AUTH);let d=await u.json();if(d.status==="pending")continue;if(d.status==="success"&&d.access_token)return{access_token:d.access_token,refresh_token:d.refresh_token??"",expires_at:new Date(d.expired_in??Date.now()).toISOString(),region:e,resource_url:d.resource_url};throw new v(`Device-code authorization failed: ${d.status}`,x.AUTH)}throw new v("Device-code authorization timed out.",x.TIMEOUT)}function eg(e){return new Promise((t)=>setTimeout(t,e))}function tg(e){let{execFile:t,spawn:n}=Ce("child_process");if(process.platform==="darwin")t("open",[e]);else if(process.platform==="win32")n("cmd.exe",["/c","start","",e],{shell:!1,detached:!0});else t("xdg-open",[e])}var Gl="659cf4c1-615c-45f6-a5f6-4bf15eb476e5",Xh="MiniMax CLI",Zh;var Wl=I(()=>{Ae();G();V();Zh=["openid","profile","coding_plan"]});async function ye(){return Q().oauth??null}async function Ci(e){let t=Q();t.oauth=e,await pe(t)}async function Hl(){let e=Q();if(!("oauth"in e))return;delete e.oauth,await pe(e)}var Xe=I(()=>{Be()});function Ri(e){return`Looked for credentials in: ${e??Re()}
173
+ ${ng}`}var ng;var js=I(()=>{Dt();ng=["Log in: mmx auth login","Pass per-call: --api-key sk-xxxxx","Or set env var: MMX_CONFIG_DIR=/path/to/.mmx"].join(`
174
+ `)});function Gt(e){return e.replace(/^https?:\/\//,"")}async function Yl(e){if(e.apiKey||e.fileApiKey)return;if(await ye())return;let t=process.env.MINIMAX_API_KEY;if(t){if(!Y({nonInteractive:e.nonInteractive}))return;if(await Mi({message:`Found MINIMAX_API_KEY in environment (${ge(t)}). Save to config file?`}))await Jl(e,t);return}if(!Y({nonInteractive:e.nonInteractive}))throw new v("No credentials found.",x.AUTH,Ri(e.configPath));let n=await Bs();if(n==="api-key"){let i=await Ie({message:"Enter your MiniMax API key:"});if(!i)throw new v("API key is required.",x.AUTH);await Jl(e,i);return}await Vs(n==="oauth-cn"?"cn":"global")}async function Bs(){let{select:e,isCancel:t}=await Promise.resolve().then(() => (Te(),_e)),n=await e({message:"How would you like to authenticate?",options:ig.map((i)=>({value:i.value,label:i.label}))});if(t(n))throw new v("Authentication cancelled.",x.AUTH);return n}async function zl(){let{select:e,isCancel:t}=await Promise.resolve().then(() => (Te(),_e)),n=await e({message:"Select an OAuth region:",options:[{value:"global",label:`Global → ${Gt(Z.global)}`},{value:"cn",label:`China → ${Gt(Z.cn)}`}]});if(t(n))throw new v("Authentication cancelled.",x.AUTH);return n}async function Vs(e){let t=await Kl(e),n=Q();delete n.api_key,n.oauth=t,n.region=e,await pe(n),process.stderr.write(`Logged in successfully.
107
175
  `),process.stderr.write(`Credentials saved to ~/.mmx/config.json
108
- `)}async function Co(e,t){let o={...P(),api_key:t};await K(o),e.fileApiKey=t,process.stderr.write(`API key saved to ${e.configPath??"~/.mmx/config.json"}
109
- `)}var bu;var Zt=C(()=>{re();se();pe();R();S();ho();De();Yt();bu=[{value:"oauth-global",label:`MiniMax (OAuth login → ${Me(U.global)})`},{value:"oauth-cn",label:`MiniMax (OAuth login → ${Me(U.cn)})`},{value:"api-key",label:`API key (${Me(U.global)} or ${Me(U.cn)})`}]});async function er(e,t="global"){let o=`${Je[t]}/oauth2/token`,n=null;for(let i=0;i<=Eo;i++){if(i>0)await new Promise((u)=>setTimeout(u,Fu*i));let s;try{s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:Eu}),signal:AbortSignal.timeout(xu)})}catch(u){let a=u instanceof Error&&(u.name==="AbortError"||u.name==="TimeoutError"||u.message.includes("timed out"));n=Error(a?"Token refresh timed out — auth server did not respond within 10 s.":`Token refresh failed: ${u instanceof Error?u.message:String(u)}`);continue}if(!s.ok){if(s.status>=400&&s.status<500)throw new m("OAuth session expired and could not be refreshed.",d.AUTH,"Re-authenticate: mmx auth login");n=Error(`Token refresh failed: HTTP ${s.status}`);continue}let r=await s.json();if(r.status!=="success"||!r.access_token)throw new m(`OAuth refresh failed: ${r.status}.`,d.AUTH,"Re-authenticate: mmx auth login");return{access_token:r.access_token,refresh_token:r.refresh_token??e,expires_at:new Date(r.expired_in??Date.now()).toISOString(),resource_url:r.resource_url}}throw new m(`Token refresh failed after ${Eo+1} attempts: ${n?.message}`,d.AUTH,`Check your network connection.
110
- Re-authenticate: mmx auth login`)}async function Fo(e){let t=new Date(e.expires_at).getTime();if(Date.now()<t-wu)return e.access_token;let o=await er(e.refresh_token,e.region??"global"),n={access_token:o.access_token,refresh_token:o.refresh_token,expires_at:o.expires_at,region:e.region,resource_url:o.resource_url??e.resource_url,account:e.account};return await st(n),n.access_token}var Eu="659cf4c1-615c-45f6-a5f6-4bf15eb476e5",Eo=2,Fu=500,xu=1e4,wu=300000;var tr=C(()=>{re();De();R();S()});async function at(e){if(e.apiKey)return{token:e.apiKey,method:"api-key",source:"flag"};let t=await Y();if(t)return{token:await Fo(t),method:"oauth",source:"config.json"};if(e.fileApiKey)return{token:e.fileApiKey,method:"api-key",source:"config.json"};throw new m("No credentials found.",d.AUTH,ut(e.configPath))}var rr=C(()=>{De();tr();R();S();Yt()});function xo(e){if(!e)return"";if(e.includes("/t2a"))return`
176
+ `)}async function Jl(e,t){let n={...Q(),api_key:t};await pe(n),e.fileApiKey=t,process.stderr.write(`API key saved to ${e.configPath??"~/.mmx/config.json"}
177
+ `)}var ig;var Gs=I(()=>{Ae();Be();Ve();G();V();Wl();Xe();js();ig=[{value:"oauth-global",label:`MiniMax (OAuth login → ${Gt(Z.global)})`},{value:"oauth-cn",label:`MiniMax (OAuth login → ${Gt(Z.cn)})`},{value:"api-key",label:`API key (${Gt(Z.global)} or ${Gt(Z.cn)})`}]});async function Ks(e,t="global"){let n=`${si[t]}/oauth2/token`,i=null;for(let r=0;r<=Ql;r++){if(r>0)await new Promise((a)=>setTimeout(a,sg*r));let s;try{s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:rg}),signal:AbortSignal.timeout(og)})}catch(a){let l=a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError"||a.message.includes("timed out"));i=Error(l?"Token refresh timed out — auth server did not respond within 10 s.":`Token refresh failed: ${a instanceof Error?a.message:String(a)}`);continue}if(!s.ok){if(s.status>=400&&s.status<500)throw new v("OAuth session expired and could not be refreshed.",x.AUTH,"Re-authenticate: mmx auth login");i=Error(`Token refresh failed: HTTP ${s.status}`);continue}let o=await s.json();if(o.status!=="success"||!o.access_token)throw new v(`OAuth refresh failed: ${o.status}.`,x.AUTH,"Re-authenticate: mmx auth login");return{access_token:o.access_token,refresh_token:o.refresh_token??e,expires_at:new Date(o.expired_in??Date.now()).toISOString(),resource_url:o.resource_url}}throw new v(`Token refresh failed after ${Ql+1} attempts: ${i?.message}`,x.AUTH,`Check your network connection.
178
+ Re-authenticate: mmx auth login`)}async function Xl(e){let t=new Date(e.expires_at).getTime();if(Date.now()<t-ag)return e.access_token;let n=await Ks(e.refresh_token,e.region??"global"),i={access_token:n.access_token,refresh_token:n.refresh_token,expires_at:n.expires_at,region:e.region,resource_url:n.resource_url??e.resource_url,account:e.account};return await Ci(i),i.access_token}var rg="659cf4c1-615c-45f6-a5f6-4bf15eb476e5",Ql=2,sg=500,og=1e4,ag=300000;var Ws=I(()=>{Ae();Xe();G();V()});async function Kt(e){if(e.apiKey)return{token:e.apiKey,method:"api-key",source:"flag"};let t=await ye();if(t)return{token:await Xl(t),method:"oauth",source:"config.json"};if(e.fileApiKey)return{token:e.fileApiKey,method:"api-key",source:"config.json"};throw new v("No credentials found.",x.AUTH,Ri(e.configPath))}var Li=I(()=>{Xe();Ws();G();V();js()});function Zl(e){if(!e)return"";if(e.includes("/t2a"))return`
111
179
 
112
180
  Speech models require the Plus plan or above.`;if(e.includes("/image_generation"))return`
113
181
 
114
182
  image-01 requires the Plus plan or above.`;if(e.includes("/video_generation")||e.includes("/query/video_generation"))return`
115
183
 
116
- Video models (Hailuo-2.3 / 2.3-Fast) require the Max plan or above.`;return""}function wo(e){return`${e?.includes("minimaxi.com")?"https://platform.minimaxi.com":"https://platform.minimax.io"}/subscribe/token-plan`}function qe(e,t,o){let n=t.base_resp?.status_msg||t.error?.message||`HTTP ${e}`,i=t.base_resp?.status_code||t.error?.code,s=t.error?.type;if(e===401||e===403)return new m(`API key rejected (HTTP ${e}).`,d.AUTH,`Check status: mmx auth status
117
- Re-authenticate: mmx auth login`);if(e===429)return new m(`Rate limit or quota exceeded. ${n}`,d.QUOTA,"Check usage: mmx quota show");if(e===402||s==="insufficient_balance_error")return new m(`Quota or balance exhausted. ${n}`,d.QUOTA,"Check your MiniMax account balance and billing settings.");if(e===408||e===504)return new m(`Request timed out (HTTP ${e}).`,d.TIMEOUT,"Try increasing --timeout or retry later.");let r=e===422&&s==="unprocessable_entity_error"&&(/sensitive content/i.test(n)||/(?:^|\D)1026(?:\D|$)/.test(n));if(i===1002||i===1039||r){let u=t.base_resp?.status_msg||t.error?.message||"content sensitivity";return new m(`Input content flagged by sensitivity filter (${u}).`,d.CONTENT_FILTER)}if(i===1028||i===1030){let u=xo(o);return new m(`Quota exhausted. ${n}`,d.QUOTA,`Check usage: mmx quota show${u}
118
- Upgrade plan: ${wo(o)}`)}if(i===2061){let u=xo(o);return new m(`This model is not available on your current Token Plan. ${n}`,d.QUOTA,`Check usage: mmx quota show${u}
119
- Upgrade plan: ${wo(o)}`)}return new m(`API error: ${n} (HTTP ${e})`,d.GENERAL)}var or=C(()=>{R();S()});import{homedir as vo}from"os";function ku(e){return e.startsWith(vo())?e.replace(vo(),"~"):e}function Ru(e){return e.replace(/^https?:\/\//,"")}function _o(e,t,o){if(e.quiet||$o||!process.stderr.isTTY)return;$o=!0;let n=e.configPath?ku(e.configPath):"~/.mmx/config.json",i=Ru(e.baseUrl),s=e.apiKey?"(flag)":"(file)",r=J(t),u=o?` ${fe}|${Q} ${fe}Model:${Q} ${_u}${o}${Q}`:"";process.stderr.write(`${vu}${$u}MINIMAX${Q} ${fe}${n}${Q} ${fe}|${Q} ${fe}URL:${Q} ${Au}${i}${Q} ${fe}|${Q} ${fe}Key:${Q} ${Su}${r}${Q} ${fe}${s}${Q}${u}
120
- `)}var $o=!1,Q="\x1B[0m",fe="\x1B[2m",vu="\x1B[1m",$u="\x1B[38;2;43;82;255m",_u="\x1B[38;2;147;51;234m",Au="\x1B[38;2;6;184;212m",Su="\x1B[38;2;236;72;153m";var Ao=()=>{};var So=()=>{};var we="1.0.21";var ct=C(()=>{So()});function ko(e){return new DOMException(e,"TimeoutError")}function Bu(e,t,o){if(!e.body)return e;let n=e.body.getReader(),i=!1,s=()=>{if(i)return;i=!0,n.releaseLock()},r=async(l)=>{if(!o.signal.aborted)o.abort(l);try{await n.cancel(l)}finally{s()}},u=new ReadableStream({async pull(l){let p;try{let f=await new Promise((D,h)=>{p=setTimeout(()=>{let E=ko(`Stream received no data for ${t}ms.`);o.abort(E),h(E)},t),n.read().then(D,h)});if(f.done)s(),l.close();else l.enqueue(f.value)}catch(f){await r(f).catch(()=>{}),l.error(f)}finally{if(p)clearTimeout(p)}},cancel(l){return r(l)}}),a=new Response(u,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(a,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),a}async function ve(e,t){let o=typeof FormData<"u"&&t.body instanceof FormData,n={"User-Agent":`mmx-cli/${we}`,...t.headers};if(!o&&!n["Content-Type"])n["Content-Type"]="application/json";if(!t.noAuth){let a=await at(e);if(t.authStyle==="x-api-key")n["x-api-key"]=a.token;else n.Authorization=`Bearer ${a.token}`;if(e.verbose)process.stderr.write(`> ${t.method??"GET"} ${t.url}
121
- `),process.stderr.write(`> Auth: ${a.token.slice(0,8)}...
122
- `);let l=t.body&&typeof t.body==="object"&&"model"in t.body?String(t.body.model):void 0;_o(e,a.token,l)}let i=(t.timeout??e.timeout)*1000,s=t.stream?new AbortController:void 0,r=s?setTimeout(()=>{s.abort(ko(`Request headers were not received within ${i}ms.`))},i):void 0,u;try{u=await fetch(t.url,{method:t.method??"GET",headers:n,body:t.body?o?t.body:JSON.stringify(t.body):void 0,signal:s?.signal??AbortSignal.timeout(i)})}finally{if(r)clearTimeout(r)}if(s)u=Bu(u,i,s);if(e.verbose)process.stderr.write(`< ${u.status} ${u.statusText}
123
- `);if(!u.ok){let a={};try{a=await u.json()}catch{}throw qe(u.status,a,t.url)}return u}async function A(e,t){let o=await ve(e,t),n;try{n=await o.json()}catch{let i=o.headers.get("content-type")||"";throw new m(`API returned non-JSON response (${i||"unknown type"}). Server may be experiencing issues.`,d.GENERAL)}if(n.base_resp?.status_code&&n.base_resp.status_code!==0)throw qe(200,{base_resp:n.base_resp},t.url);return n}var V=C(()=>{R();S();rr();or();Ao();ct()});function lt(e){return`${e}/anthropic/v1/messages`}function Ro(e){return`${e}/v1/t2a_v2`}function Bo(e){return`${e}/v1/get_voice`}function Io(e){return`${e}/v1/image_generation`}function To(e){return`${e}/v1/video_generation`}function Mo(e){return`${e}/v2/video_generation`}function mt(e,t){return`${e}/v1/query/video_generation?task_id=${t}`}function dt(e,t){return`${e}/v2/query/video_generation/${t}`}function pt(e,t){return`${e}/v1/files/retrieve?file_id=${t}`}function Oo(e){return`${e}/v1/coding_plan/search`}function Po(e){return`${e}/v1/coding_plan/vlm`}function $e(e){return`${e}/v1/token_plan/remains`}function Iu(e){return`${e}/account/query_balance`}function nr(e){return e.startsWith("sk-api-")}function ne(e,t){return nr(t)?Iu(e):$e(e)}function No(e){return`${e}/v1/files/upload`}function Lo(e){return`${e}/v1/files/list`}function Uo(e){return`${e}/v1/files/delete`}function Tu(e){return e?"on":"off"}function Go(e,t){if(console.log("Account Balance:"),console.log(` Available: ${e.available_amount}`),console.log(` Cash: ${e.cash_balance}`),console.log(` Voucher: ${e.voucher_balance}`),console.log(` Credit: ${e.credit_balance}`),console.log(` Owed: ${e.owed_amount}`),console.log(` Alert: ${Tu(e.balance_alert_switch)}`),e.balance_alert_threshold)console.log(` Threshold: ${e.balance_alert_threshold}`)}function Wo(e){if(e>=50)return["\x1B[38;2;74;222;128m","\x1B[48;2;22;163;74m"];if(e>=20)return["\x1B[38;2;250;204;21m","\x1B[48;2;202;138;4m"];return["\x1B[38;2;248;113;113m","\x1B[48;2;220;38;38m"]}function Nu(e,t){if(t!=="cn")return e;return Pu[e]??e}function Lu(e,t){if(e<=0)return t;let o=Math.floor(e/3600000),n=Math.floor(e%3600000/60000);return o>0?`${o}h ${n}m`:`${n}m`}function qo(e){return new Date(e).toISOString().slice(0,10)}function Uu(e){return e>=11904&&e<=40959||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65281&&e<=65376||e>=131072&&e<=195103}function Z(e){let t=e.replace(/\x1b\[[0-9;]*m/g,""),o=0;for(let n of t)o+=Uu(n.codePointAt(0))?2:1;return o}function Vu(e){return e===3}function ju(e){return e.current_interval_total_count===0&&e.current_weekly_total_count===0&&e.current_interval_status===3&&e.current_weekly_status===3}function ir(e){return Math.max(0,Math.min(qu,Math.round(e)))}function Hu(e){if(e===void 0||e===null)return 1;return Math.max(0,e)/1000}function Wu(e,t,o,n){let i=Hu(n);if(e!==void 0&&e!==null)return ir(e*i);return o>0?ir(t/o*100*i):0}function Ku(e,t,o=Gu,n=!0){let i=ir(e),s=Math.min(1,i/100),r=Math.round(o*s),u=o-r,a=`${i}%`.padStart(4);if(!t){let D=`[${"█".repeat(r)}${".".repeat(u)}]`;return n?`${D} ${a}`:D}let[l,p]=Wo(i),f=`${p}${" ".repeat(r)}\x1B[0m\x1B[48;2;55;65;81m${" ".repeat(u)}\x1B[0m`;return n?`${f} ${l}\x1B[1m${a}\x1B[0m`:f}function Vo(e,t,o,n,i,s,r,u){if(r){let f=(u??zu).padStart(4);if(i){let h=`\x1B[48;2;22;163;74m${" ".repeat(Ve)}\x1B[0m`;return`\x1B[2m${e}\x1B[0m ${h} \x1B[38;2;74;222;128m\x1B[1m${f}\x1B[0m`}let D=`[${"█".repeat(Ve)}]`;return`${e} ${D} ${f}`}let a=Wu(n,t,o,s),l=Ku(a,i,Ve,o<=0);if(o>0){let p=`${t.toLocaleString()} / ${o.toLocaleString()}`;return i?`\x1B[2m${e}\x1B[0m ${l} ${Wo(a)[0]}${p}\x1B[0m`:`${e} ${l} ${p}`}return`${e} ${l}`}function jo(e,t,o){if(o){let n=`\x1B[48;2;55;65;81m${" ".repeat(Ve)}\x1B[0m`;return`\x1B[2m${e}\x1B[0m ${n} \x1B[38;2;248;113;113m\x1B[1m${t}\x1B[0m`}return`${e} [${".".repeat(Ve)}] ${t}`}function Dt(e,t,o,n,i){return i?`\x1B[2m${t}${o.repeat(e)}${n}\x1B[0m`:`+${"-".repeat(e)}+`}function Ho(e,t,o,n){let i=Math.max(0,t-2-o);return n?`${"\x1B[2m"}│${"\x1B[0m"} ${e}${" ".repeat(i)} ${"\x1B[2m"}│${"\x1B[0m"}`:`| ${e}${" ".repeat(i)} |`}function Ko(e,t){let o=!t.noColor&&process.stdout.isTTY===!0,n=t.region==="cn"?Ou:Mu,i=e.map((g)=>{let y=Nu(g.model_name,t.region),v=ju(g),k=v?jo(n.current,n.notInPlan,o):Vo(n.current,g.current_interval_usage_count,g.current_interval_total_count,g.current_interval_remaining_percent,o),B=v?jo(n.weekly,n.notInPlan,o):Vo(n.weekly,g.current_weekly_usage_count,g.current_weekly_total_count,g.current_weekly_remaining_percent,o,g.weekly_boost_permille,Vu(g.current_weekly_status),t.region==="cn"?Ju:Yu),M=v?`${n.resetsIn} —`:`${n.resetsIn} ${Lu(g.remains_time,n.now)}`;return{displayName:y,current:k,weekly:B,reset:M}}),s=Math.max(6,...i.map((g)=>Z(g.displayName))),r=Math.max(...i.map((g)=>Z(g.current)),18),u=Math.max(...i.map((g)=>Z(g.weekly)),18),a=Math.max(...i.map((g)=>Z(g.reset)),10),l=Math.max(72,s+2+r+2+u+2+a+4),p=e.length>0?`${qo(e[0].weekly_start_time)} — ${qo(e[0].weekly_end_time)}`:"",f=`MINIMAX ${n.dashboard}`,D=`${n.week}: ${p}`,h=Math.max(2,l-2-Z(f)-Z(D)),E=o?`\x1B[1m\x1B[38;2;43;82;255mMINIMAX\x1B[0m \x1B[2m${n.dashboard}\x1B[0m${" ".repeat(h)}\x1B[2m${n.week}:\x1B[0m \x1B[38;2;6;184;212m${p}\x1B[0m`:`${f}${" ".repeat(h)}${D}`,x=Z(f)+h+Z(D);if(console.log(""),console.log(Dt(l,"╭","─","╮",o)),console.log(Ho(E,l,x,o)),e.length===0){console.log(Dt(l,"╰","─","╯",o)),console.log(`
124
- ${n.noData}
125
- `);return}for(let g of i){console.log(Dt(l,"├","─","┤",o));let v=`${o?`\x1B[1m${g.displayName}\x1B[0m`:g.displayName}${" ".repeat(Math.max(1,s-Z(g.displayName)+2))}${g.current}${" ".repeat(Math.max(1,r-Z(g.current)+2))}${g.weekly}${" ".repeat(Math.max(1,u-Z(g.weekly)+2))}`+g.reset;console.log(Ho(v,l,Z(v),o))}console.log(Dt(l,"╰","─","╯",o)),console.log("")}var Mu,Ou,Pu,Gu=16,Ve=10,qu=200,zu="∞",Ju="无限",Yu="unlimited";var zo=C(()=>{Mu={dashboard:"TokenPlan Quota",week:"Week",current:"Left",weekly:"Wk left",resetsIn:"Reset",noData:"No quota data available.",now:"now",notInPlan:"not in plan"},Ou={dashboard:"TokenPlan 配额面板",week:"周期",current:"剩余",weekly:"周剩余",resetsIn:"重置",noData:"暂无配额数据",now:"即将",notInPlan:"不在当前套餐中"},Pu={general:"通用",video:"视频"}});function ue(e,t,o){if(o&&nr(o)){Go(e,t);return}Ko(e.model_remains||[],t)}var ft=C(()=>{zo()});async function Xu(e,t,o){let n=[{Authorization:`Bearer ${t}`},{"x-api-key":t}],i=!1,s=!1;for(let r of n){let u;try{u=await fetch(ne(U[e],t),{headers:{...r,"Content-Type":"application/json"},signal:AbortSignal.timeout(o)})}catch{i=!0;continue}if(u.status===401||u.status===403)continue;if(!u.ok){s=!0;continue}try{if((await u.json()).base_resp?.status_code===0)return"authorized";s=!0}catch{s=!0}}if(s)return"inconclusive";if(i)return"unreachable";return"unauthorized"}async function ht(e){process.stderr.write("Detecting region...");let t=Object.keys(U),o=await Promise.all(t.map(async(s)=>({region:s,result:await Xu(s,e,5000)}))),n=o.find((s)=>s.result==="authorized");if(!n){process.stderr.write(` failed
126
- `);let s=e.startsWith("sk-api-")?"No credentials were changed. Check that the key is valid and belongs to an API secret key.":"No credentials were changed. Check that the key is valid and belongs to a Token Plan.";if(o.every((r)=>r.result==="unauthorized"))throw new m("API key was rejected by all regions.",d.AUTH,s);if(o.some((r)=>r.result==="unreachable"))throw new m("Could not reach the regional API endpoints.",d.NETWORK,"No region was changed. Check the network or proxy, then retry or pass --region global|cn explicitly.");throw new m("Could not determine the API key region.",d.GENERAL,"No region was changed because the API returned an inconclusive response. Retry later or pass --region global|cn explicitly.")}let i=n.region;return process.stderr.write(` ${i}
127
- `),i}async function Jo(e){let t=P();t.region=e,await K(t)}var sr=C(()=>{re();se();R();S()});function Qu(e){if(e instanceof m)return e.exitCode===d.NETWORK||e.exitCode===d.TIMEOUT;if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError")return!0;let t=e.message.toLowerCase(),o="code"in e?String(e.code).toLowerCase():"";return e instanceof TypeError&&t==="fetch failed"||t.includes("failed to fetch")||t.includes("unable to connect")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("connection reset")||t.includes("econnreset")||t.includes("network error")||t.includes("enotfound")||t.includes("getaddrinfo")||t.includes("proxy")||t.includes("socket")||t.includes("etimedout")||o==="connectionrefused"||o==="econnrefused"||o==="econnreset"||o==="enotfound"||o==="etimedout"}async function Zu(e){try{let t=e.apiKey||e.fileApiKey;if(t&&t.startsWith("sk-api-")){let i=ne(e.baseUrl,t),s=await A(e,{url:i});ue(s,e,t);return}let o=$e(e.baseUrl),n=await A(e,{url:o});ue(n,e)}catch{}}async function Qo(e){let{registry:t}=await Promise.resolve().then(() => (gt(),tn));t.printHelp([],process.stderr,e.region),await Zu(e)}async function Yo(e,t){await Qt(t);let o=P(),n={...e,region:t,baseUrl:o.oauth?.resource_url||U[t]};await Qo(n)}async function Xo(e,t,o){if(e.dryRun){console.log("Would validate and save API key.");return}let n=o??await ht(t),i={...e,region:n,baseUrl:U[n],apiKey:t},s=ne(i.baseUrl,t);try{await A(i,{url:s})}catch(u){if(u instanceof m&&u.exitCode===d.AUTH){let l=t.startsWith("sk-api-")?"Check that your key is valid and belongs to an API secret key.":"Check that your key is valid and belongs to a Token Plan.";throw new m("API key validation failed.",d.AUTH,l)}if(!o)throw u;let a=Qu(u)?`the ${n} API endpoint is unreachable`:`the ${n} API endpoint returned an inconclusive response`;process.stderr.write(`Warning: Could not validate the API key because ${a}.
128
- Saving the explicitly selected region "${n}". Requests may fail until validation succeeds.
129
- `)}let r=P();delete r.oauth,r.api_key=t,r.region=n,await K(r),process.stderr.write(`API key saved to ${oe()}
130
- `),await Qo(i)}var Zo;var en=C(()=>{T();R();S();Zt();V();ft();sr();Ie();se();re();Zo=w({name:"auth login",description:"Authenticate via OAuth or API key",usage:"mmx auth login [--api-key <key>] [--recommend] [--region=global|cn]",options:[{flag:"--api-key <key>",description:"Skip the menu and save this API key directly"},{flag:"--recommend",description:"Skip the menu, go straight to OAuth (combine with --region= to skip the region picker)"}],examples:["mmx auth login","mmx auth login --api-key sk-cp-xxxxx","mmx auth login --recommend","mmx auth login --recommend --region=global","mmx auth login --recommend --region=cn"],async run(e,t){let o=process.env.MINIMAX_API_KEY;if(o&&!t.apiKey){let s=J(o);if(G({nonInteractive:e.nonInteractive})){let{confirm:r,isCancel:u}=await Promise.resolve().then(() => (Fe(),Ee)),a=await r({message:`MINIMAX_API_KEY is set (${s}). Configure persistent credentials anyway?`,initialValue:!1});if(u(a)||!a)process.stdout.write(`Login skipped. Using environment variable.
184
+ Video models (Hailuo-2.3 / 2.3-Fast) require the Max plan or above.`;return""}function ec(e){return`${e?.includes("minimaxi.com")?"https://platform.minimaxi.com":"https://platform.minimax.io"}/subscribe/token-plan`}function wn(e,t,n){let i=t.base_resp?.status_msg||t.error?.message||`HTTP ${e}`,r=t.base_resp?.status_code||t.error?.code,s=t.error?.type;if(e===401||e===403)return new v(`API key rejected (HTTP ${e}).`,x.AUTH,`Check status: mmx auth status
185
+ Re-authenticate: mmx auth login`);if(e===429)return new v(`Rate limit or quota exceeded. ${i}`,x.QUOTA,"Check usage: mmx quota show");if(e===402||s==="insufficient_balance_error")return new v(`Quota or balance exhausted. ${i}`,x.QUOTA,"Check your MiniMax account balance and billing settings.");if(e===408||e===504)return new v(`Request timed out (HTTP ${e}).`,x.TIMEOUT,"Try increasing --timeout or retry later.");let o=e===422&&s==="unprocessable_entity_error"&&(/sensitive content/i.test(i)||/(?:^|\D)1026(?:\D|$)/.test(i));if(r===1002||r===1039||o){let a=t.base_resp?.status_msg||t.error?.message||"content sensitivity";return new v(`Input content flagged by sensitivity filter (${a}).`,x.CONTENT_FILTER)}if(r===1028||r===1030){let a=Zl(n);return new v(`Quota exhausted. ${i}`,x.QUOTA,`Check usage: mmx quota show${a}
186
+ Upgrade plan: ${ec(n)}`)}if(r===2061){let a=Zl(n);return new v(`This model is not available on your current Token Plan. ${i}`,x.QUOTA,`Check usage: mmx quota show${a}
187
+ Upgrade plan: ${ec(n)}`)}return new v(`API error: ${i} (HTTP ${e})`,x.GENERAL)}var Hs=I(()=>{G();V()});import{homedir as tc}from"os";function pg(e){return e.startsWith(tc())?e.replace(tc(),"~"):e}function mg(e){return e.replace(/^https?:\/\//,"")}function ic(e,t,n){if(e.quiet||nc||!process.stderr.isTTY)return;nc=!0;let i=e.configPath?pg(e.configPath):"~/.mmx/config.json",r=mg(e.baseUrl),s=e.apiKey?"(flag)":"(file)",o=ge(t),a=n?` ${Ze}|${xe} ${Ze}Model:${xe} ${ug}${n}${xe}`:"";process.stderr.write(`${lg}${cg}MINIMAX${xe} ${Ze}${i}${xe} ${Ze}|${xe} ${Ze}URL:${xe} ${fg}${r}${xe} ${Ze}|${xe} ${Ze}Key:${xe} ${dg}${o}${xe} ${Ze}${s}${xe}${a}
188
+ `)}var nc=!1,xe="\x1B[0m",Ze="\x1B[2m",lg="\x1B[1m",cg="\x1B[38;2;43;82;255m",ug="\x1B[38;2;147;51;234m",fg="\x1B[38;2;6;184;212m",dg="\x1B[38;2;236;72;153m";var rc=()=>{};var sc=()=>{};var St="1.0.24";var Pi=I(()=>{sc()});function oc(e){return new DOMException(e,"TimeoutError")}function hg(e,t,n){if(!e.body)return e;let i=e.body.getReader(),r=!1,s=()=>{if(r)return;r=!0,i.releaseLock()},o=async(c)=>{if(!n.signal.aborted)n.abort(c);try{await i.cancel(c)}finally{s()}},a=new ReadableStream({async pull(c){let f;try{let u=await new Promise((d,g)=>{f=setTimeout(()=>{let h=oc(`Stream received no data for ${t}ms.`);n.abort(h),g(h)},t),i.read().then(d,g)});if(u.done)s(),c.close();else c.enqueue(u.value)}catch(u){await o(u).catch(()=>{}),c.error(u)}finally{if(f)clearTimeout(f)}},cancel(c){return o(c)}}),l=new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function $t(e,t){let n=typeof FormData<"u"&&t.body instanceof FormData,i={"User-Agent":`mmx-cli/${St}`,...t.headers};if(!n&&!i["Content-Type"])i["Content-Type"]="application/json";if(!t.noAuth){let l=await Kt(e);if(t.authStyle==="x-api-key")i["x-api-key"]=l.token;else i.Authorization=`Bearer ${l.token}`;if(e.verbose)process.stderr.write(`> ${t.method??"GET"} ${t.url}
189
+ `),process.stderr.write(`> Auth: ${l.token.slice(0,8)}...
190
+ `);let c=t.body&&typeof t.body==="object"&&"model"in t.body?String(t.body.model):void 0;ic(e,l.token,c)}let r=(t.timeout??e.timeout)*1000,s=t.stream?new AbortController:void 0,o=s?setTimeout(()=>{s.abort(oc(`Request headers were not received within ${r}ms.`))},r):void 0,a;try{a=await fetch(t.url,{method:t.method??"GET",headers:i,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:s?.signal??AbortSignal.timeout(r)})}finally{if(o)clearTimeout(o)}if(s)a=hg(a,r,s);if(e.verbose)process.stderr.write(`< ${a.status} ${a.statusText}
191
+ `);if(!a.ok){let l={};try{l=await a.json()}catch{}throw wn(a.status,l,t.url)}return a}async function j(e,t){let n=await $t(e,t),i;try{i=await n.json()}catch{let r=n.headers.get("content-type")||"";throw new v(`API returned non-JSON response (${r||"unknown type"}). Server may be experiencing issues.`,x.GENERAL)}if(i.base_resp?.status_code&&i.base_resp.status_code!==0)throw wn(200,{base_resp:i.base_resp},t.url);return i}var oe=I(()=>{G();V();Li();Hs();rc();Pi()});function qi(e){return`${e}/anthropic/v1/messages`}function ac(e){return`${e}/v1/t2a_v2`}function lc(e){return`${e}/v1/get_voice`}function cc(e){return`${e}/v1/image_generation`}function uc(e){return`${e}/v1/video_generation`}function fc(e){return`${e}/v2/video_generation`}function Fi(e,t){return`${e}/v1/query/video_generation?task_id=${t}`}function Di(e,t){return`${e}/v2/query/video_generation/${t}`}function Ui(e,t){return`${e}/v1/files/retrieve?file_id=${t}`}function dc(e){return`${e}/v1/coding_plan/search`}function pc(e){return`${e}/v1/coding_plan/vlm`}function vn(e){return`${e}/v1/token_plan/remains`}function gg(e){return`${e}/account/query_balance`}function Js(e){return e.startsWith("sk-api-")}function Ys(e,t){if(t.method==="api-key"&&Js(t.token))return{url:gg(e),kind:"account-balance"};return{url:vn(e),kind:"quota"}}function et(e,t){return Ys(e,{token:t,method:"api-key"}).url}function mc(e){return`${e}/v1/files/upload`}function hc(e){return`${e}/v1/files/list`}function gc(e){return`${e}/v1/files/delete`}function yg(e){return e?"on":"off"}function yc(e,t){if(console.log("Account Balance:"),console.log(` Available: ${e.available_amount}`),console.log(` Cash: ${e.cash_balance}`),console.log(` Voucher: ${e.voucher_balance}`),console.log(` Credit: ${e.credit_balance}`),console.log(` Owed: ${e.owed_amount}`),console.log(` Alert: ${yg(e.balance_alert_switch)}`),e.balance_alert_threshold)console.log(` Threshold: ${e.balance_alert_threshold}`)}function ji(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0||e<0||e>t)return;let i=e;if(n!==void 0&&n!==null&&Number.isFinite(n)){let r=e/t*100,s=(t-e)/t*100,o=Math.abs(r-n),a=Math.abs(s-n);if(Math.min(o,a)>1)return;if(a<o)i=t-e}return{used:t-i,remaining:i,total:t}}function Ec(e){if(e>=50)return[Sc,kc];if(e>=20)return[vg,xg];return[$c,Sg]}function Eg(e,t){if(t!=="cn")return e;return Ag[e]??e}function _g(e,t){if(e<=0)return t;let n=Math.floor(e/3600000),i=Math.floor(e%3600000/60000);return n>0?`${n}h ${i}m`:`${i}m`}function Tg(e){if(e<=0)return"";if(e%604800000===0)return`${e/604800000}w`;if(e%86400000===0)return`${e/86400000}d`;if(e>=3600000)return`${Math.round(e/3600000)}h`;return`${Math.max(1,Math.round(e/60000))}m`}function bc(e){return new Date(e).toISOString().slice(0,10)}function Ig(e){return e>=11904&&e<=40959||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65281&&e<=65376||e>=131072&&e<=195103}function Se(e){let t=e.replace(/\x1b\[[0-9;]*m/g,""),n=0;for(let i of t)n+=Ig(i.codePointAt(0))?2:1;return n}function Ng(e){return e===3}function Cg(e){return e.current_interval_total_count===0&&e.current_weekly_total_count===0&&e.current_interval_status===3&&e.current_weekly_status===3}function zs(e){return Math.max(0,Math.min(Mg,Math.round(e)))}function Rg(e){if(e===void 0||e===null)return 1;return Math.max(0,e)/1000}function Lg(e,t,n,i){let r=Rg(i);if(e!==void 0&&e!==null)return zs(e*r);return n>0?zs(t/n*100*r):0}function Pg(e,t,n=Og,i=!0){let r=zs(e),s=Math.min(1,r/100),o=Math.round(n*s),a=n-o,l=`${r}%`.padStart(4);if(!t){let d=`[${"█".repeat(o)}${".".repeat(a)}]`;return i?`${d} ${l}`:d}let[c,f]=Ec(r),u=`${f}${" ".repeat(o)}${X}${Ac}${" ".repeat(a)}${X}`;return i?`${u} ${c}${Sn}${l}${X}`:u}function wc(e,t,n,i,r,s,o,a){if(o){let d=(a??qg).padStart(4);if(r){let h=`${kc}${" ".repeat(xn)}${X}`;return`${Oe}${e}${X} ${h} ${Sc}${Sn}${d}${X}`}let g=`[${"█".repeat(xn)}]`;return`${e} ${g} ${d}`}let l=Lg(i,t,n,s),c=ji(t,n,i),f=Pg(l,r,xn,c===void 0);if(c){let u=`${c.remaining.toLocaleString()} / ${c.total.toLocaleString()}`;return r?`${Oe}${e}${X} ${f} ${Ec(l)[0]}${u}${X}`:`${e} ${f} ${u}`}return`${e} ${f}`}function vc(e,t,n){if(n){let i=`${Ac}${" ".repeat(xn)}${X}`;return`${Oe}${e}${X} ${i} ${$c}${Sn}${t}${X}`}return`${e} [${".".repeat(xn)}] ${t}`}function Bi(e,t,n,i,r,s,o){if(s===void 0||o===void 0)return r?`${Oe}${t}${n.repeat(e)}${i}${X}`:`+${"-".repeat(e)}+`;return r?`${Oe}${t}${n.repeat(s-1)}${o}${n.repeat(e-s)}${i}${X}`:`+${"-".repeat(s-1)}+${"-".repeat(e-s)}+`}function xc(e,t,n,i){let r=Math.max(0,t-2-n);return i?`${Oe}│${X} ${e}${" ".repeat(r)} ${Oe}│${X}`:`| ${e}${" ".repeat(r)} |`}function _c(e,t){let n=!t.noColor&&process.stdout.isTTY===!0,i=t.region==="cn"?kg:$g,r=e.map((w)=>{let S=Eg(w.model_name,t.region),_=Cg(w),E=_?vc(i.current,i.notInPlan,n):wc(i.current,w.current_interval_usage_count,w.current_interval_total_count,w.current_interval_remaining_percent,n),A=_?vc(i.weekly,i.notInPlan,n):wc(i.weekly,w.current_weekly_usage_count,w.current_weekly_total_count,w.current_weekly_remaining_percent,n,w.weekly_boost_permille,Ng(w.current_weekly_status),t.region==="cn"?Fg:Dg),k=_?"":Tg(w.end_time-w.start_time),T=k?`${k} ${i.resetsIn}`:i.resetsIn,C=_?"—":_g(w.remains_time,i.now),P=n?`${Oe}${T}${X} ${C}`:`${T} ${C}`;return{displayName:S,current:E,weekly:A,reset:P}}),s=Math.max(6,...r.map((w)=>Se(w.displayName))),o=Math.max(...r.map((w)=>Se(w.current)),18),a=Math.max(...r.map((w)=>Se(w.weekly)),18),l=Math.max(...r.map((w)=>Se(w.reset)),10),c=s+2+o+2+a,f=c+3+l+2;if(f<72)c+=72-f,f=72;let u=c+3,d=e.length>0?`${bc(e[0].weekly_start_time)} — ${bc(e[0].weekly_end_time)}`:"",g=`MINIMAX ${i.dashboard}`,h=`${i.week}: ${d}`,p=Math.max(2,f-2-Se(g)-Se(h)),m=n?`${Sn}${bg}MINIMAX${X} ${Oe}${i.dashboard}${X}${" ".repeat(p)}${Oe}${i.week}:${X} ${wg}${d}${X}`:`${g}${" ".repeat(p)}${h}`,b=Se(g)+p+Se(h);if(console.log(""),console.log(Bi(f,"╭","─","╮",n)),console.log(xc(m,f,b,n)),e.length===0){console.log(Bi(f,"╰","─","╯",n)),console.log(`
192
+ ${i.noData}
193
+ `);return}r.forEach((w,S)=>{console.log(Bi(f,"├","─","┤",n,u,S===0?"┬":"┼"));let E=`${n?`${Sn}${w.displayName}${X}`:w.displayName}${" ".repeat(Math.max(1,s-Se(w.displayName)+2))}${w.current}${" ".repeat(Math.max(1,o-Se(w.current)+2))}`+w.weekly,A=n?`${Oe}│${X}`:"|",k=`${E}${" ".repeat(Math.max(0,c-Se(E)))} ${A} ${w.reset}`;console.log(xc(k,f,Se(k),n))}),console.log(Bi(f,"╰","─","╯",n,u,"┴")),console.log("")}var X="\x1B[0m",Sn="\x1B[1m",Oe="\x1B[2m",bg="\x1B[38;2;43;82;255m",wg="\x1B[38;2;6;184;212m",Sc="\x1B[38;2;74;222;128m",vg="\x1B[38;2;250;204;21m",$c="\x1B[38;2;248;113;113m",kc="\x1B[48;2;22;163;74m",xg="\x1B[48;2;202;138;4m",Sg="\x1B[48;2;220;38;38m",Ac="\x1B[48;2;55;65;81m",$g,kg,Ag,Og=16,xn=10,Mg=200,qg="∞",Fg="无限",Dg="unlimited";var Tc=I(()=>{$g={dashboard:"TokenPlan Quota",week:"Week",current:"Left",weekly:"Wk left",resetsIn:"Reset",noData:"No quota data available.",now:"now",notInPlan:"not in plan"},kg={dashboard:"TokenPlan 配额面板",week:"周期",current:"剩余",weekly:"周剩余",resetsIn:"重置",noData:"暂无配额数据",now:"即将",notInPlan:"不在当前套餐中"},Ag={general:"通用",video:"视频"}});function Ge(e,t,n){if(n&&Js(n)){yc(e,t);return}_c(e.model_remains||[],t)}var Vi=I(()=>{Tc()});async function Ug(e,t,n){let i=[{Authorization:`Bearer ${t}`},{"x-api-key":t}],r=!1,s=!1;for(let o of i){let a;try{a=await fetch(et(Z[e],t),{headers:{...o,"Content-Type":"application/json"},signal:AbortSignal.timeout(n)})}catch{r=!0;continue}if(a.status===401||a.status===403)continue;if(!a.ok){s=!0;continue}try{if((await a.json()).base_resp?.status_code===0)return"authorized";s=!0}catch{s=!0}}if(s)return"inconclusive";if(r)return"unreachable";return"unauthorized"}async function Gi(e){process.stderr.write("Detecting region...");let t=Object.keys(Z),n=await Promise.all(t.map(async(s)=>({region:s,result:await Ug(s,e,5000)}))),i=n.find((s)=>s.result==="authorized");if(!i){process.stderr.write(` failed
194
+ `);let s=e.startsWith("sk-api-")?"No credentials were changed. Check that the key is valid and belongs to an API secret key.":"No credentials were changed. Check that the key is valid and belongs to a Token Plan.";if(n.every((o)=>o.result==="unauthorized"))throw new v("API key was rejected by all regions.",x.AUTH,s);if(n.some((o)=>o.result==="unreachable"))throw new v("Could not reach the regional API endpoints.",x.NETWORK,"No region was changed. Check the network or proxy, then retry or pass --region global|cn explicitly.");throw new v("Could not determine the API key region.",x.GENERAL,"No region was changed because the API returned an inconclusive response. Retry later or pass --region global|cn explicitly.")}let r=i.region;return process.stderr.write(` ${r}
195
+ `),r}async function Ic(e){let t=Q();t.region=e,await pe(t)}var Qs=I(()=>{Ae();Be();G();V()});function jg(e){if(e instanceof v)return e.exitCode===x.NETWORK||e.exitCode===x.TIMEOUT;if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError")return!0;let t=e.message.toLowerCase(),n="code"in e?String(e.code).toLowerCase():"";return e instanceof TypeError&&t==="fetch failed"||t.includes("failed to fetch")||t.includes("unable to connect")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("connection reset")||t.includes("econnreset")||t.includes("network error")||t.includes("enotfound")||t.includes("getaddrinfo")||t.includes("proxy")||t.includes("socket")||t.includes("etimedout")||n==="connectionrefused"||n==="econnrefused"||n==="econnreset"||n==="enotfound"||n==="etimedout"}async function Bg(e){try{let t=e.apiKey||e.fileApiKey;if(t&&t.startsWith("sk-api-")){let r=et(e.baseUrl,t),s=await j(e,{url:r});Ge(s,e,t);return}let n=vn(e.baseUrl),i=await j(e,{url:n});Ge(i,e)}catch{}}async function Nc(e){let{registry:t}=await Promise.resolve().then(() => (Ki(),Lc));t.printHelp([],process.stderr,e.region),await Bg(e)}async function Oc(e,t){await Vs(t);let n=Q(),i={...e,region:t,baseUrl:n.oauth?.resource_url||Z[t]};await Nc(i)}async function Mc(e,t,n){if(e.dryRun){console.log("Would validate and save API key.");return}let i=n??await Gi(t),r={...e,region:i,baseUrl:Z[i],apiKey:t},s=et(r.baseUrl,t);try{await j(r,{url:s})}catch(a){if(a instanceof v&&a.exitCode===x.AUTH){let c=t.startsWith("sk-api-")?"Check that your key is valid and belongs to an API secret key.":"Check that your key is valid and belongs to a Token Plan.";throw new v("API key validation failed.",x.AUTH,c)}if(!n)throw a;let l=jg(a)?`the ${i} API endpoint is unreachable`:`the ${i} API endpoint returned an inconclusive response`;process.stderr.write(`Warning: Could not validate the API key because ${l}.
196
+ Saving the explicitly selected region "${i}". Requests may fail until validation succeeds.
197
+ `)}let o=Q();delete o.oauth,o.api_key=t,o.region=i,await pe(o),process.stderr.write(`API key saved to ${Re()}
198
+ `),await Nc(r)}var Cc;var Rc=I(()=>{J();G();V();Gs();oe();Vi();Qs();Dt();Be();Ae();Cc=R({name:"auth login",description:"Authenticate via OAuth or API key",usage:"mmx auth login [--api-key <key>] [--recommend] [--region=global|cn]",options:[{flag:"--api-key <key>",description:"Skip the menu and save this API key directly"},{flag:"--recommend",description:"Skip the menu, go straight to OAuth (combine with --region= to skip the region picker)"}],examples:["mmx auth login","mmx auth login --api-key sk-cp-xxxxx","mmx auth login --recommend","mmx auth login --recommend --region=global","mmx auth login --recommend --region=cn"],async run(e,t){let n=process.env.MINIMAX_API_KEY;if(n&&!t.apiKey){let s=ge(n);if(Y({nonInteractive:e.nonInteractive})){let{confirm:o,isCancel:a}=await Promise.resolve().then(() => (Te(),_e)),l=await o({message:`MINIMAX_API_KEY is set (${s}). Configure persistent credentials anyway?`,initialValue:!1});if(a(l)||!l)process.stdout.write(`Login skipped. Using environment variable.
131
199
  `),process.exit(0)}else process.stderr.write(`Warning: MINIMAX_API_KEY is already set in environment.
132
- `)}if(t.apiKey){await Xo(e,t.apiKey,t.region);return}if(e.dryRun){console.log("Would prompt for auth method (oauth-global, oauth-cn, api-key).");return}if(!G({nonInteractive:e.nonInteractive}))throw new m("--api-key is required in non-interactive mode.",d.USAGE,"mmx auth login --api-key sk-xxxxx");if(t.recommend){let s=t.region||await bo();await Yo(e,s);return}let n=await Xt();if(n==="api-key"){let{text:s,isCancel:r}=await Promise.resolve().then(() => (Fe(),Ee)),u=await s({message:"Paste your MiniMax API key:",validate:(a)=>a&&a.length>0?void 0:"API key cannot be empty."});if(r(u))throw new m("Authentication cancelled.",d.AUTH);await Xo(e,u,t.region);return}let i=t.region||(n==="oauth-cn"?"cn":"global");await Yo(e,i)}})});var rn;var on=C(()=>{T();rr();De();N();V();ft();rn=w({name:"auth status",description:"Show current authentication state and quota snapshot",usage:"mmx auth status",examples:["mmx auth status","mmx auth status --output json"],async run(e,t){try{let o=await at(e),n=_(e.output);if(n!=="text"){let s={method:o.method,source:o.source};if(o.method==="oauth"){let r=await Y();if(r){if(s.token_expires=r.expires_at,r.account)s.account=r.account}}else{s.key=J(o.token);let r=ne(e.baseUrl,o.token),u=await A(e,{url:r});s.usage=u}console.log(F(s,n));return}console.log("Authentication Status:"),console.log(` Method: ${o.method}`),console.log(` Source: ${o.source}`);let i=o.token;if(console.log(` Key: ${J(i)}`),o.method==="oauth"){let s=await Y();if(s){if(s.account)console.log(` Account: ${s.account}`);let r=new Date(s.expires_at),u=Math.round((r.getTime()-Date.now())/60000);console.log(` Expires in: ${u} minutes`)}}else{let s=ne(e.baseUrl,i);try{let r=await A(e,{url:s});ue(r,e,i)}catch(r){console.log(` Quota fetch failed: ${r.message}`)}return}process.stderr.write(`Fetching quota snapshot...
133
- `);try{let s=$e(e.baseUrl),r=await A(e,{url:s,method:"GET"});ue(r,e)}catch(s){console.log(` Quota fetch failed: ${s.message}`)}}catch{let o=_(e.output);console.log(F({authenticated:!1,message:"Not authenticated.",hint:`Run: mmx auth login
134
- Or set $MINIMAX_API_KEY`},o))}}})});var nn;var sn=C(()=>{T();R();S();De();tr();N();nn=w({name:"auth refresh",description:"Manually refresh OAuth token",usage:"mmx auth refresh",examples:["mmx auth refresh"],async run(e,t){let o=await Y();if(!o)throw new m("Not applicable: not authenticated via OAuth.",d.USAGE,"Run mmx auth login first.");if(e.dryRun){console.log("Would refresh OAuth token.");return}let n=await er(o.refresh_token,o.region??"global"),i={access_token:n.access_token,refresh_token:n.refresh_token,expires_at:n.expires_at,region:o.region,resource_url:n.resource_url??o.resource_url,account:o.account};await st(i);let s=_(e.output);if(e.quiet){console.log(i.expires_at);return}console.log(F({status:"Token refreshed",expires:i.expires_at},s))}})});var un;var an=C(()=>{T();De();se();un=w({name:"auth logout",description:"Revoke tokens and clear stored credentials",usage:"mmx auth logout [--yes] [--dry-run]",options:[{flag:"--yes",description:"Skip confirmation prompt"}],examples:["mmx auth logout","mmx auth logout --dry-run","mmx auth logout --yes"],async run(e,t){let o=await Y(),i=!!P().api_key;if(e.dryRun){if(o)console.log("Would clear oauth from ~/.mmx/config.json");if(i)console.log("Would clear api_key from ~/.mmx/config.json");if(!o&&!i)console.log("No credentials to clear.");console.log("No changes made.");return}if(!o&&!i){process.stderr.write(`No credentials to clear.
135
- `);return}if(o)await go(),process.stderr.write(`Cleared oauth from ~/.mmx/config.json
136
- `);if(i){let s=P();delete s.api_key,await K(s),process.stderr.write(`Cleared api_key from ~/.mmx/config.json
137
- `)}}})});async function*Oe(e){let t=e.body?.getReader();if(!t)return;let o=new TextDecoder,n="",i={},s=(r)=>{let u=r.endsWith("\r")?r.slice(0,-1):r;if(u===""){let f=i.data!==void 0?{data:i.data,event:i.event,id:i.id}:void 0;return i={},f}if(u.startsWith(":"))return;let a=u.indexOf(":");if(a===-1)return;let l=u.slice(0,a),p=u.slice(a+1).trimStart();switch(l){case"data":i.data=i.data!==void 0?`${i.data}
138
- ${p}`:p;break;case"event":i.event=p;break;case"id":i.id=p;break}return};try{while(!0){let{done:r,value:u}=await t.read();if(r)break;n+=o.decode(u,{stream:!0});let a=n.split(`
139
- `);n=a.pop()||"";for(let l of a){let p=s(l);if(p)yield p}}if(n+=o.decode(),n.length>0){let r=s(n);if(r)yield r}if(i.data!==void 0)yield{data:i.data,event:i.event,id:i.id}}finally{t.releaseLock()}}import{readFileSync as ur}from"fs";function ln(e,t,o){let n=(1-Math.abs(2*o-1))*t,i=n*(1-Math.abs(e/60%2-1)),s=o-n/2,r=0,u=0,a=0;if(e<60)r=n,u=i;else if(e<120)r=i,u=n;else if(e<180)u=n,a=i;else if(e<240)u=i,a=n;else if(e<300)r=i,a=n;else r=n,a=i;return[Math.round((r+s)*255),Math.round((u+s)*255),Math.round((a+s)*255)]}class mn{frame=0;startTime=0;timer=null;out;noColor;constructor(e,t){this.out=e,this.noColor=t}start(){this.frame=0,this.startTime=Date.now(),this.tick(),this.timer=setInterval(()=>this.tick(),80)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.out.write("\r\x1B[0K")}tick(){let e=cn[this.frame%cn.length],t=Math.floor((Date.now()-this.startTime)/1000),o=t>=60?`Thinking (${Math.floor(t/60)}m ${t%60}s)`:`Thinking (${t}s)`;if(this.frame++,this.noColor)this.out.write(`\r${e} ${o}\x1B[0K`);else{let[n,i,s]=ln(this.frame*17%360,0.85,0.55),[r,u,a]=ln((this.frame*17+40)%360,0.85,0.55);this.out.write(`\r\x1B[38;2;${n};${i};${s}m${e}\x1B[0m \x1B[38;2;${r};${u};${a}m${o}\x1B[0m\x1B[0K`)}}}function ea(e){let t=[],o;if(e.system)o=e.system;if(e.messagesFile){let n=e.messagesFile,i=n==="-"?ur("/dev/stdin","utf-8"):ur(n,"utf-8"),s=JSON.parse(i);for(let r of s)if(r.role==="system")o=typeof r.content==="string"?r.content:"";else t.push(r)}if(!e.message&&e.prompt)e.message=Array.isArray(e.prompt)?e.prompt:[e.prompt];if(e.message){let n=new Set(["system","user","assistant"]),i=e.message;for(let s of i){let r=s.indexOf(":"),u=r!==-1?s.slice(0,r):"";if(n.has(u)){let a=s.slice(r+1);if(u==="system")o=a;else t.push({role:u,content:a})}else t.push({role:"user",content:s})}}return{system:o,messages:t}}function ta(e){return e.filter((t)=>t.type==="text").map((t)=>t.text).join("")}var cn,dn;var pn=C(()=>{T();V();N();R();S();pe();cn=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];dn=w({name:"text chat",description:"Send a chat completion (MiniMax Messages API)",apiDocs:"/docs/api-reference/text-post",usage:"mmx text chat --message <text> [flags]",options:[{flag:"--model <model>",description:"Model ID (default: MiniMax-M3)"},{flag:"--message <text>",description:"Message text (repeatable, prefix role: to set role)",required:!0,type:"array"},{flag:"--messages-file <path>",description:"JSON file with messages array (use - for stdin)"},{flag:"--system <text>",description:"System prompt"},{flag:"--max-tokens <n>",description:"Maximum tokens to generate (default: 4096)",type:"number"},{flag:"--temperature <n>",description:"Sampling temperature (0.0, 1.0]",type:"number"},{flag:"--top-p <n>",description:"Nucleus sampling threshold",type:"number"},{flag:"--stream",description:"Stream response tokens (default: on in TTY)"},{flag:"--tool <json-or-path>",description:"Tool definition as JSON or file path (repeatable)",type:"array"}],examples:['mmx text chat --message "What is MiniMax?"','mmx text chat --model MiniMax-M3 --system "You are a coding assistant." --message "Write fizzbuzz in Python"','mmx text chat --message "Hello" --message "assistant:Hi!" --message "How are you?"',"cat conversation.json | mmx text chat --messages-file - --stream",'mmx text chat --message "Hello" --output json'],async run(e,t){let{system:o,messages:n}=ea(t),i=n;if(i.length===0)if(G({nonInteractive:e.nonInteractive})){let p=await te({message:"Enter your message:"});if(!p)process.stderr.write(`Chat cancelled.
140
- `),process.exit(1);i=[{role:"user",content:p}]}else xe("message","mmx text chat --message <text>");let s=t.model||e.defaultTextModel||"MiniMax-M3",r=_(e.output),u=t.stream===!0||t.stream===void 0&&r!=="json"&&process.stdout.isTTY,a={model:s,messages:i,max_tokens:t.maxTokens??4096,stream:u};if(o)a.system=o;if(t.temperature!==void 0)a.temperature=t.temperature;if(t.topP!==void 0)a.top_p=t.topP;if(t.tool){let p=t.tool.map((f)=>{try{return JSON.parse(f)}catch{try{let D=ur(f,"utf-8");return JSON.parse(D)}catch{throw new m(`Invalid tool definition: "${f}" is neither valid JSON nor a readable file.`,d.USAGE)}}});a.tools=p}if(e.dryRun){console.log(F({request:a},r));return}let l=lt(e.baseUrl);if(u){let p=await ve(e,{url:l,method:"POST",body:a,stream:!0,authStyle:"x-api-key"}),f=p.headers.get("content-type")||"";if(!f.includes("text/event-stream")&&!f.includes("stream"))throw new m(`Expected SSE stream but got content-type "${f}". Server may be experiencing issues.`,d.GENERAL);let D="",h=!1,E=e.noColor?"":"\x1B[2m",x=e.noColor?"":"\x1B[0m",g=r==="json",v=process.stdout.isTTY&&!g?process.stderr:process.stderr,k=g?void 0:process.stdout,B=new mn(v,e.noColor);for await(let M of Oe(p)){if(M.data==="[DONE]")break;try{let I=JSON.parse(M.data);if(I.type==="content_block_start"){if(I.content_block.type==="thinking")h=!0,B.start();else if(I.content_block.type==="text"&&h)B.stop(),h=!1,v.write(`${x}
200
+ `)}if(t.apiKey){await Mc(e,t.apiKey,t.region);return}if(e.dryRun){console.log("Would prompt for auth method (oauth-global, oauth-cn, api-key).");return}if(!Y({nonInteractive:e.nonInteractive}))throw new v("--api-key is required in non-interactive mode.",x.USAGE,"mmx auth login --api-key sk-xxxxx");if(t.recommend){let s=t.region||await zl();await Oc(e,s);return}let i=await Bs();if(i==="api-key"){let{text:s,isCancel:o}=await Promise.resolve().then(() => (Te(),_e)),a=await s({message:"Paste your MiniMax API key:",validate:(l)=>l&&l.length>0?void 0:"API key cannot be empty."});if(o(a))throw new v("Authentication cancelled.",x.AUTH);await Mc(e,a,t.region);return}let r=t.region||(i==="oauth-cn"?"cn":"global");await Oc(e,r)}})});var Pc;var qc=I(()=>{J();Li();Xe();z();oe();Vi();Pc=R({name:"auth status",description:"Show current authentication state and quota snapshot",usage:"mmx auth status",examples:["mmx auth status","mmx auth status --output json"],async run(e,t){try{let n=await Kt(e),i=F(e.output);if(i!=="text"){let s={method:n.method,source:n.source};if(n.method==="oauth"){let o=await ye();if(o){if(s.token_expires=o.expires_at,o.account)s.account=o.account}}else{s.key=ge(n.token);let o=et(e.baseUrl,n.token),a=await j(e,{url:o});s.usage=a}console.log(N(s,i));return}console.log("Authentication Status:"),console.log(` Method: ${n.method}`),console.log(` Source: ${n.source}`);let r=n.token;if(console.log(` Key: ${ge(r)}`),n.method==="oauth"){let s=await ye();if(s){if(s.account)console.log(` Account: ${s.account}`);let o=new Date(s.expires_at),a=Math.round((o.getTime()-Date.now())/60000);console.log(` Expires in: ${a} minutes`)}}else{let s=et(e.baseUrl,r);try{let o=await j(e,{url:s});Ge(o,e,r)}catch(o){console.log(` Quota fetch failed: ${o.message}`)}return}process.stderr.write(`Fetching quota snapshot...
201
+ `);try{let s=vn(e.baseUrl),o=await j(e,{url:s,method:"GET"});Ge(o,e)}catch(s){console.log(` Quota fetch failed: ${s.message}`)}}catch{let n=F(e.output);console.log(N({authenticated:!1,message:"Not authenticated.",hint:`Run: mmx auth login
202
+ Or set $MINIMAX_API_KEY`},n))}}})});var Fc;var Dc=I(()=>{J();G();V();Xe();Ws();z();Fc=R({name:"auth refresh",description:"Manually refresh OAuth token",usage:"mmx auth refresh",examples:["mmx auth refresh"],async run(e,t){let n=await ye();if(!n)throw new v("Not applicable: not authenticated via OAuth.",x.USAGE,"Run mmx auth login first.");if(e.dryRun){console.log("Would refresh OAuth token.");return}let i=await Ks(n.refresh_token,n.region??"global"),r={access_token:i.access_token,refresh_token:i.refresh_token,expires_at:i.expires_at,region:n.region,resource_url:i.resource_url??n.resource_url,account:n.account};await Ci(r);let s=F(e.output);if(e.quiet){console.log(r.expires_at);return}console.log(N({status:"Token refreshed",expires:r.expires_at},s))}})});var Uc;var jc=I(()=>{J();Xe();Be();Uc=R({name:"auth logout",description:"Revoke tokens and clear stored credentials",usage:"mmx auth logout [--yes] [--dry-run]",options:[{flag:"--yes",description:"Skip confirmation prompt"}],examples:["mmx auth logout","mmx auth logout --dry-run","mmx auth logout --yes"],async run(e,t){let n=await ye(),r=!!Q().api_key;if(e.dryRun){if(n)console.log("Would clear oauth from ~/.mmx/config.json");if(r)console.log("Would clear api_key from ~/.mmx/config.json");if(!n&&!r)console.log("No credentials to clear.");console.log("No changes made.");return}if(!n&&!r){process.stderr.write(`No credentials to clear.
203
+ `);return}if(n)await Hl(),process.stderr.write(`Cleared oauth from ~/.mmx/config.json
204
+ `);if(r){let s=Q();delete s.api_key,await pe(s),process.stderr.write(`Cleared api_key from ~/.mmx/config.json
205
+ `)}}})});async function*tt(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,i="",r={},s=(o)=>{let a=o.endsWith("\r")?o.slice(0,-1):o;if(a===""){let u=r.data!==void 0?{data:r.data,event:r.event,id:r.id}:void 0;return r={},u}if(a.startsWith(":"))return;let l=a.indexOf(":");if(l===-1)return;let c=a.slice(0,l),f=a.slice(l+1).trimStart();switch(c){case"data":r.data=r.data!==void 0?`${r.data}
206
+ ${f}`:f;break;case"event":r.event=f;break;case"id":r.id=f;break}return};try{while(!0){let{done:o,value:a}=await t.read();if(o)break;i+=n.decode(a,{stream:!0});let l=i.split(`
207
+ `);i=l.pop()||"";for(let c of l){let f=s(c);if(f)yield f}}if(i+=n.decode(),i.length>0){let o=s(i);if(o)yield o}if(r.data!==void 0)yield{data:r.data,event:r.event,id:r.id}}finally{t.releaseLock()}}import{readFileSync as Vg}from"fs";function Gg(e){return e==="-"?0:e}function Wi(e){return Vg(Gg(e),"utf-8")}var Xs=()=>{};import{readFileSync as Kg}from"fs";function Vc(e,t,n){let i=(1-Math.abs(2*n-1))*t,r=i*(1-Math.abs(e/60%2-1)),s=n-i/2,o=0,a=0,l=0;if(e<60)o=i,a=r;else if(e<120)o=r,a=i;else if(e<180)a=i,l=r;else if(e<240)a=r,l=i;else if(e<300)o=r,l=i;else o=i,l=r;return[Math.round((o+s)*255),Math.round((a+s)*255),Math.round((l+s)*255)]}class Gc{frame=0;startTime=0;timer=null;out;noColor;constructor(e,t){this.out=e,this.noColor=t}start(){this.frame=0,this.startTime=Date.now(),this.tick(),this.timer=setInterval(()=>this.tick(),80)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.out.write("\r\x1B[0K")}tick(){let e=Bc[this.frame%Bc.length],t=Math.floor((Date.now()-this.startTime)/1000),n=t>=60?`Thinking (${Math.floor(t/60)}m ${t%60}s)`:`Thinking (${t}s)`;if(this.frame++,this.noColor)this.out.write(`\r${e} ${n}\x1B[0K`);else{let[i,r,s]=Vc(this.frame*17%360,0.85,0.55),[o,a,l]=Vc((this.frame*17+40)%360,0.85,0.55);this.out.write(`\r\x1B[38;2;${i};${r};${s}m${e}\x1B[0m \x1B[38;2;${o};${a};${l}m${n}\x1B[0m\x1B[0K`)}}}function Wg(e){let t=[],n;if(e.system)n=e.system;if(e.messagesFile){let i=e.messagesFile,r=Wi(i),s=JSON.parse(r);for(let o of s)if(o.role==="system")n=typeof o.content==="string"?o.content:"";else t.push(o)}if(!e.message&&e.prompt)e.message=Array.isArray(e.prompt)?e.prompt:[e.prompt];if(e.message){let i=new Set(["system","user","assistant"]),r=e.message;for(let s of r){let o=s.indexOf(":"),a=o!==-1?s.slice(0,o):"";if(i.has(a)){let l=s.slice(o+1);if(a==="system")n=l;else t.push({role:a,content:l})}else t.push({role:"user",content:s})}}return{system:n,messages:t}}function Hg(e){return e.filter((t)=>t.type==="text").map((t)=>t.text).join("")}var Bc,Kc;var Wc=I(()=>{J();oe();z();G();V();Xs();Ve();Bc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];Kc=R({name:"text chat",description:"Send a chat completion (MiniMax Messages API)",apiDocs:"/docs/api-reference/text-post",usage:"mmx text chat --message <text> [flags]",options:[{flag:"--model <model>",description:"Model ID (default: MiniMax-M3)"},{flag:"--message <text>",description:"Message text (repeatable, prefix role: to set role)",required:!0,type:"array"},{flag:"--messages-file <path>",description:"JSON file with messages array (use - for stdin)"},{flag:"--system <text>",description:"System prompt"},{flag:"--max-tokens <n>",description:"Maximum tokens to generate (default: 4096)",type:"number"},{flag:"--temperature <n>",description:"Sampling temperature (0.0, 1.0]",type:"number"},{flag:"--top-p <n>",description:"Nucleus sampling threshold",type:"number"},{flag:"--stream",description:"Stream response tokens (default: on in TTY)"},{flag:"--tool <json-or-path>",description:"Tool definition as JSON or file path (repeatable)",type:"array"}],examples:['mmx text chat --message "What is MiniMax?"','mmx text chat --model MiniMax-M3 --system "You are a coding assistant." --message "Write fizzbuzz in Python"','mmx text chat --message "Hello" --message "assistant:Hi!" --message "How are you?"',"cat conversation.json | mmx text chat --messages-file - --stream",'mmx text chat --message "Hello" --output json'],async run(e,t){let{system:n,messages:i}=Wg(t),r=i;if(r.length===0)if(Y({nonInteractive:e.nonInteractive})){let f=await Ie({message:"Enter your message:"});if(!f)process.stderr.write(`Chat cancelled.
208
+ `),process.exit(1);r=[{role:"user",content:f}]}else xt("message","mmx text chat --message <text>");let s=t.model||e.defaultTextModel||"MiniMax-M3",o=F(e.output),a=t.stream===!0||t.stream===void 0&&o!=="json"&&process.stdout.isTTY,l={model:s,messages:r,max_tokens:t.maxTokens??4096,stream:a};if(n)l.system=n;if(t.temperature!==void 0)l.temperature=t.temperature;if(t.topP!==void 0)l.top_p=t.topP;if(t.tool){let f=t.tool.map((u)=>{try{return JSON.parse(u)}catch{try{let d=Kg(u,"utf-8");return JSON.parse(d)}catch{throw new v(`Invalid tool definition: "${u}" is neither valid JSON nor a readable file.`,x.USAGE)}}});l.tools=f}if(e.dryRun){console.log(N({request:l},o));return}let c=qi(e.baseUrl);if(a){let f=await $t(e,{url:c,method:"POST",body:l,stream:!0,authStyle:"x-api-key"}),u=f.headers.get("content-type")||"";if(!u.includes("text/event-stream")&&!u.includes("stream"))throw new v(`Expected SSE stream but got content-type "${u}". Server may be experiencing issues.`,x.GENERAL);let d="",g=!1,h=e.noColor?"":"\x1B[2m",p=e.noColor?"":"\x1B[0m",m=o==="json",w=process.stdout.isTTY&&!m?process.stderr:process.stderr,S=m?void 0:process.stdout,_=new Gc(w,e.noColor);for await(let E of tt(f)){if(E.data==="[DONE]")break;try{let A=JSON.parse(E.data);if(A.type==="content_block_start"){if(A.content_block.type==="thinking")g=!0,_.start();else if(A.content_block.type==="text"&&g)_.stop(),g=!1,w.write(`${p}
141
209
  Response:
142
- `)}else if(I.type==="content_block_delta"){if(I.delta.type==="text_delta")D+=I.delta.text,k?.write(I.delta.text)}}catch(I){process.stderr.write(`
143
- ${E}[warning] Failed to parse stream chunk: ${I instanceof Error?I.message:String(I)}${x}
144
- `)}}if(h)B.stop();if(r==="json")console.log(F({content:D},r));else k?.write(`
145
- `)}else{let p=await A(e,{url:l,method:"POST",body:a,authStyle:"x-api-key"}),f=ta(p.content);if(e.quiet||r==="text")console.log(f);else console.log(F(p,r))}}})});import{writeFileSync as ra}from"node:fs";function Dn(e){return`\x1B[${e}A`}function oa(e){return`\x1B[${e}B`}function ar(e){return`\x1B[${e}G`}function Ct(){return"\x1B[2K"}function na(){return"\x1B[0J"}function ua(){process.stdout.write(`
210
+ `)}else if(A.type==="content_block_delta"){if(A.delta.type==="text_delta")d+=A.delta.text,S?.write(A.delta.text)}}catch(A){process.stderr.write(`
211
+ ${h}[warning] Failed to parse stream chunk: ${A instanceof Error?A.message:String(A)}${p}
212
+ `)}}if(g)_.stop();if(o==="json")console.log(N({content:d},o));else S?.write(`
213
+ `)}else{let f=await j(e,{url:c,method:"POST",body:l,authStyle:"x-api-key"}),u=Hg(f.content);if(e.quiet||o==="text")console.log(u);else console.log(N(f,o))}}})});import{writeFileSync as Jg}from"node:fs";function Hc(e){return`\x1B[${e}A`}function Yg(e){return`\x1B[${e}B`}function Zs(e){return`\x1B[${e}G`}function Hi(){return"\x1B[2K"}function zg(){return"\x1B[0J"}function Zg(){process.stdout.write(`
146
214
  Available commands:
147
- `);for(let[e,t]of Object.entries(lr))process.stdout.write(` ${e.padEnd(fn+2)} ${t}
215
+ `);for(let[e,t]of Object.entries(to))process.stdout.write(` ${e.padEnd(Jc+2)} ${t}
148
216
  `);process.stdout.write(`
149
- `)}class hn{buffer="";cursor=0;history=[];historyIdx=-1;out;promptLen;dim;reset;width;lastTotal=0;resolve=null;constructor(e,t,o,n){this.out=e,this.promptLen=t.length,this.dim=o,this.reset=n,this.width=e.columns||80}readLine(){return new Promise((e)=>{this.buffer="",this.cursor=0,this.lastTotal=0,this.resolve=e,this.render()})}feed(e){let t=e.toString(),o=0;while(o<t.length){let n=t[o];if(n==="\x1B"&&o+1<t.length&&t[o+1]==="["){let i=t.slice(o,o+3);if(i==="\x1B[A"){this.historyUp(),o+=3;continue}if(i==="\x1B[B"){this.historyDown(),o+=3;continue}if(i==="\x1B[C"){if(this.cursor<this.buffer.length)this.cursor++;this.render(),o+=3;continue}if(i==="\x1B[D"){if(this.cursor>0)this.cursor--;this.render(),o+=3;continue}if(i==="\x1B[H"){this.cursor=0,this.render(),o+=3;continue}if(i==="\x1B[F"){this.cursor=this.buffer.length,this.render(),o+=3;continue}if(o+3<t.length&&t.slice(o,o+4)==="\x1B[3~"){if(this.cursor<this.buffer.length)this.buffer=this.buffer.slice(0,this.cursor)+this.buffer.slice(this.cursor+1);this.render(),o+=4;continue}o+=1;continue}if(n==="\r"||n===`
150
- `){let i=this.buffer;if(i.trim())this.history.push(i),this.historyIdx=-1;let s=this.lastTotal>0?this.lastTotal-1:0;this.out.write(oa(s)+`
151
- `),this.lastTotal=0;let r=this.resolve;if(this.resolve=null,r)r(i);o++;continue}if(n===""||n==="\b"){if(this.cursor>0)this.buffer=this.buffer.slice(0,this.cursor-1)+this.buffer.slice(this.cursor),this.cursor--;this.render(),o++;continue}if(n==="\x01"){this.cursor=0,this.render(),o++;continue}if(n==="\x05"){this.cursor=this.buffer.length,this.render(),o++;continue}if(n==="\x15"){this.buffer="",this.cursor=0,this.render(),o++;continue}if(n==="\x17"){let i=this.buffer.slice(0,this.cursor),s=this.buffer.slice(this.cursor),r=i.replace(/\S+\s*$/,"");this.cursor=r.length,this.buffer=r+s,this.render(),o++;continue}if(n==="\t"){if(this.buffer.startsWith("/")){let i=cr.filter((s)=>s.startsWith(this.buffer));if(i.length===1)this.buffer=i[0],this.cursor=this.buffer.length,this.render()}o++;continue}if(n.charCodeAt(0)>=32){this.buffer=this.buffer.slice(0,this.cursor)+n+this.buffer.slice(this.cursor),this.cursor++,this.render(),o++;continue}o++}}historyUp(){if(this.history.length===0)return;if(this.historyIdx===-1)this.historyIdx=this.history.length-1;else if(this.historyIdx>0)this.historyIdx--;this.buffer=this.history[this.historyIdx],this.cursor=this.buffer.length,this.render()}historyDown(){if(this.historyIdx===-1)return;if(this.historyIdx<this.history.length-1)this.historyIdx++,this.buffer=this.history[this.historyIdx];else this.historyIdx=-1,this.buffer="";this.cursor=this.buffer.length,this.render()}border(){return this.dim+"─".repeat(this.width)+this.reset}render(){let e=this.buffer.startsWith("/")?cr.filter((r)=>r.startsWith(this.buffer)):[],t=e.length===1&&e[0]===this.buffer,o=e.length>0&&!t,n=o?e.length:0,i=3+n,s="";if(this.lastTotal>0)s+=Dn(1);if(s+=ar(1)+Ct()+this.border()+`
152
- `,s+=Ct()+"> "+this.buffer+`
153
- `,s+=ar(1)+Ct()+this.border()+`
154
- `,o)for(let r of e)s+=Ct()+` ${this.dim}${r.padEnd(fn+2)} ${lr[r]}${this.reset}
155
- `;if(i<this.lastTotal)s+=na();s+=Dn(n+2),s+=ar(this.promptLen+this.cursor+1),this.out.write(s),this.lastTotal=i}}var ia="\x1B[?25l",sa="\x1B[?25h",lr,cr,fn,gn;var Cn=C(()=>{T();V();R();S();lr={"/exit":"Exit the conversation","/clear":"Clear conversation history (keeps system prompt)","/system":"Show or set the system prompt. Usage: /system [new prompt]","/model":"Show or set the model. Usage: /model [model-id]","/save":"Save conversation to a JSON file. Usage: /save <path>","/help":"Show available slash commands","/history":"Show conversation messages with content preview"},cr=Object.keys(lr),fn=Math.max(...cr.map((e)=>e.length));gn=w({name:"text repl",description:"Start an interactive multi-turn chat session",usage:"mmx text repl [flags]",options:[{flag:"--model <model>",description:"Model ID (default: MiniMax-M3)"},{flag:"--system <text>",description:"System prompt"},{flag:"--max-tokens <n>",description:"Maximum tokens per response (default: 4096)",type:"number"},{flag:"--temperature <n>",description:"Sampling temperature (0.0, 1.0]",type:"number"},{flag:"--top-p <n>",description:"Nucleus sampling threshold",type:"number"}],examples:["mmx text repl",'mmx text repl --model MiniMax-M3 --system "You are a coding assistant."',"mmx text repl --temperature 0.7 --max-tokens 8192"],async run(e,t){if(!G({nonInteractive:e.nonInteractive}))throw new m("The repl command requires an interactive terminal.",d.USAGE,"mmx text repl");if(!process.stdin.isTTY)throw new m("The repl command requires a TTY.",d.USAGE);let o=e.noColor?"":"\x1B[2m",n=e.noColor?"":"\x1B[0m",i={messages:[],system:t.system,model:t.model||e.defaultTextModel||"MiniMax-M3",maxTokens:t.maxTokens??4096,temperature:t.temperature!==void 0?t.temperature:void 0,topP:t.topP!==void 0?t.topP:void 0},s=e.noColor?"":"\x1B[1m";if(process.stdout.write(`
156
- ${s}MiniMax Chat REPL${n}
157
- `),process.stdout.write(`${o}Model: ${i.model}${n}
158
- `),i.system)process.stdout.write(`${o}System: ${i.system.slice(0,80)}${i.system.length>80?"...":""}${n}
159
- `);process.stdout.write(`${o}Type / to see commands, /exit to quit.${n}
160
- `);let{stdin:r,stdout:u}=process;if(typeof r.setRawMode==="function")r.setRawMode(!0);r.resume(),r.setEncoding("utf8");let a=!1,l=0;async function p(){if(i.messages.length===0){u.write(`${o}No messages to send. Type something first.${n}
161
- `);return}let x={model:i.model,messages:i.messages,max_tokens:i.maxTokens,stream:!0};if(i.system)x.system=i.system;if(i.temperature!==void 0)x.temperature=i.temperature;if(i.topP!==void 0)x.top_p=i.topP;a=!0;let g=lt(e.baseUrl);try{let y=await ve(e,{url:g,method:"POST",body:x,stream:!0,authStyle:"x-api-key"}),v=y.headers.get("content-type")||"";if(!v.includes("text/event-stream")&&!v.includes("stream"))throw new m(`Expected SSE stream but got content-type "${v}".`,d.GENERAL);let k="",B=!1;for await(let M of Oe(y)){if(M.data==="[DONE]")break;try{let I=JSON.parse(M.data);if(I.type==="content_block_start"){if(I.content_block.type==="thinking")B=!0,u.write(`${o}Thinking:
162
- `);else if(I.content_block.type==="text"&&B)u.write(`${n}
217
+ `)}class Yc{buffer="";cursor=0;history=[];historyIdx=-1;out;promptLen;dim;reset;width;lastTotal=0;resolve=null;constructor(e,t,n,i){this.out=e,this.promptLen=t.length,this.dim=n,this.reset=i,this.width=e.columns||80}readLine(){return new Promise((e)=>{this.buffer="",this.cursor=0,this.lastTotal=0,this.resolve=e,this.render()})}feed(e){let t=e.toString(),n=0;while(n<t.length){let i=t[n];if(i==="\x1B"&&n+1<t.length&&t[n+1]==="["){let r=t.slice(n,n+3);if(r==="\x1B[A"){this.historyUp(),n+=3;continue}if(r==="\x1B[B"){this.historyDown(),n+=3;continue}if(r==="\x1B[C"){if(this.cursor<this.buffer.length)this.cursor++;this.render(),n+=3;continue}if(r==="\x1B[D"){if(this.cursor>0)this.cursor--;this.render(),n+=3;continue}if(r==="\x1B[H"){this.cursor=0,this.render(),n+=3;continue}if(r==="\x1B[F"){this.cursor=this.buffer.length,this.render(),n+=3;continue}if(n+3<t.length&&t.slice(n,n+4)==="\x1B[3~"){if(this.cursor<this.buffer.length)this.buffer=this.buffer.slice(0,this.cursor)+this.buffer.slice(this.cursor+1);this.render(),n+=4;continue}n+=1;continue}if(i==="\r"||i===`
218
+ `){let r=this.buffer;if(r.trim())this.history.push(r),this.historyIdx=-1;let s=this.lastTotal>0?this.lastTotal-1:0;this.out.write(Yg(s)+`
219
+ `),this.lastTotal=0;let o=this.resolve;if(this.resolve=null,o)o(r);n++;continue}if(i===""||i==="\b"){if(this.cursor>0)this.buffer=this.buffer.slice(0,this.cursor-1)+this.buffer.slice(this.cursor),this.cursor--;this.render(),n++;continue}if(i==="\x01"){this.cursor=0,this.render(),n++;continue}if(i==="\x05"){this.cursor=this.buffer.length,this.render(),n++;continue}if(i==="\x15"){this.buffer="",this.cursor=0,this.render(),n++;continue}if(i==="\x17"){let r=this.buffer.slice(0,this.cursor),s=this.buffer.slice(this.cursor),o=r.replace(/\S+\s*$/,"");this.cursor=o.length,this.buffer=o+s,this.render(),n++;continue}if(i==="\t"){if(this.buffer.startsWith("/")){let r=eo.filter((s)=>s.startsWith(this.buffer));if(r.length===1)this.buffer=r[0],this.cursor=this.buffer.length,this.render()}n++;continue}if(i.charCodeAt(0)>=32){this.buffer=this.buffer.slice(0,this.cursor)+i+this.buffer.slice(this.cursor),this.cursor++,this.render(),n++;continue}n++}}historyUp(){if(this.history.length===0)return;if(this.historyIdx===-1)this.historyIdx=this.history.length-1;else if(this.historyIdx>0)this.historyIdx--;this.buffer=this.history[this.historyIdx],this.cursor=this.buffer.length,this.render()}historyDown(){if(this.historyIdx===-1)return;if(this.historyIdx<this.history.length-1)this.historyIdx++,this.buffer=this.history[this.historyIdx];else this.historyIdx=-1,this.buffer="";this.cursor=this.buffer.length,this.render()}border(){return this.dim+"─".repeat(this.width)+this.reset}render(){let e=this.buffer.startsWith("/")?eo.filter((o)=>o.startsWith(this.buffer)):[],t=e.length===1&&e[0]===this.buffer,n=e.length>0&&!t,i=n?e.length:0,r=3+i,s="";if(this.lastTotal>0)s+=Hc(1);if(s+=Zs(1)+Hi()+this.border()+`
220
+ `,s+=Hi()+"> "+this.buffer+`
221
+ `,s+=Zs(1)+Hi()+this.border()+`
222
+ `,n)for(let o of e)s+=Hi()+` ${this.dim}${o.padEnd(Jc+2)} ${to[o]}${this.reset}
223
+ `;if(r<this.lastTotal)s+=zg();s+=Hc(i+2),s+=Zs(this.promptLen+this.cursor+1),this.out.write(s),this.lastTotal=r}}var Qg="\x1B[?25l",Xg="\x1B[?25h",to,eo,Jc,zc;var Qc=I(()=>{J();oe();G();V();to={"/exit":"Exit the conversation","/clear":"Clear conversation history (keeps system prompt)","/system":"Show or set the system prompt. Usage: /system [new prompt]","/model":"Show or set the model. Usage: /model [model-id]","/save":"Save conversation to a JSON file. Usage: /save <path>","/help":"Show available slash commands","/history":"Show conversation messages with content preview"},eo=Object.keys(to),Jc=Math.max(...eo.map((e)=>e.length));zc=R({name:"text repl",description:"Start an interactive multi-turn chat session",usage:"mmx text repl [flags]",options:[{flag:"--model <model>",description:"Model ID (default: MiniMax-M3)"},{flag:"--system <text>",description:"System prompt"},{flag:"--max-tokens <n>",description:"Maximum tokens per response (default: 4096)",type:"number"},{flag:"--temperature <n>",description:"Sampling temperature (0.0, 1.0]",type:"number"},{flag:"--top-p <n>",description:"Nucleus sampling threshold",type:"number"}],examples:["mmx text repl",'mmx text repl --model MiniMax-M3 --system "You are a coding assistant."',"mmx text repl --temperature 0.7 --max-tokens 8192"],async run(e,t){if(!Y({nonInteractive:e.nonInteractive}))throw new v("The repl command requires an interactive terminal.",x.USAGE,"mmx text repl");if(!process.stdin.isTTY)throw new v("The repl command requires a TTY.",x.USAGE);let n=e.noColor?"":"\x1B[2m",i=e.noColor?"":"\x1B[0m",r={messages:[],system:t.system,model:t.model||e.defaultTextModel||"MiniMax-M3",maxTokens:t.maxTokens??4096,temperature:t.temperature!==void 0?t.temperature:void 0,topP:t.topP!==void 0?t.topP:void 0},s=e.noColor?"":"\x1B[1m";if(process.stdout.write(`
224
+ ${s}MiniMax Chat REPL${i}
225
+ `),process.stdout.write(`${n}Model: ${r.model}${i}
226
+ `),r.system)process.stdout.write(`${n}System: ${r.system.slice(0,80)}${r.system.length>80?"...":""}${i}
227
+ `);process.stdout.write(`${n}Type / to see commands, /exit to quit.${i}
228
+ `);let{stdin:o,stdout:a}=process;if(typeof o.setRawMode==="function")o.setRawMode(!0);o.resume(),o.setEncoding("utf8");let l=!1,c=0;async function f(){if(r.messages.length===0){a.write(`${n}No messages to send. Type something first.${i}
229
+ `);return}let p={model:r.model,messages:r.messages,max_tokens:r.maxTokens,stream:!0};if(r.system)p.system=r.system;if(r.temperature!==void 0)p.temperature=r.temperature;if(r.topP!==void 0)p.top_p=r.topP;l=!0;let m=qi(e.baseUrl);try{let b=await $t(e,{url:m,method:"POST",body:p,stream:!0,authStyle:"x-api-key"}),w=b.headers.get("content-type")||"";if(!w.includes("text/event-stream")&&!w.includes("stream"))throw new v(`Expected SSE stream but got content-type "${w}".`,x.GENERAL);let S="",_=!1;for await(let E of tt(b)){if(E.data==="[DONE]")break;try{let A=JSON.parse(E.data);if(A.type==="content_block_start"){if(A.content_block.type==="thinking")_=!0,a.write(`${n}Thinking:
230
+ `);else if(A.content_block.type==="text"&&_)a.write(`${i}
163
231
  Response:
164
- `),B=!1}else if(I.type==="content_block_delta"){if(I.delta.type==="text_delta")k+=I.delta.text,u.write(I.delta.text);else if(I.delta.type==="thinking_delta")u.write(I.delta.thinking)}}catch{}}if(B)u.write(n);if(k)i.messages.push({role:"assistant",content:k}),u.write(`
165
- `);else u.write(`${o}[empty response]${n}
166
- `)}catch(y){u.write(`${o}[error] ${y instanceof Error?y.message:String(y)}${n}
167
- `)}finally{a=!1,l=0}}function f(x){let g=x.trim().split(/\s+/),y=g[0],v=g.slice(1).join(" ");switch(y){case"/exit":return u.write(`${o}Goodbye!${n}
168
- `),"exit";case"/help":return ua(),"ok";case"/clear":return i.messages=[],u.write(`${o}Conversation cleared.${n}
169
- `),"ok";case"/system":{if(v)i.system=v,u.write(`${o}System prompt set.${n}
170
- `);else if(i.system)u.write(`${o}System prompt:${n}
171
- ${i.system}
172
- `);else u.write(`${o}No system prompt set.${n}
173
- `);return"ok"}case"/model":{if(v)i.model=v,u.write(`${o}Model set to: ${i.model}${n}
174
- `);else u.write(`${o}Current model: ${i.model}${n}
175
- `);return"ok"}case"/save":{if(!v)return u.write(`${o}Usage: /save <file-path>${n}
176
- `),"ok";try{let k=[];if(i.system)k.push({role:"system",content:i.system});for(let B of i.messages)k.push({role:B.role,content:typeof B.content==="string"?B.content:JSON.stringify(B.content)});ra(v,JSON.stringify(k,null,2),"utf-8"),u.write(`${o}Conversation saved to ${v} (${k.length} messages)${n}
177
- `)}catch(k){u.write(`${o}[error] Failed to save: ${k instanceof Error?k.message:String(k)}${n}
178
- `)}return"ok"}case"/history":{if(i.messages.length===0)return u.write(`${o}No messages in conversation.${n}
179
- `),"ok";if(i.system)u.write(`${o}[system] ${i.system.slice(0,100)}${i.system.length>100?"...":""}${n}
180
- `);let k=1;for(let B of i.messages){let M=B.role==="user"?"user":"assistant",I=typeof B.content==="string"?B.content:"[structured content]",Pe=(I.length>120?I.slice(0,120)+"...":I).replace(/\n/g,"↵"),Ke=` ${String(k).padStart(2)} ${M.padEnd(11)}`;u.write(`${o}${Ke}${n}${Pe}
181
- `),k++}return u.write(`${o}── ${k-1} messages ──${n}
182
- `),"ok"}default:if(y.startsWith("/"))return u.write(`${o}Unknown command: ${y}. Type /help for available commands.${n}
183
- `),"ok";return"ok"}}let D=()=>{if(a){u.write(`
184
- ${o}[interrupted]${n}
185
- `),l=0,a=!1;return}if(l++,l>=2){if(u.write(`
186
- ${o}Goodbye!${n}
187
- `),E=!1,typeof r.setRawMode==="function")r.setRawMode(!1);r.pause(),process.removeListener("SIGINT",D),process.exit(0)}else u.write(`
188
- ${o}Press Ctrl+C again or type /exit to quit.${n}
189
- `)};process.on("SIGINT",D);let h=new hn(u,"> ",o,n),E=!0;r.on("data",(x)=>{h.feed(x)}),u.write(ia);try{while(E){let x=await h.readLine();if(!E)break;let g=x.trim();if(!g)continue;if(g.startsWith("/")){if(f(g)==="exit"){E=!1;break}continue}i.messages.push({role:"user",content:g}),await p()}}finally{if(u.write(sa),typeof r.setRawMode==="function")r.setRawMode(!1);r.pause(),process.removeListener("SIGINT",D),r.removeAllListeners("data"),u.write(`
190
- `)}}})});import{writeFileSync as aa}from"fs";function yn(e,t,o,n){if(t){let i=e.data.audio;if(!i)throw new m("API response missing audio data (audio field is empty).",d.GENERAL);if(!/^[0-9a-fA-F]*$/.test(i))throw new m("API returned invalid audio data (not valid hex).",d.GENERAL);if(i.length%2!==0)throw new m("API returned truncated audio data (odd-length hex string).",d.GENERAL);try{aa(t,Buffer.from(i,"hex"))}catch(s){if(s.code==="ENOSPC")throw new m("Disk full — cannot write audio file.",d.GENERAL,"Free up disk space and try again.");throw s}if(n)console.log(t);else console.log(F({saved:t,duration_ms:e.extra_info?.audio_length,size_bytes:e.extra_info?.audio_size,sample_rate:e.extra_info?.audio_sample_rate},o))}else{let i=e.data.audio_url??e.data.audio;if(n)console.log(i);else console.log(F({url:i,duration_ms:e.extra_info?.audio_length,size_bytes:e.extra_info?.audio_size},o))}}var bn=C(()=>{N();R();S()});import{readFileSync as ca}from"fs";function En(e){return ca(e==="-"?"/dev/stdin":e,"utf-8")}var Fn=()=>{};function dr(e){return e.join(", ")}function xn(e,t){if(!t.includes(e))throw new m(`Invalid audio format "${e}". Supported: ${dr(t)}`,d.USAGE)}function wn(e,t){return la[e]??t}function vn(e,t){if(t&&e==="wav")throw new m("wav format is not supported in streaming mode.",d.USAGE,"Use mp3, pcm, flac, pcmu_raw, pcmu_wav, or opus for streaming.")}var mr,la;var $n=C(()=>{R();S();mr=["mp3","pcm","flac","wav","pcmu_raw","pcmu_wav","opus"];la={opus:24000,pcmu_raw:8000,pcmu_wav:8000}});function _n(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new m("API returned invalid audio data (not valid hex).",d.GENERAL);if(e.length%2!==0)throw new m("API returned truncated audio data (odd-length hex string).",d.GENERAL);return Uint8Array.from(Buffer.from(e,"hex"))}function An(e,t){let o=t.base_resp?.status_code;if(o!==void 0&&o!==0||t.error)throw qe(e.status,t,e.url||void 0)}function Sn(){return new m("API stream ended without audio data.",d.GENERAL)}async function*ma(e){let t=e.headers.get("content-type")||"";if(!t.toLowerCase().includes("text/event-stream")){let n;try{n=await e.json()}catch{throw new m(`Expected SSE audio stream but got content-type "${t||"unknown"}".`,d.GENERAL)}An(e,n);let i=n.data?.audio;if(!i)throw Sn();yield _n(i);return}let o=!1;for await(let n of Oe(e)){if(!n.data||n.data==="[DONE]")break;let i;try{i=JSON.parse(n.data)}catch(r){throw new m(`Failed to parse audio stream chunk: ${r instanceof Error?r.message:String(r)}`,d.GENERAL)}An(e,i);let s=i.data?.audio;if(s)o=!0,yield _n(s);if(i.data?.status===2)break}if(!o)throw Sn()}async function kn(e){process.stdout.on("error",(t)=>{if(t.code==="EPIPE")process.exit(0);throw t});for await(let t of ma(e))if(!process.stdout.write(t))await new Promise((o)=>process.stdout.once("drain",o))}var Rn=C(()=>{or();R();S()});import{writeFileSync as da}from"fs";var pr;var Bn=C(()=>{T();R();S();V();N();bn();Fn();$n();Rn();pr=w({name:"speech synthesize",description:"Synchronous TTS, up to 10k chars (speech-2.8-hd / 2.6 / 02)",apiDocs:"/docs/api-reference/speech-t2a-http",usage:"mmx speech synthesize --text <text> [--out <path>] [flags]",options:[{flag:"--model <model>",description:"Model ID (default: speech-2.8-hd)"},{flag:"--text <text>",description:"Text to synthesize"},{flag:"--text-file <path>",description:"Read text from file (use - for stdin)"},{flag:"--voice <id>",description:"Voice ID (default: English_expressive_narrator)"},{flag:"--speed <n>",description:"Speech speed multiplier",type:"number"},{flag:"--volume <n>",description:"Volume level",type:"number"},{flag:"--pitch <n>",description:"Pitch adjustment",type:"number"},{flag:"--emotion <emotion>",description:"Emotion: happy, sad, angry, fearful, disgusted, surprised, calm, fluent, whisper (passed through as-is; see API Reference below for new values)"},{flag:"--text-normalization",description:"Enable Chinese/English text normalization"},{flag:"--latex-read",description:"Read LaTeX formulas ($$...$$, Chinese only)"},{flag:"--format <fmt>",description:`Audio format: ${dr(mr)} (default: mp3)`},{flag:"--sample-rate <hz>",description:"Sample rate (default: 32000)",type:"number"},{flag:"--bitrate <bps>",description:"Bitrate (default: 128000)",type:"number"},{flag:"--channels <n>",description:"Audio channels (default: 1)",type:"number"},{flag:"--language <code>",description:"Language boost"},{flag:"--subtitles",description:"Include subtitle timing data"},{flag:"--pronunciation <from/to>",description:"Custom pronunciation (repeatable)",type:"array"},{flag:"--out <path>",description:"Save audio to file (uses hex decoding)"},{flag:"--stream",description:"Stream raw audio to stdout"}],examples:['mmx speech synthesize --text "Hello, world!"','mmx speech synthesize --text "Hello, world!" --out hello.mp3','mmx speech synthesize --text "Hello" --subtitles --out hello.mp3','echo "Breaking news." | mmx speech synthesize --text-file - --out news.mp3','mmx speech synthesize --text "Stream" --stream | mpv --no-terminal -'],async run(e,t){let o=t.text??t._positional?.[0];if(t.textFile)o=En(t.textFile);if(!o)throw new m("--text or --text-file is required.",d.USAGE,'mmx speech synthesize --text "Hello" --out hello.mp3');let n=t.model||e.defaultSpeechModel||"speech-2.8-hd",i=t.voice||"English_expressive_narrator",s=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-"),r=t.format||"mp3";xn(r,mr),vn(r,t.stream===!0);let u=t.out??`speech_${s}.${r}`,a="hex",l={model:n,text:o,voice_setting:{voice_id:i,speed:t.speed??void 0,vol:t.volume??void 0,pitch:t.pitch??void 0,emotion:t.emotion||void 0,text_normalization:t.textNormalization===!0?!0:void 0,latex_read:t.latexRead===!0?!0:void 0},audio_setting:{format:t.format||"mp3",sample_rate:t.sampleRate??wn(r,32000),bitrate:t.bitrate??128000,channel:t.channels??1},output_format:a,stream:t.stream===!0};if(t.language)l.language_boost=t.language;if(t.subtitles)l.subtitle_enable=!0;if(t.pronunciation)l.pronunciation_dict={tone:t.pronunciation};if(le(e,l))return;let p=_(e.output),f=Ro(e.baseUrl);if(t.stream){let h=await ve(e,{url:f,method:"POST",body:l,stream:!0});await kn(h);return}let D=await A(e,{url:f,method:"POST",body:l});if(!e.quiet)process.stderr.write(`[Model: ${n}]
191
- `);if(yn(D,u,p,e.quiet),t.subtitles&&D.data.subtitle_file)try{let h=await fetch(D.data.subtitle_file);if(!h.ok)throw new m(`Failed to download subtitle file: ${h.status}`,d.GENERAL);let E=await h.json();if(E?.length){let x=u.replace(/\.[^.]+$/,"")+".srt",g=E.map((y,v)=>{let k=(B)=>{let M=String(Math.floor(B/3600000)).padStart(2,"0"),I=String(Math.floor(B%3600000/60000)).padStart(2,"0"),We=String(Math.floor(B%60000/1000)).padStart(2,"0"),Pe=String(Math.round(B%1000)).padStart(3,"0");return`${M}:${I}:${We},${Pe}`};return`${v+1}
192
- ${k(y.time_begin)} --> ${k(y.time_end)}
193
- ${y.text}`}).join(`
232
+ `),_=!1}else if(A.type==="content_block_delta"){if(A.delta.type==="text_delta")S+=A.delta.text,a.write(A.delta.text);else if(A.delta.type==="thinking_delta")a.write(A.delta.thinking)}}catch{}}if(_)a.write(i);if(S)r.messages.push({role:"assistant",content:S}),a.write(`
233
+ `);else a.write(`${n}[empty response]${i}
234
+ `)}catch(b){a.write(`${n}[error] ${b instanceof Error?b.message:String(b)}${i}
235
+ `)}finally{l=!1,c=0}}function u(p){let m=p.trim().split(/\s+/),b=m[0],w=m.slice(1).join(" ");switch(b){case"/exit":return a.write(`${n}Goodbye!${i}
236
+ `),"exit";case"/help":return Zg(),"ok";case"/clear":return r.messages=[],a.write(`${n}Conversation cleared.${i}
237
+ `),"ok";case"/system":{if(w)r.system=w,a.write(`${n}System prompt set.${i}
238
+ `);else if(r.system)a.write(`${n}System prompt:${i}
239
+ ${r.system}
240
+ `);else a.write(`${n}No system prompt set.${i}
241
+ `);return"ok"}case"/model":{if(w)r.model=w,a.write(`${n}Model set to: ${r.model}${i}
242
+ `);else a.write(`${n}Current model: ${r.model}${i}
243
+ `);return"ok"}case"/save":{if(!w)return a.write(`${n}Usage: /save <file-path>${i}
244
+ `),"ok";try{let S=[];if(r.system)S.push({role:"system",content:r.system});for(let _ of r.messages)S.push({role:_.role,content:typeof _.content==="string"?_.content:JSON.stringify(_.content)});Jg(w,JSON.stringify(S,null,2),"utf-8"),a.write(`${n}Conversation saved to ${w} (${S.length} messages)${i}
245
+ `)}catch(S){a.write(`${n}[error] Failed to save: ${S instanceof Error?S.message:String(S)}${i}
246
+ `)}return"ok"}case"/history":{if(r.messages.length===0)return a.write(`${n}No messages in conversation.${i}
247
+ `),"ok";if(r.system)a.write(`${n}[system] ${r.system.slice(0,100)}${r.system.length>100?"...":""}${i}
248
+ `);let S=1;for(let _ of r.messages){let E=_.role==="user"?"user":"assistant",A=typeof _.content==="string"?_.content:"[structured content]",T=(A.length>120?A.slice(0,120)+"...":A).replace(/\n/g,"↵"),C=` ${String(S).padStart(2)} ${E.padEnd(11)}`;a.write(`${n}${C}${i}${T}
249
+ `),S++}return a.write(`${n}── ${S-1} messages ──${i}
250
+ `),"ok"}default:if(b.startsWith("/"))return a.write(`${n}Unknown command: ${b}. Type /help for available commands.${i}
251
+ `),"ok";return"ok"}}let d=()=>{if(l){a.write(`
252
+ ${n}[interrupted]${i}
253
+ `),c=0,l=!1;return}if(c++,c>=2){if(a.write(`
254
+ ${n}Goodbye!${i}
255
+ `),h=!1,typeof o.setRawMode==="function")o.setRawMode(!1);o.pause(),process.removeListener("SIGINT",d),process.exit(0)}else a.write(`
256
+ ${n}Press Ctrl+C again or type /exit to quit.${i}
257
+ `)};process.on("SIGINT",d);let g=new Yc(a,"> ",n,i),h=!0;o.on("data",(p)=>{g.feed(p)}),a.write(Qg);try{while(h){let p=await g.readLine();if(!h)break;let m=p.trim();if(!m)continue;if(m.startsWith("/")){if(u(m)==="exit"){h=!1;break}continue}r.messages.push({role:"user",content:m}),await f()}}finally{if(a.write(Xg),typeof o.setRawMode==="function")o.setRawMode(!1);o.pause(),process.removeListener("SIGINT",d),o.removeAllListeners("data"),a.write(`
258
+ `)}}})});import{writeFileSync as ey}from"fs";function Xc(e,t,n,i){if(t){let r=e.data.audio;if(!r)throw new v("API response missing audio data (audio field is empty).",x.GENERAL);if(!/^[0-9a-fA-F]*$/.test(r))throw new v("API returned invalid audio data (not valid hex).",x.GENERAL);if(r.length%2!==0)throw new v("API returned truncated audio data (odd-length hex string).",x.GENERAL);try{ey(t,Buffer.from(r,"hex"))}catch(s){if(s.code==="ENOSPC")throw new v("Disk full — cannot write audio file.",x.GENERAL,"Free up disk space and try again.");throw s}if(i)console.log(t);else console.log(N({saved:t,duration_ms:e.extra_info?.audio_length,size_bytes:e.extra_info?.audio_size,sample_rate:e.extra_info?.audio_sample_rate},n))}else{let r=e.data.audio_url??e.data.audio;if(i)console.log(r);else console.log(N({url:r,duration_ms:e.extra_info?.audio_length,size_bytes:e.extra_info?.audio_size},n))}}var Zc=I(()=>{z();G();V()});function io(e){return e.join(", ")}function eu(e,t){if(!t.includes(e))throw new v(`Invalid audio format "${e}". Supported: ${io(t)}`,x.USAGE)}function tu(e,t){return ty[e]??t}function nu(e,t){if(t&&e==="wav")throw new v("wav format is not supported in streaming mode.",x.USAGE,"Use mp3, pcm, flac, pcmu_raw, pcmu_wav, or opus for streaming.")}var no,ty;var iu=I(()=>{G();V();no=["mp3","pcm","flac","wav","pcmu_raw","pcmu_wav","opus"];ty={opus:24000,pcmu_raw:8000,pcmu_wav:8000}});function ru(e){if(!/^[0-9a-fA-F]+$/.test(e))throw new v("API returned invalid audio data (not valid hex).",x.GENERAL);if(e.length%2!==0)throw new v("API returned truncated audio data (odd-length hex string).",x.GENERAL);return Uint8Array.from(Buffer.from(e,"hex"))}function su(e,t){let n=t.base_resp?.status_code;if(n!==void 0&&n!==0||t.error)throw wn(e.status,t,e.url||void 0)}function ou(){return new v("API stream ended without audio data.",x.GENERAL)}async function*ny(e){let t=e.headers.get("content-type")||"";if(!t.toLowerCase().includes("text/event-stream")){let i;try{i=await e.json()}catch{throw new v(`Expected SSE audio stream but got content-type "${t||"unknown"}".`,x.GENERAL)}su(e,i);let r=i.data?.audio;if(!r)throw ou();yield ru(r);return}let n=!1;for await(let i of tt(e)){if(!i.data||i.data==="[DONE]")break;let r;try{r=JSON.parse(i.data)}catch(o){throw new v(`Failed to parse audio stream chunk: ${o instanceof Error?o.message:String(o)}`,x.GENERAL)}su(e,r);let s=r.data?.audio;if(s)n=!0,yield ru(s);if(r.data?.status===2)break}if(!n)throw ou()}async function au(e){process.stdout.on("error",(t)=>{if(t.code==="EPIPE")process.exit(0);throw t});for await(let t of ny(e))if(!process.stdout.write(t))await new Promise((n)=>process.stdout.once("drain",n))}var lu=I(()=>{Hs();G();V()});import{writeFileSync as iy}from"fs";var ro;var cu=I(()=>{J();G();V();oe();z();Zc();Xs();iu();lu();ro=R({name:"speech synthesize",description:"Synchronous TTS, up to 10k chars (speech-2.8-hd / 2.6 / 02)",apiDocs:"/docs/api-reference/speech-t2a-http",usage:"mmx speech synthesize --text <text> [--out <path>] [flags]",options:[{flag:"--model <model>",description:"Model ID (default: speech-2.8-hd)"},{flag:"--text <text>",description:"Text to synthesize"},{flag:"--text-file <path>",description:"Read text from file (use - for stdin)"},{flag:"--voice <id>",description:"Voice ID (default: English_expressive_narrator)"},{flag:"--speed <n>",description:"Speech speed multiplier",type:"number"},{flag:"--volume <n>",description:"Volume level",type:"number"},{flag:"--pitch <n>",description:"Pitch adjustment",type:"number"},{flag:"--emotion <emotion>",description:"Emotion: happy, sad, angry, fearful, disgusted, surprised, calm, fluent, whisper (passed through as-is; see API Reference below for new values)"},{flag:"--text-normalization",description:"Enable Chinese/English text normalization"},{flag:"--latex-read",description:"Read LaTeX formulas ($$...$$, Chinese only)"},{flag:"--format <fmt>",description:`Audio format: ${io(no)} (default: mp3)`},{flag:"--sample-rate <hz>",description:"Sample rate (default: 32000)",type:"number"},{flag:"--bitrate <bps>",description:"Bitrate (default: 128000)",type:"number"},{flag:"--channels <n>",description:"Audio channels (default: 1)",type:"number"},{flag:"--language <code>",description:"Language boost"},{flag:"--subtitles",description:"Include subtitle timing data"},{flag:"--pronunciation <from/to>",description:"Custom pronunciation (repeatable)",type:"array"},{flag:"--out <path>",description:"Save audio to file (uses hex decoding)"},{flag:"--stream",description:"Stream raw audio to stdout"}],examples:['mmx speech synthesize --text "Hello, world!"','mmx speech synthesize --text "Hello, world!" --out hello.mp3','mmx speech synthesize --text "Hello" --subtitles --out hello.mp3','echo "Breaking news." | mmx speech synthesize --text-file - --out news.mp3','mmx speech synthesize --text "Stream" --stream | mpv --no-terminal -'],async run(e,t){let n=t.text??t._positional?.[0];if(t.textFile)n=Wi(t.textFile);if(!n)throw new v("--text or --text-file is required.",x.USAGE,'mmx speech synthesize --text "Hello" --out hello.mp3');let i=t.model||e.defaultSpeechModel||"speech-2.8-hd",r=t.voice||"English_expressive_narrator",s=new Date().toISOString().slice(0,19).replace(/[T:]/g,"-"),o=t.format||"mp3";eu(o,no),nu(o,t.stream===!0);let a=t.out??`speech_${s}.${o}`,l="hex",c={model:i,text:n,voice_setting:{voice_id:r,speed:t.speed??void 0,vol:t.volume??void 0,pitch:t.pitch??void 0,emotion:t.emotion||void 0,text_normalization:t.textNormalization===!0?!0:void 0,latex_read:t.latexRead===!0?!0:void 0},audio_setting:{format:t.format||"mp3",sample_rate:t.sampleRate??tu(o,32000),bitrate:t.bitrate??128000,channel:t.channels??1},output_format:l,stream:t.stream===!0};if(t.language)c.language_boost=t.language;if(t.subtitles)c.subtitle_enable=!0;if(t.pronunciation)c.pronunciation_dict={tone:t.pronunciation};if(Je(e,c))return;let f=F(e.output),u=ac(e.baseUrl);if(t.stream){let g=await $t(e,{url:u,method:"POST",body:c,stream:!0});await au(g);return}let d=await j(e,{url:u,method:"POST",body:c});if(!e.quiet)process.stderr.write(`[Model: ${i}]
259
+ `);if(Xc(d,a,f,e.quiet),t.subtitles&&d.data.subtitle_file)try{let g=await fetch(d.data.subtitle_file);if(!g.ok)throw new v(`Failed to download subtitle file: ${g.status}`,x.GENERAL);let h=await g.json();if(h?.length){let p=a.replace(/\.[^.]+$/,"")+".srt",m=h.map((b,w)=>{let S=(_)=>{let E=String(Math.floor(_/3600000)).padStart(2,"0"),A=String(Math.floor(_%3600000/60000)).padStart(2,"0"),k=String(Math.floor(_%60000/1000)).padStart(2,"0"),T=String(Math.round(_%1000)).padStart(3,"0");return`${E}:${A}:${k},${T}`};return`${w+1}
260
+ ${S(b.time_begin)} --> ${S(b.time_end)}
261
+ ${b.text}`}).join(`
194
262
 
195
- `);if(da(x,g,"utf-8"),!e.quiet)console.log(F({subtitles:x},p));else console.log(x)}}catch(h){if(!e.quiet)process.stderr.write(`Warning: failed to download subtitles: ${h.message}
196
- `)}else if(t.subtitles&&!D.data.subtitle_file){if(!e.quiet)process.stderr.write(`Warning: subtitles requested but not returned by API
197
- `)}}})});function pa(e){let t=e.match(/^(.+?)_[A-Z]/);return t?t[1]:e}function Da(e,t){let o=t.toLowerCase();return e.filter((n)=>{let i=pa(n.voice_id).toLowerCase();return i===o||i.startsWith(o+"_")||i.startsWith(o+" (")})}var In;var Tn=C(()=>{T();V();N();In=w({name:"speech voices",description:"List available system voices",usage:"mmx speech voices [--language <lang>]",options:[{flag:"--language <lang>",description:"Filter voices by language (e.g. english, korean, japanese)"}],examples:["mmx speech voices","mmx speech voices --language english","mmx speech voices --language korean","mmx speech voices --output json"],async run(e,t){let o=_(e.output);if(e.dryRun){console.log(F({request:{voice_type:"system"}},o));return}let i=(await A(e,{url:Bo(e.baseUrl),method:"POST",body:{voice_type:"system"}})).system_voice??[],s=t.language;if(s){let r=Da(i,s);if(o!=="text"){console.log(F(r,o));return}for(let u of r){let a=u.description?.join("; ")||"",l=u.voice_name?` (${u.voice_name})`:"";if(console.log(` ${u.voice_id}${l}`),a)console.log(` ${a}`)}}else{if(o!=="text"){console.log(F(i.map((r)=>r.voice_id),o));return}for(let r of i)console.log(r.voice_id)}}})});function On(e){let t=process.stderr.isTTY,o=0,n=null,i=e;return{start(){if(!t)return;n=setInterval(()=>{process.stderr.write(`\r${Mn[o%Mn.length]} ${i}`),o++},80)},update(s){i=s},stop(s){if(n)clearInterval(n),n=null;if(t){if(process.stderr.write("\r\x1B[K"),s)process.stderr.write(`${s}
198
- `)}}}}function Pn(e,t=""){let o=process.stderr.isTTY,n=30;return{update(i){if(!o)return;let s=Math.min(1,i/e),r=Math.round(30*s),u=30-r,a="█".repeat(r)+"░".repeat(u),l=`${Math.round(s*100)}%`;process.stderr.write(`\r${t} ${a} ${l}`)},finish(){if(o)process.stderr.write(`
199
- `)}}}var Mn;var Dr=C(()=>{Mn=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});import{createWriteStream as fa,renameSync as ha,unlinkSync as ga}from"fs";function fr(e,t){if(!Number.isFinite(e)||e<=0)throw new m(`${t} must be a positive number.`,d.USAGE);return e}function Ea(e,t){if(!Number.isInteger(e)||e<0)throw new m(`${t} must be a non-negative integer.`,d.USAGE);return e}function Fa(e,t){if(!Number.isFinite(e)||e<0)throw new m(`${t} must be a non-negative number.`,d.USAGE);return e}function he(e,t){return e.reason instanceof Error?e.reason:new m(t,d.GENERAL)}function xa(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1000;let o=Date.parse(e);if(!Number.isFinite(o))return;return Math.max(0,o-Date.now())}function wa(e){if(!e||!/^\d+$/.test(e))return;let t=BigInt(e);return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):Number.POSITIVE_INFINITY}async function va(e,t){if(t.aborted)throw he(t,"Download aborted.");if(e<=0)return;await new Promise((o,n)=>{let i=setTimeout(()=>{t.removeEventListener("abort",s),o()},e),s=()=>{clearTimeout(i),n(he(t,"Download aborted."))};t.addEventListener("abort",s,{once:!0})})}async function bt(e,t,o,n,i=!0){if(t.signal.aborted)throw he(t.signal,"Download aborted.");let s,r,u=new Promise((l,p)=>{s=setTimeout(()=>{let f=i?new _e(`Download idle timeout while ${n} after ${o}ms.`,d.TIMEOUT):new m(`Download idle timeout while ${n} after ${o}ms.`,d.TIMEOUT);t.abort(f),p(f)},o)}),a=new Promise((l,p)=>{r=()=>p(he(t.signal,"Download aborted.")),t.signal.addEventListener("abort",r,{once:!0})});try{return await Promise.race([e,u,a])}catch(l){if(t.signal.aborted)throw he(t.signal,"Download aborted.");throw l}finally{if(s)clearTimeout(s);if(r)t.signal.removeEventListener("abort",r)}}async function $a(e,t,o){let n=new Promise((i,s)=>{let r=()=>l(i),u=(p)=>l(()=>s(p)),a=()=>l(()=>s(Error("File writer closed before draining."))),l=(p)=>{e.off("drain",r),e.off("error",u),e.off("close",a),p()};e.once("drain",r),e.once("error",u),e.once("close",a)});try{await bt(n,t,o,"waiting for disk writes",!1)}catch(i){if(i instanceof m)throw i;throw new m(`Could not write download: ${i instanceof Error?i.message:String(i)}`,d.GENERAL)}}async function _a(e,t,o){let n=new Promise((i,s)=>{let r=()=>l(i),u=(p)=>l(()=>s(p)),a=()=>{if(!e.writableFinished)l(()=>s(Error("File writer closed early.")))},l=(p)=>{e.off("finish",r),e.off("error",u),e.off("close",a),p()};e.once("finish",r),e.once("error",u),e.once("close",a),e.end()});try{await bt(n,t,o,"finishing disk writes",!1)}catch(i){if(i instanceof m)throw i;throw new m(`Could not write download: ${i instanceof Error?i.message:String(i)}`,d.GENERAL)}}async function Aa(e){if(e.closed)return;await new Promise((t)=>{let o=setTimeout(()=>{e.off("close",n),t()},Ln),n=()=>{clearTimeout(o),t()};e.once("close",n),e.destroy()})}async function Nn(e){let t;if(await Promise.race([e.catch(()=>{return}),new Promise((o)=>{t=setTimeout(o,Ln)})]),t)clearTimeout(t)}async function Sa(e,t,o,n,i){let s=new AbortController,r=()=>s.abort(he(i,"Download aborted."));if(i.aborted)r();else i.addEventListener("abort",r,{once:!0});let u,a,l,p,f=null,D=!1;try{try{u=await bt(fetch(e,{signal:s.signal}),s,n.idleTimeoutMs,"waiting for response headers")}catch(v){if(v instanceof m)throw v;throw new _e(`Download request failed: ${v instanceof Error?v.message:String(v)}`)}if(!u.ok)throw new yt(u.status,xa(u.headers.get("retry-after")));let h=wa(u.headers.get("content-length"));if(h!==void 0&&h>n.maxBytes)throw new m(`Download exceeds maximum size of ${n.maxBytes} bytes (Content-Length: ${h}).`,d.GENERAL);if(a=u.body?.getReader(),!a)throw new m("Download response has no body.",d.GENERAL);let E=u.headers.get("content-encoding")?void 0:h;p=`${t}.tmp-${process.pid}-${Date.now()}-${o}-${Math.random().toString(36).slice(2)}`,l=fa(p),f=E&&!n.quiet?Pn(E,"Downloading"):null;let x,g=new Promise((v,k)=>{l.once("error",(B)=>{x=B,k(B)})});g.catch(()=>{return});let y=0;while(!0){let v;try{v=await bt(Promise.race([a.read(),g]),s,n.idleTimeoutMs,"waiting for response data")}catch(M){if(x)throw new m(`Could not write download: ${x.message}`,d.GENERAL);if(M instanceof m)throw M;throw new _e(`Download stream failed: ${M instanceof Error?M.message:String(M)}`)}if(v.done)break;let k=y+v.value.byteLength;if(k>n.maxBytes)throw new m(`Download exceeds maximum size of ${n.maxBytes} bytes.`,d.GENERAL);let B;try{B=l.write(v.value)}catch(M){throw new m(`Could not write download: ${M instanceof Error?M.message:String(M)}`,d.GENERAL)}if(!B)await $a(l,s,n.idleTimeoutMs);y=k,f?.update(y)}if(E!==void 0&&y!==E)throw new _e(`Download truncated: expected ${E} bytes, received ${y}.`);return await _a(l,s,n.idleTimeoutMs),l=void 0,a.releaseLock(),a=void 0,ha(p,t),p=void 0,D=!0,{size:y}}finally{if(i.removeEventListener("abort",r),f?.finish(),!D){if(a){await Nn(a.cancel(s.signal.reason));try{a.releaseLock()}catch{}}else if(u?.body)await Nn(u.body.cancel(s.signal.reason));if(l)await Aa(l);if(p)try{ga(p)}catch{}}}}async function ge(e,t,o){let n=e.startsWith("http://")?e.replace("http://","https://"):e,i=Ea(o?.retries??3,"retries"),s=Fa(o?.retryDelayMs??1000,"retryDelayMs"),r=fr(o?.overallTimeoutMs??Ca,"overallTimeoutMs"),u=fr(o?.idleTimeoutMs??ya,"idleTimeoutMs"),a=fr(o?.maxBytes??ba,"maxBytes"),l=o?.quiet??!1,p=new AbortController,f=()=>p.abort(he(o.signal,"Download aborted by caller."));if(o?.signal?.aborted)f();else o?.signal?.addEventListener("abort",f,{once:!0});let D=setTimeout(()=>{p.abort(new m(`Download timed out after ${r}ms.`,d.TIMEOUT))},r),h,E;try{for(let g=0;g<=i;g++){if(g>0){let y=s*Math.pow(2,g-1),v=Math.max(y,E??0);if(!l)process.stderr.write(`
200
- Retry ${g}/${i} in ${v}ms...
201
- `);await va(v,p.signal)}try{return await Sa(n,t,g,{quiet:l,idleTimeoutMs:u,maxBytes:a},p.signal)}catch(y){if(h=y instanceof Error?y:Error(String(y)),p.signal.aborted)throw he(p.signal,"Download aborted.");if(!(y instanceof _e||y instanceof yt&&y.retryable))throw y;if(E=y instanceof yt||y instanceof _e?y.retryAfterMs:void 0,!l)process.stderr.write(`
202
- Download attempt ${g+1} failed: ${h.message}
203
- `);if(g===i)break}}}finally{clearTimeout(D),o?.signal?.removeEventListener("abort",f)}let x=h instanceof m?h.exitCode:d.NETWORK;throw new m(`Download failed after ${i+1} attempts: ${h?.message}`,x,x===d.NETWORK?"Check your network connection and proxy settings.":void 0)}function Et(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}var Ca=1800000,ya=60000,ba=5368709120,Ln=1000,_e,yt;var Ft=C(()=>{Dr();R();S();_e=class _e extends m{retryAfterMs;constructor(e,t=d.NETWORK,o){super(e,t);this.retryAfterMs=o}};yt=class yt extends m{retryable;retryAfterMs;constructor(e,t){super(`Download failed: HTTP ${e}`,d.GENERAL);this.retryable=e===408||e===429||e>=500,this.retryAfterMs=t}}});import{readFileSync as ka,existsSync as Ra,statSync as Ba}from"fs";import{extname as Un}from"path";function xt(e,t){if(t!==void 0){let s=Ba(e).size;if(s>t)throw new m(`Image file is ${(s/1024/1024).toFixed(1)} MB; MiniMax-H3 allows at most ${t/1024/1024} MB.`,d.USAGE,"Use a public URL or mm_file:// file ID for large images.")}let o=Un(e).toLowerCase(),n=Gn[o]||"image/jpeg",i=ka(e);return`data:${n};base64,${i.toString("base64")}`}function Ae(e,t){return e.startsWith("http")||e.startsWith("data:")||e.startsWith("mm_file://")?e:xt(e,t)}async function qn(e){if(e.startsWith("data:"))return e;if(e.startsWith("http://")||e.startsWith("https://")){let o=await fetch(e);if(!o.ok)throw new m(`Failed to download image: HTTP ${o.status}`,d.GENERAL);let i=(o.headers.get("content-type")||"image/jpeg").split(";")[0].trim(),s=await o.arrayBuffer();if(s.byteLength>Ia)throw new m(`Image too large (${(s.byteLength/1024/1024).toFixed(1)} MB). Maximum is 50 MB.`,d.USAGE);return`data:${i};base64,${Buffer.from(s).toString("base64")}`}if(!Ra(e))throw new m(`File not found: ${e}`,d.USAGE);let t=Un(e).toLowerCase();if(!Gn[t])throw new m(`Unsupported image format "${t}". Supported: jpg, jpeg, png, webp`,d.USAGE);return xt(e)}var Gn,Ia=52428800;var wt=C(()=>{R();S();Gn={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif"}});import{mkdirSync as Vn,existsSync as je,writeFileSync as jn}from"fs";import{dirname as Ta,join as Hn,resolve as hr}from"path";var Wn;var Kn=C(()=>{T();R();S();V();Ft();N();wt();pe();Wn=w({name:"image generate",description:"Generate images (image-01 / image-01-live)",apiDocs:"/docs/api-reference/image-generation-t2i",usage:"mmx image generate --prompt <text> [flags]",options:[{flag:"--prompt <text>",description:"Image description",required:!0},{flag:"--aspect-ratio <ratio>",description:"Aspect ratio (e.g. 16:9, 1:1). Ignored if --width and --height are both specified."},{flag:"--n <count>",description:"Number of images to generate (default: 1)",type:"number"},{flag:"--seed <n>",description:"Random seed for reproducible generation (same seed + prompt = identical output)",type:"number"},{flag:"--width <px>",description:"Custom width in pixels. Range [512, 2048], must be multiple of 8. Only effective for image-01 model. Overrides --aspect-ratio if set.",type:"number"},{flag:"--height <px>",description:"Custom height in pixels. Range [512, 2048], must be multiple of 8. Only effective for image-01 model. Overrides --aspect-ratio if set.",type:"number"},{flag:"--prompt-optimizer",description:"Automatically optimize the prompt before generation for better results."},{flag:"--aigc-watermark",description:"Embed AI-generated content watermark in the output image."},{flag:"--subject-ref <params>",description:"Subject reference for character consistency. Format: type=character,image=path-or-url"},{flag:"--out <path>",description:"Save image to exact file path (single image only)"},{flag:"--response-format <format>",description:"Response format: url (download), base64 (embed). Default: url"},{flag:"--out-dir <dir>",description:"Download images to directory"},{flag:"--out-prefix <prefix>",description:"Filename prefix (default: image)"}],examples:['mmx image generate --prompt "A cat in a spacesuit on Mars" --aspect-ratio 16:9','mmx image generate --prompt "Logo design" --n 3 --out-dir ./generated/','mmx image generate --prompt "Mountain landscape" --quiet',"# Reproducible output with seed",'mmx image generate --prompt "A castle" --seed 42',"# Custom dimensions (must be 512–2048, multiple of 8)",'mmx image generate --prompt "Wide landscape" --width 1920 --height 1080',"# Optimized prompt with watermark",'mmx image generate --prompt "sunset" --prompt-optimizer --aigc-watermark',"# Save to exact path",'mmx image generate --prompt "A cat" --out /tmp/cat.jpg',"# Base64 response (bypasses CDN, useful when image URLs are unreachable)",'mmx image generate --prompt "A cat" --response-format base64'],async run(e,t){let o=t.prompt??t._positional?.[0];o=await it({value:o,message:"Enter your image prompt:",cancelMessage:"Image generation cancelled.",flagName:"prompt",usageHint:"mmx image generate --prompt <text>",nonInteractive:e.nonInteractive});let{width:n,height:i}=t;if(n!==void 0&&i===void 0)throw new m("--width requires --height. Both must be specified together.",d.USAGE);if(i!==void 0&&n===void 0)throw new m("--height requires --width. Both must be specified together.",d.USAGE);if(n!==void 0&&i!==void 0){let D=(h,E)=>{if(E<512||E>2048)throw new m(`--${h} must be between 512 and 2048, got ${E}.`,d.USAGE);if(E%8!==0)throw new m(`--${h} must be a multiple of 8, got ${E}.`,d.USAGE)};D("width",n),D("height",i)}let s=t.out;if(s&&t.n>1)throw new m("--out cannot be used with --n > 1. Use --out-dir instead.",d.USAGE);let r=t.responseFormat||"url",u={model:"image-01",prompt:o,aspect_ratio:n!==void 0&&i!==void 0?void 0:t.aspectRatio||void 0,n:t.n??1,seed:t.seed,width:n,height:i,prompt_optimizer:t.promptOptimizer===!0||void 0,aigc_watermark:t.aigcWatermark===!0||void 0,response_format:r};if(t.subjectRef){let D=t.subjectRef,h=Object.fromEntries(D.split(",").map((x)=>{let g=x.indexOf("=");if(g===-1)return[x,""];return[x.slice(0,g),x.slice(g+1)]})),E={type:h.type||"character"};if(h.image)if(h.image.startsWith("http"))E.image_url=h.image;else E.image_file=xt(hr(h.image));u.subject_reference=[E]}if(le(e,u))return;let a=_(e.output),l=Io(e.baseUrl),p=await A(e,{url:l,method:"POST",body:u});if(!e.quiet)process.stderr.write(`[Model: image-01]
204
- `);let f=[];if(s){let D=Ta(hr(s));if(!je(D))Vn(D,{recursive:!0});let h=hr(s);if(je(h))process.stderr.write(`Warning: overwriting existing file: ${h}
205
- `);if(r==="base64"){let E=(p.data.image_base64||[])[0];if(E)jn(h,E,"base64")}else{let E=(p.data.image_urls||[])[0];if(E)await ge(E,h,{quiet:e.quiet})}f.push(h)}else{let D=t.outDir??".";if(!je(D))Vn(D,{recursive:!0});let h=t.outPrefix||"image";if(r==="base64"){let E=p.data.image_base64||[];for(let x=0;x<E.length;x++){let g=`${h}_${String(x+1).padStart(3,"0")}.jpg`,y=Hn(D,g);if(je(y))process.stderr.write(`Warning: overwriting existing file: ${y}
206
- `);jn(y,E[x],"base64"),f.push(y)}}else{let E=p.data.image_urls||[];for(let x=0;x<E.length;x++){let g=`${h}_${String(x+1).padStart(3,"0")}.jpg`,y=Hn(D,g);if(je(y))process.stderr.write(`Warning: overwriting existing file: ${y}
207
- `);await ge(E[x],y,{quiet:e.quiet}),f.push(y)}}}if(a==="json")console.log(F({id:p.data.task_id,saved:f,success_count:p.data.success_count,failed_count:p.data.failed_count},a));else if(e.quiet)console.log(f.join(`
208
- `));else console.log(F({id:p.data.task_id,saved:f,success_count:p.data.success_count,failed_count:p.data.failed_count},a))}})});async function gr(e,t){let o=Date.now()+t.timeoutSec*1000,n=On("Polling...");if(!e.quiet)n.start();try{while(Date.now()<o){let i=await A(e,{url:t.url});if(t.getStatus&&!e.quiet)n.update(`Status: ${t.getStatus(i)}`);if(t.isComplete(i))return n.stop("Done."),i;if(t.isFailed(i)){n.stop("Failed.");let s=t.getStatus?t.getStatus(i):"failed",r=i.base_resp?.status_msg,u=t.getFailureReason?.(i)??r,a=u?` (${u})`:"";throw new m(`Task ${s}.${a}`,d.GENERAL,"Check the MiniMax dashboard or --verbose output for details.")}await new Promise((s)=>setTimeout(s,t.intervalSec*1000))}}finally{n.stop()}throw new m("Polling timed out.",d.TIMEOUT,"Try increasing --timeout or check task status manually.")}var zn=C(()=>{V();R();S();Dr()});import{existsSync as Ma,readFileSync as Oa,statSync as Pa}from"fs";import{extname as Na}from"path";function Yn(e){let t=/^data:[^;,]+;base64,([\s\S]*)$/.exec(e);if(!t)return;let o=t[1].replace(/\s/g,""),n=o.endsWith("==")?2:o.endsWith("=")?1:0;return Math.max(0,Math.floor(o.length*3/4)-n)}function Cr(e,t){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mm_file://"))return e;if(e.startsWith("data:"))return t==="audio"?e.replace(/^data:audio\/mpeg;base64,/,"data:audio/mp3;base64,"):e;if(!Ma(e))throw new m(`File not found: ${e}`,d.USAGE);let o=Na(e).toLowerCase(),n=La[t],i=n[o];if(!i){let a=Object.keys(n).map((l)=>l.slice(1)).join(", ");throw new m(`Unsupported ${t} format "${o}". Supported local files: ${a}`,d.USAGE)}let s=Se[t],r=Pa(e).size;if(r>s)throw new m(`${t[0].toUpperCase()}${t.slice(1)} file is ${(r/1024/1024).toFixed(1)} MB; MiniMax-H3 allows at most ${s/1024/1024} MB.`,d.USAGE,"Use a public URL or mm_file:// file ID for large media.");let u=Oa(e);return`data:${i};base64,${u.toString("base64")}`}var La,Se,Jn=67108864;var yr=C(()=>{R();S();La={video:{".mp4":"video/mp4",".mov":"video/quicktime"},audio:{".mp3":"audio/mp3",".wav":"audio/wav"}},Se={image:31457280,video:52428800,audio:15728640}});function ke(e){return e===He}function Xn(e){return ke(e.model)}function Qn(e){let t=e.error?.code?.trim(),o=e.error?.message?.trim();if(t&&o)return`${t}: ${o}`;return o||t}function Zn(e){let t=e.images??[];if(t.length>1&&t.some((r)=>!r.role))throw new q("Each image must specify a role when multiple images are provided.");let o=[{type:"text",text:e.prompt},...t.map((r)=>({type:"image_url",image_url:{url:r.url},role:r.role??"first_frame"})),...(e.referenceVideos??[]).map((r)=>({type:"video_url",video_url:{url:r},role:"reference_video"})),...(e.referenceAudios??[]).map((r)=>({type:"audio_url",audio_url:{url:r},role:"reference_audio"}))],n=o.some((r)=>r.type==="image_url"&&(r.role==="first_frame"||r.role==="last_frame")),i=o.some((r)=>r.type!=="text"&&r.role?.startsWith("reference_")),s={model:He,content:o,resolution:e.resolution??"2K",duration:e.duration??5,ratio:n?"adaptive":e.ratio??(i?"adaptive":"16:9")};if(e.callbackUrl)s.callback_url=e.callbackUrl;return qa(s),s}function qa(e){if(!ke(e.model))throw new q(`Video Generation V2 only supports ${He}.`);let t=e.content.filter((D)=>D.type==="text");if(!t.some((D)=>D.text.trim().length>0))throw new q("MiniMax-H3 requires a non-empty text content item.");if(t.some((D)=>D.text.length>7000))throw new q("MiniMax-H3 text content must not exceed 7000 characters.");if(e.resolution!=="2K")throw new q("MiniMax-H3 currently only supports 2K resolution.");if(!Number.isInteger(e.duration)||e.duration<4||e.duration>15)throw new q("MiniMax-H3 duration must be an integer from 4 to 15 seconds.");if(e.ratio&&!Ua.has(e.ratio))throw new q("MiniMax-H3 ratio must be one of: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16.");let o=e.content.filter((D)=>D.type==="image_url"),n=e.content.filter((D)=>D.type==="video_url"),i=e.content.filter((D)=>D.type==="audio_url");if(o.some((D)=>D.role&&!Ga.has(D.role)))throw new q("MiniMax-H3 image role must be one of: first_frame, last_frame, reference_image.");if(n.some((D)=>D.role!=="reference_video"))throw new q("MiniMax-H3 video role must be reference_video.");if(i.some((D)=>D.role!=="reference_audio"))throw new q("MiniMax-H3 audio role must be reference_audio.");for(let D of o)br(D.image_url.url,"image");for(let D of n)br(D.video_url.url,"video");for(let D of i)br(D.audio_url.url,"audio");let s=Buffer.byteLength(JSON.stringify(e));if(s>Jn)throw new q(`MiniMax-H3 request body is ${(s/1024/1024).toFixed(1)} MB; the maximum is 64 MB. Use public URLs or mm_file:// file IDs instead of Base64.`);let r=o.filter((D)=>!D.role||D.role==="first_frame"),u=o.filter((D)=>D.role==="last_frame"),a=o.filter((D)=>D.role==="reference_image"),l=r.length>0||u.length>0,p=a.length>0||n.length>0||i.length>0;if(r.length>1||u.length>1)throw new q("MiniMax-H3 accepts at most one first frame and one last frame.");if(a.length>9||n.length>3||i.length>3)throw new q("MiniMax-H3 accepts up to 9 reference images, 3 reference videos, and 3 reference audios.");if(l&&p)throw new q("MiniMax-H3 frame inputs and reference inputs cannot be used together.");if(i.length>0&&a.length===0&&n.length===0)throw new q("MiniMax-H3 reference audio requires at least one reference image or reference video.");if(e.content.every((D)=>D.type==="text")&&(!e.ratio||e.ratio==="adaptive"))throw new q("MiniMax-H3 text-to-video requires a concrete ratio; adaptive is not supported.")}function br(e,t){let o=Yn(e),n=Se[t];if(o!==void 0&&o>n)throw new q(`MiniMax-H3 ${t} input is ${(o/1024/1024).toFixed(1)} MB; the maximum is ${n/1024/1024} MB.`)}var He="MiniMax-H3",Ua,Ga,q;var Er=C(()=>{yr();Ua=new Set(["adaptive","21:9","16:9","4:3","1:1","3:4","9:16"]),Ga=new Set(["first_frame","last_frame","reference_image"]);q=class q extends Error{constructor(e){super(e);this.name="VideoV2InputError"}}});var ei;var ti=C(()=>{T();R();S();V();zn();Ft();N();wt();yr();pe();Er();ei=w({name:"video generate",description:`Generate a video
263
+ `);if(iy(p,m,"utf-8"),!e.quiet)console.log(N({subtitles:p},f));else console.log(p)}}catch(g){if(!e.quiet)process.stderr.write(`Warning: failed to download subtitles: ${g.message}
264
+ `)}else if(t.subtitles&&!d.data.subtitle_file){if(!e.quiet)process.stderr.write(`Warning: subtitles requested but not returned by API
265
+ `)}}})});function ry(e){let t=e.match(/^(.+?)_[A-Z]/);return t?t[1]:e}function sy(e,t){let n=t.toLowerCase();return e.filter((i)=>{let r=ry(i.voice_id).toLowerCase();return r===n||r.startsWith(n+"_")||r.startsWith(n+" (")})}var uu;var fu=I(()=>{J();oe();z();uu=R({name:"speech voices",description:"List available system voices",usage:"mmx speech voices [--language <lang>]",options:[{flag:"--language <lang>",description:"Filter voices by language (e.g. english, korean, japanese)"}],examples:["mmx speech voices","mmx speech voices --language english","mmx speech voices --language korean","mmx speech voices --output json"],async run(e,t){let n=F(e.output);if(e.dryRun){console.log(N({request:{voice_type:"system"}},n));return}let r=(await j(e,{url:lc(e.baseUrl),method:"POST",body:{voice_type:"system"}})).system_voice??[],s=t.language;if(s){let o=sy(r,s);if(n!=="text"){console.log(N(o,n));return}for(let a of o){let l=a.description?.join("; ")||"",c=a.voice_name?` (${a.voice_name})`:"";if(console.log(` ${a.voice_id}${c}`),l)console.log(` ${l}`)}}else{if(n!=="text"){console.log(N(r.map((o)=>o.voice_id),n));return}for(let o of r)console.log(o.voice_id)}}})});function pu(e){let t=process.stderr.isTTY,n=0,i=null,r=e;return{start(){if(!t)return;i=setInterval(()=>{process.stderr.write(`\r${du[n%du.length]} ${r}`),n++},80)},update(s){r=s},stop(s){if(i)clearInterval(i),i=null;if(t){if(process.stderr.write("\r\x1B[K"),s)process.stderr.write(`${s}
266
+ `)}}}}function mu(e,t=""){let n=process.stderr.isTTY,i=30;return{update(r){if(!n)return;let s=Math.min(1,r/e),o=Math.round(30*s),a=30-o,l="█".repeat(o)+"░".repeat(a),c=`${Math.round(s*100)}%`;process.stderr.write(`\r${t} ${l} ${c}`)},finish(){if(n)process.stderr.write(`
267
+ `)}}}var du;var so=I(()=>{du=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});import{createWriteStream as oy,renameSync as ay,unlinkSync as ly}from"fs";function oo(e,t){if(!Number.isFinite(e)||e<=0)throw new v(`${t} must be a positive number.`,x.USAGE);return e}function dy(e,t){if(!Number.isInteger(e)||e<0)throw new v(`${t} must be a non-negative integer.`,x.USAGE);return e}function py(e,t){if(!Number.isFinite(e)||e<0)throw new v(`${t} must be a non-negative number.`,x.USAGE);return e}function nt(e,t){return e.reason instanceof Error?e.reason:new v(t,x.GENERAL)}function my(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1000;let n=Date.parse(e);if(!Number.isFinite(n))return;return Math.max(0,n-Date.now())}function hy(e){if(!e||!/^\d+$/.test(e))return;let t=BigInt(e);return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):Number.POSITIVE_INFINITY}async function gy(e,t){if(t.aborted)throw nt(t,"Download aborted.");if(e<=0)return;await new Promise((n,i)=>{let r=setTimeout(()=>{t.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(r),i(nt(t,"Download aborted."))};t.addEventListener("abort",s,{once:!0})})}async function Yi(e,t,n,i,r=!0){if(t.signal.aborted)throw nt(t.signal,"Download aborted.");let s,o,a=new Promise((c,f)=>{s=setTimeout(()=>{let u=r?new kt(`Download idle timeout while ${i} after ${n}ms.`,x.TIMEOUT):new v(`Download idle timeout while ${i} after ${n}ms.`,x.TIMEOUT);t.abort(u),f(u)},n)}),l=new Promise((c,f)=>{o=()=>f(nt(t.signal,"Download aborted.")),t.signal.addEventListener("abort",o,{once:!0})});try{return await Promise.race([e,a,l])}catch(c){if(t.signal.aborted)throw nt(t.signal,"Download aborted.");throw c}finally{if(s)clearTimeout(s);if(o)t.signal.removeEventListener("abort",o)}}async function yy(e,t,n){let i=new Promise((r,s)=>{let o=()=>c(r),a=(f)=>c(()=>s(f)),l=()=>c(()=>s(Error("File writer closed before draining."))),c=(f)=>{e.off("drain",o),e.off("error",a),e.off("close",l),f()};e.once("drain",o),e.once("error",a),e.once("close",l)});try{await Yi(i,t,n,"waiting for disk writes",!1)}catch(r){if(r instanceof v)throw r;throw new v(`Could not write download: ${r instanceof Error?r.message:String(r)}`,x.GENERAL)}}async function by(e,t,n){let i=new Promise((r,s)=>{let o=()=>c(r),a=(f)=>c(()=>s(f)),l=()=>{if(!e.writableFinished)c(()=>s(Error("File writer closed early.")))},c=(f)=>{e.off("finish",o),e.off("error",a),e.off("close",l),f()};e.once("finish",o),e.once("error",a),e.once("close",l),e.end()});try{await Yi(i,t,n,"finishing disk writes",!1)}catch(r){if(r instanceof v)throw r;throw new v(`Could not write download: ${r instanceof Error?r.message:String(r)}`,x.GENERAL)}}async function wy(e){if(e.closed)return;await new Promise((t)=>{let n=setTimeout(()=>{e.off("close",i),t()},gu),i=()=>{clearTimeout(n),t()};e.once("close",i),e.destroy()})}async function hu(e){let t;if(await Promise.race([e.catch(()=>{return}),new Promise((n)=>{t=setTimeout(n,gu)})]),t)clearTimeout(t)}async function vy(e,t,n,i,r){let s=new AbortController,o=()=>s.abort(nt(r,"Download aborted."));if(r.aborted)o();else r.addEventListener("abort",o,{once:!0});let a,l,c,f,u=null,d=!1;try{try{a=await Yi(fetch(e,{signal:s.signal}),s,i.idleTimeoutMs,"waiting for response headers")}catch(w){if(w instanceof v)throw w;throw new kt(`Download request failed: ${w instanceof Error?w.message:String(w)}`)}if(!a.ok)throw new Ji(a.status,my(a.headers.get("retry-after")));let g=hy(a.headers.get("content-length"));if(g!==void 0&&g>i.maxBytes)throw new v(`Download exceeds maximum size of ${i.maxBytes} bytes (Content-Length: ${g}).`,x.GENERAL);if(l=a.body?.getReader(),!l)throw new v("Download response has no body.",x.GENERAL);let h=a.headers.get("content-encoding")?void 0:g;f=`${t}.tmp-${process.pid}-${Date.now()}-${n}-${Math.random().toString(36).slice(2)}`,c=oy(f),u=h&&!i.quiet?mu(h,"Downloading"):null;let p,m=new Promise((w,S)=>{c.once("error",(_)=>{p=_,S(_)})});m.catch(()=>{return});let b=0;while(!0){let w;try{w=await Yi(Promise.race([l.read(),m]),s,i.idleTimeoutMs,"waiting for response data")}catch(E){if(p)throw new v(`Could not write download: ${p.message}`,x.GENERAL);if(E instanceof v)throw E;throw new kt(`Download stream failed: ${E instanceof Error?E.message:String(E)}`)}if(w.done)break;let S=b+w.value.byteLength;if(S>i.maxBytes)throw new v(`Download exceeds maximum size of ${i.maxBytes} bytes.`,x.GENERAL);let _;try{_=c.write(w.value)}catch(E){throw new v(`Could not write download: ${E instanceof Error?E.message:String(E)}`,x.GENERAL)}if(!_)await yy(c,s,i.idleTimeoutMs);b=S,u?.update(b)}if(h!==void 0&&b!==h)throw new kt(`Download truncated: expected ${h} bytes, received ${b}.`);return await by(c,s,i.idleTimeoutMs),c=void 0,l.releaseLock(),l=void 0,ay(f,t),f=void 0,d=!0,{size:b}}finally{if(r.removeEventListener("abort",o),u?.finish(),!d){if(l){await hu(l.cancel(s.signal.reason));try{l.releaseLock()}catch{}}else if(a?.body)await hu(a.body.cancel(s.signal.reason));if(c)await wy(c);if(f)try{ly(f)}catch{}}}}async function it(e,t,n){let i=e.startsWith("http://")?e.replace("http://","https://"):e,r=dy(n?.retries??3,"retries"),s=py(n?.retryDelayMs??1000,"retryDelayMs"),o=oo(n?.overallTimeoutMs??cy,"overallTimeoutMs"),a=oo(n?.idleTimeoutMs??uy,"idleTimeoutMs"),l=oo(n?.maxBytes??fy,"maxBytes"),c=n?.quiet??!1,f=new AbortController,u=()=>f.abort(nt(n.signal,"Download aborted by caller."));if(n?.signal?.aborted)u();else n?.signal?.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{f.abort(new v(`Download timed out after ${o}ms.`,x.TIMEOUT))},o),g,h;try{for(let m=0;m<=r;m++){if(m>0){let b=s*Math.pow(2,m-1),w=Math.max(b,h??0);if(!c)process.stderr.write(`
268
+ Retry ${m}/${r} in ${w}ms...
269
+ `);await gy(w,f.signal)}try{return await vy(i,t,m,{quiet:c,idleTimeoutMs:a,maxBytes:l},f.signal)}catch(b){if(g=b instanceof Error?b:Error(String(b)),f.signal.aborted)throw nt(f.signal,"Download aborted.");if(!(b instanceof kt||b instanceof Ji&&b.retryable))throw b;if(h=b instanceof Ji||b instanceof kt?b.retryAfterMs:void 0,!c)process.stderr.write(`
270
+ Download attempt ${m+1} failed: ${g.message}
271
+ `);if(m===r)break}}}finally{clearTimeout(d),n?.signal?.removeEventListener("abort",u)}let p=g instanceof v?g.exitCode:x.NETWORK;throw new v(`Download failed after ${r+1} attempts: ${g?.message}`,p,p===x.NETWORK?"Check your network connection and proxy settings.":void 0)}function zi(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}var cy=1800000,uy=60000,fy=5368709120,gu=1000,kt,Ji;var Qi=I(()=>{so();G();V();kt=class kt extends v{retryAfterMs;constructor(e,t=x.NETWORK,n){super(e,t);this.retryAfterMs=n}};Ji=class Ji extends v{retryable;retryAfterMs;constructor(e,t){super(`Download failed: HTTP ${e}`,x.GENERAL);this.retryable=e===408||e===429||e>=500,this.retryAfterMs=t}}});import{readFileSync as xy,existsSync as Sy,statSync as $y}from"fs";import{extname as yu}from"path";function Xi(e,t){if(t!==void 0){let s=$y(e).size;if(s>t)throw new v(`Image file is ${(s/1024/1024).toFixed(1)} MB; MiniMax-H3 allows at most ${t/1024/1024} MB.`,x.USAGE,"Use a public URL or mm_file:// file ID for large images.")}let n=yu(e).toLowerCase(),i=bu[n]||"image/jpeg",r=xy(e);return`data:${i};base64,${r.toString("base64")}`}function At(e,t){return e.startsWith("http")||e.startsWith("data:")||e.startsWith("mm_file://")?e:Xi(e,t)}async function wu(e){if(e.startsWith("data:"))return e;if(e.startsWith("http://")||e.startsWith("https://")){let n=await fetch(e);if(!n.ok)throw new v(`Failed to download image: HTTP ${n.status}`,x.GENERAL);let r=(n.headers.get("content-type")||"image/jpeg").split(";")[0].trim(),s=await n.arrayBuffer();if(s.byteLength>ky)throw new v(`Image too large (${(s.byteLength/1024/1024).toFixed(1)} MB). Maximum is 50 MB.`,x.USAGE);return`data:${r};base64,${Buffer.from(s).toString("base64")}`}if(!Sy(e))throw new v(`File not found: ${e}`,x.USAGE);let t=yu(e).toLowerCase();if(!bu[t])throw new v(`Unsupported image format "${t}". Supported: jpg, jpeg, png, webp`,x.USAGE);return Xi(e)}var bu,ky=52428800;var Zi=I(()=>{G();V();bu={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif"}});import{mkdirSync as vu,existsSync as $n,writeFileSync as xu}from"fs";import{dirname as Ay,join as Su,resolve as ao}from"path";var $u;var ku=I(()=>{J();G();V();oe();Qi();z();Zi();Ve();$u=R({name:"image generate",description:"Generate images (image-01 / image-01-live)",apiDocs:"/docs/api-reference/image-generation-t2i",usage:"mmx image generate --prompt <text> [flags]",options:[{flag:"--prompt <text>",description:"Image description",required:!0},{flag:"--aspect-ratio <ratio>",description:"Aspect ratio (e.g. 16:9, 1:1). Ignored if --width and --height are both specified."},{flag:"--n <count>",description:"Number of images to generate (default: 1)",type:"number"},{flag:"--seed <n>",description:"Random seed for reproducible generation (same seed + prompt = identical output)",type:"number"},{flag:"--width <px>",description:"Custom width in pixels. Range [512, 2048], must be multiple of 8. Only effective for image-01 model. Overrides --aspect-ratio if set.",type:"number"},{flag:"--height <px>",description:"Custom height in pixels. Range [512, 2048], must be multiple of 8. Only effective for image-01 model. Overrides --aspect-ratio if set.",type:"number"},{flag:"--prompt-optimizer",description:"Automatically optimize the prompt before generation for better results."},{flag:"--aigc-watermark",description:"Embed AI-generated content watermark in the output image."},{flag:"--subject-ref <params>",description:"Subject reference for character consistency. Format: type=character,image=path-or-url"},{flag:"--out <path>",description:"Save image to exact file path (single image only)"},{flag:"--response-format <format>",description:"Response format: url (download), base64 (embed). Default: url"},{flag:"--out-dir <dir>",description:"Download images to directory"},{flag:"--out-prefix <prefix>",description:"Filename prefix (default: image)"}],examples:['mmx image generate --prompt "A cat in a spacesuit on Mars" --aspect-ratio 16:9','mmx image generate --prompt "Logo design" --n 3 --out-dir ./generated/','mmx image generate --prompt "Mountain landscape" --quiet',"# Reproducible output with seed",'mmx image generate --prompt "A castle" --seed 42',"# Custom dimensions (must be 512–2048, multiple of 8)",'mmx image generate --prompt "Wide landscape" --width 1920 --height 1080',"# Optimized prompt with watermark",'mmx image generate --prompt "sunset" --prompt-optimizer --aigc-watermark',"# Save to exact path",'mmx image generate --prompt "A cat" --out /tmp/cat.jpg',"# Base64 response (bypasses CDN, useful when image URLs are unreachable)",'mmx image generate --prompt "A cat" --response-format base64'],async run(e,t){let n=t.prompt??t._positional?.[0];n=await Ni({value:n,message:"Enter your image prompt:",cancelMessage:"Image generation cancelled.",flagName:"prompt",usageHint:"mmx image generate --prompt <text>",nonInteractive:e.nonInteractive});let{width:i,height:r}=t;if(i!==void 0&&r===void 0)throw new v("--width requires --height. Both must be specified together.",x.USAGE);if(r!==void 0&&i===void 0)throw new v("--height requires --width. Both must be specified together.",x.USAGE);if(i!==void 0&&r!==void 0){let d=(g,h)=>{if(h<512||h>2048)throw new v(`--${g} must be between 512 and 2048, got ${h}.`,x.USAGE);if(h%8!==0)throw new v(`--${g} must be a multiple of 8, got ${h}.`,x.USAGE)};d("width",i),d("height",r)}let s=t.out;if(s&&t.n>1)throw new v("--out cannot be used with --n > 1. Use --out-dir instead.",x.USAGE);let o=t.responseFormat||"url",a={model:"image-01",prompt:n,aspect_ratio:i!==void 0&&r!==void 0?void 0:t.aspectRatio||void 0,n:t.n??1,seed:t.seed,width:i,height:r,prompt_optimizer:t.promptOptimizer===!0||void 0,aigc_watermark:t.aigcWatermark===!0||void 0,response_format:o};if(t.subjectRef){let d=t.subjectRef,g=Object.fromEntries(d.split(",").map((p)=>{let m=p.indexOf("=");if(m===-1)return[p,""];return[p.slice(0,m),p.slice(m+1)]})),h={type:g.type||"character"};if(g.image)if(g.image.startsWith("http"))h.image_url=g.image;else h.image_file=Xi(ao(g.image));a.subject_reference=[h]}if(Je(e,a))return;let l=F(e.output),c=cc(e.baseUrl),f=await j(e,{url:c,method:"POST",body:a});if(!e.quiet)process.stderr.write(`[Model: image-01]
272
+ `);let u=[];if(s){let d=Ay(ao(s));if(!$n(d))vu(d,{recursive:!0});let g=ao(s);if($n(g))process.stderr.write(`Warning: overwriting existing file: ${g}
273
+ `);if(o==="base64"){let h=(f.data.image_base64||[])[0];if(h)xu(g,h,"base64")}else{let h=(f.data.image_urls||[])[0];if(h)await it(h,g,{quiet:e.quiet})}u.push(g)}else{let d=t.outDir??".";if(!$n(d))vu(d,{recursive:!0});let g=t.outPrefix||"image";if(o==="base64"){let h=f.data.image_base64||[];for(let p=0;p<h.length;p++){let m=`${g}_${String(p+1).padStart(3,"0")}.jpg`,b=Su(d,m);if($n(b))process.stderr.write(`Warning: overwriting existing file: ${b}
274
+ `);xu(b,h[p],"base64"),u.push(b)}}else{let h=f.data.image_urls||[];for(let p=0;p<h.length;p++){let m=`${g}_${String(p+1).padStart(3,"0")}.jpg`,b=Su(d,m);if($n(b))process.stderr.write(`Warning: overwriting existing file: ${b}
275
+ `);await it(h[p],b,{quiet:e.quiet}),u.push(b)}}}if(l==="json")console.log(N({id:f.data.task_id,saved:u,success_count:f.data.success_count,failed_count:f.data.failed_count},l));else if(e.quiet)console.log(u.join(`
276
+ `));else console.log(N({id:f.data.task_id,saved:u,success_count:f.data.success_count,failed_count:f.data.failed_count},l))}})});async function lo(e,t){let n=Date.now()+t.timeoutSec*1000,i=pu("Polling...");if(!e.quiet)i.start();try{while(Date.now()<n){let r=await j(e,{url:t.url});if(t.getStatus&&!e.quiet)i.update(`Status: ${t.getStatus(r)}`);if(t.isComplete(r))return i.stop("Done."),r;if(t.isFailed(r)){i.stop("Failed.");let s=t.getStatus?t.getStatus(r):"failed",o=r.base_resp?.status_msg,a=t.getFailureReason?.(r)??o,l=a?` (${a})`:"";throw new v(`Task ${s}.${l}`,x.GENERAL,"Check the MiniMax dashboard or --verbose output for details.")}await new Promise((s)=>setTimeout(s,t.intervalSec*1000))}}finally{i.stop()}throw new v("Polling timed out.",x.TIMEOUT,"Try increasing --timeout or check task status manually.")}var Au=I(()=>{oe();G();V();so()});import{existsSync as Ey,readFileSync as _y,statSync as Ty}from"fs";import{extname as Iy}from"path";function _u(e){let t=/^data:[^;,]+;base64,([\s\S]*)$/.exec(e);if(!t)return;let n=t[1].replace(/\s/g,""),i=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.max(0,Math.floor(n.length*3/4)-i)}function co(e,t){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mm_file://"))return e;if(e.startsWith("data:"))return t==="audio"?e.replace(/^data:audio\/mpeg;base64,/,"data:audio/mp3;base64,"):e;if(!Ey(e))throw new v(`File not found: ${e}`,x.USAGE);let n=Iy(e).toLowerCase(),i=Oy[t],r=i[n];if(!r){let l=Object.keys(i).map((c)=>c.slice(1)).join(", ");throw new v(`Unsupported ${t} format "${n}". Supported local files: ${l}`,x.USAGE)}let s=Et[t],o=Ty(e).size;if(o>s)throw new v(`${t[0].toUpperCase()}${t.slice(1)} file is ${(o/1024/1024).toFixed(1)} MB; MiniMax-H3 allows at most ${s/1024/1024} MB.`,x.USAGE,"Use a public URL or mm_file:// file ID for large media.");let a=_y(e);return`data:${r};base64,${a.toString("base64")}`}var Oy,Et,Eu=67108864;var uo=I(()=>{G();V();Oy={video:{".mp4":"video/mp4",".mov":"video/quicktime"},audio:{".mp3":"audio/mp3",".wav":"audio/wav"}},Et={image:31457280,video:52428800,audio:15728640}});function _t(e){return e===kn}function Tu(e){return _t(e.model)}function Iu(e){let t=e.error?.code?.trim(),n=e.error?.message?.trim();if(t&&n)return`${t}: ${n}`;return n||t}function Ou(e){let t=e.images??[];if(t.length>1&&t.some((o)=>!o.role))throw new te("Each image must specify a role when multiple images are provided.");let n=[{type:"text",text:e.prompt},...t.map((o)=>({type:"image_url",image_url:{url:o.url},role:o.role??"first_frame"})),...(e.referenceVideos??[]).map((o)=>({type:"video_url",video_url:{url:o},role:"reference_video"})),...(e.referenceAudios??[]).map((o)=>({type:"audio_url",audio_url:{url:o},role:"reference_audio"}))],i=n.some((o)=>o.type==="image_url"&&(o.role==="first_frame"||o.role==="last_frame")),r=n.some((o)=>o.type!=="text"&&o.role?.startsWith("reference_")),s={model:kn,content:n,resolution:e.resolution??"2K",duration:e.duration??5,ratio:i?"adaptive":e.ratio??(r?"adaptive":"16:9")};if(e.callbackUrl)s.callback_url=e.callbackUrl;return Cy(s),s}function Cy(e){if(!_t(e.model))throw new te(`Video Generation V2 only supports ${kn}.`);let t=e.content.filter((d)=>d.type==="text");if(!t.some((d)=>d.text.trim().length>0))throw new te("MiniMax-H3 requires a non-empty text content item.");if(t.some((d)=>d.text.length>7000))throw new te("MiniMax-H3 text content must not exceed 7000 characters.");if(e.resolution!=="2K")throw new te("MiniMax-H3 currently only supports 2K resolution.");if(!Number.isInteger(e.duration)||e.duration<4||e.duration>15)throw new te("MiniMax-H3 duration must be an integer from 4 to 15 seconds.");if(e.ratio&&!My.has(e.ratio))throw new te("MiniMax-H3 ratio must be one of: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, 9:16.");let n=e.content.filter((d)=>d.type==="image_url"),i=e.content.filter((d)=>d.type==="video_url"),r=e.content.filter((d)=>d.type==="audio_url");if(n.some((d)=>d.role&&!Ny.has(d.role)))throw new te("MiniMax-H3 image role must be one of: first_frame, last_frame, reference_image.");if(i.some((d)=>d.role!=="reference_video"))throw new te("MiniMax-H3 video role must be reference_video.");if(r.some((d)=>d.role!=="reference_audio"))throw new te("MiniMax-H3 audio role must be reference_audio.");for(let d of n)fo(d.image_url.url,"image");for(let d of i)fo(d.video_url.url,"video");for(let d of r)fo(d.audio_url.url,"audio");let s=Buffer.byteLength(JSON.stringify(e));if(s>Eu)throw new te(`MiniMax-H3 request body is ${(s/1024/1024).toFixed(1)} MB; the maximum is 64 MB. Use public URLs or mm_file:// file IDs instead of Base64.`);let o=n.filter((d)=>!d.role||d.role==="first_frame"),a=n.filter((d)=>d.role==="last_frame"),l=n.filter((d)=>d.role==="reference_image"),c=o.length>0||a.length>0,f=l.length>0||i.length>0||r.length>0;if(o.length>1||a.length>1)throw new te("MiniMax-H3 accepts at most one first frame and one last frame.");if(l.length>9||i.length>3||r.length>3)throw new te("MiniMax-H3 accepts up to 9 reference images, 3 reference videos, and 3 reference audios.");if(c&&f)throw new te("MiniMax-H3 frame inputs and reference inputs cannot be used together.");if(r.length>0&&l.length===0&&i.length===0)throw new te("MiniMax-H3 reference audio requires at least one reference image or reference video.");if(e.content.every((d)=>d.type==="text")&&(!e.ratio||e.ratio==="adaptive"))throw new te("MiniMax-H3 text-to-video requires a concrete ratio; adaptive is not supported.")}function fo(e,t){let n=_u(e),i=Et[t];if(n!==void 0&&n>i)throw new te(`MiniMax-H3 ${t} input is ${(n/1024/1024).toFixed(1)} MB; the maximum is ${i/1024/1024} MB.`)}var kn="MiniMax-H3",My,Ny,te;var po=I(()=>{uo();My=new Set(["adaptive","21:9","16:9","4:3","1:1","3:4","9:16"]),Ny=new Set(["first_frame","last_frame","reference_image"]);te=class te extends Error{constructor(e){super(e);this.name="VideoV2InputError"}}});var Mu;var Nu=I(()=>{J();G();V();oe();Au();Qi();z();Zi();uo();Ve();po();Mu=R({name:"video generate",description:`Generate a video
209
277
  V2: MiniMax-H3 (text/image/video/audio content, 2K)
210
278
  T2V: Hailuo-2.3
211
279
  I2V: Hailuo-2.3 (default) / Hailuo-2.3-Fast (fast mode, requires --image)
212
280
  SEF: Hailuo-02 (requires --image and --last-frame)
213
- S2V: S2V-01 (requires --subject-image)`,apiDocs:"/docs/api-reference/video-generation-v2-create",usage:"mmx video generate --prompt <text> [flags]",options:[{flag:"--model <model>",description:"Model ID. V2: MiniMax-H3. Legacy: MiniMax-Hailuo-2.3 or MiniMax-Hailuo-2.3-Fast. Auto-switched to Hailuo-02 with --last-frame, or S2V-01 with --subject-image."},{flag:"--prompt <text>",description:"Video description",required:!0},{flag:"--image <path-or-url>",description:"Input image for image-to-video (local path or URL)."},{flag:"--first-frame <path-or-url>",description:"Backward-compatible alias for --image.",hidden:!0},{flag:"--last-frame <path-or-url>",description:"Optional ending image. Legacy SEF also requires --image; MiniMax-H3 supports a last frame alone."},{flag:"--subject-image <path-or-url>",description:"Subject reference image for character consistency (local path or URL). Switches to S2V-01 model."},{flag:"--reference-image <path-or-url>",description:"H3 reference image (repeatable).",type:"array"},{flag:"--reference-video <path-or-url>",description:"H3 reference video (repeatable; local MP4/MOV, URL, data URI, or mm_file:// ID).",type:"array"},{flag:"--reference-audio <path-or-url>",description:"H3 reference audio (repeatable; requires a reference image or video).",type:"array"},{flag:"--duration <seconds>",description:"Output duration. H3 supports integer values from 4 to 15 (default: 5).",type:"number"},{flag:"--ratio <ratio>",description:"H3 aspect ratio: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, or 9:16."},{flag:"--callback-url <url>",description:"Webhook URL for completion notification"},{flag:"--download <path>",description:"Save video to file on completion"},{flag:"--no-wait",description:"Return task ID immediately without waiting"},{flag:"--async",description:"Return task ID immediately (agent/CI mode, same as --no-wait but explicit)"},{flag:"--poll-interval <seconds>",description:"Polling interval when waiting (default: 5)",type:"number"}],examples:['mmx video generate --prompt "A man reads a book. Static shot."','mmx video generate --prompt "Ocean waves at sunset." --download sunset.mp4','mmx video generate --prompt "A robot painting." --async --quiet','mmx video generate --prompt "A robot painting." --no-wait --quiet',"# H3 text-to-video (Video Generation V2)",'mmx video generate --model MiniMax-H3 --prompt "Ocean waves at sunset"',"# H3 image-to-video",'mmx video generate --model MiniMax-H3 --prompt "The subject walks forward" --image start.jpg',"# H3 reference-to-video",'mmx video generate --model MiniMax-H3 --prompt "Keep the same character" --reference-image character.png --reference-video motion.mp4',"# SEF: first + last frame interpolation (uses Hailuo-02 model)",'mmx video generate --prompt "Walk forward" --image start.jpg --last-frame end.jpg',"# Subject reference: character consistency (uses S2V-01 model)",'mmx video generate --prompt "A detective walking" --subject-image character.jpg'],async run(e,t){let o=t.prompt;o=await it({value:o,message:"Enter your video prompt:",cancelMessage:"Video generation cancelled.",flagName:"prompt",usageHint:"mmx video generate --prompt <text>",nonInteractive:e.nonInteractive});let n=t.model,i=e.defaultVideoModel||"MiniMax-Hailuo-2.3",s=t.image,r=t.firstFrame;if(s&&r)throw new m("--image and --first-frame are aliases; provide only one.",d.USAGE);let u=s??r,a=Boolean(t.referenceImage||t.referenceVideo||t.referenceAudio||t.duration!==void 0||t.ratio),l;if(n)l=n;else if(ke(i))l=He;else if(t.lastFrame)l="MiniMax-Hailuo-02";else if(t.subjectImage)l="S2V-01";else l=i;if(t.lastFrame&&t.subjectImage)throw new m("--last-frame and --subject-image cannot be used together (SEF and S2V are different modes).",d.USAGE,"mmx video generate --prompt <text> --image <path> --last-frame <path>");if(n==="MiniMax-Hailuo-2.3-Fast"&&!u)throw new m("MiniMax-Hailuo-2.3-Fast only supports I2V (image-to-video). Use --image to provide an input image.",d.USAGE,"mmx video generate --prompt <text> --model MiniMax-Hailuo-2.3-Fast --image <path>");let p;if(ke(l)){if(t.subjectImage)throw new m("--subject-image is only supported by the legacy S2V-01 model. Use --reference-image for MiniMax-H3.",d.USAGE,"mmx video generate --model MiniMax-H3 --prompt <text> --reference-image <path>");let ie=[...u?[{url:Ae(u,Se.image),role:"first_frame"}]:[],...t.lastFrame?[{url:Ae(t.lastFrame,Se.image),role:"last_frame"}]:[],...(t.referenceImage??[]).map((j)=>({url:Ae(j,Se.image),role:"reference_image"}))];try{p=Zn({prompt:o,images:ie,referenceVideos:(t.referenceVideo??[]).map((j)=>Cr(j,"video")),referenceAudios:(t.referenceAudio??[]).map((j)=>Cr(j,"audio")),duration:t.duration,ratio:t.ratio,callbackUrl:t.callbackUrl})}catch(j){if(j instanceof q)throw new m(j.message,d.USAGE,"mmx video generate --model MiniMax-H3 --prompt <text>");throw j}}else{if(a)throw new m("--reference-image, --reference-video, --reference-audio, --duration, and --ratio require --model MiniMax-H3.",d.USAGE);if(p={model:l,prompt:o},u)p.first_frame_image=Ae(u);if(t.lastFrame){if(!u)throw new m("--last-frame requires --image (SEF mode).",d.USAGE,"mmx video generate --prompt <text> --image <path> --last-frame <path>");p.last_frame_image=Ae(t.lastFrame)}if(t.subjectImage)p.subject_reference=[{type:"character",image:[Ae(t.subjectImage)]}];if(t.callbackUrl)p.callback_url=t.callbackUrl}if(le(e,p))return;let f=_(e.output),D=Xn(p),h=D?Mo(e.baseUrl):To(e.baseUrl),x=(await A(e,{url:h,method:"POST",body:p})).task_id;if(!e.quiet)process.stderr.write(`[Model: ${l}]
214
- `);if(t.noWait||e.async){process.stdout.write(JSON.stringify({taskId:x})),process.stdout.write(`
215
- `);return}let g=t.pollInterval??5,y,v,k;if(D){let ie=dt(e.baseUrl,x),j=await gr(e,{url:ie,intervalSec:g,timeoutSec:e.timeout,isComplete:(ce)=>ce.task.status==="succeeded",isFailed:(ce)=>["failed","cancelled","expired"].includes(ce.task.status),getStatus:(ce)=>ce.task.status,getFailureReason:(ce)=>Qn(ce.task)});k=j.task.status,y=j.task.content?.url}else{let ie=mt(e.baseUrl,x),j=await gr(e,{url:ie,intervalSec:g,timeoutSec:e.timeout,isComplete:(Ne)=>Ne.status==="Success",isFailed:(Ne)=>Ne.status==="Failed",getStatus:(Ne)=>Ne.status});if(k=j.status,v=j.file_id,!v)throw new m("Task completed but no file_id returned.",d.GENERAL);y=(await A(e,{url:pt(e.baseUrl,v)})).file?.download_url}if(!y)throw new m("No download URL available for this file.",d.GENERAL);if(t.download){let ie=t.download,{size:j}=await ge(y,ie,{quiet:e.quiet});if(e.quiet)console.log(ie);else console.log(F({task_id:x,status:k,file_id:v,saved:ie,size:Et(j)},f));return}let B=await import("os"),{join:M}=await import("path"),I=M(B.tmpdir(),"mmx-video"),{existsSync:We,mkdirSync:Pe}=await import("fs");if(!We(I))Pe(I,{recursive:!0});let Ke=M(I,`${x}.mp4`);await ge(y,Ke,{quiet:e.quiet}),process.stdout.write(Ke),process.stdout.write(`
216
- `)}})});var ri;var oi=C(()=>{T();R();S();V();N();Er();ri=w({name:"video task get",description:"Query video task status",usage:"mmx video task get --task-id <id>",options:[{flag:"--task-id <id>",description:"Video generation task ID"},{flag:"--model <model>",description:"Use MiniMax-H3 for Video Generation V2 tasks; defaults to the legacy V1 query."}],examples:["mmx video task get --task-id 106916112212032","mmx video task get --task-id 106916112212032 --output json","mmx video task get --task-id 424010985738629 --model MiniMax-H3 --output json"],async run(e,t){let o=t.taskId;if(!o)throw new m("--task-id is required.",d.USAGE,"mmx video task get --task-id <id>");if(e.dryRun){console.log(`Would query task: ${o}`);return}let n=_(e.output),i=t.model;if(ke(i)){let u=dt(e.baseUrl,o),l=(await A(e,{url:u})).task;if(e.quiet){console.log(l.status);return}console.log(F({task_id:l.id,model:l.model,status:l.status,url:l.content?.url,resolution:l.resolution,duration:l.duration,ratio:l.ratio,error:l.error},n));return}let s=mt(e.baseUrl,o),r=await A(e,{url:s});if(e.quiet){console.log(r.status);return}console.log(F({task_id:r.task_id,status:r.status,file_id:r.file_id,video_width:r.video_width,video_height:r.video_height},n))}})});var ni;var ii=C(()=>{T();R();S();V();Ft();N();ni=w({name:"video download",description:"Download a completed video by file ID",usage:"mmx video download --file-id <id> --out <path>",options:[{flag:"--file-id <id>",description:"File ID to download"},{flag:"--out <path>",description:"Output file path"}],examples:["mmx video download --file-id 176844028768320 --out video.mp4","mmx video download --file-id 176844028768320 --out video.mp4 --quiet"],async run(e,t){let o=t.fileId;if(!o)throw new m("--file-id is required.",d.USAGE,"mmx video download --file-id <id> --out <path>");let n=t.out;if(!n)throw new m("--out is required.",d.USAGE,"mmx video download --file-id <id> --out video.mp4");if(e.dryRun){console.log(`Would download file ${o} to ${n}`);return}let i=pt(e.baseUrl,o),r=(await A(e,{url:i})).file?.download_url;if(!r)throw new m("No download URL available for this file.",d.GENERAL,"The file may still be processing. Check task status first.");let{size:u}=await ge(r,n,{quiet:e.quiet}),a=_(e.output);if(e.quiet){console.log(n);return}console.log(F({saved:n,size:Et(u)},a))}})});var Fr;var si=C(()=>{T();V();N();R();S();Fr=w({name:"search query",description:"Search the web via MiniMax. Note: the underlying /v1/coding_plan/search API returns at most 10 results per call and does not currently support pagination, so refining your --q is the only way to see different results.",usage:"mmx search query --q <query>",options:[{flag:"--q <query>",description:"Search query string"}],examples:['mmx search query --q "MiniMax AI"','mmx search query --q "latest news" --output json'],async run(e,t){let o=t.q??t.query??t._positional?.[0];if(!o)throw new m("--q is required.",d.USAGE,'mmx search query --q "your search query"');let n=_(e.output);if(e.dryRun){console.log(F({request:{q:o}},n));return}let i=Oo(e.baseUrl),s=await A(e,{url:i,method:"POST",body:{q:o}}),r=s.organic||[];if(n!=="text"){console.log(F(s,n));return}if(e.quiet){for(let u of r)console.log(`${u.title} ${u.link}`);return}if(r.length===0){console.log("No results found.");return}for(let u of r){if(console.log(`${u.title}`),console.log(` ${u.link}`),u.snippet)console.log(` ${u.snippet}`);if(u.date)console.log(` ${u.date}`);console.log("")}}})});var ui;var ai=C(()=>{T();V();N();R();S();pe();wt();ui=w({name:"vision describe",description:"Describe an image using MiniMax VLM",usage:"mmx vision describe (--image <path-or-url> | --file-id <id>) [--prompt <text>]",options:[{flag:"--image <path-or-url>",description:"Local image path or URL (base64 encoded automatically)"},{flag:"--file-id <id>",description:"Pre-uploaded file ID (skips base64 conversion)"},{flag:"--prompt <text>",description:'Question about the image (default: "Describe the image.")'}],examples:["mmx vision describe --image photo.jpg",'mmx vision describe --image https://example.com/photo.jpg --prompt "What breed is this dog?"','mmx vision describe --file-id file-123456789 --prompt "Extract the text"'],async run(e,t){let o=t.image??t.file??t.path??t._positional?.[0],n=t.fileId,i=t.prompt||"Describe the image.";if(!o&&!n)if(G({nonInteractive:e.nonInteractive})){let l=await te({message:"Enter image path, URL, or File ID:"});if(!l)process.stderr.write(`Vision describe cancelled.
217
- `),process.exit(1);if(!l.includes(".")&&!l.startsWith("http"))n=l;else o=l}else throw new m("Missing required argument. Must provide either --image or --file-id.",d.USAGE,"mmx vision describe --image <path> OR --file-id <id>");else if(o&&n)throw new m("Conflicting arguments: cannot provide both --image and --file-id.",d.USAGE);if(le(e,{prompt:i,image:o,fileId:n}))return;let s=_(e.output),r=Po(e.baseUrl),u={prompt:i};if(n)u.file_id=n;else if(o){let l=await qn(o);u.image_url=l}let a=await A(e,{url:r,method:"POST",body:u});if(s!=="text"){process.stdout.write(F(a,s)+`
218
- `);return}process.stdout.write(a.content+`
219
- `)}})});var ci;var li=C(()=>{T();V();N();ft();ci=w({name:"quota show",description:"Display Token Plan usage and remaining quotas",usage:"mmx quota show",examples:["mmx quota show","mmx quota show --output json"],async run(e,t){if(e.dryRun){console.log("Would fetch quota information.");return}let o=_(t.output),n=e.apiKey||e.fileApiKey;if(n&&n.startsWith("sk-api-")){let u=ne(e.baseUrl,n),a=await A(e,{url:u});if(o!=="text"){console.log(F(a,o));return}ue(a,e,n);return}let i=$e(e.baseUrl),s=await A(e,{url:i}),r=s.model_remains||[];if(o!=="text"){console.log(F(s,o));return}if(e.quiet){for(let u of r){let a=u.current_interval_total_count-u.current_interval_usage_count;console.log(`${u.model_name} ${u.current_interval_usage_count} ${u.current_interval_total_count} ${a}`)}return}ue(s,e)}})});var mi;var di=C(()=>{T();se();Ie();N();mi=w({name:"config show",description:"Display current configuration",usage:"mmx config show",examples:["mmx config show","mmx config show --output json"],async run(e,t){let o=P(),n=_(e.output),i={region:e.region,base_url:e.baseUrl,output:e.output,timeout:e.timeout,config_file:oe()};if(o.api_key)i.api_key=J(o.api_key);if(o.default_text_model)i.default_text_model=o.default_text_model;if(o.default_speech_model)i.default_speech_model=o.default_speech_model;if(o.default_video_model)i.default_video_model=o.default_video_model;if(o.proxy)i.proxy=o.proxy;console.log(F(i,n))}})});function Di(e,t){return e==="api_key"?J(String(t)):t}var pi,Va,fi;var hi=C(()=>{T();R();S();N();se();pi=["region","base_url","output","timeout","api_key","proxy","default_text_model","default_speech_model","default_video_model"],Va={"default-text-model":"default_text_model","default-speech-model":"default_speech_model","default-video-model":"default_video_model"};fi=w({name:"config set",description:"Set a config value",usage:"mmx config set --key <key> --value <value>",options:[{flag:"--key <key>",description:"Config key (region, base_url, output, timeout, api_key, proxy, default_text_model, default_speech_model, default_video_model)"},{flag:"--value <value>",description:"Value to set"}],examples:["mmx config set --key output --value json","mmx config set --key timeout --value 600","mmx config set --key proxy --value http://127.0.0.1:7890","mmx config set --key base_url --value https://api-uw.minimax.io"],async run(e,t){let o=t._positional,n=t.key??o?.[0],i=t.value??o?.[1];if(!n||i===void 0)throw new m("--key and --value are required.",d.USAGE,"mmx config set --key <key> --value <value>");let s=Va[n]||n;if(!pi.includes(s))throw new m(`Invalid config key "${n}". Valid keys: ${pi.join(", ")}`,d.USAGE);let r=s==="api_key"?i.trim():i;if(s==="api_key"&&r.length===0)throw new m("Invalid api_key. The value must not be empty.",d.USAGE);if(s==="region"&&!["global","cn"].includes(i))throw new m(`Invalid region "${i}". Valid values: global, cn`,d.USAGE);if(s==="output"&&!["text","json"].includes(i))throw new m(`Invalid output format "${i}". Valid values: text, json`,d.USAGE);if(s==="base_url"&&!i.startsWith("http"))throw new m(`Invalid base_url "${i}". Must start with http.`,d.USAGE);if(s==="proxy"&&!i.startsWith("http"))throw new m(`Invalid proxy "${i}". Must be a URL starting with http (e.g. http://127.0.0.1:7890).`,d.USAGE);if(s==="timeout"){let l=Number(i);if(isNaN(l)||l<=0)throw new m(`Invalid timeout "${i}". Must be a positive number.`,d.USAGE)}let u=_(e.output);if(e.dryRun){console.log(F({would_set:{[s]:Di(s,r)}},u));return}let a=P();if(a[s]=s==="timeout"?Number(r):r,s==="api_key")delete a.oauth,delete a.region;if(await K(a),!e.quiet)console.log(F({[s]:Di(s,a[s])},u))}})});function ja(e){let t=e.match(/^--([a-zA-Z0-9-]+)/),o=t?t[1]:"",n=o.replace(/-([a-zA-Z0-9])/g,(r,u)=>u.toUpperCase()),i="string",s=!1;if(!e.includes("<")&&!e.includes("["))i="boolean";else if(e.includes("<n>")||e.includes("<hz>")||e.includes("<bps>")||e.includes("<count>"))i="number";if(e.toLowerCase().includes("repeatable"))s=!0;return{name:n,kebabName:o,inferredType:i,isArray:s}}function xr(e){let o={name:`mmx_${e.name.replace(/ /g,"_")}`,description:e.description,input_schema:{type:"object",properties:{},required:[]}};if(e.options)for(let n of e.options){if(n.hidden)continue;let{name:i,inferredType:s,isArray:r}=ja(n.flag);if(!i)continue;let u=n.type,a=r?"array":u??s,l={description:n.description};if(a==="array")l.type="array",l.items={type:"string"};else l.type=a;let p=o.input_schema;if(p.properties[i]=l,n.required)p.required.push(i)}return o}var Ha,gi;var Ci=C(()=>{T();gt();R();S();Ha=["auth ","config ","update"],gi=w({name:"config export-schema",description:"Export all (or one) CLI command(s) as Anthropic/OpenAI-compatible JSON tool schemas",usage:'mmx config export-schema [--command "<name>"]',options:[{flag:"--command <name>",description:'Export schema for a specific command only (e.g. "image generate")'}],examples:["mmx config export-schema",'mmx config export-schema --command "video generate"'],async run(e,t){let o=t.command;if(o){try{let{command:s}=ae.resolve(o.split(" ")),r=xr(s);process.stdout.write(JSON.stringify(r,null,2)+`
220
- `)}catch{throw new m(`Command "${o}" not found.`,d.USAGE)}return}let i=ae.getAllCommands().filter((s)=>!Ha.some((r)=>s.name.startsWith(r))).map((s)=>xr(s));process.stdout.write(JSON.stringify(i,null,2)+`
221
- `)}})});import{existsSync as Wa}from"fs";import{readFile as Ka}from"fs/promises";import{resolve as za,basename as Ja}from"path";var yi;var bi=C(()=>{T();R();S();V();N();pe();yi=w({name:"file upload",description:"Upload a file to MiniMax storage",usage:"mmx file upload --file <path> [--purpose <purpose>]",options:[{flag:"--file <path>",description:"Local path to the file",required:!0},{flag:"--purpose <string>",description:"File purpose (default: retrieval)"}],examples:["mmx file upload --file doc.pdf","mmx file upload --file image.png --purpose vision"],async run(e,t){let o=t.file;if(!o)if(G({nonInteractive:e.nonInteractive})){if(o=await te({message:"Enter file path:"}),!o)process.stderr.write(`Upload cancelled.
222
- `),process.exit(1)}else xe("file","mmx file upload --file <path>");let n=za(o);if(!Wa(n))throw new m(`File not found: ${n}`,d.USAGE);let i=t.purpose||"retrieval",s=_(e.output);if(e.dryRun){process.stdout.write(F({request:{file:n,purpose:i}},s)+`
223
- `);return}let r=new FormData,u=await Ka(n),a=Ja(n),l=new Blob([u]);r.append("file",l,a),r.append("purpose",i);let p=No(e.baseUrl),f=await A(e,{url:p,method:"POST",body:r});if(e.quiet){process.stdout.write(f.file.file_id+`
224
- `);return}process.stdout.write(F(f.file,s)+`
225
- `)}})});var Ei;var Fi=C(()=>{T();V();N();Ei=w({name:"file list",description:"List uploaded files in MiniMax storage",usage:"mmx file list",examples:["mmx file list","mmx file list --output json"],async run(e,t){let o=_(e.output);if(e.dryRun){process.stdout.write(`Would list uploaded files.
226
- `);return}let n=Lo(e.baseUrl),i=await A(e,{url:n,method:"GET"});if(o!=="text"){process.stdout.write(F(i,o)+`
227
- `);return}if(!i.files||i.files.length===0){process.stdout.write(`No files found.
228
- `);return}let s=i.files.map((u)=>({ID:u.file_id,FILENAME:u.filename,PURPOSE:u.purpose,SIZE_KB:(u.bytes/1024).toFixed(1),CREATED:new Date(u.created_at*1000).toISOString().slice(0,16).replace("T"," ")})),{formatTable:r}=await Promise.resolve().then(() => Ir);process.stdout.write(r(s)+`
229
- `)}})});var xi;var wi=C(()=>{T();V();N();pe();xi=w({name:"file delete",description:"Delete an uploaded file from MiniMax storage",usage:"mmx file delete --file-id <id>",options:[{flag:"--file-id <id>",description:"ID of the file to delete",required:!0}],examples:["mmx file delete --file-id 123456789"],async run(e,t){let o=t.fileId;if(!o)if(G({nonInteractive:e.nonInteractive})){if(o=await te({message:"Enter file ID to delete:"}),!o)process.stderr.write(`Delete cancelled.
230
- `),process.exit(1)}else xe("file-id","mmx file delete --file-id <id>");let n=_(e.output);if(e.dryRun){process.stdout.write(F({request:{delete_file:o}},n)+`
231
- `);return}let i=Uo(e.baseUrl),s=await A(e,{url:i,method:"POST",body:{file_id:Number(o)}});if(e.quiet){process.stdout.write(`deleted
232
- `);return}process.stdout.write(F({file_id:s.file_id,deleted:!0},n)+`
233
- `)}})});var vi;var $i=C(()=>{T();ct();vi=w({name:"update",description:"Update mmx to the latest version",usage:"mmx update",examples:["mmx update"],async run(){process.stderr.write(`Current version: ${we}
281
+ S2V: S2V-01 (requires --subject-image)`,apiDocs:"/docs/api-reference/video-generation-v2-create",usage:"mmx video generate --prompt <text> [flags]",options:[{flag:"--model <model>",description:"Model ID. V2: MiniMax-H3. Legacy: MiniMax-Hailuo-2.3 or MiniMax-Hailuo-2.3-Fast. Auto-switched to Hailuo-02 with --last-frame, or S2V-01 with --subject-image."},{flag:"--prompt <text>",description:"Video description",required:!0},{flag:"--image <path-or-url>",description:"Input image for image-to-video (local path or URL)."},{flag:"--first-frame <path-or-url>",description:"Backward-compatible alias for --image.",hidden:!0},{flag:"--last-frame <path-or-url>",description:"Optional ending image. Legacy SEF also requires --image; MiniMax-H3 supports a last frame alone."},{flag:"--subject-image <path-or-url>",description:"Subject reference image for character consistency (local path or URL). Switches to S2V-01 model."},{flag:"--reference-image <path-or-url>",description:"H3 reference image (repeatable).",type:"array"},{flag:"--reference-video <path-or-url>",description:"H3 reference video (repeatable; local MP4/MOV, URL, data URI, or mm_file:// ID).",type:"array"},{flag:"--reference-audio <path-or-url>",description:"H3 reference audio (repeatable; requires a reference image or video).",type:"array"},{flag:"--duration <seconds>",description:"Output duration. H3 supports integer values from 4 to 15 (default: 5).",type:"number"},{flag:"--ratio <ratio>",description:"H3 aspect ratio: adaptive, 21:9, 16:9, 4:3, 1:1, 3:4, or 9:16."},{flag:"--callback-url <url>",description:"Webhook URL for completion notification"},{flag:"--download <path>",description:"Save video to file on completion"},{flag:"--no-wait",description:"Return task ID immediately without waiting"},{flag:"--async",description:"Return task ID immediately (agent/CI mode, same as --no-wait but explicit)"},{flag:"--poll-interval <seconds>",description:"Polling interval when waiting (default: 5)",type:"number"}],examples:['mmx video generate --prompt "A man reads a book. Static shot."','mmx video generate --prompt "Ocean waves at sunset." --download sunset.mp4','mmx video generate --prompt "A robot painting." --async --quiet','mmx video generate --prompt "A robot painting." --no-wait --quiet',"# H3 text-to-video (Video Generation V2)",'mmx video generate --model MiniMax-H3 --prompt "Ocean waves at sunset"',"# H3 image-to-video",'mmx video generate --model MiniMax-H3 --prompt "The subject walks forward" --image start.jpg',"# H3 reference-to-video",'mmx video generate --model MiniMax-H3 --prompt "Keep the same character" --reference-image character.png --reference-video motion.mp4',"# SEF: first + last frame interpolation (uses Hailuo-02 model)",'mmx video generate --prompt "Walk forward" --image start.jpg --last-frame end.jpg',"# Subject reference: character consistency (uses S2V-01 model)",'mmx video generate --prompt "A detective walking" --subject-image character.jpg'],async run(e,t){let n=t.prompt;n=await Ni({value:n,message:"Enter your video prompt:",cancelMessage:"Video generation cancelled.",flagName:"prompt",usageHint:"mmx video generate --prompt <text>",nonInteractive:e.nonInteractive});let i=t.model,r=e.defaultVideoModel||"MiniMax-Hailuo-2.3",s=t.image,o=t.firstFrame;if(s&&o)throw new v("--image and --first-frame are aliases; provide only one.",x.USAGE);let a=s??o,l=Boolean(t.referenceImage||t.referenceVideo||t.referenceAudio||t.duration!==void 0||t.ratio),c;if(i)c=i;else if(_t(r))c=kn;else if(t.lastFrame)c="MiniMax-Hailuo-02";else if(t.subjectImage)c="S2V-01";else c=r;if(t.lastFrame&&t.subjectImage)throw new v("--last-frame and --subject-image cannot be used together (SEF and S2V are different modes).",x.USAGE,"mmx video generate --prompt <text> --image <path> --last-frame <path>");if(i==="MiniMax-Hailuo-2.3-Fast"&&!a)throw new v("MiniMax-Hailuo-2.3-Fast only supports I2V (image-to-video). Use --image to provide an input image.",x.USAGE,"mmx video generate --prompt <text> --model MiniMax-Hailuo-2.3-Fast --image <path>");let f;if(_t(c)){if(t.subjectImage)throw new v("--subject-image is only supported by the legacy S2V-01 model. Use --reference-image for MiniMax-H3.",x.USAGE,"mmx video generate --model MiniMax-H3 --prompt <text> --reference-image <path>");let P=[...a?[{url:At(a,Et.image),role:"first_frame"}]:[],...t.lastFrame?[{url:At(t.lastFrame,Et.image),role:"last_frame"}]:[],...(t.referenceImage??[]).map((L)=>({url:At(L,Et.image),role:"reference_image"}))];try{f=Ou({prompt:n,images:P,referenceVideos:(t.referenceVideo??[]).map((L)=>co(L,"video")),referenceAudios:(t.referenceAudio??[]).map((L)=>co(L,"audio")),duration:t.duration,ratio:t.ratio,callbackUrl:t.callbackUrl})}catch(L){if(L instanceof te)throw new v(L.message,x.USAGE,"mmx video generate --model MiniMax-H3 --prompt <text>");throw L}}else{if(l)throw new v("--reference-image, --reference-video, --reference-audio, --duration, and --ratio require --model MiniMax-H3.",x.USAGE);if(f={model:c,prompt:n},a)f.first_frame_image=At(a);if(t.lastFrame){if(!a)throw new v("--last-frame requires --image (SEF mode).",x.USAGE,"mmx video generate --prompt <text> --image <path> --last-frame <path>");f.last_frame_image=At(t.lastFrame)}if(t.subjectImage)f.subject_reference=[{type:"character",image:[At(t.subjectImage)]}];if(t.callbackUrl)f.callback_url=t.callbackUrl}if(Je(e,f))return;let u=F(e.output),d=Tu(f),g=d?fc(e.baseUrl):uc(e.baseUrl),p=(await j(e,{url:g,method:"POST",body:f})).task_id;if(!e.quiet)process.stderr.write(`[Model: ${c}]
282
+ `);if(t.noWait||e.async){process.stdout.write(JSON.stringify({taskId:p})),process.stdout.write(`
283
+ `);return}let m=t.pollInterval??5,b,w,S;if(d){let P=Di(e.baseUrl,p),L=await lo(e,{url:P,intervalSec:m,timeoutSec:e.timeout,isComplete:(D)=>D.task.status==="succeeded",isFailed:(D)=>["failed","cancelled","expired"].includes(D.task.status),getStatus:(D)=>D.task.status,getFailureReason:(D)=>Iu(D.task)});S=L.task.status,b=L.task.content?.url}else{let P=Fi(e.baseUrl,p),L=await lo(e,{url:P,intervalSec:m,timeoutSec:e.timeout,isComplete:(U)=>U.status==="Success",isFailed:(U)=>U.status==="Failed",getStatus:(U)=>U.status});if(S=L.status,w=L.file_id,!w)throw new v("Task completed but no file_id returned.",x.GENERAL);b=(await j(e,{url:Ui(e.baseUrl,w)})).file?.download_url}if(!b)throw new v("No download URL available for this file.",x.GENERAL);if(t.download){let P=t.download,{size:L}=await it(b,P,{quiet:e.quiet});if(e.quiet)console.log(P);else console.log(N({task_id:p,status:S,file_id:w,saved:P,size:zi(L)},u));return}let _=await import("os"),{join:E}=await import("path"),A=E(_.tmpdir(),"mmx-video"),{existsSync:k,mkdirSync:T}=await import("fs");if(!k(A))T(A,{recursive:!0});let C=E(A,`${p}.mp4`);await it(b,C,{quiet:e.quiet}),process.stdout.write(C),process.stdout.write(`
284
+ `)}})});var Cu;var Ru=I(()=>{J();G();V();oe();z();po();Cu=R({name:"video task get",description:"Query video task status",usage:"mmx video task get --task-id <id>",options:[{flag:"--task-id <id>",description:"Video generation task ID"},{flag:"--model <model>",description:"Use MiniMax-H3 for Video Generation V2 tasks; defaults to the legacy V1 query."}],examples:["mmx video task get --task-id 106916112212032","mmx video task get --task-id 106916112212032 --output json","mmx video task get --task-id 424010985738629 --model MiniMax-H3 --output json"],async run(e,t){let n=t.taskId;if(!n)throw new v("--task-id is required.",x.USAGE,"mmx video task get --task-id <id>");if(e.dryRun){console.log(`Would query task: ${n}`);return}let i=F(e.output),r=t.model;if(_t(r)){let a=Di(e.baseUrl,n),c=(await j(e,{url:a})).task;if(e.quiet){console.log(c.status);return}console.log(N({task_id:c.id,model:c.model,status:c.status,url:c.content?.url,resolution:c.resolution,duration:c.duration,ratio:c.ratio,error:c.error},i));return}let s=Fi(e.baseUrl,n),o=await j(e,{url:s});if(e.quiet){console.log(o.status);return}console.log(N({task_id:o.task_id,status:o.status,file_id:o.file_id,video_width:o.video_width,video_height:o.video_height},i))}})});var Lu;var Pu=I(()=>{J();G();V();oe();Qi();z();Lu=R({name:"video download",description:"Download a completed video by file ID",usage:"mmx video download --file-id <id> --out <path>",options:[{flag:"--file-id <id>",description:"File ID to download"},{flag:"--out <path>",description:"Output file path"}],examples:["mmx video download --file-id 176844028768320 --out video.mp4","mmx video download --file-id 176844028768320 --out video.mp4 --quiet"],async run(e,t){let n=t.fileId;if(!n)throw new v("--file-id is required.",x.USAGE,"mmx video download --file-id <id> --out <path>");let i=t.out;if(!i)throw new v("--out is required.",x.USAGE,"mmx video download --file-id <id> --out video.mp4");if(e.dryRun){console.log(`Would download file ${n} to ${i}`);return}let r=Ui(e.baseUrl,n),o=(await j(e,{url:r})).file?.download_url;if(!o)throw new v("No download URL available for this file.",x.GENERAL,"The file may still be processing. Check task status first.");let{size:a}=await it(o,i,{quiet:e.quiet}),l=F(e.output);if(e.quiet){console.log(i);return}console.log(N({saved:i,size:zi(a)},l))}})});var mo;var qu=I(()=>{J();oe();z();G();V();mo=R({name:"search query",description:"Search the web via MiniMax. Note: the underlying /v1/coding_plan/search API returns at most 10 results per call and does not currently support pagination, so refining your --q is the only way to see different results.",usage:"mmx search query --q <query>",options:[{flag:"--q <query>",description:"Search query string"}],examples:['mmx search query --q "MiniMax AI"','mmx search query --q "latest news" --output json'],async run(e,t){let n=t.q??t.query??t._positional?.[0];if(!n)throw new v("--q is required.",x.USAGE,'mmx search query --q "your search query"');let i=F(e.output);if(e.dryRun){console.log(N({request:{q:n}},i));return}let r=dc(e.baseUrl),s=await j(e,{url:r,method:"POST",body:{q:n}}),o=s.organic||[];if(i!=="text"){console.log(N(s,i));return}if(e.quiet){for(let a of o)console.log(`${a.title} ${a.link}`);return}if(o.length===0){console.log("No results found.");return}for(let a of o){if(console.log(`${a.title}`),console.log(` ${a.link}`),a.snippet)console.log(` ${a.snippet}`);if(a.date)console.log(` ${a.date}`);console.log("")}}})});var Fu;var Du=I(()=>{J();oe();z();G();V();Ve();Zi();Fu=R({name:"vision describe",description:"Describe an image using MiniMax VLM",usage:"mmx vision describe (--image <path-or-url> | --file-id <id>) [--prompt <text>]",options:[{flag:"--image <path-or-url>",description:"Local image path or URL (base64 encoded automatically)"},{flag:"--file-id <id>",description:"Pre-uploaded file ID (skips base64 conversion)"},{flag:"--prompt <text>",description:'Question about the image (default: "Describe the image.")'}],examples:["mmx vision describe --image photo.jpg",'mmx vision describe --image https://example.com/photo.jpg --prompt "What breed is this dog?"','mmx vision describe --file-id file-123456789 --prompt "Extract the text"'],async run(e,t){let n=t.image??t.file??t.path??t._positional?.[0],i=t.fileId,r=t.prompt||"Describe the image.";if(!n&&!i)if(Y({nonInteractive:e.nonInteractive})){let c=await Ie({message:"Enter image path, URL, or File ID:"});if(!c)process.stderr.write(`Vision describe cancelled.
285
+ `),process.exit(1);if(!c.includes(".")&&!c.startsWith("http"))i=c;else n=c}else throw new v("Missing required argument. Must provide either --image or --file-id.",x.USAGE,"mmx vision describe --image <path> OR --file-id <id>");else if(n&&i)throw new v("Conflicting arguments: cannot provide both --image and --file-id.",x.USAGE);if(Je(e,{prompt:r,image:n,fileId:i}))return;let s=F(e.output),o=pc(e.baseUrl),a={prompt:r};if(i)a.file_id=i;else if(n){let c=await wu(n);a.image_url=c}let l=await j(e,{url:o,method:"POST",body:a});if(s!=="text"){process.stdout.write(N(l,s)+`
286
+ `);return}process.stdout.write(l.content+`
287
+ `)}})});var Uu;var ju=I(()=>{J();oe();Li();z();Vi();Uu=R({name:"quota show",description:"Display Token Plan usage and remaining quotas",usage:"mmx quota show",examples:["mmx quota show","mmx quota show --output json"],async run(e,t){if(e.dryRun){console.log("Would fetch quota information.");return}let n=F(e.output),i=await Kt(e),r=Ys(e.baseUrl,i);if(r.kind==="account-balance"){let a=await j(e,{url:r.url});if(n!=="text"){console.log(N(a,n));return}Ge(a,e,i.token);return}let s=await j(e,{url:r.url}),o=s.model_remains||[];if(n!=="text"){console.log(N(s,n));return}if(e.quiet){for(let a of o){let l=ji(a.current_interval_usage_count,a.current_interval_total_count,a.current_interval_remaining_percent);if(l){console.log(`${a.model_name} ${l.used} ${l.total} ${l.remaining}`);continue}let c=a.current_interval_remaining_percent===void 0||a.current_interval_remaining_percent===null?"-":`${a.current_interval_remaining_percent}%`;console.log(`${a.model_name} - ${a.current_interval_total_count} ${c}`)}return}Ge(s,e)}})});var Bu;var Vu=I(()=>{J();Be();Dt();z();Bu=R({name:"config show",description:"Display current configuration",usage:"mmx config show",examples:["mmx config show","mmx config show --output json"],async run(e,t){let n=Q(),i=F(e.output),r={region:e.region,base_url:e.baseUrl,output:e.output,timeout:e.timeout,config_file:Re()};if(n.api_key)r.api_key=ge(n.api_key);if(n.default_text_model)r.default_text_model=n.default_text_model;if(n.default_speech_model)r.default_speech_model=n.default_speech_model;if(n.default_video_model)r.default_video_model=n.default_video_model;if(n.proxy)r.proxy=n.proxy;console.log(N(r,i))}})});function Ku(e,t){return e==="api_key"?ge(String(t)):t}var Gu,Ry,Wu;var Hu=I(()=>{J();G();V();z();Be();Gu=["region","base_url","output","timeout","api_key","proxy","default_text_model","default_speech_model","default_video_model"],Ry={"default-text-model":"default_text_model","default-speech-model":"default_speech_model","default-video-model":"default_video_model"};Wu=R({name:"config set",description:"Set a config value",usage:"mmx config set --key <key> --value <value>",options:[{flag:"--key <key>",description:"Config key (region, base_url, output, timeout, api_key, proxy, default_text_model, default_speech_model, default_video_model)"},{flag:"--value <value>",description:"Value to set"}],examples:["mmx config set --key output --value json","mmx config set --key timeout --value 600","mmx config set --key proxy --value http://127.0.0.1:7890","mmx config set --key base_url --value https://api-uw.minimax.io"],async run(e,t){let n=t._positional,i=t.key??n?.[0],r=t.value??n?.[1];if(!i||r===void 0)throw new v("--key and --value are required.",x.USAGE,"mmx config set --key <key> --value <value>");let s=Ry[i]||i;if(!Gu.includes(s))throw new v(`Invalid config key "${i}". Valid keys: ${Gu.join(", ")}`,x.USAGE);let o=s==="api_key"?r.trim():r;if(s==="api_key"&&o.length===0)throw new v("Invalid api_key. The value must not be empty.",x.USAGE);if(s==="region"&&!["global","cn"].includes(r))throw new v(`Invalid region "${r}". Valid values: global, cn`,x.USAGE);if(s==="output"&&!["text","json"].includes(r))throw new v(`Invalid output format "${r}". Valid values: text, json`,x.USAGE);if(s==="base_url"&&!r.startsWith("http"))throw new v(`Invalid base_url "${r}". Must start with http.`,x.USAGE);if(s==="proxy"&&!r.startsWith("http"))throw new v(`Invalid proxy "${r}". Must be a URL starting with http (e.g. http://127.0.0.1:7890).`,x.USAGE);if(s==="timeout"){let c=Number(r);if(isNaN(c)||c<=0)throw new v(`Invalid timeout "${r}". Must be a positive number.`,x.USAGE)}let a=F(e.output);if(e.dryRun){console.log(N({would_set:{[s]:Ku(s,o)}},a));return}let l=Q();if(l[s]=s==="timeout"?Number(o):o,s==="api_key")delete l.oauth,delete l.region;if(await pe(l),!e.quiet)console.log(N({[s]:Ku(s,l[s])},a))}})});function Ly(e){let t=e.match(/^--([a-zA-Z0-9-]+)/),n=t?t[1]:"",i=n.replace(/-([a-zA-Z0-9])/g,(o,a)=>a.toUpperCase()),r="string",s=!1;if(!e.includes("<")&&!e.includes("["))r="boolean";else if(e.includes("<n>")||e.includes("<hz>")||e.includes("<bps>")||e.includes("<count>"))r="number";if(e.toLowerCase().includes("repeatable"))s=!0;return{name:i,kebabName:n,inferredType:r,isArray:s}}function ho(e){let n={name:`mmx_${e.name.replace(/ /g,"_")}`,description:e.description,input_schema:{type:"object",properties:{},required:[]}};if(e.options)for(let i of e.options){if(i.hidden)continue;let{name:r,inferredType:s,isArray:o}=Ly(i.flag);if(!r)continue;let a=i.type,l=o?"array":a??s,c={description:i.description};if(l==="array")c.type="array",c.items={type:"string"};else c.type=l;let f=n.input_schema;if(f.properties[r]=c,i.required)f.required.push(r)}return n}var Py,Ju;var Yu=I(()=>{J();Ki();G();V();Py=["auth ","config ","update"],Ju=R({name:"config export-schema",description:"Export all (or one) CLI command(s) as Anthropic/OpenAI-compatible JSON tool schemas",usage:'mmx config export-schema [--command "<name>"]',options:[{flag:"--command <name>",description:'Export schema for a specific command only (e.g. "image generate")'}],examples:["mmx config export-schema",'mmx config export-schema --command "video generate"'],async run(e,t){let n=t.command;if(n){try{let{command:s}=qe.resolve(n.split(" ")),o=ho(s);process.stdout.write(JSON.stringify(o,null,2)+`
288
+ `)}catch{throw new v(`Command "${n}" not found.`,x.USAGE)}return}let r=qe.getAllCommands().filter((s)=>!Py.some((o)=>s.name.startsWith(o))).map((s)=>ho(s));process.stdout.write(JSON.stringify(r,null,2)+`
289
+ `)}})});import{existsSync as qy}from"node:fs";import{readFile as Fy}from"node:fs/promises";import{basename as Dy,resolve as Uy}from"node:path";function go(e,t){let n=Uy(e);if(!qy(n))throw t(n);return n}async function zu({filePath:e,purpose:t,baseUrl:n,requestJson:i,createFileNotFoundError:r}){let s=go(e,r),o=await Fy(s),a=new FormData;return a.append("file",new Blob([o]),Dy(s)),a.append("purpose",t),i({url:mc(n),method:"POST",body:a})}var Qu=()=>{};var Xu;var Zu=I(()=>{J();G();V();oe();Qu();z();Ve();Xu=R({name:"file upload",description:"Upload a file to MiniMax storage",usage:"mmx file upload --file <path> [--purpose <purpose>]",options:[{flag:"--file <path>",description:"Local path to the file",required:!0},{flag:"--purpose <string>",description:"File purpose (default: retrieval)"}],examples:["mmx file upload --file doc.pdf","mmx file upload --file image.png --purpose vision"],async run(e,t){let n=t.file;if(!n)if(Y({nonInteractive:e.nonInteractive})){if(n=await Ie({message:"Enter file path:"}),!n)process.stderr.write(`Upload cancelled.
290
+ `),process.exit(1)}else xt("file","mmx file upload --file <path>");let i=(l)=>new v(`File not found: ${l}`,x.USAGE),r=go(n,i),s=t.purpose||"retrieval",o=F(e.output);if(e.dryRun){process.stdout.write(N({request:{file:r,purpose:s}},o)+`
291
+ `);return}let a=await zu({filePath:r,purpose:s,baseUrl:e.baseUrl,requestJson:(l)=>j(e,l),createFileNotFoundError:i});if(e.quiet){process.stdout.write(a.file.file_id+`
292
+ `);return}process.stdout.write(N(a.file,o)+`
293
+ `)}})});var ef;var tf=I(()=>{J();oe();z();ef=R({name:"file list",description:"List uploaded files in MiniMax storage",usage:"mmx file list",examples:["mmx file list","mmx file list --output json"],async run(e,t){let n=F(e.output);if(e.dryRun){process.stdout.write(`Would list uploaded files.
294
+ `);return}let i=hc(e.baseUrl),r=await j(e,{url:i,method:"GET"});if(n!=="text"){process.stdout.write(N(r,n)+`
295
+ `);return}if(!r.files||r.files.length===0){process.stdout.write(`No files found.
296
+ `);return}let s=r.files.map((a)=>({ID:a.file_id,FILENAME:a.filename,PURPOSE:a.purpose,SIZE_KB:(a.bytes/1024).toFixed(1),CREATED:new Date(a.created_at*1000).toISOString().slice(0,16).replace("T"," ")})),{formatTable:o}=await Promise.resolve().then(() => il);process.stdout.write(o(s)+`
297
+ `)}})});var nf;var rf=I(()=>{J();oe();z();Ve();nf=R({name:"file delete",description:"Delete an uploaded file from MiniMax storage",usage:"mmx file delete --file-id <id>",options:[{flag:"--file-id <id>",description:"ID of the file to delete",required:!0}],examples:["mmx file delete --file-id 123456789"],async run(e,t){let n=t.fileId;if(!n)if(Y({nonInteractive:e.nonInteractive})){if(n=await Ie({message:"Enter file ID to delete:"}),!n)process.stderr.write(`Delete cancelled.
298
+ `),process.exit(1)}else xt("file-id","mmx file delete --file-id <id>");let i=F(e.output);if(e.dryRun){process.stdout.write(N({request:{delete_file:n}},i)+`
299
+ `);return}let r=gc(e.baseUrl),s=await j(e,{url:r,method:"POST",body:{file_id:Number(n)}});if(e.quiet){process.stdout.write(`deleted
300
+ `);return}process.stdout.write(N({file_id:s.file_id,deleted:!0},i)+`
301
+ `)}})});var sf;var of=I(()=>{J();Pi();sf=R({name:"update",description:"Update mmx to the latest version",usage:"mmx update",examples:["mmx update"],async run(){process.stderr.write(`Current version: ${St}
234
302
 
235
303
  `),process.stderr.write(`Run:
236
304
  `),process.stderr.write(` npm update -g mmx-cli
237
305
 
238
- `)}})});var Ya,_i;var Ai=C(()=>{T();re();Ya=[{command:"mmx text chat",title:"Text Generation (Chat Completion)",path:"/docs/api-reference/text-post"},{command:"mmx speech synthesize",title:"Speech T2A (Text-to-Audio)",path:"/docs/api-reference/speech-t2a-http"},{command:"mmx image generate",title:"Image Generation (T2I / I2I)",path:"/docs/api-reference/image-generation-t2i"},{command:"mmx video generate",title:"Video Generation (T2V / I2V / S2V)",path:"/docs/api-reference/video-generation"},{command:"mmx search query",title:"Web Search",path:"/docs/api-reference/web-search"},{command:"mmx vision describe",title:"Vision (Image Understanding)",path:"/docs/api-reference/vision"}],_i=w({name:"help",description:"Show MiniMax API documentation links",usage:"mmx help",async run(e,t){let o=Le[e.region]||Le.global;process.stdout.write(`
306
+ `)}})});var jy,af;var lf=I(()=>{J();Ae();jy=[{command:"mmx text chat",title:"Text Generation (Chat Completion)",path:"/docs/api-reference/text-post"},{command:"mmx speech synthesize",title:"Speech T2A (Text-to-Audio)",path:"/docs/api-reference/speech-t2a-http"},{command:"mmx image generate",title:"Image Generation (T2I / I2I)",path:"/docs/api-reference/image-generation-t2i"},{command:"mmx video generate",title:"Video Generation (T2V / I2V / S2V)",path:"/docs/api-reference/video-generation"},{command:"mmx search query",title:"Web Search",path:"/docs/api-reference/web-search"},{command:"mmx vision describe",title:"Vision (Image Understanding)",path:"/docs/api-reference/vision"}],af=R({name:"help",description:"Show MiniMax API documentation links",usage:"mmx help",async run(e,t){let n=gt[e.region]||gt.global;process.stdout.write(`
239
307
  MiniMax API Documentation Links
240
308
 
241
- Official docs: ${o}/docs/api-reference
309
+ Official docs: ${n}/docs/api-reference
310
+
311
+ `);for(let i of jy)process.stdout.write(` ${i.command.padEnd(30)} ${i.title}
312
+ `),process.stdout.write(` ${" ".repeat(30)} ${n}${i.path}
313
+
314
+ `)}})});function En(e,t=!1){let n=e.length,i=0,r="",s=0,o=16,a=0,l=0,c=0,f=0,u=0;function d(S,_){let E=0,A=0;while(E<S||!_){let k=e.charCodeAt(i);if(k>=48&&k<=57)A=A*16+k-48;else if(k>=65&&k<=70)A=A*16+k-65+10;else if(k>=97&&k<=102)A=A*16+k-97+10;else break;i++,E++}if(E<S)A=-1;return A}function g(S){i=S,r="",s=0,o=16,u=0}function h(){let S=i;if(e.charCodeAt(i)===48)i++;else{i++;while(i<e.length&&Wt(e.charCodeAt(i)))i++}if(i<e.length&&e.charCodeAt(i)===46)if(i++,i<e.length&&Wt(e.charCodeAt(i))){i++;while(i<e.length&&Wt(e.charCodeAt(i)))i++}else return u=3,e.substring(S,i);let _=i;if(i<e.length&&(e.charCodeAt(i)===69||e.charCodeAt(i)===101)){if(i++,i<e.length&&e.charCodeAt(i)===43||e.charCodeAt(i)===45)i++;if(i<e.length&&Wt(e.charCodeAt(i))){i++;while(i<e.length&&Wt(e.charCodeAt(i)))i++;_=i}else u=3}return e.substring(S,_)}function p(){let S="",_=i;while(!0){if(i>=n){S+=e.substring(_,i),u=2;break}let E=e.charCodeAt(i);if(E===34){S+=e.substring(_,i),i++;break}if(E===92){if(S+=e.substring(_,i),i++,i>=n){u=2;break}switch(e.charCodeAt(i++)){case 34:S+='"';break;case 92:S+="\\";break;case 47:S+="/";break;case 98:S+="\b";break;case 102:S+="\f";break;case 110:S+=`
315
+ `;break;case 114:S+="\r";break;case 116:S+="\t";break;case 117:let k=d(4,!0);if(k>=0)S+=String.fromCharCode(k);else u=4;break;default:u=5}_=i;continue}if(E>=0&&E<=31)if(An(E)){S+=e.substring(_,i),u=2;break}else u=6;i++}return S}function m(){if(r="",u=0,s=i,l=a,f=c,i>=n)return s=n,o=17;let S=e.charCodeAt(i);if(yo(S)){do i++,r+=String.fromCharCode(S),S=e.charCodeAt(i);while(yo(S));return o=15}if(An(S)){if(i++,r+=String.fromCharCode(S),S===13&&e.charCodeAt(i)===10)i++,r+=`
316
+ `;return a++,c=i,o=14}switch(S){case 123:return i++,o=1;case 125:return i++,o=2;case 91:return i++,o=3;case 93:return i++,o=4;case 58:return i++,o=6;case 44:return i++,o=5;case 34:return i++,r=p(),o=10;case 47:let _=i-1;if(e.charCodeAt(i+1)===47){i+=2;while(i<n){if(An(e.charCodeAt(i)))break;i++}return r=e.substring(_,i),o=12}if(e.charCodeAt(i+1)===42){i+=2;let E=n-1,A=!1;while(i<E){let k=e.charCodeAt(i);if(k===42&&e.charCodeAt(i+1)===47){i+=2,A=!0;break}if(i++,An(k)){if(k===13&&e.charCodeAt(i)===10)i++;a++,c=i}}if(!A)i++,u=1;return r=e.substring(_,i),o=13}return r+=String.fromCharCode(S),i++,o=16;case 45:if(r+=String.fromCharCode(S),i++,i===n||!Wt(e.charCodeAt(i)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r+=h(),o=11;default:while(i<n&&b(S))i++,S=e.charCodeAt(i);if(s!==i){switch(r=e.substring(s,i),r){case"true":return o=8;case"false":return o=9;case"null":return o=7}return o=16}return r+=String.fromCharCode(S),i++,o=16}}function b(S){if(yo(S)||An(S))return!1;switch(S){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function w(){let S;do S=m();while(S>=12&&S<=15);return S}return{setPosition:g,getPosition:()=>i,scan:t?w:m,getToken:()=>o,getTokenValue:()=>r,getTokenOffset:()=>s,getTokenLength:()=>i-s,getTokenStartLine:()=>l,getTokenStartCharacter:()=>s-f,getTokenError:()=>u}}function yo(e){return e===32||e===9}function An(e){return e===10||e===13}function Wt(e){return e>=48&&e<=57}var cf;var er=I(()=>{(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(cf||(cf={}))});var be,bo,uf;var ff=I(()=>{be=Array(20).fill(0).map((e,t)=>" ".repeat(t)),bo={" ":{"\n":Array(200).fill(0).map((e,t)=>`
317
+ `+" ".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
318
+ `+" ".repeat(t))},"\t":{"\n":Array(200).fill(0).map((e,t)=>`
319
+ `+"\t".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+"\t".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
320
+ `+"\t".repeat(t))}},uf=[`
321
+ `,"\r",`\r
322
+ `]});function wo(e,t,n){let i,r,s,o,a;if(t){o=t.offset,a=o+t.length,s=o;while(s>0&&!_n(e,s-1))s--;let E=a;while(E<e.length&&!_n(e,E))E++;r=e.substring(s,E),i=Vy(r,n)}else r=e,i=0,s=0,o=0,a=e.length;let l=Gy(n,e),c=uf.includes(l),f=0,u=0,d;if(n.insertSpaces)d=be[n.tabSize||4]??Ht(be[1],n.tabSize||4);else d="\t";let g=d==="\t"?"\t":" ",h=En(r,!1),p=!1;function m(){if(f>1)return Ht(l,f)+Ht(d,i+u);let E=d.length*(i+u);if(!c||E>bo[g][l].length)return l+Ht(d,i+u);if(E<=0)return l;return bo[g][l][E]}function b(){let E=h.scan();f=0;while(E===15||E===14){if(E===14&&n.keepLines)f+=1;else if(E===14)f=1;E=h.scan()}return p=E===16||h.getTokenError()!==0,E}let w=[];function S(E,A,k){if(!p&&(!t||A<a&&k>o)&&e.substring(A,k)!==E)w.push({offset:A,length:k-A,content:E})}let _=b();if(n.keepLines&&f>0)S(Ht(l,f),0,0);if(_!==17){let E=h.getTokenOffset()+s,A=d.length*i<20&&n.insertSpaces?be[d.length*i]:Ht(d,i);S(A,s,E)}while(_!==17){let E=h.getTokenOffset()+h.getTokenLength()+s,A=b(),k="",T=!1;while(f===0&&(A===12||A===13)){let P=h.getTokenOffset()+s;S(be[1],E,P),E=h.getTokenOffset()+h.getTokenLength()+s,T=A===12,k=T?m():"",A=b()}if(A===2){if(_!==1)u--;if(n.keepLines&&f>0||!n.keepLines&&_!==1)k=m();else if(n.keepLines)k=be[1]}else if(A===4){if(_!==3)u--;if(n.keepLines&&f>0||!n.keepLines&&_!==3)k=m();else if(n.keepLines)k=be[1]}else{switch(_){case 3:case 1:if(u++,n.keepLines&&f>0||!n.keepLines)k=m();else k=be[1];break;case 5:if(n.keepLines&&f>0||!n.keepLines)k=m();else k=be[1];break;case 12:k=m();break;case 13:if(f>0)k=m();else if(!T)k=be[1];break;case 6:if(n.keepLines&&f>0)k=m();else if(!T)k=be[1];break;case 10:if(n.keepLines&&f>0)k=m();else if(A===6&&!T)k="";break;case 7:case 8:case 9:case 11:case 2:case 4:if(n.keepLines&&f>0)k=m();else if((A===12||A===13)&&!T)k=be[1];else if(A!==5&&A!==17)p=!0;break;case 16:p=!0;break}if(f>0&&(A===12||A===13))k=m()}if(A===17)if(n.keepLines&&f>0)k=m();else k=n.insertFinalNewline?l:"";let C=h.getTokenOffset()+s;S(k,E,C),_=A}return w}function Ht(e,t){let n="";for(let i=0;i<t;i++)n+=e;return n}function Vy(e,t){let n=0,i=0,r=t.tabSize||4;while(n<e.length){let s=e.charAt(n);if(s===be[1])i++;else if(s==="\t")i+=r;else break;n++}return Math.floor(i/r)}function Gy(e,t){for(let n=0;n<t.length;n++){let i=t.charAt(n);if(i==="\r"){if(n+1<t.length&&t.charAt(n+1)===`
323
+ `)return`\r
324
+ `;return"\r"}else if(i===`
325
+ `)return`
326
+ `}return e&&e.eol||`
327
+ `}function _n(e,t){return`\r
328
+ `.indexOf(e.charAt(t))!==-1}var vo=I(()=>{er();ff()});function df(e,t=[],n=Tn.DEFAULT){let i=null,r=[],s=[];function o(l){if(Array.isArray(r))r.push(l);else if(i!==null)r[i]=l}return So(e,{onObjectBegin:()=>{let l={};o(l),s.push(r),r=l,i=null},onObjectProperty:(l)=>{i=l},onObjectEnd:()=>{r=s.pop()},onArrayBegin:()=>{let l=[];o(l),s.push(r),r=l,i=null},onArrayEnd:()=>{r=s.pop()},onLiteralValue:o,onError:(l,c,f)=>{t.push({error:l,offset:c,length:f})}},n),r[0]}function xo(e,t=[],n=Tn.DEFAULT){let i={type:"array",offset:-1,length:-1,children:[],parent:void 0};function r(l){if(i.type==="property")i.length=l-i.offset,i=i.parent}function s(l){return i.children.push(l),l}So(e,{onObjectBegin:(l)=>{i=s({type:"object",offset:l,length:-1,parent:i,children:[]})},onObjectProperty:(l,c,f)=>{i=s({type:"property",offset:c,length:-1,parent:i,children:[]}),i.children.push({type:"string",value:l,offset:c,length:f,parent:i})},onObjectEnd:(l,c)=>{r(l+c),i.length=l+c-i.offset,i=i.parent,r(l+c)},onArrayBegin:(l,c)=>{i=s({type:"array",offset:l,length:-1,parent:i,children:[]})},onArrayEnd:(l,c)=>{i.length=l+c-i.offset,i=i.parent,r(l+c)},onLiteralValue:(l,c,f)=>{s({type:Wy(l),offset:c,length:f,parent:i,value:l}),r(c+f)},onSeparator:(l,c,f)=>{if(i.type==="property"){if(l===":")i.colonOffset=c;else if(l===",")r(c)}},onError:(l,c,f)=>{t.push({error:l,offset:c,length:f})}},n);let a=i.children[0];if(a)delete a.parent;return a}function tr(e,t){if(!e)return;let n=e;for(let i of t)if(typeof i==="string"){if(n.type!=="object"||!Array.isArray(n.children))return;let r=!1;for(let s of n.children)if(Array.isArray(s.children)&&s.children[0].value===i&&s.children.length===2){n=s.children[1],r=!0;break}if(!r)return}else{let r=i;if(n.type!=="array"||r<0||!Array.isArray(n.children)||r>=n.children.length)return;n=n.children[r]}return n}function So(e,t,n=Tn.DEFAULT){let i=En(e,!1),r=[],s=0;function o(q){return q?()=>s===0&&q(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function a(q){return q?(W)=>s===0&&q(W,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function l(q){return q?(W)=>s===0&&q(W,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>r.slice()):()=>!0}function c(q){return q?()=>{if(s>0)s++;else if(q(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>r.slice())===!1)s=1}:()=>!0}function f(q){return q?()=>{if(s>0)s--;if(s===0)q(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter())}:()=>!0}let u=c(t.onObjectBegin),d=l(t.onObjectProperty),g=f(t.onObjectEnd),h=c(t.onArrayBegin),p=f(t.onArrayEnd),m=l(t.onLiteralValue),b=a(t.onSeparator),w=o(t.onComment),S=a(t.onError),_=n&&n.disallowComments,E=n&&n.allowTrailingComma;function A(){while(!0){let q=i.scan();switch(i.getTokenError()){case 4:k(14);break;case 5:k(15);break;case 3:k(13);break;case 1:if(!_)k(11);break;case 2:k(12);break;case 6:k(16);break}switch(q){case 12:case 13:if(_)k(10);else w();break;case 16:k(1);break;case 15:case 14:break;default:return q}}}function k(q,W=[],we=[]){if(S(q),W.length+we.length>0){let je=i.getToken();while(je!==17){if(W.indexOf(je)!==-1){A();break}else if(we.indexOf(je)!==-1)break;je=A()}}}function T(q){let W=i.getTokenValue();if(q)m(W);else d(W),r.push(W);return A(),!0}function C(){switch(i.getToken()){case 11:let q=i.getTokenValue(),W=Number(q);if(isNaN(W))k(2),W=0;m(W);break;case 7:m(null);break;case 8:m(!0);break;case 9:m(!1);break;default:return!1}return A(),!0}function P(){if(i.getToken()!==10)return k(3,[],[2,5]),!1;if(T(!1),i.getToken()===6){if(b(":"),A(),!U())k(4,[],[2,5])}else k(5,[],[2,5]);return r.pop(),!0}function L(){u(),A();let q=!1;while(i.getToken()!==2&&i.getToken()!==17){if(i.getToken()===5){if(!q)k(4,[],[]);if(b(","),A(),i.getToken()===2&&E)break}else if(q)k(6,[],[]);if(!P())k(4,[],[2,5]);q=!0}if(g(),i.getToken()!==2)k(7,[2],[]);else A();return!0}function D(){h(),A();let q=!0,W=!1;while(i.getToken()!==4&&i.getToken()!==17){if(i.getToken()===5){if(!W)k(4,[],[]);if(b(","),A(),i.getToken()===4&&E)break}else if(W)k(6,[],[]);if(q)r.push(0),q=!1;else r[r.length-1]++;if(!U())k(4,[],[4,5]);W=!0}if(p(),!q)r.pop();if(i.getToken()!==4)k(8,[4],[]);else A();return!0}function U(){switch(i.getToken()){case 3:return D();case 1:return L();case 10:return T(!0);default:return C()}}if(A(),i.getToken()===17){if(n.allowEmptyContent)return!0;return k(4,[],[]),!1}if(!U())return k(4,[],[]),!1;if(i.getToken()!==17)k(9,[],[]);return!0}function Wy(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(!e)return"null";else if(Array.isArray(e))return"array";return"object"}default:return"null"}}var Tn;var $o=I(()=>{er();(function(e){e.DEFAULT={allowTrailingComma:!1}})(Tn||(Tn={}))});function pf(e,t,n,i){let r=t.slice(),o=xo(e,[]),a=void 0,l=void 0;while(r.length>0)if(l=r.pop(),a=tr(o,r),a===void 0&&n!==void 0)if(typeof l==="string")n={[l]:n};else n=[n];else break;if(!a){if(n===void 0)throw Error("Can not delete in empty document");return Tt(e,{offset:o?o.offset:0,length:o?o.length:0,content:JSON.stringify(n)},i)}else if(a.type==="object"&&typeof l==="string"&&Array.isArray(a.children)){let c=tr(a,[l]);if(c!==void 0)if(n===void 0){if(!c.parent)throw Error("Malformed AST");let f=a.children.indexOf(c.parent),u,d=c.parent.offset+c.parent.length;if(f>0){let g=a.children[f-1];u=g.offset+g.length}else if(u=a.offset+1,a.children.length>1)d=a.children[1].offset;return Tt(e,{offset:u,length:d-u,content:""},i)}else return Tt(e,{offset:c.offset,length:c.length,content:JSON.stringify(n)},i);else{if(n===void 0)return[];let f=`${JSON.stringify(l)}: ${JSON.stringify(n)}`,u=i.getInsertionIndex?i.getInsertionIndex(a.children.map((g)=>g.children[0].value)):a.children.length,d;if(u>0){let g=a.children[u-1];d={offset:g.offset+g.length,length:0,content:","+f}}else if(a.children.length===0)d={offset:a.offset+1,length:0,content:f};else d={offset:a.offset+1,length:0,content:f+","};return Tt(e,d,i)}}else if(a.type==="array"&&typeof l==="number"&&Array.isArray(a.children)){let c=l;if(c===-1){let f=`${JSON.stringify(n)}`,u;if(a.children.length===0)u={offset:a.offset+1,length:0,content:f};else{let d=a.children[a.children.length-1];u={offset:d.offset+d.length,length:0,content:","+f}}return Tt(e,u,i)}else if(n===void 0&&a.children.length>=0){let f=l,u=a.children[f],d;if(a.children.length===1)d={offset:a.offset+1,length:a.length-2,content:""};else if(a.children.length-1===f){let g=a.children[f-1],h=g.offset+g.length,p=a.offset+a.length;d={offset:h,length:p-2-h,content:""}}else d={offset:u.offset,length:a.children[f+1].offset-u.offset,content:""};return Tt(e,d,i)}else if(n!==void 0){let f,u=`${JSON.stringify(n)}`;if(!i.isArrayInsertion&&a.children.length>l){let d=a.children[l];f={offset:d.offset,length:d.length,content:u}}else if(a.children.length===0||l===0)f={offset:a.offset+1,length:0,content:a.children.length===0?u:u+","};else{let d=l>a.children.length?a.children.length:l,g=a.children[d-1];f={offset:g.offset+g.length,length:0,content:","+u}}return Tt(e,f,i)}else throw Error(`Can not ${n===void 0?"remove":i.isArrayInsertion?"insert":"modify"} Array index ${c} as length is not sufficient`)}else throw Error(`Can not add ${typeof l!=="number"?"index":"property"} to parent of type ${a.type}`)}function Tt(e,t,n){if(!n.formattingOptions)return[t];let i=nr(e,t),r=t.offset,s=t.offset+t.content.length;if(t.length===0||t.content.length===0){while(r>0&&!_n(i,r-1))r--;while(s<i.length&&!_n(i,s))s++}let o=wo(i,{offset:r,length:s-r},{...n.formattingOptions,keepLines:!1});for(let l=o.length-1;l>=0;l--){let c=o[l];i=nr(i,c),r=Math.min(r,c.offset),s=Math.max(s,c.offset+c.length),s+=c.content.length-c.length}let a=e.length-(i.length-s)-r;return[{offset:r,length:a,content:i.substring(r,s)}]}function nr(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}var mf=I(()=>{vo();$o()});function wf(e,t,n,i){return pf(e,t,n,i)}function vf(e,t){let n=t.slice(0).sort((r,s)=>{let o=r.offset-s.offset;if(o===0)return r.length-s.length;return o}),i=e.length;for(let r=n.length-1;r>=0;r--){let s=n[r];if(s.offset+s.length<=i)e=nr(e,s);else throw Error("Overlapping edit");i=s.offset}return e}var hf,gf,bf,yf;var xf=I(()=>{vo();mf();er();$o();(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(hf||(hf={}));(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(gf||(gf={}));bf=df;(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(yf||(yf={}))});var Yy,rt;var ko=I(()=>{/*!
329
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
330
+ * SPDX-License-Identifier: BSD-3-Clause
331
+ *
332
+ * Redistribution and use in source and binary forms, with or without
333
+ * modification, are permitted provided that the following conditions are met:
334
+ *
335
+ * 1. Redistributions of source code must retain the above copyright notice, this
336
+ * list of conditions and the following disclaimer.
337
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
338
+ * this list of conditions and the following disclaimer in the
339
+ * documentation and/or other materials provided with the distribution.
340
+ * 3. Neither the name of the copyright holder nor the names of its contributors
341
+ * may be used to endorse or promote products derived from this software without
342
+ * specific prior written permission.
343
+ *
344
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
345
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
346
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
347
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
348
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
349
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
350
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
351
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
352
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
353
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
354
+ */Yy=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;rt=class rt extends Date{#e=!1;#n=!1;#t=null;constructor(e){let t=!0,n=!0,i="Z";if(typeof e==="string"){let r=e.match(Yy);if(r){if(!r[1])t=!1,e=`0000-01-01T${e}`;if(n=!!r[2],n&&e[10]===" "&&(e=e.replace(" ","T")),r[2]&&+r[2]>23)e="";else if(i=r[3]||null,e=e.toUpperCase(),!i&&n)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#e=t,this.#n=n,this.#t=i}isDateTime(){return this.#e&&this.#n}isLocal(){return!this.#e||!this.#n||!this.#t}isDate(){return this.#e&&!this.#n}isTime(){return this.#n&&!this.#e}isValid(){return this.#e||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#t===null)return e.slice(0,-1);if(this.#t==="Z")return e;let t=+this.#t.slice(1,3)*60+ +this.#t.slice(4,6);return t=this.#t[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#t}static wrapAsOffsetDateTime(e,t="Z"){let n=new rt(e);return n.#t=t,n}static wrapAsLocalDateTime(e){let t=new rt(e);return t.#t=null,t}static wrapAsLocalDate(e){let t=new rt(e);return t.#n=!1,t.#t=null,t}static wrapAsLocalTime(e){let t=new rt(e);return t.#e=!1,t.#t=null,t}}});function zy(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Qy(e,t,n){let i=e.split(/\r\n|\n|\r/g),r="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=i[o-1];if(!a)continue;if(r+=o.toString().padEnd(s," "),r+=": ",r+=a,r+=`
355
+ `,o===t)r+=" ".repeat(s+n+2),r+=`^
356
+ `}return r}var B;var It=I(()=>{/*!
357
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
358
+ * SPDX-License-Identifier: BSD-3-Clause
359
+ *
360
+ * Redistribution and use in source and binary forms, with or without
361
+ * modification, are permitted provided that the following conditions are met:
362
+ *
363
+ * 1. Redistributions of source code must retain the above copyright notice, this
364
+ * list of conditions and the following disclaimer.
365
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
366
+ * this list of conditions and the following disclaimer in the
367
+ * documentation and/or other materials provided with the distribution.
368
+ * 3. Neither the name of the copyright holder nor the names of its contributors
369
+ * may be used to endorse or promote products derived from this software without
370
+ * specific prior written permission.
371
+ *
372
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
373
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
374
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
375
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
376
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
377
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
378
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
379
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
380
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
381
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
382
+ */B=class B extends Error{line;column;codeblock;constructor(e,t){let[n,i]=zy(t.toml,t.ptr),r=Qy(t.toml,n,i);super(`Invalid TOML document: ${e}
383
+
384
+ ${r}`,t);this.line=n,this.column=i,this.codeblock=r}}});function Ao(e,t=0){let n=e.indexOf(`
385
+ `,t);if(e.charCodeAt(n-1)===13)n--;return n}function ir(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new B("control characters are not allowed in comments",{toml:e.s,ptr:e.p})}}function Fe(e,t,n){let i;while(!0){while((i=e.s.charCodeAt(e.p))===32||i===9||!t&&(i===10||i===13&&e.s.charCodeAt(e.p+1)===10))e.p++;if(n||i!==35)break;ir(e)}}function Sf(e,t,n){let i=e.p;if(!n){i=Ao(e.s,i),e.p=i<0?e.s.length:i;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)ir(e);else if(r===n||r===t)return}throw new B("cannot find end of structure",{toml:e.s,ptr:i})}var rr=I(()=>{It();/*!
386
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
387
+ * SPDX-License-Identifier: BSD-3-Clause
388
+ *
389
+ * Redistribution and use in source and binary forms, with or without
390
+ * modification, are permitted provided that the following conditions are met:
391
+ *
392
+ * 1. Redistributions of source code must retain the above copyright notice, this
393
+ * list of conditions and the following disclaimer.
394
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
395
+ * this list of conditions and the following disclaimer in the
396
+ * documentation and/or other materials provided with the distribution.
397
+ * 3. Neither the name of the copyright holder nor the names of its contributors
398
+ * may be used to endorse or promote products derived from this software without
399
+ * specific prior written permission.
400
+ *
401
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
402
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
403
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
404
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
405
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
406
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
407
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
408
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
409
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
410
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
411
+ */});function sr(e){let t=e.p,n=e.s.charCodeAt(e.p++),i=n,r=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,l=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))l=l&&3;else if(n<32&&n!==9||n===127)throw new B("control characters are not allowed in strings",{toml:e.s,ptr:e.p});else if((!l||l===3)&&n===i&&(!s||e.s.charCodeAt(e.p+1)===i&&e.s.charCodeAt(e.p+2)===i)){if(s){if(e.s.charCodeAt(e.p+3)===i)e.p++;if(e.s.charCodeAt(e.p+3)===i)e.p++}if(!l)o+=e.s.slice(a,e.p);return e.p+=s?3:1,o}else if(!l){if(!r&&n===92)o+=e.s.slice(a,a=e.p),l=1}else if(l===1)if(n===120||n===117||n===85){let c=0,f=n===120?2:n===117?4:8;for(let u=0;u<f;u++,e.p++){let d=e.s.charCodeAt(e.p+1),g=d>=48&&d<=57?d-48:d>=65&&d<=70?d-65+10:d>=97&&d<=102?d-97+10:-1;if(g<0)throw new B("invalid non-hex character in unicode escape",{toml:e.s,ptr:e.p+1});c=c<<4|g}if(c<0||c>1114111||c>=55296&&c<=57343)throw new B("invalid unicode escape",{toml:e.s,ptr:e.p});o+=String.fromCodePoint(c),a=e.p+1,l=0}else if(n===32||n===9)l=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
412
+ `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else throw new B("unrecognized escape sequence",{toml:e.s,ptr:e.p});a=e.p+1,l=0}else if(n!==32&&n!==9){if(l===2)throw new B("invalid escape: only line-ending whitespace may be escaped",{toml:e.s,ptr:a});l=!r&&n===92?1:0,a=e.p}throw new B("unfinished string",{toml:e.s,ptr:t})}function tb(e,t,n){let i=e.s.slice(t,n),r=i.indexOf("#");if(r>0)ir({s:i,p:r,d:0}),i=i.slice(0,r);return i.trimEnd()}function $f(e,t,n){let i=e.p,r={toml:e.s,ptr:i};Sf(e,44,n);let s=tb(e,i,e.p);if(!s)throw new B("incomplete declaration: value expected",r);if(s==="-inf")return-1/0;if(s==="inf"||s==="+inf")return 1/0;if(s==="nan"||s==="+nan"||s==="-nan")return NaN;if(s==="-0")return t?0n:0;let o=Xy.test(s);if(o||Zy.test(s)){if(eb.test(s))throw new B("leading zeroes are not allowed",r);s=s.replace(/_/g,"");let l=+s;if(isNaN(l))throw new B("invalid number",r);if(o){if((o=!Number.isSafeInteger(l))&&!t)throw new B("integer value cannot be represented losslessly",r);if(o||t===!0)l=BigInt(s)}return l}let a=new rt(s);if(!a.isValid())throw new B("invalid value",r);return a}var Xy,Zy,eb;var Eo=I(()=>{ko();It();rr();/*!
413
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
414
+ * SPDX-License-Identifier: BSD-3-Clause
415
+ *
416
+ * Redistribution and use in source and binary forms, with or without
417
+ * modification, are permitted provided that the following conditions are met:
418
+ *
419
+ * 1. Redistributions of source code must retain the above copyright notice, this
420
+ * list of conditions and the following disclaimer.
421
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
422
+ * this list of conditions and the following disclaimer in the
423
+ * documentation and/or other materials provided with the distribution.
424
+ * 3. Neither the name of the copyright holder nor the names of its contributors
425
+ * may be used to endorse or promote products derived from this software without
426
+ * specific prior written permission.
427
+ *
428
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
429
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
430
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
431
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
432
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
433
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
434
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
435
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
436
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
437
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
438
+ */Xy=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Zy=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,eb=/^[+-]?0[0-9_]/});function In(e,t,n){let i=e.p,r=e.s.charCodeAt(i);if(r===91||r===123){if(!e.d--)throw new B("document contains excessively nested structures. aborting.",{toml:e.s,ptr:i});let s=r===91?Af(e,n):kf(e,n);return e.d++,s}if(r===34||r===39)return sr(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new B("invalid value",{toml:e.s,ptr:i});return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new B("invalid value",{toml:e.s,ptr:i});return e.p++,!1}return $f(e,n,t)}var _o=I(()=>{Eo();To();It();/*!
439
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
440
+ * SPDX-License-Identifier: BSD-3-Clause
441
+ *
442
+ * Redistribution and use in source and binary forms, with or without
443
+ * modification, are permitted provided that the following conditions are met:
444
+ *
445
+ * 1. Redistributions of source code must retain the above copyright notice, this
446
+ * list of conditions and the following disclaimer.
447
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
448
+ * this list of conditions and the following disclaimer in the
449
+ * documentation and/or other materials provided with the distribution.
450
+ * 3. Neither the name of the copyright holder nor the names of its contributors
451
+ * may be used to endorse or promote products derived from this software without
452
+ * specific prior written permission.
453
+ *
454
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
455
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
456
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
457
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
458
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
459
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
460
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
461
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
462
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
463
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
464
+ */});function or(e,t="="){let n=e.p,i=n-1,r=[],s=e.s.indexOf(t,n);if(s<0)throw new B("incomplete key-value: cannot find end of key",{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++i);if(o!==32&&o!==9)if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new B("multiline strings are not allowed in keys",{toml:e.s,ptr:e.p});let a=sr(e);i=e.s.indexOf(".",e.p);let l=e.s.slice(e.p,i<0||i>s?s:i),c=Ao(l);if(c>-1)throw new B("newlines are not allowed in keys",{toml:e.s,ptr:c});if(l.trimStart())throw new B("found extra tokens after the string part",{toml:e.s,ptr:e.p});if(s<e.p){if(s=e.s.indexOf(t,e.p),s<0)throw new B("incomplete key-value: cannot find end of key",{toml:e.s,ptr:n})}r.push(a)}else{i=e.s.indexOf(".",e.p);let a=e.s.slice(e.p,i<0||i>s?s:i);if(!nb.test(a))throw new B("only letter, numbers, dashes and underscores are allowed in keys",{toml:e.s,ptr:e.p});r.push(a.trimEnd())}}while(i+1&&i<s);return e.p=s+1,Fe(e,!0,!0),r}function kf(e,t){let n={},i=new Set,r;e.p++;while(e.p<e.s.length){if(Fe(e),(r=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,l=e.p,c=or(e);for(let u=0;u<c.length;u++){if(u)o=a?o[s]:o[s]={};if(s=c[u],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||i.has(o[s])))throw new B("trying to redefine an already defined value",{toml:e.s,ptr:l});if(!a&&s==="__proto__")Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)throw new B("trying to redefine an already defined value",{toml:e.s,ptr:e.p});let f=In(e,125,t);if(i.add(o[s]=f),Fe(e),(r=e.s.charCodeAt(e.p++))===125)return n;if(r!==44)throw new B("expected comma or end of structure",{toml:e.s,ptr:e.p-1})}throw new B("unfinished table encountered",{toml:e.s,ptr:e.p})}function Af(e,t){let n=[],i;e.p++;while(e.p<e.s.length){if(Fe(e),(i=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(In(e,93,t)),Fe(e),(i=e.s.charCodeAt(e.p++))===93)return n;if(i!==44)throw new B("expected comma or end of structure",{toml:e.s,ptr:e.p-1})}throw new B("unfinished array encountered",{toml:e.s,ptr:e.p})}var nb;var To=I(()=>{Eo();_o();rr();It();/*!
465
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
466
+ * SPDX-License-Identifier: BSD-3-Clause
467
+ *
468
+ * Redistribution and use in source and binary forms, with or without
469
+ * modification, are permitted provided that the following conditions are met:
470
+ *
471
+ * 1. Redistributions of source code must retain the above copyright notice, this
472
+ * list of conditions and the following disclaimer.
473
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
474
+ * this list of conditions and the following disclaimer in the
475
+ * documentation and/or other materials provided with the distribution.
476
+ * 3. Neither the name of the copyright holder nor the names of its contributors
477
+ * may be used to endorse or promote products derived from this software without
478
+ * specific prior written permission.
479
+ *
480
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
481
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
482
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
483
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
484
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
485
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
486
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
487
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
488
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
489
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
490
+ */nb=/^[a-zA-Z0-9-_]+[ \t]*$/});function Ef(e,t,n,i){let r=t,s=n,o,a=!1,l;for(let c=0;c<e.length;c++){if(c){if(r=a?r[o]:r[o]={},s=(l=s[o]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let f=r.length-1;r=r[f],s=s[f].c}}if(o=e[c],(a=Object.hasOwn(r,o))&&s[o]?.t===0&&s[o]?.d)return null;if(!a){if(o==="__proto__")Object.defineProperty(r,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0});s[o]={t:c<e.length-1&&i===2?3:i,d:!1,i:0,c:{}}}}if(l=s[o],l.t!==i&&!(i===1&&l.t===3))return null;if(i===2){if(!l.d)l.d=!0,r[o]=[];r[o].push(r={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}}if(l.d)return null;if(l.d=!0,i===1)r=a?r[o]:r[o]={};else if(i===0&&a)return null;return[o,r,l.c]}function On(e,{maxDepth:t=1000,integersAsBigInt:n}={}){let i={s:e,p:0,d:t},r={},s={},o,a=r,l=s;Fe(i);while(i.p<e.length){if(e.charCodeAt(i.p)===91){let c=e.charCodeAt(++i.p)===91;o=i.p+=+c;let f=or(i,"]");if(c){if(e.charCodeAt(i.p-1)!==93)throw new B("expected end of table declaration",{toml:e,ptr:i.p-1});i.p++}let u=Ef(f,r,s,c?2:1);if(!u)throw new B("trying to redefine an already defined table or value",{toml:e,ptr:o});l=u[2],a=u[1]}else{o=i.p;let c=or(i),f=Ef(c,a,l,0);if(!f)throw new B("trying to redefine an already defined table or value",{toml:e,ptr:o});f[1][f[0]]=In(i,void 0,n)}if(Fe(i,!0),i.p<e.length&&(o=e.charCodeAt(i.p))!==10&&o!==13)throw new B("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:i.p});Fe(i)}return r}var _f=I(()=>{To();_o();rr();It();/*!
491
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
492
+ * SPDX-License-Identifier: BSD-3-Clause
493
+ *
494
+ * Redistribution and use in source and binary forms, with or without
495
+ * modification, are permitted provided that the following conditions are met:
496
+ *
497
+ * 1. Redistributions of source code must retain the above copyright notice, this
498
+ * list of conditions and the following disclaimer.
499
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
500
+ * this list of conditions and the following disclaimer in the
501
+ * documentation and/or other materials provided with the distribution.
502
+ * 3. Neither the name of the copyright holder nor the names of its contributors
503
+ * may be used to endorse or promote products derived from this software without
504
+ * specific prior written permission.
505
+ *
506
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
507
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
508
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
509
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
510
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
511
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
512
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
513
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
514
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
515
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
516
+ */});var Tf=I(()=>{/*!
517
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
518
+ * SPDX-License-Identifier: BSD-3-Clause
519
+ *
520
+ * Redistribution and use in source and binary forms, with or without
521
+ * modification, are permitted provided that the following conditions are met:
522
+ *
523
+ * 1. Redistributions of source code must retain the above copyright notice, this
524
+ * list of conditions and the following disclaimer.
525
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
526
+ * this list of conditions and the following disclaimer in the
527
+ * documentation and/or other materials provided with the distribution.
528
+ * 3. Neither the name of the copyright holder nor the names of its contributors
529
+ * may be used to endorse or promote products derived from this software without
530
+ * specific prior written permission.
531
+ *
532
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
533
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
534
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
535
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
536
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
537
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
538
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
539
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
540
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
541
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
542
+ */});var If=I(()=>{_f();Tf();ko();It();/*!
543
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
544
+ * SPDX-License-Identifier: BSD-3-Clause
545
+ *
546
+ * Redistribution and use in source and binary forms, with or without
547
+ * modification, are permitted provided that the following conditions are met:
548
+ *
549
+ * 1. Redistributions of source code must retain the above copyright notice, this
550
+ * list of conditions and the following disclaimer.
551
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
552
+ * this list of conditions and the following disclaimer in the
553
+ * documentation and/or other materials provided with the distribution.
554
+ * 3. Neither the name of the copyright holder nor the names of its contributors
555
+ * may be used to endorse or promote products derived from this software without
556
+ * specific prior written permission.
557
+ *
558
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
559
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
560
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
561
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
562
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
563
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
564
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
565
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
566
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
567
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
568
+ */});var K=M(function(ub){var Io=Symbol.for("yaml.alias"),Of=Symbol.for("yaml.document"),ar=Symbol.for("yaml.map"),Mf=Symbol.for("yaml.pair"),Oo=Symbol.for("yaml.scalar"),lr=Symbol.for("yaml.seq"),Ke=Symbol.for("yaml.node.type"),ib=(e)=>!!e&&typeof e==="object"&&e[Ke]===Io,rb=(e)=>!!e&&typeof e==="object"&&e[Ke]===Of,sb=(e)=>!!e&&typeof e==="object"&&e[Ke]===ar,ob=(e)=>!!e&&typeof e==="object"&&e[Ke]===Mf,Nf=(e)=>!!e&&typeof e==="object"&&e[Ke]===Oo,ab=(e)=>!!e&&typeof e==="object"&&e[Ke]===lr;function Cf(e){if(e&&typeof e==="object")switch(e[Ke]){case ar:case lr:return!0}return!1}function lb(e){if(e&&typeof e==="object")switch(e[Ke]){case Io:case ar:case Oo:case lr:return!0}return!1}var cb=(e)=>(Nf(e)||Cf(e))&&!!e.anchor;ub.ALIAS=Io;ub.DOC=Of;ub.MAP=ar;ub.NODE_TYPE=Ke;ub.PAIR=Mf;ub.SCALAR=Oo;ub.SEQ=lr;ub.hasAnchor=cb;ub.isAlias=ib;ub.isCollection=Cf;ub.isDocument=rb;ub.isMap=sb;ub.isNode=lb;ub.isPair=ob;ub.isScalar=Nf;ub.isSeq=ab});var Mn=M(function(_b){var re=K(),me=Symbol("break visit"),Rf=Symbol("skip children"),De=Symbol("remove node");function cr(e,t){let n=Lf(t);if(re.isDocument(e)){if(Jt(null,e.contents,n,Object.freeze([e]))===De)e.contents=null}else Jt(null,e,n,Object.freeze([]))}cr.BREAK=me;cr.SKIP=Rf;cr.REMOVE=De;function Jt(e,t,n,i){let r=Pf(e,t,n,i);if(re.isNode(r)||re.isPair(r))return qf(e,i,r),Jt(e,r,n,i);if(typeof r!=="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s<t.items.length;++s){let o=Jt(s,t.items[s],n,i);if(typeof o==="number")s=o-1;else if(o===me)return me;else if(o===De)t.items.splice(s,1),s-=1}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let s=Jt("key",t.key,n,i);if(s===me)return me;else if(s===De)t.key=null;let o=Jt("value",t.value,n,i);if(o===me)return me;else if(o===De)t.value=null}}return r}async function ur(e,t){let n=Lf(t);if(re.isDocument(e)){if(await Yt(null,e.contents,n,Object.freeze([e]))===De)e.contents=null}else await Yt(null,e,n,Object.freeze([]))}ur.BREAK=me;ur.SKIP=Rf;ur.REMOVE=De;async function Yt(e,t,n,i){let r=await Pf(e,t,n,i);if(re.isNode(r)||re.isPair(r))return qf(e,i,r),Yt(e,r,n,i);if(typeof r!=="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s<t.items.length;++s){let o=await Yt(s,t.items[s],n,i);if(typeof o==="number")s=o-1;else if(o===me)return me;else if(o===De)t.items.splice(s,1),s-=1}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let s=await Yt("key",t.key,n,i);if(s===me)return me;else if(s===De)t.key=null;let o=await Yt("value",t.value,n,i);if(o===me)return me;else if(o===De)t.value=null}}return r}function Lf(e){if(typeof e==="object"&&(e.Collection||e.Node||e.Value))return Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e);return e}function Pf(e,t,n,i){if(typeof n==="function")return n(e,t,i);if(re.isMap(t))return n.Map?.(e,t,i);if(re.isSeq(t))return n.Seq?.(e,t,i);if(re.isPair(t))return n.Pair?.(e,t,i);if(re.isScalar(t))return n.Scalar?.(e,t,i);if(re.isAlias(t))return n.Alias?.(e,t,i);return}function qf(e,t,n){let i=t[t.length-1];if(re.isCollection(i))i.items[e]=n;else if(re.isPair(i))if(e==="key")i.key=n;else i.value=n;else if(re.isDocument(i))i.contents=n;else{let r=re.isAlias(i)?"alias":"scalar";throw Error(`Cannot replace node with ${r} parent`)}}_b.visit=cr;_b.visitAsync=ur});var Mo=M(function(Cb){var Ff=K(),Ob=Mn(),Mb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Nb=(e)=>e.replace(/[!,[\]{}]/g,(t)=>Mb[t]);class $e{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},$e.defaultYaml,e),this.tags=Object.assign({},$e.defaultTags,t)}clone(){let e=new $e(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new $e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:$e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},$e.defaultTags);break}return e}add(e,t){if(this.atNextDocument)this.yaml={explicit:$e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},$e.defaultTags),this.atNextDocument=!1;let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2){if(t(0,"%TAG directive should contain exactly two parts"),n.length<2)return!1}let[r,s]=n;return this.tags[r]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;else{let s=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,s),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);if(s==="!"||s==="!!")return t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null;if(e[e.length-1]!==">")t("Verbatim tags must end with a >");return s}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);if(!i)t(`The ${e} tag has no suffix`);let r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(s){return t(String(s)),null}if(n==="!")return e;return t(`Could not resolve tag: ${e}`),null}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Nb(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&Ff.isNode(e.contents)){let r={};Ob.visit(e.contents,(s,o)=>{if(Ff.isNode(o)&&o.tag)r[o.tag]=!0}),i=Object.keys(r)}else i=[];for(let[r,s]of n){if(r==="!!"&&s==="tag:yaml.org,2002:")continue;if(!e||i.some((o)=>o.startsWith(s)))t.push(`%TAG ${r} ${s}`)}return t.join(`
569
+ `)}}$e.defaultYaml={explicit:!1,version:"1.2"};$e.defaultTags={"!!":"tag:yaml.org,2002:"};Cb.Directives=$e});var fr=M(function(Fb){var Df=K(),Lb=Mn();function Pb(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(n)}return!0}function Uf(e){let t=new Set;return Lb.visit(e,{Value(n,i){if(i.anchor)t.add(i.anchor)}}),t}function jf(e,t){for(let n=1;;++n){let i=`${e}${n}`;if(!t.has(i))return i}}function qb(e,t){let n=[],i=new Map,r=null;return{onAnchor:(s)=>{n.push(s),r??(r=Uf(e));let o=jf(t,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o==="object"&&o.anchor&&(Df.isScalar(o.node)||Df.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}Fb.anchorIsValid=Pb;Fb.anchorNames=Uf;Fb.createNodeAnchors=qb;Fb.findNewAnchor=jf});var No=M(function(Vb){function Nn(e,t,n,i){if(i&&typeof i==="object")if(Array.isArray(i))for(let r=0,s=i.length;r<s;++r){let o=i[r],a=Nn(e,i,String(r),o);if(a===void 0)delete i[r];else if(a!==o)i[r]=a}else if(i instanceof Map)for(let r of Array.from(i.keys())){let s=i.get(r),o=Nn(e,i,r,s);if(o===void 0)i.delete(r);else if(o!==s)i.set(r,o)}else if(i instanceof Set)for(let r of Array.from(i)){let s=Nn(e,i,r,r);if(s===void 0)i.delete(r);else if(s!==r)i.delete(r),i.add(s)}else for(let[r,s]of Object.entries(i)){let o=Nn(e,i,r,s);if(o===void 0)delete i[r];else if(o!==s)i[r]=o}return e.call(t,n,i)}Vb.applyReviver=Nn});var st=M(function(Wb){var Kb=K();function Bf(e,t,n){if(Array.isArray(e))return e.map((i,r)=>Bf(i,String(r),n));if(e&&typeof e.toJSON==="function"){if(!n||!Kb.hasAnchor(e))return e.toJSON(t,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=(s)=>{i.res=s,delete n.onCreate};let r=e.toJSON(t,n);if(n.onCreate)n.onCreate(r);return r}if(typeof e==="bigint"&&!n?.keep)return Number(e);return e}Wb.toJS=Bf});var dr=M(function(zb){var Jb=No(),Vf=K(),Yb=st();class Gf{constructor(e){Object.defineProperty(this,Vf.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)e.range=this.range.slice();return e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Vf.isDocument(e))throw TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==="number"?n:100},o=Yb.toJS(this,"",s);if(typeof i==="function")for(let{count:a,res:l}of s.anchors.values())i(l,a);return typeof r==="function"?Jb.applyReviver(r,{"":o},"",o):o}}zb.NodeBase=Gf});var Cn=M(function(n0){var Xb=fr(),Zb=Mn(),zt=K(),e0=dr(),t0=st();class Kf extends e0.NodeBase{constructor(e){super(zt.ALIAS);this.source=e,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let n;if(t?.aliasResolveCache)n=t.aliasResolveCache;else if(n=[],Zb.visit(e,{Node:(r,s)=>{if(zt.isAlias(s)||zt.hasAnchor(s))n.push(s)}}),t)t.aliasResolveCache=n;let i=void 0;for(let r of n){if(r===this)break;if(r.anchor===this.source)i=r}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:r}=t,s=this.resolve(i,t);if(!s){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(a)}let o=n.get(s);if(!o)t0.toJS(s,null,t),o=n.get(s);if(o?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(r>=0){if(o.count+=1,o.aliasCount===0)o.aliasCount=pr(i,s,n);if(o.count*o.aliasCount>r)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return o.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Xb.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(r)}if(e.implicitKey)return`${i} `}return i}}function pr(e,t,n){if(zt.isAlias(t)){let i=t.resolve(e),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(zt.isCollection(t)){let i=0;for(let r of t.items){let s=pr(e,r,n);if(s>i)i=s}return i}else if(zt.isPair(t)){let i=pr(e,t.key,n),r=pr(e,t.value,n);return Math.max(i,r)}return 1}n0.Alias=Kf});var ne=M(function(l0){var r0=K(),s0=dr(),o0=st(),a0=(e)=>!e||typeof e!=="function"&&typeof e!=="object";class Ot extends s0.NodeBase{constructor(e){super(r0.SCALAR);this.value=e}toJSON(e,t){return t?.keep?this.value:o0.toJS(this.value,e,t)}toString(){return String(this.value)}}Ot.BLOCK_FOLDED="BLOCK_FOLDED";Ot.BLOCK_LITERAL="BLOCK_LITERAL";Ot.PLAIN="PLAIN";Ot.QUOTE_DOUBLE="QUOTE_DOUBLE";Ot.QUOTE_SINGLE="QUOTE_SINGLE";l0.Scalar=Ot;l0.isScalarValue=a0});var Rn=M(function(h0){var f0=Cn(),Mt=K(),Wf=ne(),d0="tag:yaml.org,2002:";function p0(e,t,n){if(t){let i=n.filter((s)=>s.tag===t),r=i.find((s)=>!s.format)??i[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find((i)=>i.identify?.(e)&&!i.format)}function m0(e,t,n){if(Mt.isDocument(e))e=e.contents;if(Mt.isNode(e))return e;if(Mt.isPair(e)){let u=n.schema[Mt.MAP].createNode?.(n.schema,null,n);return u.items.push(e),u}if(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)e=e.valueOf();let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,l=void 0;if(i&&e&&typeof e==="object")if(l=a.get(e),l)return l.anchor??(l.anchor=r(e)),new f0.Alias(l.anchor);else l={anchor:null,node:null},a.set(e,l);if(t?.startsWith("!!"))t=d0+t.slice(2);let c=p0(e,t,o.tags);if(!c){if(e&&typeof e.toJSON==="function")e=e.toJSON();if(!e||typeof e!=="object"){let u=new Wf.Scalar(e);if(l)l.node=u;return u}c=e instanceof Map?o[Mt.MAP]:(Symbol.iterator in Object(e))?o[Mt.SEQ]:o[Mt.MAP]}if(s)s(c),delete n.onTagObj;let f=c?.createNode?c.createNode(n.schema,e,n):typeof c?.nodeClass?.from==="function"?c.nodeClass.from(n.schema,e,n):new Wf.Scalar(e);if(t)f.tag=t;else if(!c.default)f.tag=c.tag;if(l)l.node=f;return f}h0.createNode=m0});var mr=M(function(w0){var y0=Rn(),Ue=K(),b0=dr();function Co(e,t,n){let i=n;for(let r=t.length-1;r>=0;--r){let s=t[r];if(typeof s==="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return y0.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Hf=(e)=>e==null||typeof e==="object"&&!!e[Symbol.iterator]().next().done;class Jf extends b0.NodeBase{constructor(e,t){super(e);Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(e)t.schema=e;if(t.items=t.items.map((n)=>Ue.isNode(n)||Ue.isPair(n)?n.clone(e):n),this.range)t.range=this.range.slice();return t}addIn(e,t){if(Hf(e))this.add(t);else{let[n,...i]=e,r=this.get(n,!0);if(Ue.isCollection(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Co(this.schema,i,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(Ue.isCollection(i))return i.deleteIn(n);else throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,r=this.get(n,!0);if(i.length===0)return!t&&Ue.isScalar(r)?r.value:r;else return Ue.isCollection(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every((t)=>{if(!Ue.isPair(t))return!1;let n=t.value;return n==null||e&&Ue.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return Ue.isCollection(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let r=this.get(n,!0);if(Ue.isCollection(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Co(this.schema,i,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}w0.Collection=Jf;w0.collectionFromPath=Co;w0.isEmptyPath=Hf});var Ln=M(function(A0){var $0=(e)=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ro(e,t){if(/^\n+$/.test(e))return e.substring(1);return t?e.replace(/^(?! *$)/gm,t):e}var k0=(e,t,n)=>e.endsWith(`
570
+ `)?Ro(n,t):n.includes(`
571
+ `)?`
572
+ `+Ro(n,t):(e.endsWith(" ")?"":" ")+n;A0.indentComment=Ro;A0.lineComment=k0;A0.stringifyComment=$0});var zf=M(function(O0){function I0(e,t,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return e;if(r<s)s=0;let l=Math.max(1+s,1+r-t.length);if(e.length<=l)return e;let c=[],f={},u=r-t.length;if(typeof i==="number")if(i>r-Math.max(2,s))c.push(0);else u=r-i;let d=void 0,g=void 0,h=!1,p=-1,m=-1,b=-1;if(n==="block"){if(p=Yf(e,p,t.length),p!==-1)u=p+l}for(let S;S=e[p+=1];){if(n==="quoted"&&S==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}b=p}if(S===`
573
+ `){if(n==="block")p=Yf(e,p,t.length);u=p+t.length+l,d=void 0}else{if(S===" "&&g&&g!==" "&&g!==`
574
+ `&&g!=="\t"){let _=e[p+1];if(_&&_!==" "&&_!==`
575
+ `&&_!=="\t")d=p}if(p>=u)if(d)c.push(d),u=d+l,d=void 0;else if(n==="quoted"){while(g===" "||g==="\t")g=S,S=e[p+=1],h=!0;let _=p>b+1?p-2:m-1;if(f[_])return e;c.push(_),f[_]=!0,u=_+l,d=void 0}else h=!0}g=S}if(h&&a)a();if(c.length===0)return e;if(o)o();let w=e.slice(0,c[0]);for(let S=0;S<c.length;++S){let _=c[S],E=c[S+1]||e.length;if(_===0)w=`
576
+ ${t}${e.slice(0,E)}`;else{if(n==="quoted"&&f[_])w+=`${e[_]}\\`;w+=`
577
+ ${t}${e.slice(_+1,E)}`}}return w}function Yf(e,t,n){let i=t,r=t+1,s=e[r];while(s===" "||s==="\t")if(t<r+n)s=e[++t];else{do s=e[++t];while(s&&s!==`
578
+ `);i=t,r=t+1,s=e[r]}return i}O0.FOLD_BLOCK="block";O0.FOLD_FLOW="flow";O0.FOLD_QUOTED="quoted";O0.foldFlowLines=I0});var qn=M(function(F0){var Me=ne(),ot=zf(),gr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),yr=(e)=>/^(%|---|\.\.\.)/m.test(e);function L0(e,t,n){if(!t||t<0)return!1;let i=t-n,r=e.length;if(r<=i)return!1;for(let s=0,o=0;s<r;++s)if(e[s]===`
579
+ `){if(s-o>i)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Pn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=t,r=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(yr(e)?" ":""),o="",a=0;for(let l=0,c=n[l];c;c=n[++l]){if(c===" "&&n[l+1]==="\\"&&n[l+2]==="n")o+=n.slice(a,l)+"\\ ",l+=1,a=l,c="\\";if(c==="\\")switch(n[l+1]){case"u":{o+=n.slice(a,l);let f=n.substr(l+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:if(f.substr(0,2)==="00")o+="\\x"+f.substr(2);else o+=n.substr(l,6)}l+=5,a=l+1}break;case"n":if(i||n[l+2]==='"'||n.length<r)l+=1;else{o+=n.slice(a,l)+`
580
+
581
+ `;while(n[l+2]==="\\"&&n[l+3]==="n"&&n[l+4]!=='"')o+=`
582
+ `,l+=2;if(o+=s,n[l+2]===" ")o+="\\";l+=1,a=l+1}break;default:l+=1}}return o=a?o+n.slice(a):n,i?o:ot.foldFlowLines(o,s,ot.FOLD_QUOTED,gr(t,!1))}function Lo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
583
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Pn(e,t);let n=t.indent||(yr(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
584
+ ${n}`)+"'";return t.implicitKey?i:ot.foldFlowLines(i,n,ot.FOLD_FLOW,gr(t,!1))}function Qt(e,t){let{singleQuote:n}=t.options,i;if(n===!1)i=Pn;else{let r=e.includes('"'),s=e.includes("'");if(r&&!s)i=Lo;else if(s&&!r)i=Pn;else i=n?Lo:Pn}return i(e,t)}var Po;try{Po=new RegExp(`(^|(?<!
585
+ ))
586
+ +(?!
587
+ |$)`,"g")}catch{Po=/\n+(?!\n|$)/g}function hr({comment:e,type:t,value:n},i,r,s){let{blockQuote:o,commentString:a,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(n))return Qt(n,i);let c=i.indent||(i.forceBlockIndent||yr(n)?" ":""),f=o==="literal"?!0:o==="folded"||t===Me.Scalar.BLOCK_FOLDED?!1:t===Me.Scalar.BLOCK_LITERAL?!0:!L0(n,l,c.length);if(!n)return f?`|
588
+ `:`>
589
+ `;let u,d;for(d=n.length;d>0;--d){let E=n[d-1];if(E!==`
590
+ `&&E!=="\t"&&E!==" ")break}let g=n.substring(d),h=g.indexOf(`
591
+ `);if(h===-1)u="-";else if(n===g||h!==g.length-1){if(u="+",s)s()}else u="";if(g){if(n=n.slice(0,-g.length),g[g.length-1]===`
592
+ `)g=g.slice(0,-1);g=g.replace(Po,`$&${c}`)}let p=!1,m,b=-1;for(m=0;m<n.length;++m){let E=n[m];if(E===" ")p=!0;else if(E===`
593
+ `)b=m;else break}let w=n.substring(0,b<m?b+1:m);if(w)n=n.substring(w.length),w=w.replace(/\n+/g,`$&${c}`);let _=(p?c?"2":"1":"")+u;if(e){if(_+=" "+a(e.replace(/ ?[\r\n]+/g," ")),r)r()}if(!f){let E=n.replace(/\n+/g,`
594
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),A=!1,k=gr(i,!0);if(o!=="folded"&&t!==Me.Scalar.BLOCK_FOLDED)k.onOverflow=()=>{A=!0};let T=ot.foldFlowLines(`${w}${E}${g}`,c,ot.FOLD_BLOCK,k);if(!A)return`>${_}
595
+ ${c}${T}`}return n=n.replace(/\n+/g,`$&${c}`),`|${_}
596
+ ${c}${w}${n}${g}`}function P0(e,t,n,i){let{type:r,value:s}=e,{actualString:o,implicitKey:a,indent:l,indentStep:c,inFlow:f}=t;if(a&&s.includes(`
597
+ `)||f&&/[[\]{},]/.test(s))return Qt(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(`
598
+ `)?Qt(s,t):hr(e,t,n,i);if(!a&&!f&&r!==Me.Scalar.PLAIN&&s.includes(`
599
+ `))return hr(e,t,n,i);if(yr(s)){if(l==="")return t.forceBlockIndent=!0,hr(e,t,n,i);else if(a&&l===c)return Qt(s,t)}let u=s.replace(/\n+/g,`$&
600
+ ${l}`);if(o){let d=(p)=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:g,tags:h}=t.doc.schema;if(h.some(d)||g?.some(d))return Qt(s,t)}return a?u:ot.foldFlowLines(u,l,ot.FOLD_FLOW,gr(t,!1))}function q0(e,t,n,i){let{implicitKey:r,inFlow:s}=t,o=typeof e.value==="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;if(a!==Me.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value))a=Me.Scalar.QUOTE_DOUBLE}let l=(f)=>{switch(f){case Me.Scalar.BLOCK_FOLDED:case Me.Scalar.BLOCK_LITERAL:return r||s?Qt(o.value,t):hr(o,t,n,i);case Me.Scalar.QUOTE_DOUBLE:return Pn(o.value,t);case Me.Scalar.QUOTE_SINGLE:return Lo(o.value,t);case Me.Scalar.PLAIN:return P0(o,t,n,i);default:return null}},c=l(a);if(c===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=r&&f||u;if(c=l(d),c===null)throw Error(`Unsupported default string type ${d}`)}return c}F0.stringifyString=q0});var Fn=M(function(H0){var U0=fr(),at=K(),j0=Ln(),B0=qn();function V0(e,t){let n=Object.assign({blockQuote:!0,commentString:j0.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent==="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function G0(e,t){if(t.tag){let r=e.filter((s)=>s.tag===t.tag);if(r.length>0)return r.find((s)=>s.format===t.format)??r[0]}let n=void 0,i;if(at.isScalar(t)){i=t.value;let r=e.filter((s)=>s.identify?.(i));if(r.length>1){let s=r.filter((o)=>o.test);if(s.length>0)r=s}n=r.find((s)=>s.format===t.format)??r.find((s)=>!s.format)}else i=t,n=e.find((r)=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw Error(`Tag not resolved for ${r} value`)}return n}function K0(e,t,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(at.isScalar(e)||at.isCollection(e))&&e.anchor;if(s&&U0.anchorIsValid(s))n.add(s),r.push(`&${s}`);let o=e.tag??(t.default?null:t.tag);if(o)r.push(i.directives.tagString(o));return r.join(" ")}function W0(e,t,n,i){if(at.isPair(e))return e.toString(t,n,i);if(at.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(t.resolvedAliases)t.resolvedAliases.add(e);else t.resolvedAliases=new Set([e]);e=e.resolve(t.doc)}}let r=void 0,s=at.isNode(e)?e:t.doc.createNode(e,{onTagObj:(l)=>r=l});r??(r=G0(t.doc.schema.tags,s));let o=K0(s,r,t);if(o.length>0)t.indentAtStart=(t.indentAtStart??0)+o.length+1;let a=typeof r.stringify==="function"?r.stringify(s,t,n,i):at.isScalar(s)?B0.stringifyString(s,t,n,i):s.toString(t,n,i);if(!o)return a;return at.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
601
+ ${t.indent}${a}`}H0.createStringifyContext=V0;H0.stringify=W0});var Zf=M(function(Q0){var We=K(),Qf=ne(),Xf=Fn(),Dn=Ln();function z0({key:e,value:t},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:l,options:{commentString:c,indentSeq:f,simpleKeys:u}}=n,d=We.isNode(e)&&e.comment||null;if(u){if(d)throw Error("With simple keys, key nodes cannot have comments");if(We.isCollection(e)||!We.isNode(e)&&typeof e==="object")throw Error("With simple keys, collection cannot be used as a key value")}let g=!u&&(!e||d&&t==null&&!n.inFlow||We.isCollection(e)||(We.isScalar(e)?e.type===Qf.Scalar.BLOCK_FOLDED||e.type===Qf.Scalar.BLOCK_LITERAL:typeof e==="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!g&&(u||!s),indent:a+l});let h=!1,p=!1,m=Xf.stringify(e,n,()=>h=!0,()=>p=!0);if(!g&&!n.inFlow&&m.length>1024){if(u)throw Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(n.inFlow){if(s||t==null){if(h&&i)i();return m===""?"?":g?`? ${m}`:m}}else if(s&&!u||t==null&&g){if(m=`? ${m}`,d&&!h)m+=Dn.lineComment(m,n.indent,c(d));else if(p&&r)r();return m}if(h)d=null;if(g){if(d)m+=Dn.lineComment(m,n.indent,c(d));m=`? ${m}
602
+ ${a}:`}else if(m=`${m}:`,d)m+=Dn.lineComment(m,n.indent,c(d));let b,w,S;if(We.isNode(t))b=!!t.spaceBefore,w=t.commentBefore,S=t.comment;else if(b=!1,w=null,S=null,t&&typeof t==="object")t=o.createNode(t);if(n.implicitKey=!1,!g&&!d&&We.isScalar(t))n.indentAtStart=m.length+1;if(p=!1,!f&&l.length>=2&&!n.inFlow&&!g&&We.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor)n.indent=n.indent.substring(2);let _=!1,E=Xf.stringify(t,n,()=>_=!0,()=>p=!0),A=" ";if(d||b||w){if(A=b?`
603
+ `:"",w){let k=c(w);A+=`
604
+ ${Dn.indentComment(k,n.indent)}`}if(E===""&&!n.inFlow){if(A===`
605
+ `&&S)A=`
606
+
607
+ `}else A+=`
608
+ ${n.indent}`}else if(!g&&We.isCollection(t)){let k=E[0],T=E.indexOf(`
609
+ `),C=T!==-1,P=n.inFlow??t.flow??t.items.length===0;if(C||!P){let L=!1;if(C&&(k==="&"||k==="!")){let D=E.indexOf(" ");if(k==="&"&&D!==-1&&D<T&&E[D+1]==="!")D=E.indexOf(" ",D+1);if(D===-1||T<D)L=!0}if(!L)A=`
610
+ ${n.indent}`}}else if(E===""||E[0]===`
611
+ `)A="";if(m+=A+E,n.inFlow){if(_&&i)i()}else if(S&&!_)m+=Dn.lineComment(m,n.indent,c(S));else if(p&&r)r();return m}Q0.stringifyPair=z0});var qo=M(function(tw){var ed=Ce("process");function Z0(e,...t){if(e==="debug")console.log(...t)}function ew(e,t){if(e==="debug"||e==="warn")if(typeof ed.emitWarning==="function")ed.emitWarning(t);else console.warn(t)}tw.debug=Z0;tw.warn=ew});var xr=M(function(sw){var vr=K(),td=ne(),br="<<",wr={identify:(e)=>e===br||typeof e==="symbol"&&e.description===br,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new td.Scalar(Symbol(br)),{addToJSMap:nd}),stringify:()=>br},rw=(e,t)=>(wr.identify(t)||vr.isScalar(t)&&(!t.type||t.type===td.Scalar.PLAIN)&&wr.identify(t.value))&&e?.doc.schema.tags.some((n)=>n.tag===wr.tag&&n.default);function nd(e,t,n){let i=id(e,n);if(vr.isSeq(i))for(let r of i.items)Fo(e,t,r);else if(Array.isArray(i))for(let r of i)Fo(e,t,r);else Fo(e,t,i)}function Fo(e,t,n){let i=id(e,n);if(!vr.isMap(i))throw Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,e,Map);for(let[s,o]of r)if(t instanceof Map){if(!t.has(s))t.set(s,o)}else if(t instanceof Set)t.add(s);else if(!Object.prototype.hasOwnProperty.call(t,s))Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function id(e,t){return e&&vr.isAlias(t)?t.resolve(e.doc,e):t}sw.addMergeToJSMap=nd;sw.isMergeKey=rw;sw.merge=wr});var Uo=M(function(pw){var cw=qo(),rd=xr(),uw=Fn(),sd=K(),Do=st();function fw(e,t,{key:n,value:i}){if(sd.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,i);else if(rd.isMergeKey(e,n))rd.addMergeToJSMap(e,t,i);else{let r=Do.toJS(n,"",e);if(t instanceof Map)t.set(r,Do.toJS(i,r,e));else if(t instanceof Set)t.add(r);else{let s=dw(n,r,e),o=Do.toJS(i,s,e);if(s in t)Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});else t[s]=o}}return t}function dw(e,t,n){if(t===null)return"";if(typeof t!=="object")return String(t);if(sd.isNode(e)&&n?.doc){let i=uw.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=e.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);if(s.length>40)s=s.substring(0,36)+'..."';cw.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}pw.addPairToJSMap=fw});var lt=M(function(bw){var od=Rn(),hw=Zf(),gw=Uo(),Sr=K();function yw(e,t,n){let i=od.createNode(e,void 0,n),r=od.createNode(t,void 0,n);return new $r(i,r)}class $r{constructor(e,t=null){Object.defineProperty(this,Sr.NODE_TYPE,{value:Sr.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;if(Sr.isNode(t))t=t.clone(e);if(Sr.isNode(n))n=n.clone(e);return new $r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return gw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?hw.stringifyPair(this,e,t,n):JSON.stringify(this)}}bw.Pair=$r;bw.createPair=yw});var jo=M(function(kw){var Nt=K(),ad=Fn(),kr=Ln();function xw(e,t,n){return(t.inFlow??e.flow?$w:Sw)(e,t,n)}function Sw({comment:e,items:t},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:l,options:{commentString:c}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let h=0;h<t.length;++h){let p=t[h],m=null;if(Nt.isNode(p)){if(!u&&p.spaceBefore)d.push("");if(Ar(n,d,p.commentBefore,u),p.comment)m=p.comment}else if(Nt.isPair(p)){let w=Nt.isNode(p.key)?p.key:null;if(w){if(!u&&w.spaceBefore)d.push("");Ar(n,d,w.commentBefore,u)}}u=!1;let b=ad.stringify(p,f,()=>m=null,()=>u=!0);if(m)b+=kr.lineComment(b,s,c(m));if(u&&m)u=!1;d.push(i+b)}let g;if(d.length===0)g=r.start+r.end;else{g=d[0];for(let h=1;h<d.length;++h){let p=d[h];g+=p?`
612
+ ${l}${p}`:`
613
+ `}}if(e){if(g+=`
614
+ `+kr.indentComment(c(e),l),a)a()}else if(u&&o)o();return g}function $w({items:e},t,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;i+=s;let l=Object.assign({},t,{indent:i,inFlow:!0,type:null}),c=!1,f=0,u=[];for(let h=0;h<e.length;++h){let p=e[h],m=null;if(Nt.isNode(p)){if(p.spaceBefore)u.push("");if(Ar(t,u,p.commentBefore,!1),p.comment)m=p.comment}else if(Nt.isPair(p)){let w=Nt.isNode(p.key)?p.key:null;if(w){if(w.spaceBefore)u.push("");if(Ar(t,u,w.commentBefore,!1),w.comment)c=!0}let S=Nt.isNode(p.value)?p.value:null;if(S){if(S.comment)m=S.comment;if(S.commentBefore)c=!0}else if(p.value==null&&w?.comment)m=w.comment}if(m)c=!0;let b=ad.stringify(p,l,()=>m=null);if(c||(c=u.length>f||b.includes(`
615
+ `)),h<e.length-1)b+=",";else if(t.options.trailingComma){if(t.options.lineWidth>0)c||(c=u.reduce((w,S)=>w+S.length+2,2)+(b.length+2)>t.options.lineWidth);if(c)b+=","}if(m)b+=kr.lineComment(b,i,a(m));u.push(b),f=u.length}let{start:d,end:g}=n;if(u.length===0)return d+g;else{if(!c){let h=u.reduce((p,m)=>p+m.length+2,2);c=t.options.lineWidth>0&&h>t.options.lineWidth}if(c){let h=d;for(let p of u)h+=p?`
616
+ ${s}${r}${p}`:`
617
+ `;return`${h}
618
+ ${r}${g}`}else return`${d}${o}${u.join(" ")}${o}${g}`}}function Ar({indent:e,options:{commentString:t}},n,i,r){if(i&&r)i=i.replace(/^\n+/,"");if(i){let s=kr.indentComment(t(i),e);n.push(s.trimStart())}}kw.stringifyCollection=xw});var ut=M(function(Ow){var Ew=jo(),_w=Uo(),Tw=mr(),ct=K(),Er=lt(),Iw=ne();function Un(e,t){let n=ct.isScalar(t)?t.value:t;for(let i of e)if(ct.isPair(i)){if(i.key===t||i.key===n)return i;if(ct.isScalar(i.key)&&i.key.value===n)return i}return}class ld extends Tw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ct.MAP,e);this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:r}=n,s=new this(e),o=(a,l)=>{if(typeof r==="function")l=r.call(t,a,l);else if(Array.isArray(r)&&!r.includes(a))return;if(l!==void 0||i)s.items.push(Er.createPair(a,l,n))};if(t instanceof Map)for(let[a,l]of t)o(a,l);else if(t&&typeof t==="object")for(let a of Object.keys(t))o(a,t[a]);if(typeof e.sortMapEntries==="function")s.items.sort(e.sortMapEntries);return s}add(e,t){let n;if(ct.isPair(e))n=e;else if(!e||typeof e!=="object"||!("key"in e))n=new Er.Pair(e,e?.value);else n=new Er.Pair(e.key,e.value);let i=Un(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw Error(`Key ${n.key} already set`);if(ct.isScalar(i.value)&&Iw.isScalarValue(n.value))i.value.value=n.value;else i.value=n.value}else if(r){let s=this.items.findIndex((o)=>r(n,o)<0);if(s===-1)this.items.push(n);else this.items.splice(s,0,n)}else this.items.push(n)}delete(e){let t=Un(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){let i=Un(this.items,e)?.value;return(!t&&ct.isScalar(i)?i.value:i)??void 0}has(e){return!!Un(this.items,e)}set(e,t){this.add(new Er.Pair(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};if(t?.onCreate)t.onCreate(i);for(let r of this.items)_w.addPairToJSMap(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ct.isPair(i))throw Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);if(!e.allNullValues&&this.hasAllNullValues(!1))e=Object.assign({},e,{allNullValues:!0});return Ew.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}Ow.YAMLMap=ld;Ow.findPair=Un});var Xt=M(function(Lw){var Cw=K(),cd=ut(),Rw={collection:"map",default:!0,nodeClass:cd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){if(!Cw.isMap(e))t("Expected a mapping for this tag");return e},createNode:(e,t,n)=>cd.YAMLMap.from(e,t,n)};Lw.map=Rw});var ft=M(function(Bw){var qw=Rn(),Fw=jo(),Dw=mr(),Tr=K(),Uw=ne(),jw=st();class ud extends Dw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Tr.SEQ,e);this.items=[]}add(e){this.items.push(e)}delete(e){let t=_r(e);if(typeof t!=="number")return!1;return this.items.splice(t,1).length>0}get(e,t){let n=_r(e);if(typeof n!=="number")return;let i=this.items[n];return!t&&Tr.isScalar(i)?i.value:i}has(e){let t=_r(e);return typeof t==="number"&&t<this.items.length}set(e,t){let n=_r(e);if(typeof n!=="number")throw Error(`Expected a valid index, not ${e}.`);let i=this.items[n];if(Tr.isScalar(i)&&Uw.isScalarValue(t))i.value=t;else this.items[n]=t}toJSON(e,t){let n=[];if(t?.onCreate)t.onCreate(n);let i=0;for(let r of this.items)n.push(jw.toJS(r,String(i++),t));return n}toString(e,t,n){if(!e)return JSON.stringify(this);return Fw.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t})}static from(e,t,n){let{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let o of t){if(typeof i==="function"){let a=t instanceof Set?o:String(s++);o=i.call(t,a,o)}r.items.push(qw.createNode(o,void 0,n))}}return r}}function _r(e){let t=Tr.isScalar(e)?e.value:e;if(t&&typeof t==="string")t=Number(t);return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:null}Bw.YAMLSeq=ud});var Zt=M(function(Ww){var Gw=K(),fd=ft(),Kw={collection:"seq",default:!0,nodeClass:fd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){if(!Gw.isSeq(e))t("Expected a sequence for this tag");return e},createNode:(e,t,n)=>fd.YAMLSeq.from(e,t,n)};Ww.seq=Kw});var jn=M(function(zw){var Jw=qn(),Yw={identify:(e)=>typeof e==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(e)=>e,stringify(e,t,n,i){return t=Object.assign({actualString:!0},t),Jw.stringifyString(e,t,n,i)}};zw.string=Yw});var Ir=M(function(Xw){var dd=ne(),pd={identify:(e)=>e==null,createNode:()=>new dd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new dd.Scalar(null),stringify:({source:e},t)=>typeof e==="string"&&pd.test.test(e)?e:t.options.nullStr};Xw.nullTag=pd});var Bo=M(function(t1){var e1=ne(),md={identify:(e)=>typeof e==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(e)=>new e1.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&md.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?n.options.trueStr:n.options.falseStr}};t1.boolTag=md});var en=M(function(r1){function i1({format:e,minFractionDigits:t,tag:n,value:i}){if(typeof i==="bigint")return String(i);let r=typeof i==="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");if(o<0)o=s.length,s+=".";let a=t-(s.length-o-1);while(a-- >0)s+="0"}return s}r1.stringifyNumber=i1});var Go=M(function(u1){var o1=ne(),Vo=en(),a1={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(e)=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Vo.stringifyNumber},l1={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(e)=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Vo.stringifyNumber(e)}},c1={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new o1.Scalar(parseFloat(e)),n=e.indexOf(".");if(n!==-1&&e[e.length-1]==="0")t.minFractionDigits=e.length-n-1;return t},stringify:Vo.stringifyNumber};u1.float=c1;u1.floatExp=l1;u1.floatNaN=a1});var Wo=M(function(y1){var hd=en(),Or=(e)=>typeof e==="bigint"||Number.isInteger(e),Ko=(e,t,n,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),n);function gd(e,t,n){let{value:i}=e;if(Or(i)&&i>=0)return n+i.toString(t);return hd.stringifyNumber(e)}var m1={identify:(e)=>Or(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Ko(e,2,8,n),stringify:(e)=>gd(e,8,"0o")},h1={identify:Or,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Ko(e,0,10,n),stringify:hd.stringifyNumber},g1={identify:(e)=>Or(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Ko(e,2,16,n),stringify:(e)=>gd(e,16,"0x")};y1.int=h1;y1.intHex=g1;y1.intOct=m1});var yd=M(function(_1){var x1=Xt(),S1=Ir(),$1=Zt(),k1=jn(),A1=Bo(),Ho=Go(),Jo=Wo(),E1=[x1.map,$1.seq,k1.string,S1.nullTag,A1.boolTag,Jo.intOct,Jo.int,Jo.intHex,Ho.floatNaN,Ho.floatExp,Ho.float];_1.schema=E1});var wd=M(function(L1){var I1=ne(),O1=Xt(),M1=Zt();function bd(e){return typeof e==="bigint"||Number.isInteger(e)}var Mr=({value:e})=>JSON.stringify(e),N1=[{identify:(e)=>typeof e==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(e)=>e,stringify:Mr},{identify:(e)=>e==null,createNode:()=>new I1.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Mr},{identify:(e)=>typeof e==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(e)=>e==="true",stringify:Mr},{identify:bd,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>bd(e)?e.toString():JSON.stringify(e)},{identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(e)=>parseFloat(e),stringify:Mr}],C1={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},R1=[O1.map,M1.seq].concat(N1,C1);L1.schema=R1});var zo=M(function(D1){var Bn=Ce("buffer"),Yo=ne(),q1=qn(),F1={identify:(e)=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Bn.Buffer==="function")return Bn.Buffer.from(e,"base64");else if(typeof atob==="function"){let n=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r<n.length;++r)i[r]=n.charCodeAt(r);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},i,r,s){if(!n)return"";let o=n,a;if(typeof Bn.Buffer==="function")a=o instanceof Bn.Buffer?o.toString("base64"):Bn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa==="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);a=btoa(l)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Yo.Scalar.BLOCK_LITERAL),t!==Yo.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(a.length/l),f=Array(c);for(let u=0,d=0;u<c;++u,d+=l)f[u]=a.substr(d,l);a=f.join(t===Yo.Scalar.BLOCK_LITERAL?`
619
+ `:" ")}return q1.stringifyString({comment:e,type:t,value:a},i,r,s)}};D1.binary=F1});var Cr=M(function(G1){var Nr=K(),Qo=lt(),j1=ne(),B1=ft();function vd(e,t){if(Nr.isSeq(e))for(let n=0;n<e.items.length;++n){let i=e.items[n];if(Nr.isPair(i))continue;else if(Nr.isMap(i)){if(i.items.length>1)t("Each pair must have its own sequence indicator");let r=i.items[0]||new Qo.Pair(new j1.Scalar(null));if(i.commentBefore)r.key.commentBefore=r.key.commentBefore?`${i.commentBefore}
620
+ ${r.key.commentBefore}`:i.commentBefore;if(i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment}
621
+ ${s.comment}`:i.comment}i=r}e.items[n]=Nr.isPair(i)?i:new Qo.Pair(i)}else t("Expected a sequence for this tag");return e}function xd(e,t,n){let{replacer:i}=n,r=new B1.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){if(typeof i==="function")o=i.call(t,String(s++),o);let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)a=c[0],l=o[a];else throw TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=o;r.items.push(Qo.createPair(a,l,n))}return r}var V1={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vd,createNode:xd};G1.createPairs=xd;G1.pairs=V1;G1.resolvePairs=vd});var Zo=M(function(z1){var Sd=K(),Xo=st(),Vn=ut(),J1=ft(),$d=Cr();class Ct extends J1.YAMLSeq{constructor(){super();this.add=Vn.YAMLMap.prototype.add.bind(this),this.delete=Vn.YAMLMap.prototype.delete.bind(this),this.get=Vn.YAMLMap.prototype.get.bind(this),this.has=Vn.YAMLMap.prototype.has.bind(this),this.set=Vn.YAMLMap.prototype.set.bind(this),this.tag=Ct.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;if(t?.onCreate)t.onCreate(n);for(let i of this.items){let r,s;if(Sd.isPair(i))r=Xo.toJS(i.key,"",t),s=Xo.toJS(i.value,r,t);else r=Xo.toJS(i,"",t);if(n.has(r))throw Error("Ordered maps must not include duplicate keys");n.set(r,s)}return n}static from(e,t,n){let i=$d.createPairs(e,t,n),r=new this;return r.items=i.items,r}}Ct.tag="tag:yaml.org,2002:omap";var Y1={collection:"seq",identify:(e)=>e instanceof Map,nodeClass:Ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=$d.resolvePairs(e,t),i=[];for(let{key:r}of n.items)if(Sd.isScalar(r))if(i.includes(r.value))t(`Ordered maps must not include duplicate keys: ${r.value}`);else i.push(r.value);return Object.assign(new Ct,n)},createNode:(e,t,n)=>Ct.from(e,t,n)};z1.YAMLOMap=Ct;z1.omap=Y1});var Td=M(function(Z1){var kd=ne();function Ad({value:e,source:t},n){if(t&&(e?Ed:_d).test.test(t))return t;return e?n.options.trueStr:n.options.falseStr}var Ed={identify:(e)=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new kd.Scalar(!0),stringify:Ad},_d={identify:(e)=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new kd.Scalar(!1),stringify:Ad};Z1.falseTag=_d;Z1.trueTag=Ed});var Id=M(function(ov){var nv=ne(),ea=en(),iv={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(e)=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ea.stringifyNumber},rv={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(e)=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ea.stringifyNumber(e)}},sv={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new nv.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let i=e.substring(n+1).replace(/_/g,"");if(i[i.length-1]==="0")t.minFractionDigits=i.length}return t},stringify:ea.stringifyNumber};ov.float=sv;ov.floatExp=rv;ov.floatNaN=iv});var Md=M(function(mv){var Od=en(),Gn=(e)=>typeof e==="bigint"||Number.isInteger(e);function Rr(e,t,n,{intAsBigInt:i}){let r=e[0];if(r==="-"||r==="+")t+=1;if(e=e.substring(t).replace(/_/g,""),i){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return r==="-"?-1*s:s}function ta(e,t,n){let{value:i}=e;if(Gn(i)){let r=i.toString(t);return i<0?"-"+n+r.substr(1):n+r}return Od.stringifyNumber(e)}var uv={identify:Gn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Rr(e,2,2,n),stringify:(e)=>ta(e,2,"0b")},fv={identify:Gn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Rr(e,1,8,n),stringify:(e)=>ta(e,8,"0")},dv={identify:Gn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Rr(e,0,10,n),stringify:Od.stringifyNumber},pv={identify:Gn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Rr(e,2,16,n),stringify:(e)=>ta(e,16,"0x")};mv.int=dv;mv.intBin=uv;mv.intHex=pv;mv.intOct=fv});var na=M(function(vv){var qr=K(),Lr=lt(),Pr=ut();class Rt extends Pr.YAMLMap{constructor(e){super(e);this.tag=Rt.tag}add(e){let t;if(qr.isPair(e))t=e;else if(e&&typeof e==="object"&&"key"in e&&"value"in e&&e.value===null)t=new Lr.Pair(e.key,null);else t=new Lr.Pair(e,null);if(!Pr.findPair(this.items,t.key))this.items.push(t)}get(e,t){let n=Pr.findPair(this.items,e);return!t&&qr.isPair(n)?qr.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Pr.findPair(this.items,e);if(n&&!t)this.items.splice(this.items.indexOf(n),1);else if(!n&&t)this.items.push(new Lr.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);else throw Error("Set items must all have null values")}static from(e,t,n){let{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let s of t){if(typeof i==="function")s=i.call(t,s,s);r.items.push(Lr.createPair(s,null,n))}return r}}Rt.tag="tag:yaml.org,2002:set";var wv={collection:"map",identify:(e)=>e instanceof Set,nodeClass:Rt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Rt.from(e,t,n),resolve(e,t){if(qr.isMap(e))if(e.hasAllNullValues(!0))return Object.assign(new Rt,e);else t("Set items must all have null values");else t("Expected a mapping for this tag");return e}};vv.YAMLSet=Rt;vv.set=wv});var ra=M(function(Ev){var $v=en();function ia(e,t){let n=e[0],i=n==="-"||n==="+"?e.substring(1):e,r=(o)=>t?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Nd(e){let{value:t}=e,n=(o)=>o;if(typeof t==="bigint")n=(o)=>BigInt(o);else if(isNaN(t)||!isFinite(t))return $v.stringifyNumber(e);let i="";if(t<0)i="-",t*=n(-1);let r=n(60),s=[t%r];if(t<60)s.unshift(0);else if(t=(t-s[0])/r,s.unshift(t%r),t>=60)t=(t-s[0])/r,s.unshift(t);return i+s.map((o)=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var kv={identify:(e)=>typeof e==="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ia(e,n),stringify:Nd},Av={identify:(e)=>typeof e==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(e)=>ia(e,!1),stringify:Nd},Cd={identify:(e)=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Cd.test);if(!t)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(n,i-1,r,s||0,o||0,a||0,l),f=t[8];if(f&&f!=="Z"){let u=ia(f,!1);if(Math.abs(u)<30)u*=60;c-=60000*u}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ev.floatTime=Av;Ev.intTime=kv;Ev.timestamp=Cd});var Ld=M(function(Uv){var Ov=Xt(),Mv=Ir(),Nv=Zt(),Cv=jn(),Rv=zo(),Rd=Td(),sa=Id(),Fr=Md(),Lv=xr(),Pv=Zo(),qv=Cr(),Fv=na(),oa=ra(),Dv=[Ov.map,Nv.seq,Cv.string,Mv.nullTag,Rd.trueTag,Rd.falseTag,Fr.intBin,Fr.intOct,Fr.int,Fr.intHex,sa.floatNaN,sa.floatExp,sa.float,Rv.binary,Lv.merge,Pv.omap,qv.pairs,Fv.set,oa.intTime,oa.floatTime,oa.timestamp];Uv.schema=Dv});var Kd=M(function(Yv){var Dd=Xt(),Bv=Ir(),Ud=Zt(),Vv=jn(),Gv=Bo(),aa=Go(),la=Wo(),Kv=yd(),Wv=wd(),jd=zo(),Kn=xr(),Bd=Zo(),Vd=Cr(),Pd=Ld(),Gd=na(),Dr=ra(),qd=new Map([["core",Kv.schema],["failsafe",[Dd.map,Ud.seq,Vv.string]],["json",Wv.schema],["yaml11",Pd.schema],["yaml-1.1",Pd.schema]]),Fd={binary:jd.binary,bool:Gv.boolTag,float:aa.float,floatExp:aa.floatExp,floatNaN:aa.floatNaN,floatTime:Dr.floatTime,int:la.int,intHex:la.intHex,intOct:la.intOct,intTime:Dr.intTime,map:Dd.map,merge:Kn.merge,null:Bv.nullTag,omap:Bd.omap,pairs:Vd.pairs,seq:Ud.seq,set:Gd.set,timestamp:Dr.timestamp},Hv={"tag:yaml.org,2002:binary":jd.binary,"tag:yaml.org,2002:merge":Kn.merge,"tag:yaml.org,2002:omap":Bd.omap,"tag:yaml.org,2002:pairs":Vd.pairs,"tag:yaml.org,2002:set":Gd.set,"tag:yaml.org,2002:timestamp":Dr.timestamp};function Jv(e,t,n){let i=qd.get(t);if(i&&!e)return n&&!i.includes(Kn.merge)?i.concat(Kn.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let s=Array.from(qd.keys()).filter((o)=>o!=="yaml11").map((o)=>JSON.stringify(o)).join(", ");throw Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)r=r.concat(s);else if(typeof e==="function")r=e(r.slice());if(n)r=r.concat(Kn.merge);return r.reduce((s,o)=>{let a=typeof o==="string"?Fd[o]:o;if(!a){let l=JSON.stringify(o),c=Object.keys(Fd).map((f)=>JSON.stringify(f)).join(", ");throw Error(`Unknown custom tag ${l}; use one of ${c}`)}if(!s.includes(a))s.push(a);return s},[])}Yv.coreKnownTags=Hv;Yv.getTags=Jv});var fa=M(function(nx){var ca=K(),Xv=Xt(),Zv=Zt(),ex=jn(),Ur=Kd(),tx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class ua{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?Ur.getTags(e,"compat"):e?Ur.getTags(null,e):null,this.name=typeof r==="string"&&r||"core",this.knownTags=i?Ur.coreKnownTags:{},this.tags=Ur.getTags(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,ca.MAP,{value:Xv.map}),Object.defineProperty(this,ca.SCALAR,{value:ex.string}),Object.defineProperty(this,ca.SEQ,{value:Zv.seq}),this.sortMapEntries=typeof s==="function"?s:s===!0?tx:null}clone(){let e=Object.create(ua.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}nx.Schema=ua});var Wd=M(function(ox){var rx=K(),da=Fn(),Wn=Ln();function sx(e,t){let n=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);if(l)n.push(l),i=!0;else if(e.directives.docStart)i=!0}if(i)n.push("---");let r=da.createStringifyContext(e,t),{commentString:s}=r.options;if(e.commentBefore){if(n.length!==1)n.unshift("");let l=s(e.commentBefore);n.unshift(Wn.indentComment(l,""))}let o=!1,a=null;if(e.contents){if(rx.isNode(e.contents)){if(e.contents.spaceBefore&&i)n.push("");if(e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Wn.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let l=a?void 0:()=>o=!0,c=da.stringify(e.contents,r,()=>a=null,l);if(a)c+=Wn.lineComment(c,"",s(a));if((c[0]==="|"||c[0]===">")&&n[n.length-1]==="---")n[n.length-1]=`--- ${c}`;else n.push(c)}else n.push(da.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let l=s(e.comment);if(l.includes(`
622
+ `))n.push("..."),n.push(Wn.indentComment(l,""));else n.push(`... ${l}`)}else n.push("...");else{let l=e.comment;if(l&&o)l=l.replace(/^\n+/,"");if(l){if((!o||a)&&n[n.length-1]!=="")n.push("");n.push(Wn.indentComment(s(l),""))}}return n.join(`
623
+ `)+`
624
+ `}ox.stringifyDocument=sx});var Hn=M(function(hx){var lx=Cn(),tn=mr(),ke=K(),cx=lt(),ux=st(),fx=fa(),dx=Wd(),pa=fr(),px=No(),mx=Rn(),ma=Mo();class ha{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke.NODE_TYPE,{value:ke.DOC});let i=null;if(typeof t==="function"||Array.isArray(t))i=t;else if(n===void 0&&t)n=t,t=void 0;let r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:s}=r;if(n?._directives){if(this.directives=n._directives.atDocument(),this.directives.yaml.explicit)s=this.directives.yaml.version}else this.directives=new ma.Directives({version:s});this.setSchema(s,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(ha.prototype,{[ke.NODE_TYPE]:{value:ke.DOC}});if(e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives)e.directives=this.directives.clone();if(e.schema=this.schema.clone(),e.contents=ke.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range)e.range=this.range.slice();return e}add(e){if(nn(this.contents))this.contents.add(e)}addIn(e,t){if(nn(this.contents))this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=pa.anchorNames(this);e.anchor=!t||n.has(t)?pa.findNewAnchor(t||"a",n):t}return new lx.Alias(e.anchor)}createNode(e,t,n){let i=void 0;if(typeof t==="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let p=(b)=>typeof b==="number"||b instanceof String||b instanceof Number,m=t.filter(p).map(String);if(m.length>0)t=t.concat(m);i=t}else if(n===void 0&&t)n=t,t=void 0;let{aliasDuplicateObjects:r,anchorPrefix:s,flow:o,keepUndefined:a,onTagObj:l,tag:c}=n??{},{onAnchor:f,setAnchors:u,sourceObjects:d}=pa.createNodeAnchors(this,s||"a"),g={aliasDuplicateObjects:r??!0,keepUndefined:a??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:d},h=mx.createNode(e,c,g);if(o&&ke.isCollection(h))h.flow=!0;return u(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new cx.Pair(i,r)}delete(e){return nn(this.contents)?this.contents.delete(e):!1}deleteIn(e){if(tn.isEmptyPath(e)){if(this.contents==null)return!1;return this.contents=null,!0}return nn(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ke.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){if(tn.isEmptyPath(e))return!t&&ke.isScalar(this.contents)?this.contents.value:this.contents;return ke.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ke.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){if(tn.isEmptyPath(e))return this.contents!==void 0;return ke.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){if(this.contents==null)this.contents=tn.collectionFromPath(this.schema,[e],t);else if(nn(this.contents))this.contents.set(e,t)}setIn(e,t){if(tn.isEmptyPath(e))this.contents=t;else if(this.contents==null)this.contents=tn.collectionFromPath(this.schema,Array.from(e),t);else if(nn(this.contents))this.contents.setIn(e,t)}setSchema(e,t={}){if(typeof e==="number")e=String(e);let n;switch(e){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new ma.Directives({version:"1.1"});n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=e;else this.directives=new ma.Directives({version:e});n={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;n=null;break;default:{let i=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new fx.Schema(Object.assign(n,t));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i==="number"?i:100},a=ux.toJS(this.contents,t??"",o);if(typeof r==="function")for(let{count:l,res:c}of o.anchors.values())r(c,l);return typeof s==="function"?px.applyReviver(s,{"":a},"",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return dx.stringifyDocument(this,e)}}function nn(e){if(ke.isCollection(e))return!0;throw Error("Expected a YAML collection as document contents")}hx.Document=ha});var Jn=M(function(bx){class jr extends Error{constructor(e,t,n,i){super();this.name=e,this.code=n,this.message=i,this.pos=t}}class Hd extends jr{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Jd extends jr{constructor(e,t,n){super("YAMLWarning",e,t,n)}}var yx=(e,t)=>(n)=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map((a)=>t.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80)o=o.substring(0,79)+"…";if(i>1&&/^ *$/.test(o.substring(0,s))){let a=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);if(a.length>80)a=a.substring(0,79)+`…
625
+ `;o=a+o}if(/[^ ]/.test(o)){let a=1,l=n.linePos[1];if(l?.line===i&&l.col>r)a=Math.max(1,Math.min(l.col-r,80-s));let c=" ".repeat(s)+"^".repeat(a);n.message+=`:
626
+
627
+ ${o}
628
+ ${c}
629
+ `}};bx.YAMLError=jr;bx.YAMLParseError=Hd;bx.YAMLWarning=Jd;bx.prettifyError=yx});var Yn=M(function(kx){function $x(e,{flow:t,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let l=!1,c=a,f=a,u="",d="",g=!1,h=!1,p=null,m=null,b=null,w=null,S=null,_=null,E=null;for(let T of e){if(h){if(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma")s(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");h=!1}if(p){if(c&&T.type!=="comment"&&T.type!=="newline")s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation");p=null}switch(T.type){case"space":if(!t&&(n!=="doc-start"||i?.type!=="flow-collection")&&T.source.includes("\t"))p=T;f=!0;break;case"comment":{if(!f)s(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=T.source.substring(1)||" ";if(!u)u=C;else u+=d+C;d="",c=!1;break}case"newline":if(c){if(u)u+=T.source;else if(!_||n!=="seq-item-ind")l=!0}else d+=T.source;if(c=!0,g=!0,m||b)w=T;f=!0;break;case"anchor":if(m)s(T,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(T.source.endsWith(":"))s(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);m=T,E??(E=T.offset),c=!1,f=!1,h=!0;break;case"tag":{if(b)s(T,"MULTIPLE_TAGS","A node can have at most one tag");b=T,E??(E=T.offset),c=!1,f=!1,h=!0;break}case n:if(m||b)s(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`);if(_)s(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${t??"collection"}`);_=T,c=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){if(S)s(T,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`);S=T,c=!1,f=!1;break}default:s(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),c=!1,f=!1}}let A=e[e.length-1],k=A?A.offset+A.source.length:r;if(h&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!==""))s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(p&&(c&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq"))s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:S,found:_,spaceBefore:l,comment:u,hasNewline:g,anchor:m,tag:b,newlineAfterProp:w,end:k,start:E??k}}kx.resolveProps=$x});var Br=M(function(Ex){function ga(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
630
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(ga(t.key)||ga(t.value))return!0}return!1;default:return!0}}Ex.containsNewline=ga});var ya=M(function(Ox){var Tx=Br();function Ix(e,t,n){if(t?.type==="flow-collection"){let i=t.end[0];if(i.indent===e&&(i.source==="]"||i.source==="}")&&Tx.containsNewline(t))n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ox.flowIndentCheck=Ix});var ba=M(function(Cx){var Yd=K();function Nx(e,t,n){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let r=typeof i==="function"?i:(s,o)=>s===o||Yd.isScalar(s)&&Yd.isScalar(o)&&s.value===o.value;return t.some((s)=>r(s.key,n))}Cx.mapIncludes=Nx});var ep=M(function(Dx){var zd=lt(),Lx=ut(),Qd=Yn(),Px=Br(),Xd=ya(),qx=ba(),Zd="All mapping items must start at the same column";function Fx({composeNode:e,composeEmptyNode:t},n,i,r,s){let a=new(s?.nodeClass??Lx.YAMLMap)(n.schema);if(n.atRoot)n.atRoot=!1;let l=i.offset,c=null;for(let f of i.items){let{start:u,key:d,sep:g,value:h}=f,p=Qd.resolveProps(u,{indicator:"explicit-key-ind",next:d??g?.[0],offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d){if(d.type==="block-seq")r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in d&&d.indent!==i.indent)r(l,"BAD_INDENT",Zd)}if(!p.anchor&&!p.tag&&!g){if(c=p.end,p.comment)if(a.comment)a.comment+=`
631
+ `+p.comment;else a.comment=p.comment;continue}if(p.newlineAfterProp||Px.containsNewline(d))r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(p.found?.indent!==i.indent)r(l,"BAD_INDENT",Zd);n.atKey=!0;let b=p.end,w=d?e(n,d,p,r):t(n,b,u,null,p,r);if(n.schema.compat)Xd.flowIndentCheck(i.indent,d,r);if(n.atKey=!1,qx.mapIncludes(n,a.items,w))r(b,"DUPLICATE_KEY","Map keys must be unique");let S=Qd.resolveProps(g??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(l=S.end,S.found){if(m){if(h?.type==="block-map"&&!S.hasNewline)r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(n.options.strict&&p.start<S.found.offset-1024)r(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let _=h?e(n,h,S,r):t(n,l,g,null,S,r);if(n.schema.compat)Xd.flowIndentCheck(i.indent,h,r);l=_.range[2];let E=new zd.Pair(w,_);if(n.options.keepSourceTokens)E.srcToken=f;a.items.push(E)}else{if(m)r(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(S.comment)if(w.comment)w.comment+=`
632
+ `+S.comment;else w.comment=S.comment;let _=new zd.Pair(w);if(n.options.keepSourceTokens)_.srcToken=f;a.items.push(_)}}if(c&&c<l)r(c,"IMPOSSIBLE","Map comment with trailing content");return a.range=[i.offset,l,c??l],a}Dx.resolveBlockMap=Fx});var tp=M(function(Kx){var jx=ft(),Bx=Yn(),Vx=ya();function Gx({composeNode:e,composeEmptyNode:t},n,i,r,s){let a=new(s?.nodeClass??jx.YAMLSeq)(n.schema);if(n.atRoot)n.atRoot=!1;if(n.atKey)n.atKey=!1;let l=i.offset,c=null;for(let{start:f,value:u}of i.items){let d=Bx.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)if(u?.type==="block-seq")r(d.end,"BAD_INDENT","All sequence items must start at the same column");else r(l,"MISSING_CHAR","Sequence item without - indicator");else{if(c=d.end,d.comment)a.comment=d.comment;continue}let g=u?e(n,u,d,r):t(n,d.end,f,null,d,r);if(n.schema.compat)Vx.flowIndentCheck(i.indent,u,r);l=g.range[2],a.items.push(g)}return a.range=[i.offset,l,c??l],a}Kx.resolveBlockSeq=Gx});var rn=M(function(Jx){function Hx(e,t,n,i){let r="";if(e){let s=!1,o="";for(let a of e){let{source:l,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{if(n&&!s)i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=l.substring(1)||" ";if(!r)r=f;else r+=o+f;o="";break}case"newline":if(r)o+=l;s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:r,offset:t}}Jx.resolveEnd=Hx});var rp=M(function(iS){var zx=K(),Qx=lt(),np=ut(),Xx=ft(),Zx=rn(),ip=Yn(),eS=Br(),tS=ba(),wa="Block collections are not allowed within flow collections",va=(e)=>e&&(e.type==="block-map"||e.type==="block-seq");function nS({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=new(s?.nodeClass??(o?np.YAMLMap:Xx.YAMLSeq))(n.schema);c.flow=!0;let f=n.atRoot;if(f)n.atRoot=!1;if(n.atKey)n.atKey=!1;let u=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let b=i.items[m],{start:w,key:S,sep:_,value:E}=b,A=ip.resolveProps(w,{flow:a,indicator:"explicit-key-ind",next:S??_?.[0],offset:u,onError:r,parentIndent:i.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!_&&!E){if(m===0&&A.comma)r(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(m<i.items.length-1)r(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`);if(A.comment)if(c.comment)c.comment+=`
633
+ `+A.comment;else c.comment=A.comment;u=A.end;continue}if(!o&&n.options.strict&&eS.containsNewline(S))r(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0){if(A.comma)r(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`)}else{if(!A.comma)r(A.start,"MISSING_CHAR",`Missing , between ${a} items`);if(A.comment){let k="";e:for(let T of w)switch(T.type){case"comma":case"space":break;case"comment":k=T.source.substring(1);break e;default:break e}if(k){let T=c.items[c.items.length-1];if(zx.isPair(T))T=T.value??T.key;if(T.comment)T.comment+=`
634
+ `+k;else T.comment=k;A.comment=A.comment.substring(k.length+1)}}}if(!o&&!_&&!A.found){let k=E?e(n,E,A,r):t(n,A.end,_,null,A,r);if(c.items.push(k),u=k.range[2],va(E))r(k.range,"BLOCK_IN_FLOW",wa)}else{n.atKey=!0;let k=A.end,T=S?e(n,S,A,r):t(n,k,w,null,A,r);if(va(S))r(T.range,"BLOCK_IN_FLOW",wa);n.atKey=!1;let C=ip.resolveProps(_??[],{flow:a,indicator:"map-value-ind",next:E,offset:T.range[2],onError:r,parentIndent:i.indent,startOnNewline:!1});if(C.found){if(!o&&!A.found&&n.options.strict){if(_)for(let D of _){if(D===C.found)break;if(D.type==="newline"){r(D,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(A.start<C.found.offset-1024)r(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(E)if("source"in E&&E.source?.[0]===":")r(E,"MISSING_CHAR",`Missing space after : in ${a}`);else r(C.start,"MISSING_CHAR",`Missing , or : between ${a} items`);let P=E?e(n,E,C,r):C.found?t(n,C.end,_,null,C,r):null;if(P){if(va(E))r(P.range,"BLOCK_IN_FLOW",wa)}else if(C.comment)if(T.comment)T.comment+=`
635
+ `+C.comment;else T.comment=C.comment;let L=new Qx.Pair(T,P);if(n.options.keepSourceTokens)L.srcToken=b;if(o){let D=c;if(tS.mapIncludes(n,D.items,T))r(k,"DUPLICATE_KEY","Map keys must be unique");D.items.push(L)}else{let D=new np.YAMLMap(n.schema);D.flow=!0,D.items.push(L);let U=(P??T).range;D.range=[T.range[0],U[1],U[2]],c.items.push(D)}u=P?P.range[2]:C.end}}let d=o?"}":"]",[g,...h]=i.end,p=u;if(g?.source===d)p=g.offset+g.source.length;else{let m=a[0].toUpperCase()+a.substring(1),b=f?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;if(r(u,f?"MISSING_CHAR":"BAD_INDENT",b),g&&g.source.length!==1)h.unshift(g)}if(h.length>0){let m=Zx.resolveEnd(h,p,n.options.strict,r);if(m.comment)if(c.comment)c.comment+=`
636
+ `+m.comment;else c.comment=m.comment;c.range=[i.offset,p,m.offset]}else c.range=[i.offset,p,p];return c}iS.resolveFlowCollection=nS});var sp=M(function(pS){var sS=K(),oS=ne(),aS=ut(),lS=ft(),cS=ep(),uS=tp(),fS=rp();function xa(e,t,n,i,r,s){let o=n.type==="block-map"?cS.resolveBlockMap(e,t,n,i,s):n.type==="block-seq"?uS.resolveBlockSeq(e,t,n,i,s):fS.resolveFlowCollection(e,t,n,i,s),a=o.constructor;if(r==="!"||r===a.tagName)return o.tag=a.tagName,o;if(r)o.tag=r;return o}function dS(e,t,n,i,r){let s=i.tag,o=!s?null:t.directives.tagName(s.source,(d)=>r(s,"TAG_RESOLVE_FAILED",d));if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:g}=i,h=d&&s?d.offset>s.offset?d:s:d??s;if(h&&(!g||g.offset<h.offset))r(h,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===aS.YAMLMap.tagName&&a==="map"||o===lS.YAMLSeq.tagName&&a==="seq")return xa(e,t,n,r,o);let l=t.schema.tags.find((d)=>d.tag===o&&d.collection===a);if(!l){let d=t.schema.knownTags[o];if(d?.collection===a)t.schema.tags.push(Object.assign({},d,{default:!1})),l=d;else{if(d)r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0);else r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0);return xa(e,t,n,r,o)}}let c=xa(e,t,n,r,o,l),f=l.resolve?.(c,(d)=>r(s,"TAG_RESOLVE_FAILED",d),t.options)??c,u=sS.isNode(f)?f:new oS.Scalar(f);if(u.range=c.range,u.tag=o,l?.format)u.format=l.format;return u}pS.composeCollection=dS});var $a=M(function(bS){var Sa=ne();function hS(e,t,n){let i=t.offset,r=gS(t,e.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?Sa.Scalar.BLOCK_FOLDED:Sa.Scalar.BLOCK_LITERAL,o=t.source?yS(t.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?`
637
+ `.repeat(Math.max(1,o.length-1)):"",m=i+r.length;if(t.source)m+=t.source.length;return{value:p,type:s,comment:r.comment,range:[i,m,m]}}let l=t.indent+r.indent,c=t.offset+r.length,f=0;for(let p=0;p<a;++p){let[m,b]=o[p];if(b===""||b==="\r"){if(r.indent===0&&m.length>l)l=m.length}else{if(m.length<l)n(c+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(r.indent===0)l=m.length;if(f=p,l===0&&!e.atRoot)n(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=m.length+b.length+1}for(let p=o.length-1;p>=a;--p)if(o[p][0].length>l)a=p+1;let u="",d="",g=!1;for(let p=0;p<f;++p)u+=o[p][0].slice(l)+`
638
+ `;for(let p=f;p<a;++p){let[m,b]=o[p];c+=m.length+b.length+1;let w=b[b.length-1]==="\r";if(w)b=b.slice(0,-1);if(b&&m.length<l){let _=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;n(c-b.length-(w?2:1),"BAD_INDENT",_),m=""}if(s===Sa.Scalar.BLOCK_LITERAL)u+=d+m.slice(l)+b,d=`
639
+ `;else if(m.length>l||b[0]==="\t"){if(d===" ")d=`
640
+ `;else if(!g&&d===`
641
+ `)d=`
642
+
643
+ `;u+=d+m.slice(l)+b,d=`
644
+ `,g=!0}else if(b==="")if(d===`
645
+ `)u+=`
646
+ `;else d=`
647
+ `;else u+=d+b,d=" ",g=!1}switch(r.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)u+=`
648
+ `+o[p][0].slice(l);if(u[u.length-1]!==`
649
+ `)u+=`
650
+ `;break;default:u+=`
651
+ `}let h=i+r.length+t.source.length;return{value:u,type:s,comment:r.comment,range:[i,h,h]}}function gS({offset:e,props:t},n,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],s=r[0],o=0,a="",l=-1;for(let d=1;d<r.length;++d){let g=r[d];if(!a&&(g==="-"||g==="+"))a=g;else{let h=Number(g);if(!o&&h)o=h;else if(l===-1)l=e+d}}if(l!==-1)i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let c=!1,f="",u=r.length;for(let d=1;d<t.length;++d){let g=t[d];switch(g.type){case"space":c=!0;case"newline":u+=g.source.length;break;case"comment":if(n&&!c)i(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");u+=g.source.length,f=g.source.substring(1);break;case"error":i(g,"UNEXPECTED_TOKEN",g.message),u+=g.source.length;break;default:{let h=`Unexpected token in block scalar header: ${g.type}`;i(g,"UNEXPECTED_TOKEN",h);let p=g.source;if(p&&typeof p==="string")u+=p.length}}}return{mode:s,indent:o,chomp:a,comment:f,length:u}}function yS(e){let t=e.split(/\n( *)/),n=t[0],i=n.match(/^( *)/),s=[i?.[1]?[i[1],n.slice(i[1].length)]:["",n]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}bS.resolveBlockScalar=hS});var Aa=M(function(TS){var ka=ne(),vS=rn();function xS(e,t,n){let{offset:i,type:r,source:s,end:o}=e,a,l,c=(d,g,h)=>n(i+d,g,h);switch(r){case"scalar":a=ka.Scalar.PLAIN,l=SS(s,c);break;case"single-quoted-scalar":a=ka.Scalar.QUOTE_SINGLE,l=$S(s,c);break;case"double-quoted-scalar":a=ka.Scalar.QUOTE_DOUBLE,l=kS(s,c);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=vS.resolveEnd(o,f,t,n);return{value:l,type:a,comment:u.comment,range:[i,f,u.offset]}}function SS(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}if(n)t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return op(e)}function $S(e,t){if(e[e.length-1]!=="'"||e.length===1)t(e.length,"MISSING_CHAR","Missing closing 'quote");return op(e.slice(1,-1)).replace(/''/g,"'")}function op(e){let t,n;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
652
+ `,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
653
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let r=i[1],s=" ",o=t.lastIndex;n.lastIndex=o;while(i=n.exec(e)){if(i[1]==="")if(s===`
654
+ `)r+=s;else s=`
655
+ `;else r+=s+i[1],s=" ";o=n.lastIndex}let a=/[ \t]*(.*)/sy;return a.lastIndex=o,i=a.exec(e),r+s+(i?.[1]??"")}function kS(e,t){let n="";for(let i=1;i<e.length-1;++i){let r=e[i];if(r==="\r"&&e[i+1]===`
656
+ `)continue;if(r===`
657
+ `){let{fold:s,offset:o}=AS(e,i);n+=s,i=o}else if(r==="\\"){let s=e[++i],o=ES[s];if(o)n+=o;else if(s===`
658
+ `){s=e[i+1];while(s===" "||s==="\t")s=e[++i+1]}else if(s==="\r"&&e[i+1]===`
659
+ `){s=e[++i+1];while(s===" "||s==="\t")s=e[++i+1]}else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=_S(e,i+1,a,t),i+=a}else{let a=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(r===" "||r==="\t"){let s=i,o=e[i+1];while(o===" "||o==="\t")o=e[++i+1];if(o!==`
660
+ `&&!(o==="\r"&&e[i+2]===`
661
+ `))n+=i>s?e.slice(s,i+1):r}else n+=r}if(e[e.length-1]!=='"'||e.length===1)t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}function AS(e,t){let n="",i=e[t+1];while(i===" "||i==="\t"||i===`
662
+ `||i==="\r"){if(i==="\r"&&e[t+2]!==`
663
+ `)break;if(i===`
664
+ `)n+=`
665
+ `;t+=1,i=e[t+1]}if(!n)n=" ";return{fold:n,offset:t}}var ES={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
666
+ `,r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function _S(e,t,n,i){let r=e.substr(t,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,n+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}TS.resolveFlowScalar=xS});var lp=M(function(LS){var Lt=K(),ap=ne(),OS=$a(),MS=Aa();function NS(e,t,n,i){let{value:r,type:s,comment:o,range:a}=t.type==="block-scalar"?OS.resolveBlockScalar(e,t,i):MS.resolveFlowScalar(t,e.options.strict,i),l=n?e.directives.tagName(n.source,(u)=>i(n,"TAG_RESOLVE_FAILED",u)):null,c;if(e.options.stringKeys&&e.atKey)c=e.schema[Lt.SCALAR];else if(l)c=CS(e.schema,r,l,n,i);else if(t.type==="scalar")c=RS(e,r,t,i);else c=e.schema[Lt.SCALAR];let f;try{let u=c.resolve(r,(d)=>i(n??t,"TAG_RESOLVE_FAILED",d),e.options);f=Lt.isScalar(u)?u:new ap.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??t,"TAG_RESOLVE_FAILED",d),f=new ap.Scalar(r)}if(f.range=a,f.source=r,s)f.type=s;if(l)f.tag=l;if(c.format)f.format=c.format;if(o)f.comment=o;return f}function CS(e,t,n,i,r){if(n==="!")return e[Lt.SCALAR];let s=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(t))return a;let o=e.knownTags[n];if(o&&!o.collection)return e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o;return r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Lt.SCALAR]}function RS({atKey:e,directives:t,schema:n},i,r,s){let o=n.tags.find((a)=>(a.default===!0||e&&a.default==="key")&&a.test?.test(i))||n[Lt.SCALAR];if(n.compat){let a=n.compat.find((l)=>l.default&&l.test?.test(i))??n[Lt.SCALAR];if(o.tag!==a.tag){let l=t.tagString(o.tag),c=t.tagString(a.tag),f=`Value may be parsed as either ${l} or ${c}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}LS.composeScalar=NS});var cp=M(function(FS){function qS(e,t,n){if(t){n??(n=t.length);for(let i=n-1;i>=0;--i){let r=t[i];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}r=t[++i];while(r?.type==="space")e+=r.source.length,r=t[++i];break}}return e}FS.emptyScalarPosition=qS});var dp=M(function(HS){var US=Cn(),jS=K(),BS=sp(),up=lp(),VS=rn(),GS=cp(),KS={composeNode:fp,composeEmptyNode:Ea};function fp(e,t,n,i){let r=e.atKey,{spaceBefore:s,comment:o,anchor:a,tag:l}=n,c,f=!0;switch(t.type){case"alias":if(c=WS(e,t,i),a||l)i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(c=up.composeScalar(e,t,l,i),a)c.anchor=a.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(c=BS.composeCollection(KS,e,t,n,i),a)c.anchor=a.source.substring(1)}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}if(c??(c=Ea(e,t.offset,void 0,null,n,i)),a&&c.anchor==="")i(a,"BAD_ALIAS","Anchor cannot be an empty string");if(r&&e.options.stringKeys&&(!jS.isScalar(c)||typeof c.value!=="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str"))i(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(s)c.spaceBefore=!0;if(o)if(t.type==="scalar"&&t.source==="")c.comment=o;else c.commentBefore=o;if(e.options.keepSourceTokens&&f)c.srcToken=t;return c}function Ea(e,t,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:l},c){let f={type:"scalar",offset:GS.emptyScalarPosition(t,n,i),indent:-1,source:""},u=up.composeScalar(e,f,a,c);if(o){if(u.anchor=o.source.substring(1),u.anchor==="")c(o,"BAD_ALIAS","Anchor cannot be an empty string")}if(r)u.spaceBefore=!0;if(s)u.comment=s,u.range[2]=l;return u}function WS({options:e},{offset:t,source:n,end:i},r){let s=new US.Alias(n.substring(1));if(s.source==="")r(t,"BAD_ALIAS","Alias cannot be an empty string");if(s.source.endsWith(":"))r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=VS.resolveEnd(i,o,e.strict,r);if(s.range=[t,o,a.offset],a.comment)s.comment=a.comment;return s}HS.composeEmptyNode=Ea;HS.composeNode=fp});var mp=M(function(e$){var zS=Hn(),pp=dp(),QS=rn(),XS=Yn();function ZS(e,t,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:t},e),l=new zS.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},f=XS.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});if(f.found){if(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline)o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}l.contents=r?pp.composeNode(c,r,f,o):pp.composeEmptyNode(c,f.end,i,null,f,o);let u=l.contents.range[2],d=QS.resolveEnd(s,u,!1,o);if(d.comment)l.comment=d.comment;return l.range=[n,u,d.offset],l}e$.composeDoc=ZS});var _a=M(function(a$){var n$=Ce("process"),i$=Mo(),r$=Hn(),zn=Jn(),hp=K(),s$=mp(),o$=rn();function Qn(e){if(typeof e==="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==="string"?n.length:1)]}function gp(e){let t="",n=!1,i=!1;for(let r=0;r<e.length;++r){let s=e[r];switch(s[0]){case"#":t+=(t===""?"":i?`
667
+
668
+ `:`
669
+ `)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":if(e[r+1]?.[0]!=="#")r+=1;n=!1;break;default:if(!n)i=!0;n=!1}}return{comment:t,afterEmptyLine:i}}class yp{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{let s=Qn(t);if(r)this.warnings.push(new zn.YAMLWarning(s,n,i));else this.errors.push(new zn.YAMLParseError(s,n,i))},this.directives=new i$.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=gp(this.prelude);if(n){let r=e.contents;if(t)e.comment=e.comment?`${e.comment}
670
+ ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(hp.isCollection(r)&&!r.flow&&r.items.length>0){let s=r.items[0];if(hp.isPair(s))s=s.key;let o=s.commentBefore;s.commentBefore=o?`${n}
671
+ ${o}`:n}else{let s=r.commentBefore;r.commentBefore=s?`${n}
672
+ ${s}`:n}}if(t){for(let r=0;r<this.errors.length;++r)e.errors.push(this.errors[r]);for(let r=0;r<this.warnings.length;++r)e.warnings.push(this.warnings[r])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:gp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){if(n$.env.LOG_STREAM)console.dir(e,{depth:null});switch(e.type){case"directive":this.directives.add(e.source,(t,n,i)=>{let r=Qn(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=s$.composeDoc(this.options,this.directives,e,this.onError);if(this.atDirectives&&!t.directives.docStart)this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(t,!1),this.doc)yield this.doc;this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new zn.YAMLParseError(Qn(e),"UNEXPECTED_TOKEN",t);if(this.atDirectives||!this.doc)this.errors.push(n);else this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){this.errors.push(new zn.YAMLParseError(Qn(e),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let t=o$.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
673
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new zn.YAMLParseError(Qn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new r$.Document(void 0,n);if(this.atDirectives)this.onError(t,"MISSING_CHAR","Missing directives-end indicator line");i.range=[0,t,t],this.decorate(i,!1),yield i}}}a$.Composer=yp});var vp=M(function(g$){var c$=$a(),u$=Aa(),f$=Jn(),bp=qn();function d$(e,t=!0,n){if(e){let i=(r,s,o)=>{let a=typeof r==="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new f$.YAMLParseError([a,a+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return u$.resolveFlowScalar(e,t,i);case"block-scalar":return c$.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function p$(e,t){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=t,a=bp.stringifyString({type:o,value:e},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:i,source:`
674
+ `}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
675
+ `),f=a.substring(0,c),u=a.substring(c+1)+`
676
+ `,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];if(!wp(d,l))d.push({type:"newline",offset:-1,indent:i,source:`
677
+ `});return{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:l};default:return{type:"scalar",offset:s,indent:i,source:a,end:l}}}function m$(e,t,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(i&&typeof a==="number")a+=2;if(!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=e.props[0];if(c.type!=="block-scalar-header")throw Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=bp.stringifyString({type:o,value:t},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":h$(e,l);break;case'"':Ta(e,l,"double-quoted-scalar");break;case"'":Ta(e,l,"single-quoted-scalar");break;default:Ta(e,l,"scalar")}}function h$(e,t){let n=t.indexOf(`
678
+ `),i=t.substring(0,n),r=t.substring(n+1)+`
679
+ `;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw Error("Invalid block scalar header");s.source=i,e.source=r}else{let{offset:s}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];if(!wp(a,"end"in e?e.end:void 0))a.push({type:"newline",offset:-1,indent:o,source:`
680
+ `});for(let l of Object.keys(e))if(l!=="type"&&l!=="offset")delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:r})}}function wp(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Ta(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),r=t.length;if(e.props[0].type==="block-scalar-header")r-=e.props[0].source.length;for(let s of i)s.offset+=r;delete e.props,Object.assign(e,{type:n,source:t,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
681
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter((s)=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))if(s!=="type"&&s!=="offset")delete e[s];Object.assign(e,{type:n,indent:i,source:t,end:r})}}}g$.createScalarToken=p$;g$.resolveAsScalar=d$;g$.setScalarValue=m$});var xp=M(function(x$){var v$=(e)=>("type"in e)?Gr(e):Vr(e);function Gr(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Gr(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Vr(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Vr(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Vr(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Vr({start:e,key:t,sep:n,value:i}){let r="";for(let s of e)r+=s.source;if(t)r+=Gr(t);if(n)for(let s of n)r+=s.source;if(i)r+=Gr(i);return r}x$.stringify=v$});var kp=M(function(k$){var Ia=Symbol("break visit"),$$=Symbol("skip children"),Sp=Symbol("remove item");function Pt(e,t){if("type"in e&&e.type==="document")e={start:e.start,value:e.value};$p(Object.freeze([]),e,t)}Pt.BREAK=Ia;Pt.SKIP=$$;Pt.REMOVE=Sp;Pt.itemAtPath=(e,t)=>{let n=e;for(let[i,r]of t){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};Pt.parentCollection=(e,t)=>{let n=Pt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw Error("Parent collection not found")};function $p(e,t,n){let i=n(t,e);if(typeof i==="symbol")return i;for(let r of["key","value"]){let s=t[r];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let a=$p(Object.freeze(e.concat([[r,o]])),s.items[o],n);if(typeof a==="number")o=a-1;else if(a===Ia)return Ia;else if(a===Sp)s.items.splice(o,1),o-=1}if(typeof i==="function"&&r==="key")i=i(t,e)}}return typeof i==="function"?i(t,e):i}k$.visit=Pt});var Kr=M(function(N$){var Oa=vp(),E$=xp(),_$=kp(),Ma="\uFEFF",Na="\x02",Ca="\x18",Ra="\x1F",T$=(e)=>!!e&&("items"in e),I$=(e)=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function O$(e){switch(e){case Ma:return"<BOM>";case Na:return"<DOC>";case Ca:return"<FLOW_END>";case Ra:return"<SCALAR>";default:return JSON.stringify(e)}}function M$(e){switch(e){case Ma:return"byte-order-mark";case Na:return"doc-mode";case Ca:return"flow-error-end";case Ra:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
682
+ `:case`\r
683
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}N$.createScalarToken=Oa.createScalarToken;N$.resolveAsScalar=Oa.resolveAsScalar;N$.setScalarValue=Oa.setScalarValue;N$.stringify=E$.stringify;N$.visit=_$.visit;N$.BOM=Ma;N$.DOCUMENT=Na;N$.FLOW_END=Ca;N$.SCALAR=Ra;N$.isCollection=T$;N$.isScalar=I$;N$.prettyToken=O$;N$.tokenType=M$});var Pa=M(function(J$){var Xn=Kr();function Ne(e){switch(e){case void 0:case" ":case`
684
+ `:case"\r":case"\t":return!0;default:return!1}}var Ap=new Set("0123456789ABCDEFabcdef"),W$=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wr=new Set(",[]{}"),H$=new Set(` ,[]{}
685
+ \r `),La=(e)=>!e||H$.has(e);class Ep{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";while(n&&(t||this.hasChars(1)))n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];while(t===" "||t==="\t")t=this.buffer[++e];if(!t||t==="#"||t===`
686
+ `)return!0;if(t==="\r")return this.buffer[e+1]===`
687
+ `;return!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;while(t===" ")t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===`
688
+ `||!i&&!this.atEnd)return e+n+1}return t===`
689
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Ne(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;if(typeof e!=="number"||e!==-1&&e<this.pos)e=this.buffer.indexOf(`
690
+ `,this.pos),this.lineEndPos=e;if(e===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[e-1]==="\r")e-=1;return this.buffer.substring(this.pos,e)}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Xn.BOM)yield*this.pushCount(1),e=e.substring(1);if(e[0]==="%"){let t=e.length,n=e.indexOf("#");while(n!==-1){let r=e[n-1];if(r===" "||r==="\t"){t=n-1;break}else n=e.indexOf("#",n+1)}while(!0){let r=e[t-1];if(r===" "||r==="\t")t-=1;else break}let i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Xn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Ne(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ne(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ne(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(La),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do{if(e=yield*this.pushNewline(),e>0)t=yield*this.pushSpaces(!1),this.indentValue=n=t;else t=0;t+=yield*this.pushSpaces(!0)}while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if(n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Ne(i[3])){if(!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Xn.FLOW_END,yield*this.parseLineStart()}let r=0;while(i[r]===",")r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(La),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||Ne(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")while(t!==-1&&this.buffer[t+1]==="'")t=this.buffer.indexOf("'",t+2);else while(t!==-1){let r=0;while(this.buffer[t-1-r]==="\\")r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),i=n.indexOf(`
691
+ `,this.pos);if(i!==-1){while(i!==-1){let r=this.continueScalar(i+1);if(r===-1)break;i=n.indexOf(`
692
+ `,r)}if(i!==-1)t=i-(n[i-1]==="\r"?2:1)}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;while(!0){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil((t)=>Ne(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case" ":t+=1;break;case`
693
+ `:e=r,t=0;break;case"\r":{let s=this.buffer[r+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
694
+ `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=t;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let r=this.continueScalar(e+1);if(r===-1)break;e=this.buffer.indexOf(`
695
+ `,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;n=this.buffer[i];while(n===" ")n=this.buffer[++i];if(n==="\t"){while(n==="\t"||n===" "||n==="\r"||n===`
696
+ `)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let r=e-1,s=this.buffer[r];if(s==="\r")s=this.buffer[--r];let o=r;while(s===" ")s=this.buffer[--r];if(s===`
697
+ `&&r>=this.pos&&r+1+t>o)e=r;else break}while(!0);return yield Xn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;while(i=this.buffer[++n])if(i===":"){let r=this.buffer[n+1];if(Ne(r)||e&&Wr.has(r))break;t=n}else if(Ne(i)){let r=this.buffer[n+1];if(i==="\r")if(r===`
698
+ `)n+=1,i=`
699
+ `,r=this.buffer[n+1];else t=n;if(r==="#"||e&&Wr.has(r))break;if(i===`
700
+ `){let s=this.continueScalar(n+1);if(s===-1)break;n=Math.max(n,s-2)}}else{if(e&&Wr.has(i))break;t=n}if(!i&&!this.atEnd)return this.setNext("plain-scalar");return yield Xn.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc"}*pushCount(e){if(e>0)return yield this.buffer.substr(this.pos,e),this.pos+=e,e;return 0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);if(n)return yield n,this.pos+=n.length,n.length;else if(t)yield"";return 0}*pushIndicators(){let e=0;e:while(!0){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(La),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Ne(n)||t&&Wr.has(n)){if(!t)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];while(!Ne(t)&&t!==">")t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];while(t)if(W$.has(t))t=this.buffer[++e];else if(t==="%"&&Ap.has(this.buffer[e+1])&&Ap.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];if(e===`
701
+ `)return yield*this.pushCount(1);else if(e==="\r"&&this.charAt(1)===`
702
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n==="\t");let i=t-this.pos;if(i>0)yield this.buffer.substr(this.pos,i),this.pos=t;return i}*pushUntil(e){let t=this.pos,n=this.buffer[t];while(!e(n))n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}J$.Lexer=Ep});var qa=M(function(z$){class _p{constructor(){this.lineStarts=[],this.addNewLine=(e)=>this.lineStarts.push(e),this.linePos=(e)=>{let t=0,n=this.lineStarts.length;while(t<n){let r=t+n>>1;if(this.lineStarts[r]<e)t=r+1;else n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}z$.LineCounter=_p});var Fa=M(function(ek){var X$=Ce("process"),Tp=Kr(),Z$=Pa();function dt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Ip(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Mp(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Hr(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function sn(e){if(e.length===0)return[];let t=e.length;e:while(--t>=0)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}while(e[++t]?.type==="space");return e.splice(t,e.length)}function Jr(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Op(e){if(e.start.type==="flow-seq-start"){for(let t of e.items)if(t.sep&&!t.value&&!dt(t.start,"explicit-key-ind")&&!dt(t.sep,"map-value-ind")){if(t.key)t.value=t.key;if(delete t.key,Mp(t.value))if(t.value.end)Jr(t.value.end,t.sep);else t.value.end=t.sep;else Jr(t.start,t.sep);delete t.sep}}}class Np{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Z$.Lexer,this.onNewLine=e}*parse(e,t=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);if(!t)yield*this.end()}*next(e){if(this.source=e,X$.env.LOG_TOKENS)console.log("|",Tp.prettyToken(e));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Tp.tokenType(e);if(!t){let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}else if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+e.length);break;case"space":if(this.atNewLine&&e[0]===" ")this.indent+=e.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=e.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);if(t.type==="block-scalar")t.indent="indent"in n?n.indent:0;else if(t.type==="flow-collection"&&n.type==="document")t.indent=0;if(t.type==="flow-collection")Op(t);switch(n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];if(i.value)n.items.push({start:[],value:t});else i.value=t;break}case"flow-collection":{let i=n.items[n.items.length-1];if(!i||i.value)n.items.push({start:[],key:t,sep:[]});else if(i.sep)i.value=t;else Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let i=t.items[t.items.length-1];if(i&&!i.sep&&!i.value&&i.start.length>0&&Ip(i.start)===-1&&(t.indent===0||i.start.every((r)=>r.type!=="comment"||r.indent<t.indent))){if(n.type==="document")n.end=i.start;else n.items.push({start:i.start});t.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")e.start.push(this.sourceToken);this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{if(Ip(e.start)!==-1)yield*this.pop(),yield*this.step();else e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);if(t)this.stack.push(t);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=Hr(this.peek(2)),n=sn(t),i;if(e.end)i=e.end,i.push(this.sourceToken),delete e.end;else i=[this.sourceToken];let r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
703
+ `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
704
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Jr(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",r=[];if(i&&t.sep&&!t.value){let s=[];for(let o=0;o<t.sep.length;++o){let a=t.sep[o];switch(a.type){case"newline":s.push(o);break;case"space":break;case"comment":if(a.indent>e.indent)s.length=0;break;default:s.length=0}}if(s.length>=2)r=t.sep.splice(s[1])}switch(this.type){case"anchor":case"tag":if(i||t.value)r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(i||t.value)r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(dt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let s=sn(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(dt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(Mp(t.key)&&!dt(t.sep,"newline")){let s=sn(t.start),o=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:o,sep:a}]})}else if(r.length>0)t.sep=t.sep.concat(r,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||i)e.items.push({start:r,key:null,sep:[this.sourceToken]});else if(dt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);if(i||t.value)e.items.push({start:r,key:s,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(s);else Object.assign(t,{key:s,sep:[]}),this.onKeyLine=!0;return}default:{let s=this.startBlockValue(e);if(s){if(s.type==="block-seq"){if(!t.explicitKey&&t.sep&&!dt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(n)e.items.push({start:r});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;if((Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Jr(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||dt(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:i,sep:[]});else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);if(n)this.stack.push(n);else yield*this.pop(),yield*this.step()}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Hr(n),r=sn(i);Op(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
705
+ `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
706
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Hr(e),n=sn(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Hr(e),n=sn(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((n)=>n.type==="newline"||n.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ek.Parser=Np});var qp=M(function(ck){var Cp=_a(),nk=Hn(),Zn=Jn(),ik=qo(),rk=K(),sk=qa(),Rp=Fa();function Lp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new sk.LineCounter||null,prettyErrors:t}}function ok(e,t={}){let{lineCounter:n,prettyErrors:i}=Lp(t),r=new Rp.Parser(n?.addNewLine),s=new Cp.Composer(t),o=Array.from(s.compose(r.parse(e)));if(i&&n)for(let a of o)a.errors.forEach(Zn.prettifyError(e,n)),a.warnings.forEach(Zn.prettifyError(e,n));if(o.length>0)return o;return Object.assign([],{empty:!0},s.streamInfo())}function Pp(e,t={}){let{lineCounter:n,prettyErrors:i}=Lp(t),r=new Rp.Parser(n?.addNewLine),s=new Cp.Composer(t),o=null;for(let a of s.compose(r.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Zn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(i&&n)o.errors.forEach(Zn.prettifyError(e,n)),o.warnings.forEach(Zn.prettifyError(e,n));return o}function ak(e,t,n){let i=void 0;if(typeof t==="function")i=t;else if(n===void 0&&t&&typeof t==="object")n=t;let r=Pp(e,n);if(!r)return null;if(r.warnings.forEach((s)=>ik.warn(r.options.logLevel,s)),r.errors.length>0)if(r.options.logLevel!=="silent")throw r.errors[0];else r.errors=[];return r.toJS(Object.assign({reviver:i},n))}function lk(e,t,n){let i=null;if(typeof t==="function"||Array.isArray(t))i=t;else if(n===void 0&&t)n=t;if(typeof n==="string")n=n.length;if(typeof n==="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}if(rk.isDocument(e)&&!i)return e.toString(n);return new nk.Document(e,i,n).toString(n)}ck.parse=ak;ck.parseAllDocuments=ok;ck.parseDocument=Pp;ck.stringify=lk});var mk,hk,gk,Da,yk,pt,bk,wk,vk,xk,dC,Sk,$k,kk,Yr,Fp,Ak,Ek,_k,Tk,Ik,Ok,Mk,Nk,Ck,Rk,Lk,Pk,qk,Fk,Dk,Uk,jk,Bk,Vk,Gk,Kk,Wk,Hk,Jk,Ua,Yk,zk,Qk;var Dp=I(()=>{mk=_a(),hk=Hn(),gk=fa(),Da=Jn(),yk=Cn(),pt=K(),bk=lt(),wk=ne(),vk=ut(),xk=ft(),dC=Kr(),Sk=Pa(),$k=qa(),kk=Fa(),Yr=qp(),Fp=Mn();Ak=mk.Composer,Ek=hk.Document,_k=gk.Schema,Tk=Da.YAMLError,Ik=Da.YAMLParseError,Ok=Da.YAMLWarning,Mk=yk.Alias,Nk=pt.isAlias,Ck=pt.isCollection,Rk=pt.isDocument,Lk=pt.isMap,Pk=pt.isNode,qk=pt.isPair,Fk=pt.isScalar,Dk=pt.isSeq,Uk=bk.Pair,jk=wk.Scalar,Bk=vk.YAMLMap,Vk=xk.YAMLSeq,Gk=Sk.Lexer,Kk=$k.LineCounter,Wk=kk.Parser,Hk=Yr.parse,Jk=Yr.parseAllDocuments,Ua=Yr.parseDocument,Yk=Yr.stringify,zk=Fp.visit,Qk=Fp.visitAsync});var on,ue,ja;var zr=I(()=>{on=["claude-code","codex","grok","opencode","hermes","pi"],ue=[{id:"MiniMax-M3",contextWindow:1e6,maxTokens:128000,input:["text","image"]},{id:"MiniMax-M2.7",contextWindow:204800,maxTokens:131072,input:["text"]},{id:"MiniMax-M2.7-highspeed",contextWindow:204800,maxTokens:131072,input:["text"]}],ja=ue[0].id});import{chmodSync as Ba,closeSync as Up,existsSync as ei,lstatSync as Xk,mkdirSync as Zk,openSync as e2,readFileSync as t2,realpathSync as n2,renameSync as i2,rmSync as un,statSync as r2,writeFileSync as Ga}from"fs";import{homedir as s2,tmpdir as o2}from"os";import{basename as a2,dirname as Vp,isAbsolute as Gp,join as ie,resolve as Ka}from"path";function Wp(e){let t=ue.find((n)=>n.id===e);if(!t)throw new v(`Unsupported MiniMax model: ${e}`,x.USAGE);return t}function an(e){return e==="MiniMax-M3"?`${e}[1m]`:e}function jp(e){return e==="MiniMax-M3"?"minimax":e.toLowerCase().replaceAll(".","-")}function ht(e){let t=e==="cn"?"https://api.minimaxi.com":"https://api.minimax.io";return{anthropic:`${t}/anthropic`,openai:`${t}/v1`}}function ln(e,t,n){if(!e?.trim())return t;return Gp(e)?e:Ka(n,e)}function u2(e,t){let n=t.homeDir??s2(),i=t.env??process.env;switch(e){case"claude-code":{let r=ln(i.CLAUDE_CONFIG_DIR,ie(n,".claude"),n);return[ie(r,"settings.json")]}case"codex":{let r=ln(i.CODEX_HOME,ie(n,".codex"),n);return[ie(r,"config.toml"),ie(r,Qr)]}case"grok":return[ie(ln(i.GROK_HOME,ie(n,".grok"),n),"config.toml")];case"opencode":{if(i.OPENCODE_CONFIG?.trim()){let l=i.OPENCODE_CONFIG.trim();return[Gp(l)?l:Ka(l)]}let r=ln(i.XDG_CONFIG_HOME,ie(n,".config"),n),s=ie(r,"opencode"),o=ie(s,"opencode.json"),a=ie(s,"opencode.jsonc");if(ei(o)&&ei(a))throw new v(`Both OpenCode global config files exist: ${o} and ${a}.`,x.GENERAL,"Keep one global config file, or set OPENCODE_CONFIG to the file mmx should update.");return[ei(a)?a:o]}case"hermes":{let r=ln(i.HERMES_HOME,ie(n,".hermes"),n);return[ie(r,"config.yaml"),ie(r,".env")]}case"pi":{let r=ln(i.PI_CODING_AGENT_DIR,ie(n,".pi","agent"),n);return[ie(r,"models.json"),ie(r,"settings.json")]}}}function cn(e){return ei(e)?t2(e,"utf8"):null}function He(e){let t=Wa(e);return{targetPath:t,before:cn(t)}}function Hp(e,t){de(e,`${t} must contain a JSON object at its root.`)}function de(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw new v(t,x.GENERAL,mt)}function ti(e,t){let n=[],i=bf(e,n,{allowTrailingComma:!0,disallowComments:!1});if(n.length>0)throw new v(`${t} is not valid JSON/JSONC.`,x.GENERAL,mt);return Hp(i,t),i}function Xr(e,t,n){let i=e??`{}
707
+ `;ti(i,t);for(let r of n)i=vf(i,wf(i,r.path,r.value,{formattingOptions:l2}));return i.endsWith(`
708
+ `)?i:`${i}
709
+ `}function f2(e,t){let n=e.match(/.*(?:\r?\n|$)/g)?.filter(Boolean)??[],i=0,r;for(let s of n){let o=s.match(/^\s*\[([^\][\r\n]+)]\s*(?:#.*)?(?:\r?\n)?$/),a=s.match(/^\s*\[\[([^\][\r\n]+)]]\s*(?:#.*)?(?:\r?\n)?$/);if(o||a){if(r)return r.end=i,r;if(o?.[1]?.trim()===t)r={bodyStart:i+s.length,end:e.length}}i+=s.length}return r}function d2(e){let t;for(let n=0;n<e.length;n+=1){let i=e[n];if(t==='"'&&i==="\\"){n+=1;continue}if(t){if(i===t)t=void 0;continue}if(i==='"'||i==="'"){t=i;continue}if(i==="#"){let r=n;while(r>0&&/[ \t]/.test(e[r-1]))r-=1;return e.slice(r)}}return""}function Va(e,t){let n=e;for(let[i,r]of Object.entries(t)){if(!c2.test(i))throw new v(`Invalid TOML key: ${i}`,x.GENERAL);let s=typeof r==="string"?JSON.stringify(r):String(r),o=`${i} = ${s}`,a=new RegExp(`^(\\s*)${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*=.*$`,"m");if(a.test(n))n=n.replace(a,(l,c)=>`${c}${o}${d2(l)}`);else{if(n.length>0&&!n.endsWith(`
710
+ `))n+=`
711
+ `;n+=`${o}
712
+ `}}return n}function p2(e,t,n){let i=f2(e,t);if(i){let s=e.slice(i.bodyStart,i.end);return e.slice(0,i.bodyStart)+Va(s,n)+e.slice(i.end)}let r=e;if(r.length>0&&!r.endsWith(`
713
+ `))r+=`
714
+ `;if(r.length>0&&!r.endsWith(`
242
715
 
243
- `);for(let n of Ya)process.stdout.write(` ${n.command.padEnd(30)} ${n.title}
244
- `),process.stdout.write(` ${" ".repeat(30)} ${o}${n.path}
716
+ `))r+=`
717
+ `;return r+=`[${t}]
718
+ ${Va("",n)}`,r}function Jp(e,t){let n=e.search(/^\s*\[/m),i=n===-1?e.length:n;return Va(e.slice(0,i),t)+e.slice(i)}function Yp(e,t,n,i){let r=e??"";try{On(r)}catch{throw new v(`${t} is not valid TOML.`,x.GENERAL,mt)}if(r.includes('"""')||r.includes("'''"))throw new v(`${t} contains a multiline string that mmx cannot safely preserve.`,x.GENERAL,"Update this configuration manually. No files were changed.");r=Jp(r,n);for(let s of i)r=p2(r,s.name,s.entries);if(!r.endsWith(`
719
+ `))r+=`
720
+ `;try{On(r)}catch{throw new v(`Could not safely merge ${t}.`,x.GENERAL,"No files were changed. Convert inline TOML tables to standard table sections and retry.")}return r}function m2(e,t,n,i){let r=Ua(e??`{}
721
+ `);if(r.errors.length>0)throw new v(`Hermes config.yaml is not valid YAML: ${r.errors[0]?.message??"parse error"}`,x.GENERAL,mt);let s=r.toJS();if(Hp(s,"Hermes config.yaml"),typeof s.model==="string")r.deleteIn(["model"]);else if(s.model!==void 0)de(s.model,"Hermes config.yaml model section must be an object.");if(s.providers!==void 0)de(s.providers,"Hermes config.yaml providers section must be an object.");let o=s.providers?.[t];if(o!==void 0)de(o,`Hermes config.yaml providers.${t} section must be an object.`);let a=o?.models;if(a!==void 0&&!Array.isArray(a)&&(typeof a!=="object"||a===null))throw new v(`Hermes config.yaml providers.${t}.models must be an object or array.`,x.GENERAL,mt);if(Array.isArray(a)){let c=new Set(a.flatMap((f)=>{if(typeof f==="string")return[f];if(typeof f==="object"&&f!==null&&!Array.isArray(f)){let u=f.id;return typeof u==="string"?[u]:[]}return[]}));for(let f of ue)if(!c.has(f.id))r.addIn(["providers",t,"models"],{id:f.id,context_length:f.contextWindow})}else{let c=a;for(let f of ue){if(c?.[f.id]!==void 0)de(c[f.id],`Hermes model definition for ${f.id} must be an object.`);r.setIn(["providers",t,"models",f.id,"context_length"],f.contextWindow)}}let l=Wp(n);return r.setIn(["model","default"],n),r.setIn(["model","provider"],t),r.setIn(["model","base_url"],i),r.setIn(["model","context_length"],l.contextWindow),r.setIn(["model","max_tokens"],l.maxTokens),r.toString()}function h2(e){return/^[A-Za-z0-9_./:-]+$/.test(e)?e:JSON.stringify(e)}function g2(e,t,n){let i=e??"",r=`${t}=${h2(n)}`,s=new RegExp(`^(?:export\\s+)?${t}=.*$`,"gm"),o=!1,a=i.replace(s,()=>{if(o)return"";return o=!0,r});if(!o){if(a.length>0&&!a.endsWith(`
722
+ `))a+=`
723
+ `;a+=`${r}
724
+ `}return a.endsWith(`
725
+ `)?a:`${a}
726
+ `}function y2(e,t){let n=He(t),r=ti(n.before??"{}","Claude Code settings.json").modelPicker;if(r!==void 0)de(r,"Claude Code settings.json modelPicker section must be an object.");let s=r?.options;if(s!==void 0&&!Array.isArray(s))throw new v("Claude Code settings.json modelPicker.options must be an array.",x.GENERAL,mt);let o=r?.replaceBuiltInOptions;if(o!==void 0&&typeof o!=="boolean")throw new v("Claude Code settings.json modelPicker.replaceBuiltInOptions must be a boolean.",x.GENERAL,mt);let a=ht(e.region),l=an(e.model),c=ue.map((g)=>({model:an(g.id),label:g.id,description:g.id.endsWith("-highspeed")?"204.8K context · faster inference":`${g.contextWindow===1e6?"1M":"204.8K"} context`})),f=new Set(ue.flatMap((g)=>[g.id,an(g.id)])),u=[];if(s===void 0)u.push({path:["modelPicker","options"],value:c});else{let g=s.flatMap((p,m)=>{if(typeof p!=="object"||p===null||Array.isArray(p))return[];let b=p.model;return typeof b==="string"&&f.has(b)?[m]:[]});for(let p of g.reverse())u.push({path:["modelPicker","options",p],value:void 0});let h=s.length-g.length;c.forEach((p,m)=>{u.push({path:["modelPicker","options",h+m],value:p})})}let d={ANTHROPIC_BASE_URL:a.anthropic,ANTHROPIC_AUTH_TOKEN:e.apiKey,API_TIMEOUT_MS:"3000000",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",CLAUDE_CODE_AUTO_COMPACT_WINDOW:String(Wp(e.model).contextWindow),ANTHROPIC_MODEL:l,ANTHROPIC_DEFAULT_SONNET_MODEL:an("MiniMax-M2.7"),ANTHROPIC_DEFAULT_OPUS_MODEL:an("MiniMax-M3"),ANTHROPIC_DEFAULT_HAIKU_MODEL:an("MiniMax-M2.7-highspeed")};return[{agent:"claude-code",path:t,...n,after:Xr(n.before,"Claude Code settings.json",[...Object.entries(d).map(([g,h])=>({path:["env",g],value:h})),...u,{path:["modelPicker","replaceBuiltInOptions"],value:o??!0}])}]}function b2(){return`${JSON.stringify({_managed_by:Kp,models:ue.map((e,t)=>({slug:e.id,display_name:e.id,description:"MiniMax",default_reasoning_level:"high",supported_reasoning_levels:[{effort:"none",description:"Think-Off"},{effort:"high",description:"Deep"}],shell_type:"shell_command",visibility:"list",supported_in_api:!0,priority:t,base_instructions:`You are Codex, a coding agent based on ${e.id}. You and the user share the same workspace and collaborate to achieve the user's goals.`,supports_reasoning_summaries:!0,default_reasoning_summary:"none",support_verbosity:!1,truncation_policy:{mode:"bytes",limit:1e4},supports_parallel_tool_calls:!0,experimental_supported_tools:[],context_window:e.contextWindow,max_context_window:e.contextWindow,input_modalities:[...e.input]}))},null,2)}
727
+ `}function w2(e,t){let[n,i]=t;if(!n||!i)throw new v("Codex paths are incomplete.",x.GENERAL);let r=He(n),s=ht(e.region),o=Yp(r.before,"Codex config.toml",{model:e.model,model_provider:"minimax"},[{name:"model_providers.minimax",entries:{name:"MiniMax",base_url:s.openai,experimental_bearer_token:e.apiKey,wire_api:"responses"}}]),a=On(o).model_catalog_json;if(a!==void 0&&a!==Qr)throw new v("Codex config.toml already uses a user-managed model catalog.",x.GENERAL,"Remove model_catalog_json to let mmx manage a MiniMax-only catalog, or configure Codex manually. No files were changed.");let l=He(i);if(l.before!==null){if(ti(l.before,"Codex mmx-model-catalog.json")._managed_by!==Kp)throw new v(`Codex ${Qr} is not managed by mmx.`,x.GENERAL,"Rename or remove that file, then retry. No files were changed.")}return o=Jp(o,{model_catalog_json:Qr}),[{agent:"codex",path:n,...r,after:o},{agent:"codex",path:i,...l,after:b2()}]}function v2(e,t){let n=He(t),i=ht(e.region),r=ue.map((s)=>({name:`model.${jp(s.id)}`,entries:{model:s.id,base_url:i.openai,name:s.id,api_key:e.apiKey,api_backend:"chat_completions",context_window:s.contextWindow,max_completion_tokens:s.maxTokens}}));return[{agent:"grok",path:t,...n,after:Yp(n.before,"Grok config.toml",{},[{name:"models",entries:{default:jp(e.model)}},...r])}]}function x2(e,t){let n=He(t),r=ti(n.before??"{}","OpenCode opencode.json").provider;if(r!==void 0)de(r,"OpenCode opencode.json provider section must be an object.");let s=r?.minimax;if(s!==void 0)de(s,"OpenCode opencode.json provider.minimax section must be an object.");for(let c of["options","models"]){let f=s?.[c];if(f!==void 0)de(f,`OpenCode opencode.json provider.minimax.${c} section must be an object.`)}let o=s?.models;for(let c of ue){let f=o?.[c.id];if(f!==void 0)de(f,`OpenCode model definition for ${c.id} must be an object.`);let u=f?.limit;if(u!==void 0)de(u,`OpenCode model definition for ${c.id} limit must be an object.`);let d=f?.modalities;if(d!==void 0)de(d,`OpenCode model definition for ${c.id} modalities must be an object.`)}let a=ht(e.region),l=ue.flatMap((c)=>{let f=[...c.input];return[{path:["provider","minimax","models",c.id,"name"],value:c.id},{path:["provider","minimax","models",c.id,"attachment"],value:f.includes("image")},{path:["provider","minimax","models",c.id,"modalities","input"],value:f},{path:["provider","minimax","models",c.id,"modalities","output"],value:["text"]},{path:["provider","minimax","models",c.id,"limit","context"],value:c.contextWindow},{path:["provider","minimax","models",c.id,"limit","output"],value:c.maxTokens}]});return[{agent:"opencode",path:t,...n,after:Xr(n.before,"OpenCode opencode.json",[{path:["provider","minimax","npm"],value:"@ai-sdk/openai-compatible"},{path:["provider","minimax","name"],value:"MiniMax"},{path:["provider","minimax","options","baseURL"],value:a.openai},{path:["provider","minimax","options","apiKey"],value:e.apiKey},{path:["provider","minimax","options","setCacheKey"],value:!0},...l,{path:["model"],value:`minimax/${e.model}`}])}]}function S2(e,t){let[n,i]=t;if(!n||!i)throw new v("Hermes paths are incomplete.",x.GENERAL);let r=He(n),s=He(i),o=ht(e.region),a=e.region==="cn"?"minimax-cn":"minimax",l=e.region==="cn"?"MINIMAX_CN_API_KEY":"MINIMAX_API_KEY";return[{agent:"hermes",path:n,...r,after:m2(r.before,a,e.model,o.anthropic)},{agent:"hermes",path:i,...s,after:g2(s.before,l,e.apiKey)}]}function $2(e,t){let[n,i]=t;if(!n||!i)throw new v("Pi paths are incomplete.",x.GENERAL);let r=He(n),s=He(i),o=ti(r.before??"{}","Pi models.json"),a=ht(e.region),l=e.region==="cn"?"minimax-cn":"minimax",c=o.providers;if(c!==void 0)de(c,"Pi models.json providers section must be an object.");let f=c?.[l];if(f!==void 0)de(f,`Pi models.json providers.${l} section must be an object.`);let u=f?.models;if(u!==void 0&&!Array.isArray(u))throw new v(`Pi models.json providers.${l}.models must be an array.`,x.GENERAL,mt);let d=[{path:["providers",l,"name"],value:"MiniMax"},{path:["providers",l,"baseUrl"],value:a.anthropic},{path:["providers",l,"apiKey"],value:e.apiKey},{path:["providers",l,"api"],value:"anthropic-messages"}],g=ue.map((h)=>({id:h.id,name:h.id,reasoning:!0,input:[...h.input],contextWindow:h.contextWindow,maxTokens:h.maxTokens}));if(u===void 0)d.push({path:["providers",l,"models"],value:g});else{let h=u.length;for(let p of g){let m=u.findIndex((w)=>typeof w==="object"&&w!==null&&!Array.isArray(w)&&w.id===p.id),b=["providers",l,"models",m>=0?m:h++];if(m<0){d.push({path:b,value:p});continue}de(u[m],`Pi model definition for ${p.id} must be an object.`);for(let[w,S]of Object.entries(p))if(w!=="id")d.push({path:[...b,w],value:S})}}return[{agent:"pi",path:n,...r,after:Xr(r.before,"Pi models.json",d)},{agent:"pi",path:i,...s,after:Xr(s.before,"Pi settings.json",[{path:["defaultProvider"],value:l},{path:["defaultModel"],value:e.model}])}]}function zp(e){let t=[];for(let n of e.agents){let i=u2(n,e);switch(n){case"claude-code":t.push(...y2(e,i[0]));break;case"codex":t.push(...w2(e,i));break;case"grok":t.push(...v2(e,i[0]));break;case"opencode":t.push(...x2(e,i[0]));break;case"hermes":t.push(...S2(e,i));break;case"pi":t.push(...$2(e,i));break}}return t}function Bp(e,t,n){let i=Vp(e);Zk(i,{recursive:!0,mode:448});let r=ie(i,`.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),s=()=>{if(Wa(n)!==e)throw new v(`Configuration path changed while mmx was writing it: ${n}`,x.GENERAL)};try{s(),Ga(r,t,{encoding:"utf8",mode:384,flag:"wx"}),s(),i2(r,e)}catch(o){throw un(r,{force:!0}),o}}function k2(e,t,n){for(let i=0;;i+=1){let r=`${e}.bak.${n}${i===0?"":`.${i}`}`;try{return Ga(r,t,{encoding:"utf8",mode:384,flag:"wx"}),r}catch(s){if(s.code==="EEXIST")continue;throw un(r,{force:!0}),s}}}function A2(){return new Date().toISOString().replace(/[-:]/g,"").replace("T","-").replace(/\.\d{3}Z$/,"Z")}function Wa(e){let t=e,n=[];while(!0)try{return ie(n2(t),...n)}catch(i){if(i.code!=="ENOENT")throw i;try{if(Xk(t).isSymbolicLink())throw new v(`Configuration path contains a dangling symbolic link: ${e}`,x.GENERAL,"Fix the symbolic link and retry. No files were changed.")}catch(s){if(s instanceof v)throw s;if(s.code!=="ENOENT")throw s}let r=Vp(t);if(r===t)return Ka(e);n.unshift(a2(t)),t=r}}function E2(e){return process.platform!=="win32"&&(e&63)!==0}function _2(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function T2(){let e=typeof process.getuid==="function"?String(process.getuid()):(process.env.USERNAME??process.env.USER??"user").replace(/[^A-Za-z0-9_-]/g,"_"),t=ie(o2(),`mmx-agent-setup-${e}.lock`),n=`${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`;try{let i=e2(t,"wx",384);try{Ga(i,`${n}
728
+ `,"utf8")}catch(r){if(Up(i),cn(t)?.trim()===n)un(t,{force:!0});throw r}return()=>{if(Up(i),cn(t)?.trim()===n)un(t,{force:!0})}}catch(i){if(i.code!=="EEXIST")throw i;let s=(cn(t)?.trim()??"").match(/^(\d+):/),o=s?.[1]?Number(s[1]):void 0,a=o!==void 0&&!_2(o);throw new v(a?"A stale mmx agent setup lock exists.":"Another mmx agent setup is already running.",x.GENERAL,a?`Confirm no setup process is running, remove ${t}, then retry. No files were changed.`:"Wait for it to finish, then retry. No files were changed.")}}function Qp(e,t=!1){let n=t?void 0:T2();try{let i=e.filter((u)=>u.before!==u.after),r=new Set;for(let u of e){let d=u.targetPath;if(r.has(d))throw new v(`Multiple agent configuration paths resolve to ${d}.`,x.GENERAL,"No files were changed. Use distinct configuration paths and retry.");r.add(d)}let s=new Map,o=new Map;for(let u of e)if(u.before!==null&&ei(u.targetPath)){let d=r2(u.targetPath).mode&511;if(s.set(u,d),u.before===u.after&&E2(d))o.set(u,d)}if(t)return e.map((u)=>({agent:u.agent,path:u.path,status:u.before===u.after&&!o.has(u)?"unchanged":"would-configure"}));let a=(u,d)=>{if(Wa(u.path)!==u.targetPath||cn(u.targetPath)!==u.before)throw new v(`Configuration changed while mmx was preparing it: ${u.path}`,x.GENERAL,d)};for(let u of e)if(u.before!==u.after||o.has(u))a(u,"No files were changed. Retry the command.");let l=A2(),c=new Map,f=[];try{for(let u of i)if(u.before!==null)a(u,"No files were changed. Retry the command."),c.set(u.path,k2(u.targetPath,u.before,l));for(let u of e){if(!o.has(u))continue;a(u,"The completed writes were rolled back. Retry the command."),Ba(u.targetPath,384)}for(let u of i)a(u,"The completed writes were rolled back. Retry the command."),Bp(u.targetPath,u.after,u.path),f.push({file:u,target:u.targetPath})}catch(u){let d=[],g;for(let{file:h,target:p}of f.reverse())try{if(cn(p)!==h.after){d.push(h.path);continue}if(h.before===null)un(p,{force:!0});else{Bp(p,h.before,h.path);let m=s.get(h);if(m!==void 0)Ba(p,m)}}catch(m){g??=m}for(let[h,p]of o)try{Ba(h.targetPath,p)}catch(m){g??=m}if(d.length===0&&g===void 0)for(let h of c.values())try{un(h,{force:!0})}catch(p){g??=p}if(d.length>0||g!==void 0)throw new v("Could not fully roll back agent configuration.",x.GENERAL,`Review the affected files${c.size>0?` and backups: ${[...c.values()].join(", ")}`:"."}`);throw u}return e.map((u)=>({agent:u.agent,path:u.path,status:u.before===u.after&&!o.has(u)?"unchanged":"configured",...c.has(u.path)?{backup:c.get(u.path)}:{}}))}finally{n?.()}}var l2,c2,Qr="mmx-model-catalog.json",Kp="mmx agent setup",mt="Fix the existing configuration file and retry. No files were changed.";var Ha=I(()=>{xf();If();Dp();G();V();zr();l2={insertSpaces:!0,tabSize:2,eol:`
729
+ `},c2=/^[A-Za-z0-9_-]+$/});import{accessSync as I2,constants as Xp,statSync as O2}from"fs";import{delimiter as M2,join as N2}from"path";function Zp(e=process.env){let t=process.platform==="win32"?e.PATH??e.Path:e.PATH;if(t===void 0)return new Set;let n=t.split(M2).map((s)=>s.replace(/^"|"$/g,"")),i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""],r=process.platform==="win32"?Xp.F_OK:Xp.X_OK;return new Set(on.filter((s)=>C2[s].some((o)=>n.some((a)=>i.some((l)=>{let c=N2(a,`${o}${l}`);try{if(!O2(c).isFile())return!1;return I2(c,r),!0}catch{return!1}})))))}var C2;var em=I(()=>{zr();C2={"claude-code":["claude"],codex:["codex"],grok:["grok","grok-build","grok-cli"],opencode:["opencode"],hermes:["hermes"],pi:["pi"]}});async function tm(e){let t=`${ht(e.region).openai}/responses`,n;try{n=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:e.model,input:"Reply with exactly OK.",max_output_tokens:16,stream:!0}),signal:AbortSignal.timeout((e.timeoutSeconds??30)*1000)})}catch(r){throw new v(`Could not reach the MiniMax agent endpoint: ${r instanceof Error?r.message:String(r)}`,x.NETWORK,"No agent configuration files were changed.")}if(!n.ok)throw await n.body?.cancel().catch(()=>{return}),new v(`MiniMax rejected the agent verification request (${n.status}).`,n.status===401||n.status===403?x.AUTH:x.GENERAL,"No agent configuration files were changed. Check --region, --model, and the API key.");let i=!1;try{for await(let r of tt(n)){let s;try{s=JSON.parse(r.data)}catch{continue}if(typeof s!=="object"||s===null||Array.isArray(s))continue;let o=s,a=o.response;if(o.type==="response.created"&&typeof a==="object"&&a!==null&&!Array.isArray(a)&&typeof a.id==="string"&&typeof a.model==="string"){i=!0;break}}}catch{throw new v("Could not read the MiniMax agent verification response.",x.NETWORK,"No agent configuration files were changed.")}finally{await n.body?.cancel().catch(()=>{return})}if(!i)throw new v("MiniMax returned an invalid agent verification response.",x.GENERAL,"No agent configuration files were changed. Check --region, --model, and the API key.");return{region:e.region,model:e.model,endpoint:t,status:"ok"}}var nm=I(()=>{G();V();Ha()});function P2(e){if(e.startsWith("sk-cp-"))return"token-plan";if(e.startsWith("sk-api-"))return"paygo";return}function q2(e,t,n){if(t==="json"||!n)return N(e,t);let i=Ya.default.cyan,r=Ya.default.green;return N({[i("verification")]:{[i("region")]:e.verification.region,[i("model")]:e.verification.model,[i("endpoint")]:e.verification.endpoint,[i("status")]:r(e.verification.status)},[i("agents")]:e.agents.map((s)=>r(s)),[i("files")]:e.files.map((s)=>({[i("agent")]:r(s.agent),[i("path")]:s.path,[i("status")]:r(s.status),...s.backup?{[i("backup")]:s.backup}:{}}))},"text")}function im(e){let t=[];for(let n of e){let i=n.trim().toLowerCase(),r=R2[i];if(!r)throw new v(`Unsupported agent "${n}".`,x.USAGE,`Supported agents: ${on.join(", ")}`);if(!t.includes(r))t.push(r)}return t}function F2(e){if(e._hasExplicitOptions===!0)return!1;return Object.values(e).every((t)=>t===void 0||t===!1)}async function D2(e,t){let n=await Vl({message:"Select agents to configure",choices:on.map((d)=>({value:d,label:t.has(d)?ni[d]:`${ni[d]} (not detected on PATH)`})),initialValues:L2.filter((d)=>t.has(d)),required:!0});if(!n?.length)throw new v("Agent setup cancelled.",x.GENERAL);let i=im(n),r=await Us({message:"Select your MiniMax service region",choices:[{value:"global",label:"Global (minimax.io)"},{value:"cn",label:"Mainland China (minimaxi.com)"}],initialValue:e.region});if(r!=="global"&&r!=="cn")throw new v("Agent setup cancelled.",x.GENERAL);let s=await Us({message:"Choose an API key type",choices:Ja,initialValue:"token-plan"}),o=Ja.find((d)=>d.value===s);if(!o)throw new v("Agent setup cancelled.",x.GENERAL);await Ds({title:o.noteTitle,message:`${gt[r]}${o.pagePath}
245
730
 
246
- `)}})});var tn={};$t(tn,{registry:()=>ae});class Si{root={children:new Map};constructor(e){for(let[t,o]of Object.entries(e))this.register(t,o)}register(e,t){let o=e.split(" "),n=this.root;for(let i of o){if(!n.children.has(i))n.children.set(i,{children:new Map});n=n.children.get(i)}n.command=t}getAllCommands(){let e=new Set,t=[],o=(n)=>{if(n.command&&!e.has(n.command))e.add(n.command),t.push(n.command);for(let i of n.children.values())o(i)};return o(this.root),t}resolve(e){let t=this.root,o=[];for(let n of e){let i=t.children.get(n);if(!i)break;t=i,o.push(n)}if(t.command)return{command:t.command,extra:e.slice(o.length)};if(o.length>0&&t.children.size===1){let[,n]=t.children.entries().next().value;if(n.command)return{command:n.command,extra:e.slice(o.length)}}if(o.length>0&&t.children.size>1){let i=Array.from(t.children.values()).map((r)=>r.command),s=i[0];if(s&&i.every((r)=>r===s))return{command:s,extra:e.slice(o.length)}}if(o.length>0&&t.children.size>0){let n=Array.from(t.children.entries()).map(([i,s])=>{if(s.command)return` ${o.join(" ")} ${i} ${s.command.description}`;let r=Array.from(s.children.keys()).join(", ");return` ${o.join(" ")} ${i} [${r}]`}).join(`
247
- `);throw new m(`Unknown command: mmx ${e.join(" ")}
731
+ Copy the key, then paste it below.`});let a=(await jl({message:o.prompt}))?.trim(),l=a?P2(a):void 0;if(l&&l!==o.value){let d=Ja.find((g)=>g.value===l);if(d)await Ds({title:"API key type detected",message:`This looks like ${d.label}. ${d.hint}.`})}if(!a)throw new v("A MiniMax API key is required.",x.USAGE);let c=i.filter((d)=>!t.has(d)),f=`Configure ${i.map((d)=>ni[d]).join(", ")}? mmx will write configuration files.`;if(c.length>0)f+=` Not detected on PATH: ${c.map((d)=>ni[d]).join(", ")}. mmx will still write configuration files for them, but will not download or install them for you.`;if(!await Mi({message:f}))throw new v("Agent setup cancelled.",x.GENERAL);return{agents:i,apiKey:a,region:r,model:ja}}function U2(e){if(e._positional?.length)throw new v("Unexpected positional argument.",x.USAGE,"Select agents with --agent <name> or --all.");let n=im(e.agent??[]),i=e.all?[...on]:n;if(i.length===0)throw new v("At least one --agent or --all is required in non-interactive mode.",x.USAGE,"mmx agent setup --agent codex --api-key <key> --region global");if(e.region!=="global"&&e.region!=="cn")throw new v("--region global|cn is required in non-interactive mode.",x.USAGE,"Supplying the region makes scripts deterministic and prevents writing configs for the wrong service.");let r=e.apiKey?.trim();if(!r)throw new v("A MiniMax API key is required in non-interactive mode.",x.USAGE,`Pass --api-key <key>.
732
+ Token Plan keys (sk-cp-...) and pay-as-you-go keys (sk-api-...) use separate quotas.`);let s=(e.model??ja).trim();if(!s)throw new v("--model must not be empty.",x.USAGE);let o=ue.find((a)=>a.id===s)?.id;if(!o)throw new v(`Unsupported MiniMax model "${s}".`,x.USAGE,`Supported models: ${ue.map((a)=>a.id).join(", ")}`);return{agents:i,apiKey:r,region:e.region,model:o}}var Ya,R2,ni,L2,Ja,rm;var sm=I(()=>{J();Ha();em();zr();nm();G();V();z();Ve();Ae();Ya=Ft(dn(),1),R2={claude:"claude-code",claudecode:"claude-code","claude-code":"claude-code",codex:"codex",grok:"grok","grok-build":"grok","grok-cli":"grok",opencode:"opencode",hermes:"hermes",pi:"pi"},ni={"claude-code":"Claude Code",codex:"Codex",grok:"Grok CLI (Grok Build)",opencode:"OpenCode",hermes:"Hermes Agent",pi:"Pi"},L2=["claude-code","codex"],Ja=[{value:"token-plan",label:"Token Plan (sk-cp-...)",hint:"Uses plan quota and Credits",pagePath:"/user-center/payment/token-plan",noteTitle:"Get your Token Plan key",prompt:"Paste your Token Plan key"},{value:"paygo",label:"Pay-as-you-go (sk-api-...)",hint:"Uses account balance",pagePath:"/user-center/basic-information/interface-key",noteTitle:"Create a pay-as-you-go key",prompt:"Paste your pay-as-you-go key"}];rm=R({name:"agent setup",description:"Configure external coding agents using a MiniMax API key (does not install or launch them)",usage:"mmx agent setup [--agent <name> ... | --all] [--api-key <key>] [--region <region>]",options:[{flag:"--agent <name>",description:"Agent: claude-code, codex, grok/grok-build, opencode, hermes, pi (repeatable)",type:"array"},{flag:"--api-key <key>",description:"API key only; Token Plan (sk-cp) and pay-as-you-go (sk-api) keys are not interchangeable"},{flag:"--all",description:"Configure every supported agent"},{flag:"--model <model>",description:`Default model (${ue.map((e)=>e.id).join(", ")})`}],examples:["mmx agent setup","mmx agent setup --agent claude-code --agent codex --api-key <key> --region global","mmx agent setup --all --api-key <key> --region cn --output json","mmx agent setup --agent opencode --api-key <key> --region cn --dry-run"],async run(e,t){let n=Zp(),i=F2(t),r=i?await D2(e,n):U2(t),s={region:r.region,model:r.model,endpoint:"",status:"skipped"};if(!e.dryRun){let f=()=>tm({apiKey:r.apiKey,region:r.region,model:r.model,timeoutSeconds:Math.min(e.timeout,60)});s=i?await Bl({message:"Verifying API key with MiniMax...",successMessage:"API key verified.",errorMessage:"API key verification failed."},f):await f()}let o=zp(r),a=Qp(o,e.dryRun),l=F(e.output);console.log(q2({verification:s,agents:r.agents,files:a},l,i&&!e.noColor));let c=r.agents.filter((f)=>!n.has(f));if(!i&&c.length>0&&!e.quiet)process.stderr.write(`Warning: Not detected on PATH: ${c.map((f)=>ni[f]).join(", ")}. mmx can write configuration files for them, but will not download or install them for you.
733
+ `)}})});var Lc={};ii(Lc,{registry:()=>qe});class om{root={children:new Map};constructor(e){for(let[t,n]of Object.entries(e))this.register(t,n)}register(e,t){let n=e.split(" "),i=this.root;for(let r of n){if(!i.children.has(r))i.children.set(r,{children:new Map});i=i.children.get(r)}i.command=t}getAllCommands(){let e=new Set,t=[],n=(i)=>{if(i.command&&!e.has(i.command))e.add(i.command),t.push(i.command);for(let r of i.children.values())n(r)};return n(this.root),t}resolve(e){let t=this.root,n=[];for(let i of e){let r=t.children.get(i);if(!r)break;t=r,n.push(i)}if(t.command)return{command:t.command,extra:e.slice(n.length)};if(n.length>0&&t.children.size===1){let[,i]=t.children.entries().next().value;if(i.command)return{command:i.command,extra:e.slice(n.length)}}if(n.length>0&&t.children.size>1){let r=Array.from(t.children.values()).map((o)=>o.command),s=r[0];if(s&&r.every((o)=>o===s))return{command:s,extra:e.slice(n.length)}}if(n.length>0&&t.children.size>0){let i=Array.from(t.children.entries()).map(([r,s])=>{if(s.command)return` ${n.join(" ")} ${r} ${s.command.description}`;let o=Array.from(s.children.keys()).join(", ");return` ${n.join(" ")} ${r} [${o}]`}).join(`
734
+ `);throw new v(`Unknown command: mmx ${e.join(" ")}
248
735
 
249
736
  Available commands:
250
- ${n}`,d.USAGE,`mmx ${o.join(" ")} --help`)}throw new m(`Unknown command: mmx ${e.join(" ")}`,d.USAGE,"mmx --help")}bold=(e,t)=>t.isTTY?`\x1B[1m${e}\x1B[0m`:e;accent=(e,t)=>t.isTTY?`\x1B[38;2;248;103;58m${e}\x1B[0m`:e;dim=(e,t)=>t.isTTY?`\x1B[2m${e}\x1B[0m`:e;printHelp(e,t=process.stdout,o="global"){if(e.length===0){this.printRootHelp(t);return}let n=this.root;for(let s of e){let r=n.children.get(s);if(!r){this.printRootHelp(t);return}n=r}if(n.command){this.printCommandHelp(n.command,t,o);return}let i=e.join(" ");t.write(`
251
- ${this.bold("Usage:",t)} mmx ${i} <command> [flags]
737
+ ${i}`,x.USAGE,`mmx ${n.join(" ")} --help`)}throw new v(`Unknown command: mmx ${e.join(" ")}`,x.USAGE,"mmx --help")}bold=(e,t)=>t.isTTY?`\x1B[1m${e}\x1B[0m`:e;accent=(e,t)=>t.isTTY?`\x1B[38;2;248;103;58m${e}\x1B[0m`:e;dim=(e,t)=>t.isTTY?`\x1B[2m${e}\x1B[0m`:e;printHelp(e,t=process.stdout,n="global"){if(e.length===0){this.printRootHelp(t);return}let i=this.root;for(let s of e){let o=i.children.get(s);if(!o){this.printRootHelp(t);return}i=o}if(i.command){this.printCommandHelp(i.command,t,n);return}let r=e.join(" ");t.write(`
738
+ ${this.bold("Usage:",t)} mmx ${r} <command> [flags]
252
739
 
253
740
  `),t.write(`${this.bold("Commands:",t)}
254
- `),this.printChildren(n,i,t),t.write(`
255
- `)}printRootHelp(e){let t=["███╗ ███╗███╗ ███╗██╗ ██╗","████╗ ████║████╗ ████║╚██╗██╔╝","██╔████╔██║██╔████╔██║ ╚███╔╝ ","██║╚██╔╝██║██║╚██╔╝██║ ██╔██╗ ","██║ ╚═╝ ██║██║ ╚═╝ ██║██╔╝ ██╗","╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝"],o=[[240,23,122],[242,43,106],[244,63,90],[246,83,74],[248,103,58],[250,123,42]];e.write(`
256
- `);for(let r=0;r<t.length;r++)if(e.isTTY){let[u,a,l]=o[r];e.write(`\x1B[1;38;2;${u};${a};${l}m${t[r]}\x1B[0m
257
- `)}else e.write(t[r]+`
258
- `);let n=(r)=>this.bold(r,e),i=(r)=>this.accent(r,e),s=(r)=>this.dim(r,e);e.write(`
259
- ${n("Usage:")} mmx <resource> <command> [flags]
741
+ `),this.printChildren(i,r,t),t.write(`
742
+ `)}printRootHelp(e){let t=["███╗ ███╗███╗ ███╗██╗ ██╗","████╗ ████║████╗ ████║╚██╗██╔╝","██╔████╔██║██╔████╔██║ ╚███╔╝ ","██║╚██╔╝██║██║╚██╔╝██║ ██╔██╗ ","██║ ╚═╝ ██║██║ ╚═╝ ██║██╔╝ ██╗","╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝"],n=[[240,23,122],[242,43,106],[244,63,90],[246,83,74],[248,103,58],[250,123,42]];e.write(`
743
+ `);for(let o=0;o<t.length;o++)if(e.isTTY){let[a,l,c]=n[o];e.write(`\x1B[1;38;2;${a};${l};${c}m${t[o]}\x1B[0m
744
+ `)}else e.write(t[o]+`
745
+ `);let i=(o)=>this.bold(o,e),r=(o)=>this.accent(o,e),s=(o)=>this.dim(o,e);e.write(`
746
+ ${i("Usage:")} mmx <resource> <command> [flags]
260
747
 
261
- ${n("Resources:")}
262
- ${i("auth")} ${s("Authentication (login, status, refresh, logout)")}
263
- ${i("text")} ${s("Text generation (chat)")}
264
- ${i("speech")} ${s("Speech synthesis (synthesize, voices)")}
265
- ${i("image")} ${s("Image generation (generate)")}
266
- ${i("video")} ${s("Video generation (generate, task get, download)")}
267
- ${i("search")} ${s("Web search (query)")}
268
- ${i("vision")} ${s("Image understanding (describe)")}
269
- ${i("quota")} ${s("Usage quotas (show)")}
270
- ${i("config")} ${s("CLI configuration (show, set, export-schema)")}
271
- ${i("file")} ${s("File storage (upload, list, delete)")}
272
- ${i("update")} ${s("Update mmx to a newer version")}
748
+ ${i("Resources:")}
749
+ ${r("auth")} ${s("Authentication (login, status, refresh, logout)")}
750
+ ${r("text")} ${s("Text generation (chat)")}
751
+ ${r("speech")} ${s("Speech synthesis (synthesize, voices)")}
752
+ ${r("image")} ${s("Image generation (generate)")}
753
+ ${r("video")} ${s("Video generation (generate, task get, download)")}
754
+ ${r("search")} ${s("Web search (query)")}
755
+ ${r("vision")} ${s("Image understanding (describe)")}
756
+ ${r("quota")} ${s("Usage quotas (show)")}
757
+ ${r("config")} ${s("CLI configuration (show, set, export-schema)")}
758
+ ${r("agent")} ${s("External coding agent integration (setup)")}
759
+ ${r("file")} ${s("File storage (upload, list, delete)")}
760
+ ${r("update")} ${s("Update mmx to a newer version")}
273
761
 
274
- ${n("Global Flags:")}
275
- ${i("--api-key <key>")} ${s("API key (overrides all other auth)")}
276
- ${i("--region <region>")} ${s("API region: global (default), cn")}
277
- ${i("--base-url <url>")} ${s("API base URL (overrides region)")}
278
- ${i("--output <format>")} ${s("Output format: text, json")}
279
- ${i("--quiet")} ${s("Suppress non-essential output")}
280
- ${i("--verbose")} ${s("Print HTTP request/response details")}
281
- ${i("--timeout <seconds>")} ${s("Request timeout (default: 300)")}
282
- ${i("--no-color")} ${s("Disable ANSI colors and spinners")}
283
- ${i("--dry-run")} ${s("Show what would happen without executing")}
284
- ${i("--non-interactive")} ${s("Disable interactive prompts (CI/agent mode)")}
285
- ${i("--version")} ${s("Print version and exit")}
286
- ${i("--help")} ${s("Show help")}
762
+ ${i("Global Flags:")}
763
+ ${r("--api-key <key>")} ${s("API key (overrides all other auth)")}
764
+ ${r("--region <region>")} ${s("API region: global (default), cn")}
765
+ ${r("--base-url <url>")} ${s("API base URL (overrides region)")}
766
+ ${r("--output <format>")} ${s("Output format: text, json")}
767
+ ${r("--quiet")} ${s("Suppress non-essential output")}
768
+ ${r("--verbose")} ${s("Print HTTP request/response details")}
769
+ ${r("--timeout <seconds>")} ${s("Request timeout (default: 300)")}
770
+ ${r("--no-color")} ${s("Disable ANSI colors and spinners")}
771
+ ${r("--dry-run")} ${s("Show what would happen without executing")}
772
+ ${r("--non-interactive")} ${s("Disable interactive prompts (CI/agent mode)")}
773
+ ${r("--version")} ${s("Print version and exit")}
774
+ ${r("--help")} ${s("Show help")}
287
775
 
288
- ${n("Getting Help:")}
776
+ ${i("Getting Help:")}
289
777
  ${s("Add --help after any command to see its full list of options, defaults,")}
290
778
  ${s("and usage examples. For example:")} mmx text chat --help
291
- `)}printCommandHelp(e,t,o="global"){let n=(u)=>this.bold(u,t),i=(u)=>this.accent(u,t),s=(u)=>this.dim(u,t);if(t.write(`
779
+ `)}printCommandHelp(e,t,n="global"){let i=(a)=>this.bold(a,t),r=(a)=>this.accent(a,t),s=(a)=>this.dim(a,t);if(t.write(`
292
780
  ${e.description}
293
- `),e.usage)t.write(`${n("Usage:")} ${e.usage}
294
- `);let r=e.options?.filter((u)=>!u.hidden)??[];if(r.length>0){let u=Math.max(...r.map((a)=>a.flag.length));t.write(`
295
- ${n("Options:")}
296
- `);for(let a of r)t.write(` ${i(a.flag.padEnd(u+2))} ${s(a.description)}
781
+ `),e.usage)t.write(`${i("Usage:")} ${e.usage}
782
+ `);let o=e.options?.filter((a)=>!a.hidden)??[];if(o.length>0){let a=Math.max(...o.map((l)=>l.flag.length));t.write(`
783
+ ${i("Options:")}
784
+ `);for(let l of o)t.write(` ${r(l.flag.padEnd(a+2))} ${s(l.description)}
297
785
  `)}if(e.examples&&e.examples.length>0){t.write(`
298
- ${n("Examples:")}
299
- `);for(let u of e.examples)t.write(` ${s(u)}
786
+ ${i("Examples:")}
787
+ `);for(let a of e.examples)t.write(` ${s(a)}
300
788
  `)}if(e.apiDocs)t.write(`
301
- ${n("API Reference:")} ${s(Le[o]+e.apiDocs)}
789
+ ${i("API Reference:")} ${s(gt[n]+e.apiDocs)}
302
790
  `);t.write(`
303
791
  ${s("Global flags (--api-key, --output, --quiet, etc.) are always available.")}
304
792
  `),t.write(`${s("Run")} mmx --help ${s("for the full list.")}
305
- `)}printChildren(e,t,o){let n=[],i=(r,u)=>{for(let[a,l]of r.children){if(l.command)n.push({fullName:`${u} ${a}`,description:l.command.description});if(l.children.size>0)i(l,`${u} ${a}`)}};i(e,t);let s=Math.max(...n.map((r)=>r.fullName.length));for(let{fullName:r,description:u}of n)o.write(` ${this.accent(r.padEnd(s),o)} ${this.dim(u,o)}
306
- `)}}var ae;var gt=C(()=>{R();S();re();en();on();sn();an();pn();Cn();Bn();Tn();Kn();ti();oi();ii();si();ai();li();di();hi();Ci();bi();Fi();wi();$i();Ai();ae=new Si({"auth login":Zo,"auth status":rn,"auth refresh":nn,"auth logout":un,"text chat":dn,"text repl":gn,"speech synthesize":pr,"speech generate":pr,"speech voices":In,"image generate":Wn,"video generate":ei,"video task get":ri,"video download":ni,"search query":Fr,"search web":Fr,"vision describe":ui,"quota show":ci,"config show":mi,"config set":fi,"config export-schema":gi,"file upload":yi,"file list":Ei,"file delete":xi,update:vi,help:_i})});var Vi=new Set(["true","1","yes","on"]),ji=new Set(["false","0","no","off"]);function _t(e){return e.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}function Hi(e){let t=e.flag.match(/^--([a-z][a-z0-9-]*)/i);return t?_t(t[1]):null}function Wi(e){if(e.type==="boolean")return!0;if(e.type==="string"||e.type==="number"||e.type==="array")return!1;return!e.flag.includes("<")&&!e.flag.includes("[")}function $r(e){let t=new Set,o=new Set,n=new Set;for(let i of e){let s=Hi(i);if(!s)continue;if(Wi(i))t.add(s);else if(i.type==="number")o.add(s);else if(i.type==="array")n.add(s)}return{booleans:t,numbers:o,arrays:n}}function _r(e,t=[]){let o=$r(t),n=[],i=0;while(i<e.length){let s=e[i];if(s==="--")break;if(s.startsWith("--")){let r=s.indexOf("="),u=r!==-1?s.slice(2,r):s.slice(2),a=_t(u);if(!o.booleans.has(a)&&r===-1)i+=2;else i+=1;continue}if(s.startsWith("-")){i++;continue}n.push(s),i++}return n}function At(e,t){let o=$r(t),n={quiet:!1,verbose:!1,noColor:!1,yes:!1,dryRun:!1,help:!1,nonInteractive:!1,async:!1},i=0;while(i<e.length){let s=e[i];if(s==="--help"||s==="-h"){n.help=!0,i++;continue}if(s==="--")break;if(s.startsWith("--")){let r=s.indexOf("="),u,a;if(r!==-1)u=s.slice(2,r),a=s.slice(r+1);else u=s.slice(2);let l=_t(u);if(o.booleans.has(l)){if(a===void 0)n[l]=!0;else{let p=a.trim().toLowerCase();if(Vi.has(p))n[l]=!0;else if(ji.has(p))n[l]=!1;else throw Error(`Flag --${u} requires a boolean value (e.g. true/false), got "${a}".`)}i++;continue}if(a===void 0)i++,a=e[i];if(a===void 0)throw Error(`Flag --${u} requires a value.`);if(o.arrays.has(l)){let p=n[l];if(p)p.push(a);else n[l]=[a]}else if(o.numbers.has(l)){let p=Number(a);if(a.trim()===""||!Number.isFinite(p))throw Error(`Flag --${u} requires a numeric value, got "${a}".`);n[l]=p}else n[l]=a}i++}return n}gt();T();R();S();N();function Re(e){if(e instanceof m){if(_(process.env.MINIMAX_OUTPUT)==="json")process.stderr.write(JSON.stringify(e.toJSON(),null,2)+`
793
+ `)}printChildren(e,t,n){let i=[],r=(o,a)=>{for(let[l,c]of o.children){if(c.command)i.push({fullName:`${a} ${l}`,description:c.command.description});if(c.children.size>0)r(c,`${a} ${l}`)}};r(e,t);let s=Math.max(...i.map((o)=>o.fullName.length));for(let{fullName:o,description:a}of i)n.write(` ${this.accent(o.padEnd(s),n)} ${this.dim(a,n)}
794
+ `)}}var qe;var Ki=I(()=>{G();V();Ae();Rc();qc();Dc();jc();Wc();Qc();cu();fu();ku();Nu();Ru();Pu();qu();Du();ju();Vu();Hu();Yu();Zu();tf();rf();of();lf();sm();qe=new om({"auth login":Cc,"auth status":Pc,"auth refresh":Fc,"auth logout":Uc,"text chat":Kc,"text repl":zc,"speech synthesize":ro,"speech generate":ro,"speech voices":uu,"image generate":$u,"video generate":Mu,"video task get":Cu,"video download":Lu,"search query":mo,"search web":mo,"vision describe":Fu,"quota show":Uu,"config show":Bu,"config set":Wu,"config export-schema":Ju,"file upload":Xu,"file list":ef,"file delete":nf,update:sf,help:af,"agent setup":rm})});var Sm=new Set(["true","1","yes","on"]),$m=new Set(["false","0","no","off"]);function ri(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}function km(e){let t=e.flag.match(/^--([a-z][a-z0-9-]*)/i);return t?ri(t[1]):null}function Am(e){if(e.type==="boolean")return!0;if(e.type==="string"||e.type==="number"||e.type==="array")return!1;return!e.flag.includes("<")&&!e.flag.includes("[")}function es(e){let t=new Set,n=new Set,i=new Set,r=new Set;for(let s of e){let o=km(s);if(!o)continue;if(r.add(o),Am(s))t.add(o);else if(s.type==="number")n.add(o);else if(s.type==="array")i.add(o)}return{booleans:t,numbers:n,arrays:i,keys:r}}function Qa(e,t){let n=es(t),i=0;while(i<e.length){let r=e[i];if(r==="--")break;if(r.startsWith("--")){let s=r.indexOf("="),o=s===-1?r.slice(2):r.slice(2,s),a=ri(o);if(!n.keys.has(a))return`Unknown option: --${o}`;if(s!==-1&&!n.booleans.has(a)&&r.slice(s+1).trim()==="")return`Option --${o} requires a value.`;if(s===-1&&!n.booleans.has(a)){let l=e[i+1];if(l===void 0||l.startsWith("-"))return`Option --${o} requires a value.`;i+=2;continue}i+=1;continue}if(r.startsWith("-")&&r!=="-h"&&r!=="-v")return`Unknown option: ${r}`;i+=1}return}function ts(e,t=[]){let n=es(t),i=[],r=0;while(r<e.length){let s=e[r];if(s==="--")break;if(s.startsWith("--")){let o=s.indexOf("="),a=o!==-1?s.slice(2,o):s.slice(2),l=ri(a);if(!n.booleans.has(l)&&o===-1)r+=2;else r+=1;continue}if(s.startsWith("-")){r++;continue}i.push(s),r++}return i}function ns(e,t){let n=es(t),i={quiet:!1,verbose:!1,noColor:!1,yes:!1,dryRun:!1,help:!1,nonInteractive:!1,async:!1},r=0;while(r<e.length){let s=e[r];if(s==="--help"||s==="-h"){i.help=!0,r++;continue}if(s==="--")break;if(s.startsWith("--")){let o=s.indexOf("="),a,l;if(o!==-1)a=s.slice(2,o),l=s.slice(o+1);else a=s.slice(2);let c=ri(a);if(n.booleans.has(c)){if(l===void 0)i[c]=!0;else{let f=l.trim().toLowerCase();if(Sm.has(f))i[c]=!0;else if($m.has(f))i[c]=!1;else throw Error(`Flag --${a} requires a boolean value (e.g. true/false), got "${l}".`)}r++;continue}if(l===void 0)r++,l=e[r];if(l===void 0)throw Error(`Flag --${a} requires a value.`);if(n.arrays.has(c)){let f=i[c];if(f)f.push(l);else i[c]=[l]}else if(n.numbers.has(c)){let f=Number(l);if(l.trim()===""||!Number.isFinite(f))throw Error(`Flag --${a} requires a numeric value, got "${l}".`);i[c]=f}else i[c]=l}r++}return i}Ki();J();G();V();G();V();z();function qt(e){if(e instanceof v){if(F(process.env.MINIMAX_OUTPUT)==="json")process.stderr.write(JSON.stringify(e.toJSON(),null,2)+`
307
795
  `);else{if(process.stderr.write(`
308
796
  Error: ${e.message}
309
797
  `),e.hint)process.stderr.write(`
@@ -311,25 +799,25 @@ Error: ${e.message}
311
799
  `).join(`
312
800
  `)}
313
801
  `);process.stderr.write(` (exit code ${e.exitCode})
314
- `)}process.exit(e.exitCode)}if(e instanceof Error){if(e.name==="AbortError"||e.name==="TimeoutError"||e.message.includes("timed out")){let i=new m("Request timed out.",d.TIMEOUT,`Try increasing --timeout (e.g. --timeout 60).
802
+ `)}process.exit(e.exitCode)}if(e instanceof Error){if(e.name==="AbortError"||e.name==="TimeoutError"||e.message.includes("timed out")){let r=new v("Request timed out.",x.TIMEOUT,`Try increasing --timeout (e.g. --timeout 60).
315
803
  If this happens on every request with a valid API key, you may be hitting the wrong region.
316
804
  `+`Run: mmx auth status — to check your credentials and region.
317
- `+"Run: mmx config set region global (or cn) — to override the region.");return Re(i)}if(e instanceof TypeError&&e.message==="fetch failed"){let i=new m("Network request failed.",d.NETWORK,`Check your network connection.
318
- To use a proxy: set HTTPS_PROXY env var, or run: mmx config set --key proxy --value http://HOST:PORT`);return Re(i)}let t=e.message.toLowerCase();if(t.includes("failed to fetch")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("connection reset")||t.includes("econnreset")||t.includes("network error")||t.includes("enotfound")||t.includes("getaddrinfo")||t.includes("proxy")||t.includes("socket")||t.includes("etimedout")||t.includes("timeout")||t.includes("eai_AGAIN")){let i=`Check your network connection.
319
- To use a proxy: set HTTPS_PROXY env var, or run: mmx config set --key proxy --value http://HOST:PORT`;if(t.includes("proxy"))i=`Proxy connection failed — verify your proxy URL and authentication.
320
- `+"Check: HTTPS_PROXY / HTTP_PROXY env vars, or mmx config show for configured proxy.";let s=new m("Network request failed.",d.NETWORK,i);return Re(s)}let n=e.code;if(n==="ENOENT"||n==="EACCES"||n==="ENOSPC"||n==="ENOTDIR"||n==="EISDIR"||n==="EPERM"||n==="EBUSY"){let i="Check the file path and permissions.";if(n==="ENOENT")i="File or directory not found.";if(n==="EACCES"||n==="EPERM")i="Permission denied — check file or directory permissions.";if(n==="ENOSPC")i="Disk full — free up space and try again.";let s=new m(`File system error: ${e.message}`,d.GENERAL,i);return Re(s)}else if(typeof n==="string"&&n.startsWith("E")){let i=new m(`File system error: ${e.message}`,d.GENERAL,"Check the file path and permissions.");return Re(i)}if(process.stderr.write(`
805
+ `+"Run: mmx config set region global (or cn) — to override the region.");return qt(r)}if(e instanceof TypeError&&e.message==="fetch failed"){let r=new v("Network request failed.",x.NETWORK,`Check your network connection.
806
+ To use a proxy: set HTTPS_PROXY env var, or run: mmx config set --key proxy --value http://HOST:PORT`);return qt(r)}let t=e.message.toLowerCase();if(t.includes("failed to fetch")||t.includes("connection refused")||t.includes("econnrefused")||t.includes("connection reset")||t.includes("econnreset")||t.includes("network error")||t.includes("enotfound")||t.includes("getaddrinfo")||t.includes("proxy")||t.includes("socket")||t.includes("etimedout")||t.includes("timeout")||t.includes("eai_AGAIN")){let r=`Check your network connection.
807
+ To use a proxy: set HTTPS_PROXY env var, or run: mmx config set --key proxy --value http://HOST:PORT`;if(t.includes("proxy"))r=`Proxy connection failed — verify your proxy URL and authentication.
808
+ `+"Check: HTTPS_PROXY / HTTP_PROXY env vars, or mmx config show for configured proxy.";let s=new v("Network request failed.",x.NETWORK,r);return qt(s)}let i=e.code;if(i==="ENOENT"||i==="EACCES"||i==="ENOSPC"||i==="ENOTDIR"||i==="EISDIR"||i==="EPERM"||i==="EBUSY"){let r="Check the file path and permissions.";if(i==="ENOENT")r="File or directory not found.";if(i==="EACCES"||i==="EPERM")r="Permission denied — check file or directory permissions.";if(i==="ENOSPC")r="Disk full — free up space and try again.";let s=new v(`File system error: ${e.message}`,x.GENERAL,r);return qt(s)}else if(typeof i==="string"&&i.startsWith("E")){let r=new v(`File system error: ${e.message}`,x.GENERAL,"Check the file path and permissions.");return qt(r)}if(process.stderr.write(`
321
809
  Error: ${e.message}
322
810
  `),process.env.MINIMAX_VERBOSE==="1")process.stderr.write(`${e.stack}
323
811
  `)}else process.stderr.write(`
324
812
  Error: ${String(e)}
325
- `);process.exit(d.GENERAL)}se();sr();re();Ie();import{join as Xa}from"path";import{readFileSync as Qa,writeFileSync as Za}from"fs";var ki=()=>Xa(Xe(),"update-state.json"),ec=86400000,tc=3000,rc="MiniMax-AI-Dev/minimax-cli";function oc(){try{let e=Qa(ki(),"utf-8");return JSON.parse(e)}catch{return null}}function nc(e){try{Za(ki(),JSON.stringify(e))}catch{}}async function ic(){try{let e=await fetch(`https://api.github.com/repos/${rc}/releases/latest`,{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(tc)});if(!e.ok)return null;return(await e.json()).tag_name??null}catch{return null}}var wr=null;function Ri(){return wr}async function Bi(e){if(process.env.CI||!process.stderr.isTTY)return;let t=oc(),o=Date.now();if(t&&o-t.lastChecked<ec){if(t.latestVersion&&t.latestVersion!==`v${e}`)wr=t.latestVersion;return}let n=await ic();if(!n)return;if(nc({lastChecked:o,latestVersion:n}),n!==`v${e}`)wr=n}De();Zt();ct();import{ProxyAgent as sc,setGlobalDispatcher as uc}from"undici";process.on("SIGINT",()=>{process.stderr.write(`
813
+ `);process.exit(x.GENERAL)}Be();Qs();Ae();Dt();import{join as j2}from"path";import{readFileSync as B2,writeFileSync as V2}from"fs";var am=()=>j2(oi(),"update-state.json"),G2=86400000,K2=3000,W2="MiniMax-AI-Dev/minimax-cli";function H2(){try{let e=B2(am(),"utf-8");return JSON.parse(e)}catch{return null}}function J2(e){try{V2(am(),JSON.stringify(e))}catch{}}async function Y2(){try{let e=await fetch(`https://api.github.com/repos/${W2}/releases/latest`,{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(K2)});if(!e.ok)return null;return(await e.json()).tag_name??null}catch{return null}}var za=null;function lm(){return za}async function cm(e){if(process.env.CI||!process.stderr.isTTY)return;let t=H2(),n=Date.now();if(t&&n-t.lastChecked<G2){if(t.latestVersion&&t.latestVersion!==`v${e}`)za=t.latestVersion;return}let i=await Y2();if(!i)return;if(J2({lastChecked:n,latestVersion:i}),i!==`v${e}`)za=i}Xe();Gs();Pi();import{ProxyAgent as z2,setGlobalDispatcher as Q2}from"undici";process.on("SIGINT",()=>{process.stderr.write(`
326
814
  Interrupted. Exiting.
327
- `),process.exit(130)});process.stdout.on("error",(e)=>{if(e.code==="EPIPE")process.exit(0);else throw e});var ac=[["auth","login"],["auth","logout"],["config","show"],["config","set"],["config","export-schema"],["update"]];async function cc(){let e=process.argv.slice(2);if(e.includes("--version")||e.includes("-v"))console.log(`mmx ${we}`),process.exit(0);let t=_r(e,Ye),o=P(),n=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||process.env.ALL_PROXY||process.env.all_proxy||o.proxy;if(n)uc(new sc(n));if(e.includes("--help")||e.includes("-h")){let f=e.indexOf("--region"),D=f>=0&&e[f+1]||process.env.MINIMAX_REGION||o.region||"global";ae.printHelp(t,process.stderr,D),process.exit(0)}if(t.length===0){ae.printHelp([],process.stderr);let{command:f}=ae.resolve(["quota","show"]),D=At(e,[...Ye,...f.options??[]]),h=kt(D),E=!!(h.apiKey||h.fileApiKey),x=!!await Y();if(E||x)await f.execute(h,D);else process.stderr.write(` Not logged in.
815
+ `),process.exit(130)});process.stdout.on("error",(e)=>{if(e.code==="EPIPE")process.exit(0);else throw e});var X2=[["auth","login"],["auth","logout"],["config","show"],["config","set"],["config","export-schema"],["update"]];async function Z2(){let e=process.argv.slice(2);if(e.includes("--version")||e.includes("-v"))console.log(`mmx ${St}`),process.exit(0);let t=ts(e,fn);if(t[0]==="agent"){let{command:p}=qe.resolve(["agent","setup"]);if(t=ts(e,[...fn,...p.options??[]]),t.length===1)t.push("setup")}let n=Q(),i=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||process.env.ALL_PROXY||process.env.all_proxy||n.proxy;if(i)Q2(new z2(i));if(e.includes("--help")||e.includes("-h")){let p=e.indexOf("--region"),m=p>=0&&e[p+1]||process.env.MINIMAX_REGION||n.region||"global";qe.printHelp(t,process.stderr,m),process.exit(0)}if(t.length===0){qe.printHelp([],process.stderr);let{command:p}=qe.resolve(["quota","show"]),m=ns(e,[...fn,...p.options??[]]),b=rs(m),w=!!(b.apiKey||b.fileApiKey),S=!!await ye();if(w||S)await p.execute(b,m);else process.stderr.write(` Not logged in.
328
816
  `),process.stderr.write(` mmx auth login Choose MiniMax OAuth (Global/China) or paste an API key
329
817
  `),process.stderr.write(` mmx auth login --api-key Save an API key directly
330
818
 
331
- `);process.exit(0)}let{command:i,extra:s}=ae.resolve(t),r=At(e,[...Ye,...i.options??[]]);if(s.length>0)r._positional=s;let u=kt(r);if(!ac.some((f)=>f.every((D,h)=>t[h]===D)))await yo(u);if(u.needsRegionDetection){let f=u.apiKey||u.fileApiKey;if(f){let D=await ht(f);u.region=D,u.baseUrl=U[D],u.needsRegionDetection=!1,await Jo(D)}}let l=Bi(we).catch(()=>{});await i.execute(u,r),await l;let p=Ri();if(p&&!u.quiet)process.stderr.write(`
332
- Update available: ${p}
819
+ `);process.exit(0)}let{command:r,extra:s}=qe.resolve(t),o=r.name==="agent setup",a=[...fn,...r.options??[]];if(o){let p=Qa(e,a);if(p)throw new v(p,x.USAGE,"Run mmx agent setup --help to see supported options.")}let l=ns(e,a),c=o?e.indexOf("--"):-1,f=c>=0?[...s,...e.slice(c+1)]:s;if(f.length>0)l._positional=f;if(o)l._hasExplicitOptions=f.length>0||e.some((p)=>p.startsWith("-"));let u=rs(l);if(!o&&!X2.some((p)=>p.every((m,b)=>t[b]===m)))await Yl(u);if(u.needsRegionDetection&&!o){let p=u.apiKey||u.fileApiKey;if(p){let m=await Gi(p);u.region=m,u.baseUrl=Z[m],u.needsRegionDetection=!1,await Ic(m)}}let g=o&&u.dryRun?Promise.resolve():cm(St).catch(()=>{});await r.execute(u,l),await g;let h=lm();if(h&&!u.quiet)process.stderr.write(`
820
+ Update available: ${h}
333
821
  `),process.stderr.write(` npm update -g mmx-cli
334
822
 
335
- `)}cc().catch(Re);
823
+ `)}Z2().catch(qt);