aicommits 2.0.0-develop.29 → 2.0.0-develop.30

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.
@@ -1,92 +1,92 @@
1
- var BD=Object.defineProperty;var i=(e,t)=>BD(e,"name",{value:t,configurable:!0});var Jn,Cn,Kn,Yn,Xn,Qn,er,tr,nr,rr,nn,or,ar,wn,Fn,sr,ir,ur,lr,cr,En,dr,pr,fr,mr,hr,Dr,gr,vr,yr,_r,br,Cr,wr,Fr,Er,xr,kr,Ir,Ar,$r,Tr,Sr,Br,Or,Rr,Nr,Pr,Mr,jr,zr,qr;import OD from"tty";import{Buffer as RD}from"node:buffer";import In from"node:path";import _l,{ChildProcess as ND}from"node:child_process";import qe,{stdin as bl,stdout as Cl}from"node:process";import PD,{exec as wl}from"child_process";import bt from"path";import is from"fs";import{fileURLToPath as Fl}from"node:url";import MD,{constants as El}from"node:os";import jD from"assert";import zD from"events";import{createWriteStream as qD,createReadStream as LD}from"node:fs";import UD from"buffer";import us from"stream";import ZD,{promisify as VD}from"util";import{debuglog as GD}from"node:util";import*as zo from"node:readline";import xl from"node:readline";import{Writable as WD}from"node:stream";import He from"fs/promises";import kl from"os";import HD from"crypto";import{fileURLToPath as JD,pathToFileURL as KD}from"url";var YD=Object.defineProperty,Ue=i((e,t)=>YD(e,"name",{value:t,configurable:!0}),"a");const XD="known-flag",QD="unknown-flag",eg="argument",tg=/\B([A-Z])/g,ng=Ue(e=>e.replaceAll(tg,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:rg}=Object.prototype,to=Ue((e,t)=>rg.call(e,t),"hasOwn"),ls=Ue(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:ls(e.type),"parseFlagType"),Il=Ue((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),Al=Ue((e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),"applyParser"),og=/[\s.:=]/,ag=Ue(e=>{const t=`Flag name "${e}"`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const n=e.match(og);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),cs=Ue((e,t,n)=>{if(to(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),sg=Ue(e=>{const t={};for(const n in e){if(!to(e,n))continue;ag(n);const r=e[n],o=[[],...ls(r),r];cs(t,n,o);const s=ng(n);if(n!==s&&cs(t,s,o),"alias"in r&&typeof r.alias=="string"){const{alias:a}=r,u=`Flag alias "${a}" for flag "${n}"`;if(a.length===0)throw new Error(`${u} cannot be empty`);if(a.length>1)throw new Error(`${u} must be a single character`);cs(t,a,o)}}return t},"createRegistry"),ig=Ue((e,t)=>{const n={};for(const r in e){if(!to(e,r))continue;const[o,,s,a]=t[r];if(o.length===0&&"default"in a){let{default:u}=a;typeof u=="function"&&(u=u()),n[r]=u}else n[r]=s?o:o.pop()}return n},"finalizeFlags"),qo="--",ug=3,lg=/^-{1,2}\w/,$l=Ue(e=>{if(!lg.test(e))return;const t=!e.startsWith(qo);let n=e.slice(t?1:2),r,o=-1;for(const s of["=",":","."]){const a=n.indexOf(s);a!==-1&&(o===-1||a<o)&&(o=a)}return o!==-1&&(r=n.slice(o+1),n=n.slice(0,o)),[n,r,t]},"parseFlagArgv"),Tl=Ue((e,{onFlag:t,onArgument:n})=>{let r;const o=Ue((s,a)=>{if(typeof r!="function")return!0;r(s,a),r=void 0},"triggerValueCallback");for(let s=0;s<e.length;s+=1){const a=e[s];if(a===qo){o();const l=e.slice(s+1);n?.(l,[s],!0);break}const u=$l(a);if(u){if(o(),!t)continue;const[l,c,d]=u;if(d)for(let f=0;f<l.length;f+=1){o();const h=f===l.length-1;r=t(l[f],h?c:void 0,[s,f+1,h])}else r=t(l,c,[s])}else o(a,[s])&&n?.([a],[s])}o()},"argvIterator"),Sl=Ue((e,t)=>{for(let n=t.length-1;n>=0;n-=1){const[r,o,s]=t[n];if(o){const a=e[r];let u=a.slice(0,o);if(s||(u+=a.slice(o+1)),u!=="-"){e[r]=u;continue}}e.splice(r,1)}},"spliceFromArgv"),cg=Ue((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],o=sg(e),s={},a=[];return a[qo]=[],Tl(t,{onFlag(u,l,c){const d=(c.length===ug||u.length>1)&&to(o,u);if(!n?.(d?XD:QD,u,l)){if(d){const[f,h]=o[u],D=Il(h,l),m=Ue((v,y)=>{r.push(c),y&&r.push(y),f.push(Al(h,v||""))},"getFollowingValue");return D===void 0?m:m(D)}to(s,u)||(s[u]=[]),s[u].push(l===void 0?!0:l),r.push(c)}},onArgument:Ue((u,l,c)=>{n?.(eg,t[l[0]])||(a.push(...u),c?(a[qo]=u,t.splice(l[0])):r.push(l))},"onArgument")}),Sl(t,r),{flags:ig(e,o),unknownFlags:s,_:a}},"typeFlag");Ue((e,t,n=process.argv.slice(2))=>{const r=new Set(e.split(",").map(l=>$l(l)?.[0])),[o,s]=ls(t),a=[],u=[];return Tl(n,{onFlag:Ue((l,c,d)=>{if(!r.has(l)||!s&&a.length>0)return;const f=Il(o,c),h=Ue((D,m)=>{u.push(d),m&&u.push(m),a.push(Al(o,D||""))},"getFollowingValue");return f===void 0?h:h(f)},"onFlag")}),Sl(n,u),s?a:a[0]},"getFlag");var dg=Object.defineProperty,ae=i((e,t)=>dg(e,"name",{value:t,configurable:!0}),"n");const pg=ae(e=>{const t=process.stdout.columns??Number.POSITIVE_INFINITY;return typeof e=="function"&&(e=e(t)),e||(e={}),Array.isArray(e)?{columns:e,stdoutColumns:t}:{columns:e.columns??[],stdoutColumns:e.stdoutColumns??t}},"getOptions");function Bl({onlyFirst:e=!1}={}){const 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")}i(Bl,"j$1"),ae(Bl,"ansiRegex");const fg=Bl();function ds(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(fg,"")}i(ds,"w$2"),ae(ds,"stripAnsi");function Ol(e){return 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}i(Ol,"P$2"),ae(Ol,"isAmbiguous");function Rl(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}i(Rl,"z$2"),ae(Rl,"isFullWidth");function Nl(e){return 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>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||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<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&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>=101631&&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>=119552&&e<=119638||e>=119648&&e<=119670||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<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}i(Nl,"G$3"),ae(Nl,"isWide");function Pl(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}i(Pl,"Z$1"),ae(Pl,"validate");function Ml(e,{ambiguousAsWide:t=!1}={}){return Pl(e),Rl(e)||Nl(e)||t&&Ol(e)?2:1}i(Ml,"V$3"),ae(Ml,"eastAsianWidth");var mg=ae(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\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?|[\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](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\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-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,"emojiRegex");const hg=new Intl.Segmenter,Dg=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Ut(e,t={}){if(typeof e!="string"||e.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=ds(e)),e.length===0)return 0;let o=0;const s={ambiguousAsWide:!n};for(const{segment:a}of hg.segment(e)){const u=a.codePointAt(0);if(!(u<=31||u>=127&&u<=159)&&!(u>=8203&&u<=8207||u===65279)&&!(u>=768&&u<=879||u>=6832&&u<=6911||u>=7616&&u<=7679||u>=8400&&u<=8447||u>=65056&&u<=65071)&&!(u>=55296&&u<=57343)&&!(u>=65024&&u<=65039)&&!Dg.test(a)){if(mg().test(a)){o+=2;continue}o+=Ml(u,s)}}return o}i(Ut,"d$2"),ae(Ut,"stringWidth");const jl=ae(e=>Math.max(...e.split(`
2
- `).map(t=>Ut(t))),"getLongestLineWidth"),gg=ae(e=>{const t=[];for(const n of e){const{length:r}=n,o=r-t.length;for(let s=0;s<o;s+=1)t.push(0);for(let s=0;s<r;s+=1){const a=jl(n[s]);a>t[s]&&(t[s]=a)}}return t},"getColumnContentWidths"),zl=/^\d+%$/,ql={width:"auto",align:"left",contentWidth:0,paddingLeft:0,paddingRight:0,paddingTop:0,paddingBottom:0,horizontalPadding:0,paddingLeftString:"",paddingRightString:""},vg=ae((e,t)=>{const n=[];for(let r=0;r<e.length;r+=1){const o=t[r]??"auto";if(typeof o=="number"||o==="auto"||o==="content-width"||typeof o=="string"&&zl.test(o)){n.push({...ql,width:o,contentWidth:e[r]});continue}if(o&&typeof o=="object"){const s={...ql,...o,contentWidth:e[r]};s.horizontalPadding=s.paddingLeft+s.paddingRight,n.push(s);continue}throw new Error(`Invalid column width: ${JSON.stringify(o)}`)}return n},"initColumns"),yg=ae((e,t)=>{for(const n of e){const{width:r}=n;if(r==="content-width"&&(n.width=n.contentWidth),r==="auto"){const l=Math.min(20,n.contentWidth);n.width=l,n.autoOverflow=n.contentWidth-l}if(typeof r=="string"&&zl.test(r)){const l=Number.parseFloat(r.slice(0,-1))/100;n.width=Math.floor(t*l)-(n.paddingLeft+n.paddingRight)}const{horizontalPadding:o}=n,s=1,a=s+o;if(a>=t){const l=a-t,c=Math.ceil(n.paddingLeft/o*l),d=l-c;n.paddingLeft-=c,n.paddingRight-=d,n.horizontalPadding=n.paddingLeft+n.paddingRight}n.paddingLeftString=n.paddingLeft?" ".repeat(n.paddingLeft):"",n.paddingRightString=n.paddingRight?" ".repeat(n.paddingRight):"";const u=t-n.horizontalPadding;n.width=Math.max(Math.min(n.width,u),s)}},"resolveColumnWidths"),Ll=ae(()=>Object.assign([],{columns:0}),"makeRow"),_g=ae((e,t)=>{const n=[Ll()];let[r]=n;for(const o of e){const s=o.width+o.horizontalPadding;r.columns+s>t&&(r=Ll(),n.push(r)),r.push(o),r.columns+=s}for(const o of n){const s=o.reduce((h,D)=>h+D.width+D.horizontalPadding,0);let a=t-s;if(a===0)continue;const u=o.filter(h=>"autoOverflow"in h),l=u.filter(h=>h.autoOverflow>0),c=l.reduce((h,D)=>h+D.autoOverflow,0),d=Math.min(c,a);for(const h of l){const D=Math.floor(h.autoOverflow/c*d);h.width+=D,a-=D}const f=Math.floor(a/u.length);for(let h=0;h<u.length;h+=1){const D=u[h];h===u.length-1?D.width+=a:D.width+=f,a-=f}}return n},"balanceAuto"),bg=ae((e,t,n)=>{const r=vg(n,t);return yg(r,e),_g(r,e)},"computeColumnWidths"),ps=10,Ul=ae((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),Zl=ae((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),Vl=ae((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"wrapAnsi16m"),$e={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($e.modifier);const Cg=Object.keys($e.color),wg=Object.keys($e.bgColor);[...Cg,...wg];function Gl(){const e=new Map;for(const[t,n]of Object.entries($e)){for(const[r,o]of Object.entries(n))$e[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=$e[r],e.set(o[0],o[1]);Object.defineProperty($e,t,{value:n,enumerable:!1})}return Object.defineProperty($e,"codes",{value:e,enumerable:!1}),$e.color.close="\x1B[39m",$e.bgColor.close="\x1B[49m",$e.color.ansi=Ul(),$e.color.ansi256=Zl(),$e.color.ansi16m=Vl(),$e.bgColor.ansi=Ul(ps),$e.bgColor.ansi256=Zl(ps),$e.bgColor.ansi16m=Vl(ps),Object.defineProperties($e,{rgbToAnsi256:{value:ae((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:ae(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:ae(t=>$e.rgbToAnsi256(...$e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:ae(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:ae((t,n,r)=>$e.ansi256ToAnsi($e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:ae(t=>$e.ansi256ToAnsi($e.hexToAnsi256(t)),"value"),enumerable:!1}}),$e}i(Gl,"FD$1"),ae(Gl,"assembleStyles");const Fg=Gl(),Lo=new Set(["\x1B","\x9B"]),Eg=39,fs="\x07",Wl="[",xg="]",Hl="m",Uo=`${xg}8;;`,Jl=ae(e=>`${Lo.values().next().value}${Wl}${e}${Hl}`,"wrapAnsiCode"),Kl=ae(e=>`${Lo.values().next().value}${Uo}${e}${fs}`,"wrapAnsiHyperlink"),kg=ae(e=>e.split(" ").map(t=>Ut(t)),"wordLengths"),ms=ae((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=Ut(ds(e.at(-1)));for(const[u,l]of r.entries()){const c=Ut(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),Lo.has(l)&&(o=!0,s=r.slice(u+1,u+1+Uo.length).join("")===Uo),o){s?l===fs&&(o=!1,s=!1):l===Hl&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"wrapWord"),Ig=ae(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(Ut(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"stringVisibleTrimSpacesRight"),Ag=ae((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=kg(e);let u=[""];for(const[f,h]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u.at(-1).trimStart());let D=Ut(u.at(-1));if(f!==0&&(D>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),D=0),(D>0||n.trim===!1)&&(u[u.length-1]+=" ",D++)),n.hard&&a[f]>t){const m=t-D,v=1+Math.floor((a[f]-m-1)/t);Math.floor((a[f]-1)/t)<v&&u.push(""),ms(u,h,t);continue}if(D+a[f]>t&&D>0&&a[f]>0){if(n.wordWrap===!1&&D<t){ms(u,h,t);continue}u.push("")}if(D+a[f]>t&&n.wordWrap===!1){ms(u,h,t);continue}u[u.length-1]+=h}n.trim!==!1&&(u=u.map(f=>Ig(f)));const l=u.join(`
3
- `),c=[...l];let d=0;for(const[f,h]of c.entries()){if(r+=h,Lo.has(h)){const{groups:m}=new RegExp(`(?:\\${Wl}(?<code>\\d+)m|\\${Uo}(?<uri>.*)${fs})`).exec(l.slice(d))||{groups:{}};if(m.code!==void 0){const v=Number.parseFloat(m.code);o=v===Eg?void 0:v}else m.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}const D=Fg.codes.get(Number(o));c[f+1]===`
4
- `?(s&&(r+=Kl("")),o&&D&&(r+=Jl(D))):h===`
5
- `&&(o&&D&&(r+=Jl(o)),s&&(r+=Kl(s))),d+=h.length}return r},"exec");function Yl(e,t,n){return String(e).normalize().replaceAll(`\r
1
+ var ND=Object.defineProperty;var i=(e,t)=>ND(e,"name",{value:t,configurable:!0});var Xn,In,Qn,er,tr,nr,rr,or,ar,sr,on,ir,ur,An,$n,lr,cr,dr,pr,fr,Tn,mr,hr,Dr,gr,vr,yr,_r,br,Cr,wr,Fr,Er,xr,kr,Ir,Ar,$r,Tr,Sr,Br,Or,Rr,Nr,Pr,Mr,jr,zr,Lr,qr,Ur,Zr;import PD from"tty";import{Buffer as MD}from"node:buffer";import On from"node:path";import wl,{ChildProcess as jD}from"node:child_process";import Le,{stdin as Fl,stdout as El}from"node:process";import zD,{exec as fs,execSync as an}from"child_process";import Ct from"path";import ms from"fs";import{fileURLToPath as xl}from"node:url";import LD,{constants as kl}from"node:os";import qD from"assert";import UD from"events";import{createWriteStream as ZD,createReadStream as VD}from"node:fs";import GD from"buffer";import hs from"stream";import WD,{promisify as Il}from"util";import{debuglog as HD}from"node:util";import*as Zo from"node:readline";import Al from"node:readline";import{Writable as JD}from"node:stream";import He from"fs/promises";import $l from"os";import KD from"crypto";import{fileURLToPath as YD,pathToFileURL as XD}from"url";var QD=Object.defineProperty,Ue=i((e,t)=>QD(e,"name",{value:t,configurable:!0}),"a");const eg="known-flag",tg="unknown-flag",ng="argument",rg=/\B([A-Z])/g,og=Ue(e=>e.replaceAll(rg,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:ag}=Object.prototype,oo=Ue((e,t)=>ag.call(e,t),"hasOwn"),Ds=Ue(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:Ds(e.type),"parseFlagType"),Tl=Ue((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),Sl=Ue((e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),"applyParser"),sg=/[\s.:=]/,ig=Ue(e=>{const t=`Flag name "${e}"`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const n=e.match(sg);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),gs=Ue((e,t,n)=>{if(oo(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),ug=Ue(e=>{const t={};for(const n in e){if(!oo(e,n))continue;ig(n);const r=e[n],o=[[],...Ds(r),r];gs(t,n,o);const s=og(n);if(n!==s&&gs(t,s,o),"alias"in r&&typeof r.alias=="string"){const{alias:a}=r,u=`Flag alias "${a}" for flag "${n}"`;if(a.length===0)throw new Error(`${u} cannot be empty`);if(a.length>1)throw new Error(`${u} must be a single character`);gs(t,a,o)}}return t},"createRegistry"),lg=Ue((e,t)=>{const n={};for(const r in e){if(!oo(e,r))continue;const[o,,s,a]=t[r];if(o.length===0&&"default"in a){let{default:u}=a;typeof u=="function"&&(u=u()),n[r]=u}else n[r]=s?o:o.pop()}return n},"finalizeFlags"),Vo="--",cg=3,dg=/^-{1,2}\w/,Bl=Ue(e=>{if(!dg.test(e))return;const t=!e.startsWith(Vo);let n=e.slice(t?1:2),r,o=-1;for(const s of["=",":","."]){const a=n.indexOf(s);a!==-1&&(o===-1||a<o)&&(o=a)}return o!==-1&&(r=n.slice(o+1),n=n.slice(0,o)),[n,r,t]},"parseFlagArgv"),Ol=Ue((e,{onFlag:t,onArgument:n})=>{let r;const o=Ue((s,a)=>{if(typeof r!="function")return!0;r(s,a),r=void 0},"triggerValueCallback");for(let s=0;s<e.length;s+=1){const a=e[s];if(a===Vo){o();const l=e.slice(s+1);n?.(l,[s],!0);break}const u=Bl(a);if(u){if(o(),!t)continue;const[l,c,d]=u;if(d)for(let f=0;f<l.length;f+=1){o();const m=f===l.length-1;r=t(l[f],m?c:void 0,[s,f+1,m])}else r=t(l,c,[s])}else o(a,[s])&&n?.([a],[s])}o()},"argvIterator"),Rl=Ue((e,t)=>{for(let n=t.length-1;n>=0;n-=1){const[r,o,s]=t[n];if(o){const a=e[r];let u=a.slice(0,o);if(s||(u+=a.slice(o+1)),u!=="-"){e[r]=u;continue}}e.splice(r,1)}},"spliceFromArgv"),pg=Ue((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],o=ug(e),s={},a=[];return a[Vo]=[],Ol(t,{onFlag(u,l,c){const d=(c.length===cg||u.length>1)&&oo(o,u);if(!n?.(d?eg:tg,u,l)){if(d){const[f,m]=o[u],D=Tl(m,l),h=Ue((v,y)=>{r.push(c),y&&r.push(y),f.push(Sl(m,v||""))},"getFollowingValue");return D===void 0?h:h(D)}oo(s,u)||(s[u]=[]),s[u].push(l===void 0?!0:l),r.push(c)}},onArgument:Ue((u,l,c)=>{n?.(ng,t[l[0]])||(a.push(...u),c?(a[Vo]=u,t.splice(l[0])):r.push(l))},"onArgument")}),Rl(t,r),{flags:lg(e,o),unknownFlags:s,_:a}},"typeFlag");Ue((e,t,n=process.argv.slice(2))=>{const r=new Set(e.split(",").map(l=>Bl(l)?.[0])),[o,s]=Ds(t),a=[],u=[];return Ol(n,{onFlag:Ue((l,c,d)=>{if(!r.has(l)||!s&&a.length>0)return;const f=Tl(o,c),m=Ue((D,h)=>{u.push(d),h&&u.push(h),a.push(Sl(o,D||""))},"getFollowingValue");return f===void 0?m:m(f)},"onFlag")}),Rl(n,u),s?a:a[0]},"getFlag");var fg=Object.defineProperty,ae=i((e,t)=>fg(e,"name",{value:t,configurable:!0}),"n");const mg=ae(e=>{const t=process.stdout.columns??Number.POSITIVE_INFINITY;return typeof e=="function"&&(e=e(t)),e||(e={}),Array.isArray(e)?{columns:e,stdoutColumns:t}:{columns:e.columns??[],stdoutColumns:e.stdoutColumns??t}},"getOptions");function Nl({onlyFirst:e=!1}={}){const 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")}i(Nl,"j$1"),ae(Nl,"ansiRegex");const hg=Nl();function vs(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(hg,"")}i(vs,"w$2"),ae(vs,"stripAnsi");function Pl(e){return 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}i(Pl,"P$2"),ae(Pl,"isAmbiguous");function Ml(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}i(Ml,"z$2"),ae(Ml,"isFullWidth");function jl(e){return 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>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||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<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&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>=101631&&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>=119552&&e<=119638||e>=119648&&e<=119670||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<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}i(jl,"G$3"),ae(jl,"isWide");function zl(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}i(zl,"Z$1"),ae(zl,"validate");function Ll(e,{ambiguousAsWide:t=!1}={}){return zl(e),Ml(e)||jl(e)||t&&Pl(e)?2:1}i(Ll,"V$3"),ae(Ll,"eastAsianWidth");var Dg=ae(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\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?|[\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](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\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-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,"emojiRegex");const gg=new Intl.Segmenter,vg=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Zt(e,t={}){if(typeof e!="string"||e.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=vs(e)),e.length===0)return 0;let o=0;const s={ambiguousAsWide:!n};for(const{segment:a}of gg.segment(e)){const u=a.codePointAt(0);if(!(u<=31||u>=127&&u<=159)&&!(u>=8203&&u<=8207||u===65279)&&!(u>=768&&u<=879||u>=6832&&u<=6911||u>=7616&&u<=7679||u>=8400&&u<=8447||u>=65056&&u<=65071)&&!(u>=55296&&u<=57343)&&!(u>=65024&&u<=65039)&&!vg.test(a)){if(Dg().test(a)){o+=2;continue}o+=Ll(u,s)}}return o}i(Zt,"d$2"),ae(Zt,"stringWidth");const ql=ae(e=>Math.max(...e.split(`
2
+ `).map(t=>Zt(t))),"getLongestLineWidth"),yg=ae(e=>{const t=[];for(const n of e){const{length:r}=n,o=r-t.length;for(let s=0;s<o;s+=1)t.push(0);for(let s=0;s<r;s+=1){const a=ql(n[s]);a>t[s]&&(t[s]=a)}}return t},"getColumnContentWidths"),Ul=/^\d+%$/,Zl={width:"auto",align:"left",contentWidth:0,paddingLeft:0,paddingRight:0,paddingTop:0,paddingBottom:0,horizontalPadding:0,paddingLeftString:"",paddingRightString:""},_g=ae((e,t)=>{const n=[];for(let r=0;r<e.length;r+=1){const o=t[r]??"auto";if(typeof o=="number"||o==="auto"||o==="content-width"||typeof o=="string"&&Ul.test(o)){n.push({...Zl,width:o,contentWidth:e[r]});continue}if(o&&typeof o=="object"){const s={...Zl,...o,contentWidth:e[r]};s.horizontalPadding=s.paddingLeft+s.paddingRight,n.push(s);continue}throw new Error(`Invalid column width: ${JSON.stringify(o)}`)}return n},"initColumns"),bg=ae((e,t)=>{for(const n of e){const{width:r}=n;if(r==="content-width"&&(n.width=n.contentWidth),r==="auto"){const l=Math.min(20,n.contentWidth);n.width=l,n.autoOverflow=n.contentWidth-l}if(typeof r=="string"&&Ul.test(r)){const l=Number.parseFloat(r.slice(0,-1))/100;n.width=Math.floor(t*l)-(n.paddingLeft+n.paddingRight)}const{horizontalPadding:o}=n,s=1,a=s+o;if(a>=t){const l=a-t,c=Math.ceil(n.paddingLeft/o*l),d=l-c;n.paddingLeft-=c,n.paddingRight-=d,n.horizontalPadding=n.paddingLeft+n.paddingRight}n.paddingLeftString=n.paddingLeft?" ".repeat(n.paddingLeft):"",n.paddingRightString=n.paddingRight?" ".repeat(n.paddingRight):"";const u=t-n.horizontalPadding;n.width=Math.max(Math.min(n.width,u),s)}},"resolveColumnWidths"),Vl=ae(()=>Object.assign([],{columns:0}),"makeRow"),Cg=ae((e,t)=>{const n=[Vl()];let[r]=n;for(const o of e){const s=o.width+o.horizontalPadding;r.columns+s>t&&(r=Vl(),n.push(r)),r.push(o),r.columns+=s}for(const o of n){const s=o.reduce((m,D)=>m+D.width+D.horizontalPadding,0);let a=t-s;if(a===0)continue;const u=o.filter(m=>"autoOverflow"in m),l=u.filter(m=>m.autoOverflow>0),c=l.reduce((m,D)=>m+D.autoOverflow,0),d=Math.min(c,a);for(const m of l){const D=Math.floor(m.autoOverflow/c*d);m.width+=D,a-=D}const f=Math.floor(a/u.length);for(let m=0;m<u.length;m+=1){const D=u[m];m===u.length-1?D.width+=a:D.width+=f,a-=f}}return n},"balanceAuto"),wg=ae((e,t,n)=>{const r=_g(n,t);return bg(r,e),Cg(r,e)},"computeColumnWidths"),ys=10,Gl=ae((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),Wl=ae((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),Hl=ae((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"wrapAnsi16m"),$e={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($e.modifier);const Fg=Object.keys($e.color),Eg=Object.keys($e.bgColor);[...Fg,...Eg];function Jl(){const e=new Map;for(const[t,n]of Object.entries($e)){for(const[r,o]of Object.entries(n))$e[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=$e[r],e.set(o[0],o[1]);Object.defineProperty($e,t,{value:n,enumerable:!1})}return Object.defineProperty($e,"codes",{value:e,enumerable:!1}),$e.color.close="\x1B[39m",$e.bgColor.close="\x1B[49m",$e.color.ansi=Gl(),$e.color.ansi256=Wl(),$e.color.ansi16m=Hl(),$e.bgColor.ansi=Gl(ys),$e.bgColor.ansi256=Wl(ys),$e.bgColor.ansi16m=Hl(ys),Object.defineProperties($e,{rgbToAnsi256:{value:ae((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:ae(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:ae(t=>$e.rgbToAnsi256(...$e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:ae(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:ae((t,n,r)=>$e.ansi256ToAnsi($e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:ae(t=>$e.ansi256ToAnsi($e.hexToAnsi256(t)),"value"),enumerable:!1}}),$e}i(Jl,"FD$1"),ae(Jl,"assembleStyles");const xg=Jl(),Go=new Set(["\x1B","\x9B"]),kg=39,_s="\x07",Kl="[",Ig="]",Yl="m",Wo=`${Ig}8;;`,Xl=ae(e=>`${Go.values().next().value}${Kl}${e}${Yl}`,"wrapAnsiCode"),Ql=ae(e=>`${Go.values().next().value}${Wo}${e}${_s}`,"wrapAnsiHyperlink"),Ag=ae(e=>e.split(" ").map(t=>Zt(t)),"wordLengths"),bs=ae((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=Zt(vs(e.at(-1)));for(const[u,l]of r.entries()){const c=Zt(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),Go.has(l)&&(o=!0,s=r.slice(u+1,u+1+Wo.length).join("")===Wo),o){s?l===_s&&(o=!1,s=!1):l===Yl&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"wrapWord"),$g=ae(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(Zt(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"stringVisibleTrimSpacesRight"),Tg=ae((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Ag(e);let u=[""];for(const[f,m]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u.at(-1).trimStart());let D=Zt(u.at(-1));if(f!==0&&(D>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),D=0),(D>0||n.trim===!1)&&(u[u.length-1]+=" ",D++)),n.hard&&a[f]>t){const h=t-D,v=1+Math.floor((a[f]-h-1)/t);Math.floor((a[f]-1)/t)<v&&u.push(""),bs(u,m,t);continue}if(D+a[f]>t&&D>0&&a[f]>0){if(n.wordWrap===!1&&D<t){bs(u,m,t);continue}u.push("")}if(D+a[f]>t&&n.wordWrap===!1){bs(u,m,t);continue}u[u.length-1]+=m}n.trim!==!1&&(u=u.map(f=>$g(f)));const l=u.join(`
3
+ `),c=[...l];let d=0;for(const[f,m]of c.entries()){if(r+=m,Go.has(m)){const{groups:h}=new RegExp(`(?:\\${Kl}(?<code>\\d+)m|\\${Wo}(?<uri>.*)${_s})`).exec(l.slice(d))||{groups:{}};if(h.code!==void 0){const v=Number.parseFloat(h.code);o=v===kg?void 0:v}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const D=xg.codes.get(Number(o));c[f+1]===`
4
+ `?(s&&(r+=Ql("")),o&&D&&(r+=Xl(D))):m===`
5
+ `&&(o&&D&&(r+=Xl(o)),s&&(r+=Ql(s))),d+=m.length}return r},"exec");function ec(e,t,n){return String(e).normalize().replaceAll(`\r
6
6
  `,`
7
7
  `).split(`
8
- `).map(r=>Ag(r,t,n)).join(`
9
- `)}i(Yl,"BD$1"),ae(Yl,"wrapAnsi");const Xl=ae(e=>Array.from({length:e}).fill(""),"emptyLines"),$g=ae((e,t)=>{const n=[];let r=0;for(const o of e){let s=0;const a=o.map(l=>{let c=t[r]??"";r+=1,l.preprocess&&(c=l.preprocess(c)),jl(c)>l.width&&(c=Yl(c,l.width,{hard:!0}));let d=c.split(`
10
- `);if(l.postprocess){const{postprocess:f}=l;d=d.map((h,D)=>f.call(l,h,D))}return l.paddingTop&&d.unshift(...Xl(l.paddingTop)),l.paddingBottom&&d.push(...Xl(l.paddingBottom)),d.length>s&&(s=d.length),{...l,lines:d}}),u=[];for(let l=0;l<s;l+=1){const c=a.map(d=>{const f=d.lines[l]??"",h=Number.isFinite(d.width)?" ".repeat(d.width-Ut(f)):"";let D=d.paddingLeftString;return d.align==="right"&&(D+=h),D+=f,d.align==="left"&&(D+=h),D+d.paddingRightString}).join("");u.push(c)}n.push(u.join(`
8
+ `).map(r=>Tg(r,t,n)).join(`
9
+ `)}i(ec,"BD$1"),ae(ec,"wrapAnsi");const tc=ae(e=>Array.from({length:e}).fill(""),"emptyLines"),Sg=ae((e,t)=>{const n=[];let r=0;for(const o of e){let s=0;const a=o.map(l=>{let c=t[r]??"";r+=1,l.preprocess&&(c=l.preprocess(c)),ql(c)>l.width&&(c=ec(c,l.width,{hard:!0}));let d=c.split(`
10
+ `);if(l.postprocess){const{postprocess:f}=l;d=d.map((m,D)=>f.call(l,m,D))}return l.paddingTop&&d.unshift(...tc(l.paddingTop)),l.paddingBottom&&d.push(...tc(l.paddingBottom)),d.length>s&&(s=d.length),{...l,lines:d}}),u=[];for(let l=0;l<s;l+=1){const c=a.map(d=>{const f=d.lines[l]??"",m=Number.isFinite(d.width)?" ".repeat(d.width-Zt(f)):"";let D=d.paddingLeftString;return d.align==="right"&&(D+=m),D+=f,d.align==="left"&&(D+=m),D+d.paddingRightString}).join("");u.push(c)}n.push(u.join(`
11
11
  `))}return n.join(`
12
- `)},"renderRow"),Tg=ae((e,t)=>{if(!e||e.length===0)return"";const n=gg(e),r=n.length;if(r===0)return"";const{stdoutColumns:o,columns:s}=pg(t);if(s.length>r)throw new Error(`${s.length} columns defined, but only ${r} columns found`);const a=bg(o,s,n);return e.map(u=>$g(a,u)).join(`
13
- `)},"terminalColumns"),Sg=["<",">","=",">=","<="],Bg=ae(e=>{if(!Sg.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),Og=ae(e=>{const t=Object.keys(e).map(n=>{const[r,o]=n.split(" ");Bg(r);const s=Number.parseInt(o,10);if(Number.isNaN(s))throw new TypeError(`Invalid breakpoint value: ${o}`);const a=e[n];return{operator:r,breakpoint:s,value:a}}).sort((n,r)=>r.breakpoint-n.breakpoint);return n=>t.find(({operator:r,breakpoint:o})=>r==="="&&n===o||r===">"&&n>o||r==="<"&&n<o||r===">="&&n>=o||r==="<="&&n<=o)?.value},"breakpoints");var Rg=Object.defineProperty,ke=i((e,t)=>Rg(e,"name",{value:t,configurable:!0}),"s");const Ng=ke(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),Pg=ke(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),Mg={"> 80":[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"auto"}],"> 40":[{width:"auto",paddingLeft:2,paddingRight:8,preprocess:ke(e=>e.trim(),"preprocess")},{width:"100%",paddingLeft:2,paddingBottom:1}],"> 0":{stdoutColumns:1e3,columns:[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"content-width"}]}};function Ql(e){let t=!1;return{type:"table",data:{tableData:Object.keys(e).sort((n,r)=>n.localeCompare(r)).map(n=>{const r=e[n],o="alias"in r;return o&&(t=!0),{name:n,flag:r,flagFormatted:`--${Pg(n)}`,aliasesEnabled:t,aliasFormatted:o?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:Mg}}}i(Ql,"T"),ke(Ql,"renderFlags");const ec=ke(e=>!e||(e.version??(e.help?e.help.version:void 0)),"getVersion"),tc=ke(e=>{const t="parent"in e&&e.parent?.name;return(t?`${t} `:"")+e.name},"getName");function nc(e){const t=[];e.name&&t.push(tc(e));const n=ec(e)??("parent"in e&&ec(e.parent));if(n&&t.push(`v${n}`),t.length!==0)return{id:"name",type:"text",data:`${t.join(" ")}
14
- `}}i(nc,"k$2"),ke(nc,"getNameAndVersion");function rc(e){const{help:t}=e;if(!(!t||!t.description))return{id:"description",type:"text",data:`${t.description}
15
- `}}i(rc,"_$1"),ke(rc,"getDescription");function oc(e){const t=e.help||{};if("usage"in t)return t.usage?{id:"usage",type:"section",data:{title:"Usage:",body:Array.isArray(t.usage)?t.usage.join(`
16
- `):t.usage}}:void 0;if(e.name){const n=[],r=[tc(e)];if(e.flags&&Object.keys(e.flags).length>0&&r.push("[flags...]"),e.parameters&&e.parameters.length>0){const{parameters:o}=e,s=o.indexOf("--"),a=s!==-1&&o.slice(s+1).some(u=>u.startsWith("<"));r.push(o.map(u=>u!=="--"?u:a?"--":"[--]").join(" "))}if(r.length>1&&n.push(r.join(" ")),"commands"in e&&e.commands?.length&&n.push(`${e.name} <command>`),n.length>0)return{id:"usage",type:"section",data:{title:"Usage:",body:n.join(`
17
- `)}}}}i(oc,"F"),ke(oc,"getUsage");function ac(e){return!("commands"in e)||!e.commands?.length?void 0:{id:"commands",type:"section",data:{title:"Commands:",body:{type:"table",data:{tableData:e.commands.map(t=>[t.options.name,t.options.help?t.options.help.description:""]),tableOptions:[{width:"content-width",paddingLeft:2,paddingRight:8}]}},indentBody:0}}}i(ac,"H"),ke(ac,"getCommands");function sc(e){if(!(!e.flags||Object.keys(e.flags).length===0))return{id:"flags",type:"section",data:{title:"Flags:",body:Ql(e.flags),indentBody:0}}}i(sc,"U$1"),ke(sc,"getFlags");function ic(e){const{help:t}=e;if(!t||!t.examples||t.examples.length===0)return;let{examples:n}=t;if(Array.isArray(n)&&(n=n.join(`
18
- `)),n)return{id:"examples",type:"section",data:{title:"Examples:",body:n}}}i(ic,"V$2"),ke(ic,"getExamples");function uc(e){if(!("alias"in e)||!e.alias)return;const{alias:t}=e;return{id:"aliases",type:"section",data:{title:"Aliases:",body:Array.isArray(t)?t.join(", "):t}}}i(uc,"J$1"),ke(uc,"getAliases");const jg=ke(e=>[nc,rc,oc,ac,sc,ic,uc].map(t=>t(e)).filter(Boolean),"generateHelp"),zg=OD.WriteStream.prototype.hasColors(),lc=(Jn=class{text(t){return t}bold(t){return zg?`\x1B[1m${t}\x1B[22m`:t.toLocaleUpperCase()}indentText({text:t,spaces:n}){return t.replaceAll(/^/gm," ".repeat(n))}heading(t){return this.bold(t)}section({title:t,body:n,indentBody:r=2}){return`${(t?`${this.heading(t)}
12
+ `)},"renderRow"),Bg=ae((e,t)=>{if(!e||e.length===0)return"";const n=yg(e),r=n.length;if(r===0)return"";const{stdoutColumns:o,columns:s}=mg(t);if(s.length>r)throw new Error(`${s.length} columns defined, but only ${r} columns found`);const a=wg(o,s,n);return e.map(u=>Sg(a,u)).join(`
13
+ `)},"terminalColumns"),Og=["<",">","=",">=","<="],Rg=ae(e=>{if(!Og.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),Ng=ae(e=>{const t=Object.keys(e).map(n=>{const[r,o]=n.split(" ");Rg(r);const s=Number.parseInt(o,10);if(Number.isNaN(s))throw new TypeError(`Invalid breakpoint value: ${o}`);const a=e[n];return{operator:r,breakpoint:s,value:a}}).sort((n,r)=>r.breakpoint-n.breakpoint);return n=>t.find(({operator:r,breakpoint:o})=>r==="="&&n===o||r===">"&&n>o||r==="<"&&n<o||r===">="&&n>=o||r==="<="&&n<=o)?.value},"breakpoints");var Pg=Object.defineProperty,ke=i((e,t)=>Pg(e,"name",{value:t,configurable:!0}),"s");const Mg=ke(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),jg=ke(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),zg={"> 80":[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"auto"}],"> 40":[{width:"auto",paddingLeft:2,paddingRight:8,preprocess:ke(e=>e.trim(),"preprocess")},{width:"100%",paddingLeft:2,paddingBottom:1}],"> 0":{stdoutColumns:1e3,columns:[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"content-width"}]}};function nc(e){let t=!1;return{type:"table",data:{tableData:Object.keys(e).sort((n,r)=>n.localeCompare(r)).map(n=>{const r=e[n],o="alias"in r;return o&&(t=!0),{name:n,flag:r,flagFormatted:`--${jg(n)}`,aliasesEnabled:t,aliasFormatted:o?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:zg}}}i(nc,"T"),ke(nc,"renderFlags");const rc=ke(e=>!e||(e.version??(e.help?e.help.version:void 0)),"getVersion"),oc=ke(e=>{const t="parent"in e&&e.parent?.name;return(t?`${t} `:"")+e.name},"getName");function ac(e){const t=[];e.name&&t.push(oc(e));const n=rc(e)??("parent"in e&&rc(e.parent));if(n&&t.push(`v${n}`),t.length!==0)return{id:"name",type:"text",data:`${t.join(" ")}
14
+ `}}i(ac,"k$2"),ke(ac,"getNameAndVersion");function sc(e){const{help:t}=e;if(!(!t||!t.description))return{id:"description",type:"text",data:`${t.description}
15
+ `}}i(sc,"_$1"),ke(sc,"getDescription");function ic(e){const t=e.help||{};if("usage"in t)return t.usage?{id:"usage",type:"section",data:{title:"Usage:",body:Array.isArray(t.usage)?t.usage.join(`
16
+ `):t.usage}}:void 0;if(e.name){const n=[],r=[oc(e)];if(e.flags&&Object.keys(e.flags).length>0&&r.push("[flags...]"),e.parameters&&e.parameters.length>0){const{parameters:o}=e,s=o.indexOf("--"),a=s!==-1&&o.slice(s+1).some(u=>u.startsWith("<"));r.push(o.map(u=>u!=="--"?u:a?"--":"[--]").join(" "))}if(r.length>1&&n.push(r.join(" ")),"commands"in e&&e.commands?.length&&n.push(`${e.name} <command>`),n.length>0)return{id:"usage",type:"section",data:{title:"Usage:",body:n.join(`
17
+ `)}}}}i(ic,"F"),ke(ic,"getUsage");function uc(e){return!("commands"in e)||!e.commands?.length?void 0:{id:"commands",type:"section",data:{title:"Commands:",body:{type:"table",data:{tableData:e.commands.map(t=>[t.options.name,t.options.help?t.options.help.description:""]),tableOptions:[{width:"content-width",paddingLeft:2,paddingRight:8}]}},indentBody:0}}}i(uc,"H"),ke(uc,"getCommands");function lc(e){if(!(!e.flags||Object.keys(e.flags).length===0))return{id:"flags",type:"section",data:{title:"Flags:",body:nc(e.flags),indentBody:0}}}i(lc,"U$1"),ke(lc,"getFlags");function cc(e){const{help:t}=e;if(!t||!t.examples||t.examples.length===0)return;let{examples:n}=t;if(Array.isArray(n)&&(n=n.join(`
18
+ `)),n)return{id:"examples",type:"section",data:{title:"Examples:",body:n}}}i(cc,"V$2"),ke(cc,"getExamples");function dc(e){if(!("alias"in e)||!e.alias)return;const{alias:t}=e;return{id:"aliases",type:"section",data:{title:"Aliases:",body:Array.isArray(t)?t.join(", "):t}}}i(dc,"J$1"),ke(dc,"getAliases");const Lg=ke(e=>[ac,sc,ic,uc,lc,cc,dc].map(t=>t(e)).filter(Boolean),"generateHelp"),qg=PD.WriteStream.prototype.hasColors(),pc=(Xn=class{text(t){return t}bold(t){return qg?`\x1B[1m${t}\x1B[22m`:t.toLocaleUpperCase()}indentText({text:t,spaces:n}){return t.replaceAll(/^/gm," ".repeat(n))}heading(t){return this.bold(t)}section({title:t,body:n,indentBody:r=2}){return`${(t?`${this.heading(t)}
19
19
  `:"")+(n?this.indentText({text:this.render(n),spaces:r}):"")}
20
- `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return Tg(t.map(o=>o.map(s=>this.render(s))),r?Og(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:o,aliasFormatted:s}=t;let a="";if(s?a+=`${s}, `:o&&(a+=" "),a+=r,"placeholder"in n&&typeof n.placeholder=="string")a+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(a+=`${this.flagOperator(t)}${u}`)}return a}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
- `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},i(Jn,"_z"),Jn);ke(lc,"Renderers");let qg=lc;const hs=ke(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:Tt}=JSON,Lg=/[|\\{}()[\]^$+*?.]/;function Zo(e){const t=[];let n,r;for(const o of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${Tt(r)} must be last`);const s=o[0],a=o.at(-1);let u;if(s==="<"&&a===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${Tt(o)} cannot come after optional parameter ${Tt(n)}`);if(s==="["&&a==="]"&&(u=!1,n=o),u===void 0)throw new Error(`Invalid parameter: ${Tt(o)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=o.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=o,l=l.slice(0,-3));const d=l.match(Lg);if(d)throw new Error(`Invalid parameter: ${Tt(o)}. Invalid character found ${Tt(d[0])}`);t.push({name:l,required:u,spread:c})}return t}i(Zo,"b$1"),ke(Zo,"parseParameters");function Vo(e,t,n,r){for(let o=0;o<t.length;o+=1){const{name:s,required:a,spread:u}=t[o],l=Ng(s);if(l in e)throw new Error(`Invalid parameter: ${Tt(s)} is used more than once.`);const c=u?n.slice(o):n[o];if(u&&(o=t.length),a&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${Tt(s)}
22
- `),r(),process.exit(1);e[l]=c}}i(Vo,"v"),ke(Vo,"mapParametersToArguments");function cc(e){return e===void 0||e!==!1}i(cc,"G$2"),ke(cc,"helpEnabled");function Ds(e,t,n,r){const o={...t.flags},s=t.version&&!("version"in o);s&&(o.version={type:Boolean,description:"Show version"});const{help:a}=t,u=cc(a);u&&!("help"in o)&&(o.help={type:Boolean,alias:"h",description:"Show help"});const l=cg(o,r,{ignore:t.ignoreArgv}),c=ke(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new qg,f=u&&a?.render?a.render:v=>d.render(v),h=ke(v=>{const y=jg({...t,...v?{help:v}:{},flags:o});console.log(f(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const b=v.indexOf("--"),C=v.slice(b+1),w=Object.create(null);if(b>-1&&C.length>0){v=v.slice(0,b);const E=l._["--"];y=y.slice(0,-E.length||void 0),Vo(w,Zo(v),y,h),Vo(w,Zo(C),E,h)}else Vo(w,Zo(v),y,h);Object.assign(l._,w)}const D={...l,showVersion:c,showHelp:h},m={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),m)}return m}i(Ds,"j"),ke(Ds,"cliBase");function dc(e,t){const n=new Map;for(const r of t){const o=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?o.push(...s):o.push(s));for(const a of o){if(n.has(a))throw new Error(`Duplicate command name found: ${Tt(a)}`);n.set(a,r)}}return n.get(e)}i(dc,"K$1"),ke(dc,"getCommand");function pc(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!hs(e.name)))throw new Error(`Invalid script name: ${Tt(e.name)}`);const r=n[0];if(e.commands&&r&&hs(r)){const o=dc(r,e.commands);if(o)return Ds(o.options.name,{...o.options,parent:e},o.callback,n.slice(1))}return Ds(void 0,e,t,n)}i(pc,"Q"),ke(pc,"cli");function An(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!hs(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(An,"X"),ke(An,"command");var Ug="aicommits",Zg="2.0.0-develop.29",Vg="Writes your git commit messages for you with AI",Gg=["ai","git","commit","code changes"],Wg="MIT",Hg={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},Jg="Hassan El Mghari (@nutlope)",Kg="module",Yg=["dist"],Xg={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},Qg={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},ev={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.97","@ai-sdk/openai":"^3.0.30","@ai-sdk/openai-compatible":"^2.0.30",pkgroll:"^2.20.1",tsx:"^4.21.0",typescript:"^5.9.3"},tv={branches:["main",{name:"develop",prerelease:!0}]},gs={name:Ug,version:Zg,description:Vg,keywords:Gg,license:Wg,repository:Hg,author:Jg,type:Kg,files:Yg,bin:Xg,scripts:Qg,devDependencies:ev,release:tv},Zt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(rn,"getDefaultExportFromCjs");var on={exports:{}},vs,fc;function nv(){if(fc)return vs;fc=1,vs=r,r.sync=o;var e=is;function t(s,a){var u=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,a,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(a,u)}i(n,"checkStat");function r(s,a,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,a))})}i(r,"isexe");function o(s,a){return n(e.statSync(s),s,a)}return i(o,"sync"),vs}i(nv,"requireWindows");var ys,mc;function rv(){if(mc)return ys;mc=1,ys=t,t.sync=n;var e=is;function t(s,a,u){e.stat(s,function(l,c){u(l,l?!1:r(c,a))})}i(t,"isexe");function n(s,a){return r(e.statSync(s),a)}i(n,"sync");function r(s,a){return s.isFile()&&o(s,a)}i(r,"checkStat");function o(s,a){var u=s.mode,l=s.uid,c=s.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),m=parseInt("001",8),v=h|D,y=u&m||u&D&&c===f||u&h&&l===d||u&v&&d===0;return y}return i(o,"checkMode"),ys}i(rv,"requireMode");var _s,hc;function ov(){if(hc)return _s;hc=1;var e;process.platform==="win32"||Zt.TESTING_WINDOWS?e=nv():e=rv(),_s=t,t.sync=n;function t(r,o,s){if(typeof o=="function"&&(s=o,o={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,u){t(r,o||{},function(l,c){l?u(l):a(c)})})}e(r,o||{},function(a,u){a&&(a.code==="EACCES"||o&&o.ignoreErrors)&&(a=null,u=!1),s(a,u)})}i(t,"isexe");function n(r,o){try{return e.sync(r,o||{})}catch(s){if(o&&o.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),_s}i(ov,"requireIsexe");var bs,Dc;function av(){if(Dc)return bs;Dc=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=bt,n=e?";":":",r=ov(),o=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,f=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:f,pathExt:D,pathExtExe:h}},"getPathInfo"),a=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:f,pathExt:h,pathExtExe:D}=s(l,c),m=[],v=i(b=>new Promise((C,w)=>{if(b===f.length)return c.all&&m.length?C(m):w(o(l));const E=f[b],T=/^".*"$/.test(E)?E.slice(1,-1):E,O=t.join(T,l),$=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+O:O;C(y($,b,0))}),"step"),y=i((b,C,w)=>new Promise((E,T)=>{if(w===h.length)return E(v(C+1));const O=h[w];r(b+O,{pathExt:D},($,I)=>{if(!$&&I)if(c.all)m.push(b+O);else return E(b+O);return E(y(b,C,w+1))})}),"subStep");return d?v(0).then(b=>d(null,b),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:f,pathExtExe:h}=s(l,c),D=[];for(let m=0;m<d.length;m++){const v=d[m],y=/^".*"$/.test(v)?v.slice(1,-1):v,b=t.join(y,l),C=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+b:b;for(let w=0;w<f.length;w++){const E=C+f[w];try{if(r.sync(E,{pathExt:h}))if(c.all)D.push(E);else return E}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw o(l)},"whichSync");return bs=a,a.sync=u,bs}i(av,"requireWhich");var Go={exports:{}},gc;function sv(){if(gc)return Go.exports;gc=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"},"pathKey");return Go.exports=e,Go.exports.default=e,Go.exports}i(sv,"requirePathKey");var Cs,vc;function iv(){if(vc)return Cs;vc=1;const e=bt,t=av(),n=sv();function r(s,a){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let f;try{f=t.sync(s.command,{path:u[n({env:u})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return f&&(f=e.resolve(c?s.options.cwd:"",f)),f}i(r,"resolveCommandAttempt");function o(s){return r(s)||r(s,!0)}return i(o,"resolveCommand"),Cs=o,Cs}i(iv,"requireResolveCommand");var Wo={},yc;function uv(){if(yc)return Wo;yc=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,o){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),o&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Wo.command=t,Wo.argument=n,Wo}i(uv,"require_escape");var ws,_c;function lv(){return _c||(_c=1,ws=/^#!(.*)/),ws}i(lv,"requireShebangRegex");var Fs,bc;function cv(){if(bc)return Fs;bc=1;const e=lv();return Fs=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s},"shebangCommand"),Fs}i(cv,"requireShebangCommand");var Es,Cc;function dv(){if(Cc)return Es;Cc=1;const e=is,t=cv();function n(r){const s=Buffer.alloc(150);let a;try{a=e.openSync(r,"r"),e.readSync(a,s,0,150,0),e.closeSync(a)}catch{}return t(s.toString())}return i(n,"readShebang"),Es=n,Es}i(dv,"requireReadShebang");var xs,wc;function pv(){if(wc)return xs;wc=1;const e=bt,t=iv(),n=uv(),r=dv(),o=process.platform==="win32",s=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const f=d.file&&r(d.file);return f?(d.args.unshift(d.file),d.command=f,t(d)):d.file}i(u,"detectShebang");function l(d){if(!o)return d;const f=u(d),h=!s.test(f);if(d.options.forceShell||h){const D=a.test(f);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const m=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${m}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,f,h){f&&!Array.isArray(f)&&(h=f,f=null),f=f?f.slice(0):[],h=Object.assign({},h);const D={command:d,args:f,options:h,file:void 0,original:{command:d,args:f}};return h.shell?D:l(D)}return i(c,"parse"),xs=c,xs}i(pv,"requireParse");var ks,Fc;function fv(){if(Fc)return ks;Fc=1;const e=process.platform==="win32";function t(s,a){return Object.assign(new Error(`${a} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${a} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,a){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,a);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,a){return e&&s===1&&!a.file?t(a.original,"spawn"):null}i(r,"verifyENOENT");function o(s,a){return e&&s===1&&!a.file?t(a.original,"spawnSync"):null}return i(o,"verifyENOENTSync"),ks={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:o,notFoundError:t},ks}i(fv,"requireEnoent");var Ec;function mv(){if(Ec)return on.exports;Ec=1;const e=PD,t=pv(),n=fv();function r(s,a,u){const l=t(s,a,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function o(s,a,u){const l=t(s,a,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(o,"spawnSync"),on.exports=r,on.exports.spawn=r,on.exports.sync=o,on.exports._parse=t,on.exports._enoent=n,on.exports}i(mv,"requireCrossSpawn");var hv=mv(),Dv=rn(hv);function gv(e){const t=typeof e=="string"?`
23
- `:10,n=typeof e=="string"?"\r":13;return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}i(gv,"stripFinalNewline");function xc(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}i(xc,"pathKey");const vv=i(({cwd:e=qe.cwd(),path:t=qe.env[xc()],preferLocal:n=!0,execPath:r=qe.execPath,addExecPath:o=!0}={})=>{const s=e instanceof URL?Fl(e):e,a=In.resolve(s),u=[];return n&&yv(u,a),o&&_v(u,r,a),[...u,t].join(In.delimiter)},"npmRunPath"),yv=i((e,t)=>{let n;for(;n!==t;)e.push(In.join(t,"node_modules/.bin")),n=t,t=In.resolve(t,"..")},"applyPreferLocal"),_v=i((e,t,n)=>{const r=t instanceof URL?Fl(t):t;e.push(In.resolve(n,r,".."))},"applyExecPath"),bv=i(({env:e=qe.env,...t}={})=>{e={...e};const n=xc({env:e});return t.path=e[n],e[n]=vv(t),e},"npmRunPathEnv"),Cv=i((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const o=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!wv(o,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),wv=i(function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},"canCopyProperty"),Fv=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),Ev=i((e,t)=>`/* Wrapped ${e}*/
24
- ${t}`,"wrappedToString"),xv=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),kv=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Iv=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,o=Ev.bind(null,r,t.toString());Object.defineProperty(o,"name",kv),Object.defineProperty(e,"toString",{...xv,value:o})},"changeToString");function Av(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const o of Reflect.ownKeys(t))Cv(e,t,o,n);return Fv(e,t),Iv(e,t,r),e}i(Av,"mimicFunction");const Ho=new WeakMap,kc=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const o=e.displayName||e.name||"<anonymous>",s=i(function(...a){if(Ho.set(s,++r),r===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${o}\` can only be called once`);return n},"onetime2");return Av(s,e),Ho.set(s,r),s},"onetime");kc.callCount=e=>{if(!Ho.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Ho.get(e)};const $v=i(()=>{const e=Ac-Ic+1;return Array.from({length:e},Tv)},"getRealtimeSignals"),Tv=i((e,t)=>({name:`SIGRT${t+1}`,number:Ic+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),Ic=34,Ac=64,Sv=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],$c=i(()=>{const e=$v();return[...Sv,...e].map(Bv)},"getSignals"),Bv=i(({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=El,u=a!==void 0;return{name:e,number:u?a:t,description:n,supported:u,action:r,forced:o,standard:s}},"normalizeSignal"),Ov=i(()=>{const e=$c();return Object.fromEntries(e.map(Rv))},"getSignalsByName"),Rv=i(({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a}],"getSignalByName"),Nv=Ov(),Pv=i(()=>{const e=$c(),t=Ac+1,n=Array.from({length:t},(r,o)=>Mv(o,e));return Object.assign({},...n)},"getSignalsByNumber"),Mv=i((e,t)=>{const n=jv(e,t);if(n===void 0)return{};const{name:r,description:o,supported:s,action:a,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:u,standard:l}}},"getSignalByNumber"),jv=i((e,t)=>{const n=t.find(({name:r})=>El.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");Pv();const zv=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${o})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),Tc=i(({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:a,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:f,cwd:h=qe.cwd()}}})=>{s=s===null?void 0:s,o=o===null?void 0:o;const D=o===void 0?void 0:Nv[o].description,m=r&&r.code,y=`Command ${zv({timedOut:l,timeout:f,errorCode:m,signal:o,signalDescription:D,exitCode:s,isCanceled:c})}: ${a}`,b=Object.prototype.toString.call(r)==="[object Error]",C=b?`${y}
20
+ `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return Bg(t.map(o=>o.map(s=>this.render(s))),r?Ng(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:o,aliasFormatted:s}=t;let a="";if(s?a+=`${s}, `:o&&(a+=" "),a+=r,"placeholder"in n&&typeof n.placeholder=="string")a+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(a+=`${this.flagOperator(t)}${u}`)}return a}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
+ `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},i(Xn,"_z"),Xn);ke(pc,"Renderers");let Ug=pc;const Cs=ke(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:St}=JSON,Zg=/[|\\{}()[\]^$+*?.]/;function Ho(e){const t=[];let n,r;for(const o of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${St(r)} must be last`);const s=o[0],a=o.at(-1);let u;if(s==="<"&&a===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${St(o)} cannot come after optional parameter ${St(n)}`);if(s==="["&&a==="]"&&(u=!1,n=o),u===void 0)throw new Error(`Invalid parameter: ${St(o)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=o.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=o,l=l.slice(0,-3));const d=l.match(Zg);if(d)throw new Error(`Invalid parameter: ${St(o)}. Invalid character found ${St(d[0])}`);t.push({name:l,required:u,spread:c})}return t}i(Ho,"b$1"),ke(Ho,"parseParameters");function Jo(e,t,n,r){for(let o=0;o<t.length;o+=1){const{name:s,required:a,spread:u}=t[o],l=Mg(s);if(l in e)throw new Error(`Invalid parameter: ${St(s)} is used more than once.`);const c=u?n.slice(o):n[o];if(u&&(o=t.length),a&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${St(s)}
22
+ `),r(),process.exit(1);e[l]=c}}i(Jo,"v"),ke(Jo,"mapParametersToArguments");function fc(e){return e===void 0||e!==!1}i(fc,"G$2"),ke(fc,"helpEnabled");function ws(e,t,n,r){const o={...t.flags},s=t.version&&!("version"in o);s&&(o.version={type:Boolean,description:"Show version"});const{help:a}=t,u=fc(a);u&&!("help"in o)&&(o.help={type:Boolean,alias:"h",description:"Show help"});const l=pg(o,r,{ignore:t.ignoreArgv}),c=ke(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new Ug,f=u&&a?.render?a.render:v=>d.render(v),m=ke(v=>{const y=Lg({...t,...v?{help:v}:{},flags:o});console.log(f(y,d))},"showHelp");if(u&&l.flags.help===!0)return m(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const b=v.indexOf("--"),C=v.slice(b+1),w=Object.create(null);if(b>-1&&C.length>0){v=v.slice(0,b);const E=l._["--"];y=y.slice(0,-E.length||void 0),Jo(w,Ho(v),y,m),Jo(w,Ho(C),E,m)}else Jo(w,Ho(v),y,m);Object.assign(l._,w)}const D={...l,showVersion:c,showHelp:m},h={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),h)}return h}i(ws,"j"),ke(ws,"cliBase");function mc(e,t){const n=new Map;for(const r of t){const o=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?o.push(...s):o.push(s));for(const a of o){if(n.has(a))throw new Error(`Duplicate command name found: ${St(a)}`);n.set(a,r)}}return n.get(e)}i(mc,"K$1"),ke(mc,"getCommand");function hc(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!Cs(e.name)))throw new Error(`Invalid script name: ${St(e.name)}`);const r=n[0];if(e.commands&&r&&Cs(r)){const o=mc(r,e.commands);if(o)return ws(o.options.name,{...o.options,parent:e},o.callback,n.slice(1))}return ws(void 0,e,t,n)}i(hc,"Q"),ke(hc,"cli");function sn(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!Cs(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(sn,"X"),ke(sn,"command");var Vg="aicommits",Gg="2.0.0-develop.30",Wg="Writes your git commit messages for you with AI",Hg=["ai","git","commit","code changes"],Jg="MIT",Kg={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},Yg="Hassan El Mghari (@nutlope)",Xg="module",Qg=["dist"],ev={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},tv={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},nv={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.97","@ai-sdk/openai":"^3.0.30","@ai-sdk/openai-compatible":"^2.0.30",pkgroll:"^2.20.1",tsx:"^4.21.0",typescript:"^5.9.3"},rv={branches:["main",{name:"develop",prerelease:!0}]},Vt={name:Vg,version:Gg,description:Wg,keywords:Hg,license:Jg,repository:Kg,author:Yg,type:Xg,files:Qg,bin:ev,scripts:tv,devDependencies:nv,release:rv},Gt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function un(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(un,"getDefaultExportFromCjs");var ln={exports:{}},Fs,Dc;function ov(){if(Dc)return Fs;Dc=1,Fs=r,r.sync=o;var e=ms;function t(s,a){var u=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,a,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(a,u)}i(n,"checkStat");function r(s,a,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,a))})}i(r,"isexe");function o(s,a){return n(e.statSync(s),s,a)}return i(o,"sync"),Fs}i(ov,"requireWindows");var Es,gc;function av(){if(gc)return Es;gc=1,Es=t,t.sync=n;var e=ms;function t(s,a,u){e.stat(s,function(l,c){u(l,l?!1:r(c,a))})}i(t,"isexe");function n(s,a){return r(e.statSync(s),a)}i(n,"sync");function r(s,a){return s.isFile()&&o(s,a)}i(r,"checkStat");function o(s,a){var u=s.mode,l=s.uid,c=s.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),m=parseInt("100",8),D=parseInt("010",8),h=parseInt("001",8),v=m|D,y=u&h||u&D&&c===f||u&m&&l===d||u&v&&d===0;return y}return i(o,"checkMode"),Es}i(av,"requireMode");var xs,vc;function sv(){if(vc)return xs;vc=1;var e;process.platform==="win32"||Gt.TESTING_WINDOWS?e=ov():e=av(),xs=t,t.sync=n;function t(r,o,s){if(typeof o=="function"&&(s=o,o={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,u){t(r,o||{},function(l,c){l?u(l):a(c)})})}e(r,o||{},function(a,u){a&&(a.code==="EACCES"||o&&o.ignoreErrors)&&(a=null,u=!1),s(a,u)})}i(t,"isexe");function n(r,o){try{return e.sync(r,o||{})}catch(s){if(o&&o.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),xs}i(sv,"requireIsexe");var ks,yc;function iv(){if(yc)return ks;yc=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=Ct,n=e?";":":",r=sv(),o=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,f=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],m=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?m.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:f,pathExt:D,pathExtExe:m}},"getPathInfo"),a=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:f,pathExt:m,pathExtExe:D}=s(l,c),h=[],v=i(b=>new Promise((C,w)=>{if(b===f.length)return c.all&&h.length?C(h):w(o(l));const E=f[b],T=/^".*"$/.test(E)?E.slice(1,-1):E,O=t.join(T,l),$=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+O:O;C(y($,b,0))}),"step"),y=i((b,C,w)=>new Promise((E,T)=>{if(w===m.length)return E(v(C+1));const O=m[w];r(b+O,{pathExt:D},($,I)=>{if(!$&&I)if(c.all)h.push(b+O);else return E(b+O);return E(y(b,C,w+1))})}),"subStep");return d?v(0).then(b=>d(null,b),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:f,pathExtExe:m}=s(l,c),D=[];for(let h=0;h<d.length;h++){const v=d[h],y=/^".*"$/.test(v)?v.slice(1,-1):v,b=t.join(y,l),C=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+b:b;for(let w=0;w<f.length;w++){const E=C+f[w];try{if(r.sync(E,{pathExt:m}))if(c.all)D.push(E);else return E}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw o(l)},"whichSync");return ks=a,a.sync=u,ks}i(iv,"requireWhich");var Ko={exports:{}},_c;function uv(){if(_c)return Ko.exports;_c=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"},"pathKey");return Ko.exports=e,Ko.exports.default=e,Ko.exports}i(uv,"requirePathKey");var Is,bc;function lv(){if(bc)return Is;bc=1;const e=Ct,t=iv(),n=uv();function r(s,a){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let f;try{f=t.sync(s.command,{path:u[n({env:u})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return f&&(f=e.resolve(c?s.options.cwd:"",f)),f}i(r,"resolveCommandAttempt");function o(s){return r(s)||r(s,!0)}return i(o,"resolveCommand"),Is=o,Is}i(lv,"requireResolveCommand");var Yo={},Cc;function cv(){if(Cc)return Yo;Cc=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,o){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),o&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Yo.command=t,Yo.argument=n,Yo}i(cv,"require_escape");var As,wc;function dv(){return wc||(wc=1,As=/^#!(.*)/),As}i(dv,"requireShebangRegex");var $s,Fc;function pv(){if(Fc)return $s;Fc=1;const e=dv();return $s=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s},"shebangCommand"),$s}i(pv,"requireShebangCommand");var Ts,Ec;function fv(){if(Ec)return Ts;Ec=1;const e=ms,t=pv();function n(r){const s=Buffer.alloc(150);let a;try{a=e.openSync(r,"r"),e.readSync(a,s,0,150,0),e.closeSync(a)}catch{}return t(s.toString())}return i(n,"readShebang"),Ts=n,Ts}i(fv,"requireReadShebang");var Ss,xc;function mv(){if(xc)return Ss;xc=1;const e=Ct,t=lv(),n=cv(),r=fv(),o=process.platform==="win32",s=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const f=d.file&&r(d.file);return f?(d.args.unshift(d.file),d.command=f,t(d)):d.file}i(u,"detectShebang");function l(d){if(!o)return d;const f=u(d),m=!s.test(f);if(d.options.forceShell||m){const D=a.test(f);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const h=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${h}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,f,m){f&&!Array.isArray(f)&&(m=f,f=null),f=f?f.slice(0):[],m=Object.assign({},m);const D={command:d,args:f,options:m,file:void 0,original:{command:d,args:f}};return m.shell?D:l(D)}return i(c,"parse"),Ss=c,Ss}i(mv,"requireParse");var Bs,kc;function hv(){if(kc)return Bs;kc=1;const e=process.platform==="win32";function t(s,a){return Object.assign(new Error(`${a} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${a} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,a){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,a);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,a){return e&&s===1&&!a.file?t(a.original,"spawn"):null}i(r,"verifyENOENT");function o(s,a){return e&&s===1&&!a.file?t(a.original,"spawnSync"):null}return i(o,"verifyENOENTSync"),Bs={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:o,notFoundError:t},Bs}i(hv,"requireEnoent");var Ic;function Dv(){if(Ic)return ln.exports;Ic=1;const e=zD,t=mv(),n=hv();function r(s,a,u){const l=t(s,a,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function o(s,a,u){const l=t(s,a,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(o,"spawnSync"),ln.exports=r,ln.exports.spawn=r,ln.exports.sync=o,ln.exports._parse=t,ln.exports._enoent=n,ln.exports}i(Dv,"requireCrossSpawn");var gv=Dv(),vv=un(gv);function yv(e){const t=typeof e=="string"?`
23
+ `:10,n=typeof e=="string"?"\r":13;return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}i(yv,"stripFinalNewline");function Ac(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}i(Ac,"pathKey");const _v=i(({cwd:e=Le.cwd(),path:t=Le.env[Ac()],preferLocal:n=!0,execPath:r=Le.execPath,addExecPath:o=!0}={})=>{const s=e instanceof URL?xl(e):e,a=On.resolve(s),u=[];return n&&bv(u,a),o&&Cv(u,r,a),[...u,t].join(On.delimiter)},"npmRunPath"),bv=i((e,t)=>{let n;for(;n!==t;)e.push(On.join(t,"node_modules/.bin")),n=t,t=On.resolve(t,"..")},"applyPreferLocal"),Cv=i((e,t,n)=>{const r=t instanceof URL?xl(t):t;e.push(On.resolve(n,r,".."))},"applyExecPath"),wv=i(({env:e=Le.env,...t}={})=>{e={...e};const n=Ac({env:e});return t.path=e[n],e[n]=_v(t),e},"npmRunPathEnv"),Fv=i((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const o=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!Ev(o,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),Ev=i(function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},"canCopyProperty"),xv=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),kv=i((e,t)=>`/* Wrapped ${e}*/
24
+ ${t}`,"wrappedToString"),Iv=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Av=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),$v=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,o=kv.bind(null,r,t.toString());Object.defineProperty(o,"name",Av),Object.defineProperty(e,"toString",{...Iv,value:o})},"changeToString");function Tv(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const o of Reflect.ownKeys(t))Fv(e,t,o,n);return xv(e,t),$v(e,t,r),e}i(Tv,"mimicFunction");const Xo=new WeakMap,$c=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const o=e.displayName||e.name||"<anonymous>",s=i(function(...a){if(Xo.set(s,++r),r===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${o}\` can only be called once`);return n},"onetime2");return Tv(s,e),Xo.set(s,r),s},"onetime");$c.callCount=e=>{if(!Xo.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Xo.get(e)};const Sv=i(()=>{const e=Sc-Tc+1;return Array.from({length:e},Bv)},"getRealtimeSignals"),Bv=i((e,t)=>({name:`SIGRT${t+1}`,number:Tc+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),Tc=34,Sc=64,Ov=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Bc=i(()=>{const e=Sv();return[...Ov,...e].map(Rv)},"getSignals"),Rv=i(({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=kl,u=a!==void 0;return{name:e,number:u?a:t,description:n,supported:u,action:r,forced:o,standard:s}},"normalizeSignal"),Nv=i(()=>{const e=Bc();return Object.fromEntries(e.map(Pv))},"getSignalsByName"),Pv=i(({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a}],"getSignalByName"),Mv=Nv(),jv=i(()=>{const e=Bc(),t=Sc+1,n=Array.from({length:t},(r,o)=>zv(o,e));return Object.assign({},...n)},"getSignalsByNumber"),zv=i((e,t)=>{const n=Lv(e,t);if(n===void 0)return{};const{name:r,description:o,supported:s,action:a,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:u,standard:l}}},"getSignalByNumber"),Lv=i((e,t)=>{const n=t.find(({name:r})=>kl.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");jv();const qv=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${o})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),Oc=i(({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:a,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:f,cwd:m=Le.cwd()}}})=>{s=s===null?void 0:s,o=o===null?void 0:o;const D=o===void 0?void 0:Mv[o].description,h=r&&r.code,y=`Command ${qv({timedOut:l,timeout:f,errorCode:h,signal:o,signalDescription:D,exitCode:s,isCanceled:c})}: ${a}`,b=Object.prototype.toString.call(r)==="[object Error]",C=b?`${y}
25
25
  ${r.message}`:y,w=[C,t,e].filter(Boolean).join(`
26
- `);return b?(r.originalMessage=r.message,r.message=w):r=new Error(w),r.shortMessage=C,r.command=a,r.escapedCommand=u,r.exitCode=s,r.signal=o,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Jo=["stdin","stdout","stderr"],qv=i(e=>Jo.some(t=>e[t]!==void 0),"hasAlias"),Lv=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Jo.map(r=>e[r]);if(qv(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Jo.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Jo.length);return Array.from({length:n},(r,o)=>t[o])},"normalizeStdio");var an={exports:{}},Is={exports:{}},Sc;function Uv(){return Sc||(Sc=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(Is)),Is.exports}i(Uv,"requireSignals");var Bc;function Zv(){if(Bc)return an.exports;Bc=1;var e=Zt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))an.exports=function(){return function(){}};else{var n=jD,r=Uv(),o=/^win/i.test(e.platform),s=zD;typeof s!="function"&&(s=s.EventEmitter);var a;e.__signal_exit_emitter__?a=e.__signal_exit_emitter__:(a=e.__signal_exit_emitter__=new s,a.count=0,a.emitted={}),a.infinite||(a.setMaxListeners(1/0),a.infinite=!0),an.exports=function(y,b){if(!t(Zt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&f();var C="exit";b&&b.alwaysLast&&(C="afterexit");var w=i(function(){a.removeListener(C,y),a.listeners("exit").length===0&&a.listeners("afterexit").length===0&&u()},"remove");return a.on(C,y),w};var u=i(function(){!d||!t(Zt.process)||(d=!1,r.forEach(function(b){try{e.removeListener(b,c[b])}catch{}}),e.emit=m,e.reallyExit=h,a.count-=1)},"unload2");an.exports.unload=u;var l=i(function(b,C,w){a.emitted[b]||(a.emitted[b]=!0,a.emit(b,C,w))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(Zt.process)){var C=e.listeners(y);C.length===a.count&&(u(),l("exit",null,y),l("afterexit",null,y),o&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),an.exports.signals=function(){return r};var d=!1,f=i(function(){d||!t(Zt.process)||(d=!0,a.count+=1,r=r.filter(function(b){try{return e.on(b,c[b]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");an.exports.load=f;var h=e.reallyExit,D=i(function(b){t(Zt.process)&&(e.exitCode=b||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),m=e.emit,v=i(function(b,C){if(b==="exit"&&t(Zt.process)){C!==void 0&&(e.exitCode=C);var w=m.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),w}else return m.apply(this,arguments)},"processEmit2")}return an.exports}i(Zv,"requireSignalExit");var Vv=Zv(),Gv=rn(Vv);const Wv=1e3*5,Hv=i((e,t="SIGTERM",n={})=>{const r=e(t);return Jv(e,t,n,r),r},"spawnedKill"),Jv=i((e,t,n,r)=>{if(!Kv(t,n,r))return;const o=Xv(n),s=setTimeout(()=>{e("SIGKILL")},o);s.unref&&s.unref()},"setKillTimeout"),Kv=i((e,{forceKillAfterTimeout:t},n)=>Yv(e)&&t!==!1&&n,"shouldForceKill"),Yv=i(e=>e===MD.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),Xv=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Wv;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),Qv=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),ey=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),ty=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let o;const s=new Promise((u,l)=>{o=setTimeout(()=>{ey(e,n,l)},t)}),a=r.finally(()=>{clearTimeout(o)});return Promise.race([s,a])},"setupTimeout"),ny=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),ry=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const o=Gv(()=>{e.kill()});return r.finally(()=>{o()})},"setExitHandler");function Oc(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(Oc,"isStream");function Rc(e){return Oc(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(Rc,"isWritableStream");const oy=i(e=>e instanceof ND&&typeof e.then=="function","isExecaChildProcess"),As=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(qD(n)),e;if(Rc(n))return e[t].pipe(n),e;if(!oy(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Rc(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),ay=i(e=>{e.stdout!==null&&(e.pipeStdout=As.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=As.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=As.bind(void 0,e,"all"))},"addPipeMethods");var $n={exports:{}},$s,Nc;function sy(){if(Nc)return $s;Nc=1;const{PassThrough:e}=us;return $s=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;n?s=!(r||o):r=r||"utf8",o&&(r=null);const a=new e({objectMode:s});r&&a.setEncoding(r);let u=0;const l=[];return a.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),a.getBufferedValue=()=>n?l:o?Buffer.concat(l,u):l.join(""),a.getBufferedLength=()=>u,a},"bufferStream"),$s}i(sy,"requireBufferStream");var Pc;function iy(){if(Pc)return $n.exports;Pc=1;const{constants:e}=UD,t=us,{promisify:n}=ZD,r=sy(),o=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function a(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,f=r(c);return await new Promise((h,D)=>{const m=i(v=>{v&&f.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=f.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await o(l,f),h()}catch(v){m(v)}})(),f.on("data",()=>{f.getBufferedLength()>d&&m(new s)})}),f.getBufferedValue()}return i(a,"getStream"),$n.exports=a,$n.exports.buffer=(l,c)=>a(l,{...c,encoding:"buffer"}),$n.exports.array=(l,c)=>a(l,{...c,array:!0}),$n.exports.MaxBufferError=s,$n.exports}i(iy,"requireGetStream");var uy=iy(),Mc=rn(uy),Ts,jc;function ly(){if(jc)return Ts;jc=1;const{PassThrough:e}=us;return Ts=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=o,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(a){return Array.isArray(a)?(a.forEach(r),this):(t.push(a),a.once("end",s.bind(null,a)),a.once("error",n.emit.bind(n,"error")),a.pipe(n,{end:!1}),this)}i(r,"add");function o(){return t.length==0}i(o,"isEmpty");function s(a){t=t.filter(function(u){return u!==a}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),Ts}i(ly,"requireMergeStream");var cy=ly(),dy=rn(cy);const py=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),fy=i(({input:e,inputFile:t})=>typeof t!="string"?e:(py(e),LD(t)),"getInput"),my=i((e,t)=>{const n=fy(t);n!==void 0&&(Oc(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),hy=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=dy();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),Ss=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),Bs=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Mc(e,{encoding:t,maxBuffer:r}):Mc.buffer(e,{maxBuffer:r})},"getStreamPromise"),Dy=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:o,maxBuffer:s},a)=>{const u=Bs(e,{encoding:r,buffer:o,maxBuffer:s}),l=Bs(t,{encoding:r,buffer:o,maxBuffer:s}),c=Bs(n,{encoding:r,buffer:o,maxBuffer:s*2});try{return await Promise.all([a,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Ss(e,u),Ss(t,l),Ss(n,c)])}},"getSpawnedResult"),gy=(async()=>{})().constructor.prototype,vy=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(gy,e)]),zc=i((e,t)=>{for(const[n,r]of vy){const o=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:o})}},"mergePromise"),yy=i(e=>new Promise((t,n)=>{e.on("exit",(r,o)=>{t({exitCode:r,signal:o})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),qc=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),_y=/^[\w.-]+$/,by=/"/g,Cy=i(e=>typeof e!="string"||_y.test(e)?e:`"${e.replace(by,'\\"')}"`,"escapeArg"),wy=i((e,t)=>qc(e,t).join(" "),"joinCommand"),Fy=i((e,t)=>qc(e,t).map(n=>Cy(n)).join(" "),"getEscapedCommand"),Ey=GD("execa").enabled,Ko=i((e,t)=>String(e).padStart(t,"0"),"padField"),xy=i(()=>{const e=new Date;return`${Ko(e.getHours(),2)}:${Ko(e.getMinutes(),2)}:${Ko(e.getSeconds(),2)}.${Ko(e.getMilliseconds(),3)}`},"getTimestamp"),ky=i((e,{verbose:t})=>{t&&qe.stderr.write(`[${xy()}] ${e}
27
- `)},"logCommand"),Iy=1e3*1e3*100,Ay=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const s=t?{...qe.env,...e}:e;return n?bv({env:s,cwd:r,execPath:o}):s},"getEnv"),$y=i((e,t,n={})=>{const r=Dv._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:Iy,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||qe.cwd(),execPath:qe.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ey,...n},n.env=Ay(n),n.stdio=Lv(n),qe.platform==="win32"&&In.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),Os=i((e,t,n)=>typeof t!="string"&&!RD.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?gv(t):t,"handleOutput");function Je(e,t,n){const r=$y(e,t,n),o=wy(e,t),s=Fy(e,t);ky(s,r.options),ny(r.options);let a;try{a=_l.spawn(r.file,r.args,r.options)}catch(D){const m=new _l.ChildProcess,v=Promise.reject(Tc({error:D,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return zc(m,v),m}const u=yy(a),l=ty(a,r.options,u),c=ry(a,r.options,l),d={isCanceled:!1};a.kill=Hv.bind(null,a.kill.bind(a)),a.cancel=Qv.bind(null,a,d);const h=kc(i(async()=>{const[{error:D,exitCode:m,signal:v,timedOut:y},b,C,w]=await Dy(a,r.options,c),E=Os(r.options,b),T=Os(r.options,C),O=Os(r.options,w);if(D||m!==0||v!==null){const $=Tc({error:D,exitCode:m,signal:v,stdout:E,stderr:T,all:O,command:o,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:a.killed});if(!r.options.reject)return $;throw $}return{command:o,escapedCommand:s,exitCode:0,stdout:E,stderr:T,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return my(a,r.options),a.all=hy(a,r.options),ay(a),zc(a,h),a}i(Je,"execa");let sn=!0;const Tn=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let no=0;if(Tn.process&&Tn.process.env&&Tn.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:o}=Tn.process.env;t||n||e==="0"?sn=!1:e==="1"||e==="2"||e==="3"?sn=!0:r==="dumb"?sn=!1:"CI"in Tn.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in Tn.process.env)?sn=!0:sn=process.stdout.isTTY,sn&&(process.platform==="win32"||o&&(o==="truecolor"||o==="24bit")?no=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?no=2:no=1)}let Rs={enabled:sn,supportLevel:no};function Sn(e,t,n=1){const r=`\x1B[${e}m`,o=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return a=>Rs.enabled&&Rs.supportLevel>=n?r+(""+a).replace(s,r)+o:""+a}i(Sn,"kolorist");const Ns=Sn(2,22),Yo=Sn(30,39),Ps=Sn(31,39),St=Sn(32,39),Ms=Sn(33,39),Xo=Sn(46,49);var Ty=Object.freeze({__proto__:null,bgCyan:Xo,black:Yo,dim:Ns,green:St,options:Rs,red:Ps,yellow:Ms});async function Lc(e){try{return process.platform==="darwin"?await Je("pbcopy",{input:e}):process.platform==="win32"?await Je("clip",{input:e}):await Je("xclip",["-selection","clipboard"],{input:e}).catch(()=>Je("xsel",["--clipboard","--input"],{input:e})),!0}catch{return!1}}i(Lc,"copyToClipboard");var js,Uc;function Sy(){if(Uc)return js;Uc=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(a,u){return u?`${t}${u+1};${a+1}H`:`${t}${a+1}G`},move(a,u){let l="";return a<0?l+=`${t}${-a}D`:a>0&&(l+=`${t}${a}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((a=1)=>`${t}${a}A`,"up"),down:i((a=1)=>`${t}${a}B`,"down"),forward:i((a=1)=>`${t}${a}C`,"forward"),backward:i((a=1)=>`${t}${a}D`,"backward"),nextLine:i((a=1)=>`${t}E`.repeat(a),"nextLine"),prevLine:i((a=1)=>`${t}F`.repeat(a),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},o={up:i((a=1)=>`${t}S`.repeat(a),"up"),down:i((a=1)=>`${t}T`.repeat(a),"down")},s={screen:`${t}2J`,up:i((a=1)=>`${t}1J`.repeat(a),"up"),down:i((a=1)=>`${t}J`.repeat(a),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(a){let u="";for(let l=0;l<a;l++)u+=this.line+(l<a-1?r.up():"");return a&&(u+=r.left),u}};return js={cursor:r,scroll:o,erase:s,beep:n},js}i(Sy,"requireSrc");var Xe=Sy(),Qo={exports:{}},Zc;function By(){if(Zc)return Qo.exports;Zc=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),o=i((u,l,c=u)=>d=>{let f=""+d,h=f.indexOf(l,u.length);return~h?u+s(f,l,c,h)+l:u+f+l},"formatter"),s=i((u,l,c,d)=>{let f="",h=0;do f+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return f+u.substring(h)},"replaceClose"),a=i((u=r)=>{let l=u?o:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return Qo.exports=a(),Qo.exports.createColors=a,Qo.exports}i(By,"requirePicocolors");var Oy=By(),q=rn(Oy);function Ry({onlyFirst:e=!1}={}){const 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")}i(Ry,"DD");const Ny=Ry();function Vc(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Ny,"")}i(Vc,"P$1");function Gc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(Gc,"L$1");var Wc={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var o=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,a=o;return 55296<=o&&o<=56319&&56320<=s&&s<=57343&&(o&=1023,s&=1023,a=o<<10|s,a+=65536),a==12288||65281<=a&&a<=65376||65504<=a&&a<=65510?"F":a==8361||65377<=a&&a<=65470||65474<=a&&a<=65479||65482<=a&&a<=65487||65490<=a&&a<=65495||65498<=a&&a<=65500||65512<=a&&a<=65518?"H":4352<=a&&a<=4447||4515<=a&&a<=4519||4602<=a&&a<=4607||9001<=a&&a<=9002||11904<=a&&a<=11929||11931<=a&&a<=12019||12032<=a&&a<=12245||12272<=a&&a<=12283||12289<=a&&a<=12350||12353<=a&&a<=12438||12441<=a&&a<=12543||12549<=a&&a<=12589||12593<=a&&a<=12686||12688<=a&&a<=12730||12736<=a&&a<=12771||12784<=a&&a<=12830||12832<=a&&a<=12871||12880<=a&&a<=13054||13056<=a&&a<=19903||19968<=a&&a<=42124||42128<=a&&a<=42182||43360<=a&&a<=43388||44032<=a&&a<=55203||55216<=a&&a<=55238||55243<=a&&a<=55291||63744<=a&&a<=64255||65040<=a&&a<=65049||65072<=a&&a<=65106||65108<=a&&a<=65126||65128<=a&&a<=65131||110592<=a&&a<=110593||127488<=a&&a<=127490||127504<=a&&a<=127546||127552<=a&&a<=127560||127568<=a&&a<=127569||131072<=a&&a<=194367||177984<=a&&a<=196605||196608<=a&&a<=262141?"W":32<=a&&a<=126||162<=a&&a<=163||165<=a&&a<=166||a==172||a==175||10214<=a&&a<=10221||10629<=a&&a<=10630?"Na":a==161||a==164||167<=a&&a<=168||a==170||173<=a&&a<=174||176<=a&&a<=180||182<=a&&a<=186||188<=a&&a<=191||a==198||a==208||215<=a&&a<=216||222<=a&&a<=225||a==230||232<=a&&a<=234||236<=a&&a<=237||a==240||242<=a&&a<=243||247<=a&&a<=250||a==252||a==254||a==257||a==273||a==275||a==283||294<=a&&a<=295||a==299||305<=a&&a<=307||a==312||319<=a&&a<=322||a==324||328<=a&&a<=331||a==333||338<=a&&a<=339||358<=a&&a<=359||a==363||a==462||a==464||a==466||a==468||a==470||a==472||a==474||a==476||a==593||a==609||a==708||a==711||713<=a&&a<=715||a==717||a==720||728<=a&&a<=731||a==733||a==735||768<=a&&a<=879||913<=a&&a<=929||931<=a&&a<=937||945<=a&&a<=961||963<=a&&a<=969||a==1025||1040<=a&&a<=1103||a==1105||a==8208||8211<=a&&a<=8214||8216<=a&&a<=8217||8220<=a&&a<=8221||8224<=a&&a<=8226||8228<=a&&a<=8231||a==8240||8242<=a&&a<=8243||a==8245||a==8251||a==8254||a==8308||a==8319||8321<=a&&a<=8324||a==8364||a==8451||a==8453||a==8457||a==8467||a==8470||8481<=a&&a<=8482||a==8486||a==8491||8531<=a&&a<=8532||8539<=a&&a<=8542||8544<=a&&a<=8555||8560<=a&&a<=8569||a==8585||8592<=a&&a<=8601||8632<=a&&a<=8633||a==8658||a==8660||a==8679||a==8704||8706<=a&&a<=8707||8711<=a&&a<=8712||a==8715||a==8719||a==8721||a==8725||a==8730||8733<=a&&a<=8736||a==8739||a==8741||8743<=a&&a<=8748||a==8750||8756<=a&&a<=8759||8764<=a&&a<=8765||a==8776||a==8780||a==8786||8800<=a&&a<=8801||8804<=a&&a<=8807||8810<=a&&a<=8811||8814<=a&&a<=8815||8834<=a&&a<=8835||8838<=a&&a<=8839||a==8853||a==8857||a==8869||a==8895||a==8978||9312<=a&&a<=9449||9451<=a&&a<=9547||9552<=a&&a<=9587||9600<=a&&a<=9615||9618<=a&&a<=9621||9632<=a&&a<=9633||9635<=a&&a<=9641||9650<=a&&a<=9651||9654<=a&&a<=9655||9660<=a&&a<=9661||9664<=a&&a<=9665||9670<=a&&a<=9672||a==9675||9678<=a&&a<=9681||9698<=a&&a<=9701||a==9711||9733<=a&&a<=9734||a==9737||9742<=a&&a<=9743||9748<=a&&a<=9749||a==9756||a==9758||a==9792||a==9794||9824<=a&&a<=9825||9827<=a&&a<=9829||9831<=a&&a<=9834||9836<=a&&a<=9837||a==9839||9886<=a&&a<=9887||9918<=a&&a<=9919||9924<=a&&a<=9933||9935<=a&&a<=9953||a==9955||9960<=a&&a<=9983||a==10045||a==10071||10102<=a&&a<=10111||11093<=a&&a<=11097||12872<=a&&a<=12879||57344<=a&&a<=63743||65024<=a&&a<=65039||a==65533||127232<=a&&a<=127242||127248<=a&&a<=127277||127280<=a&&a<=127337||127344<=a&&a<=127386||917760<=a&&a<=917999||983040<=a&&a<=1048573||1048576<=a&&a<=1114109?"A":"N"},t.characterLength=function(r){var o=this.eastAsianWidth(r);return o=="F"||o=="W"||o=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var o=n(r),s=0,a=0;a<o.length;a++)s=s+this.characterLength(o[a]);return s},t.slice=function(r,o,s){textLen=t.length(r),o=o||0,s=s||1,o<0&&(o=textLen+o),s<0&&(s=textLen+s);for(var a="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],f=t.length(d);if(u>=o-(f==2?1:0))if(u+f<=s)a+=d;else break;u+=f}return a}})(Wc);var Py=Wc.exports;const My=Gc(Py);var jy=i(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},"FD");const zy=Gc(jy);function ro(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Vc(e),e.length===0))return 0;e=e.replace(zy()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const o of e){const s=o.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(My.eastAsianWidth(o)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(ro,"p");const zs=10,Hc=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),Jc=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Kc=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Te={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(Te.modifier);const qy=Object.keys(Te.color),Ly=Object.keys(Te.bgColor);[...qy,...Ly];function Uy(){const e=new Map;for(const[t,n]of Object.entries(Te)){for(const[r,o]of Object.entries(n))Te[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=Te[r],e.set(o[0],o[1]);Object.defineProperty(Te,t,{value:n,enumerable:!1})}return Object.defineProperty(Te,"codes",{value:e,enumerable:!1}),Te.color.close="\x1B[39m",Te.bgColor.close="\x1B[49m",Te.color.ansi=Hc(),Te.color.ansi256=Jc(),Te.color.ansi16m=Kc(),Te.bgColor.ansi=Hc(zs),Te.bgColor.ansi256=Jc(zs),Te.bgColor.ansi16m=Kc(zs),Object.defineProperties(Te,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Te.rgbToAnsi256(...Te.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Te.ansi256ToAnsi(Te.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Te.ansi256ToAnsi(Te.hexToAnsi256(t)),"value"),enumerable:!1}}),Te}i(Uy,"rD");const Zy=Uy(),ea=new Set(["\x1B","\x9B"]),Vy=39,qs="\x07",Yc="[",Gy="]",Xc="m",Ls=`${Gy}8;;`,Qc=i(e=>`${ea.values().next().value}${Yc}${e}${Xc}`,"z"),ed=i(e=>`${ea.values().next().value}${Ls}${e}${qs}`,"K"),Wy=i(e=>e.split(" ").map(t=>ro(t)),"aD"),Us=i((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=ro(Vc(e[e.length-1]));for(const[u,l]of r.entries()){const c=ro(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),ea.has(l)&&(o=!0,s=r.slice(u+1).join("").startsWith(Ls)),o){s?l===qs&&(o=!1,s=!1):l===Xc&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),Hy=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(ro(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),Jy=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Wy(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let f=ro(u[u.length-1]);if(c!==0&&(f>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),f=0),(f>0||n.trim===!1)&&(u[u.length-1]+=" ",f++)),n.hard&&a[c]>t){const h=t-f,D=1+Math.floor((a[c]-h-1)/t);Math.floor((a[c]-1)/t)<D&&u.push(""),Us(u,d,t);continue}if(f+a[c]>t&&f>0&&a[c]>0){if(n.wordWrap===!1&&f<t){Us(u,d,t);continue}u.push("")}if(f+a[c]>t&&n.wordWrap===!1){Us(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Hy(c)));const l=[...u.join(`
28
- `)];for(const[c,d]of l.entries()){if(r+=d,ea.has(d)){const{groups:h}=new RegExp(`(?:\\${Yc}(?<code>\\d+)m|\\${Ls}(?<uri>.*)${qs})`).exec(l.slice(c).join(""))||{groups:{}};if(h.code!==void 0){const D=Number.parseFloat(h.code);o=D===Vy?void 0:D}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const f=Zy.codes.get(Number(o));l[c+1]===`
29
- `?(s&&(r+=ed("")),o&&f&&(r+=Qc(f))):d===`
30
- `&&(o&&f&&(r+=Qc(o)),s&&(r+=ed(s)))}return r},"lD");function td(e,t,n){return String(e).normalize().replace(/\r\n/g,`
26
+ `);return b?(r.originalMessage=r.message,r.message=w):r=new Error(w),r.shortMessage=C,r.command=a,r.escapedCommand=u,r.exitCode=s,r.signal=o,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=m,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Qo=["stdin","stdout","stderr"],Uv=i(e=>Qo.some(t=>e[t]!==void 0),"hasAlias"),Zv=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Qo.map(r=>e[r]);if(Uv(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Qo.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Qo.length);return Array.from({length:n},(r,o)=>t[o])},"normalizeStdio");var cn={exports:{}},Os={exports:{}},Rc;function Vv(){return Rc||(Rc=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(Os)),Os.exports}i(Vv,"requireSignals");var Nc;function Gv(){if(Nc)return cn.exports;Nc=1;var e=Gt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))cn.exports=function(){return function(){}};else{var n=qD,r=Vv(),o=/^win/i.test(e.platform),s=UD;typeof s!="function"&&(s=s.EventEmitter);var a;e.__signal_exit_emitter__?a=e.__signal_exit_emitter__:(a=e.__signal_exit_emitter__=new s,a.count=0,a.emitted={}),a.infinite||(a.setMaxListeners(1/0),a.infinite=!0),cn.exports=function(y,b){if(!t(Gt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&f();var C="exit";b&&b.alwaysLast&&(C="afterexit");var w=i(function(){a.removeListener(C,y),a.listeners("exit").length===0&&a.listeners("afterexit").length===0&&u()},"remove");return a.on(C,y),w};var u=i(function(){!d||!t(Gt.process)||(d=!1,r.forEach(function(b){try{e.removeListener(b,c[b])}catch{}}),e.emit=h,e.reallyExit=m,a.count-=1)},"unload2");cn.exports.unload=u;var l=i(function(b,C,w){a.emitted[b]||(a.emitted[b]=!0,a.emit(b,C,w))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(Gt.process)){var C=e.listeners(y);C.length===a.count&&(u(),l("exit",null,y),l("afterexit",null,y),o&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),cn.exports.signals=function(){return r};var d=!1,f=i(function(){d||!t(Gt.process)||(d=!0,a.count+=1,r=r.filter(function(b){try{return e.on(b,c[b]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");cn.exports.load=f;var m=e.reallyExit,D=i(function(b){t(Gt.process)&&(e.exitCode=b||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),m.call(e,e.exitCode))},"processReallyExit2"),h=e.emit,v=i(function(b,C){if(b==="exit"&&t(Gt.process)){C!==void 0&&(e.exitCode=C);var w=h.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),w}else return h.apply(this,arguments)},"processEmit2")}return cn.exports}i(Gv,"requireSignalExit");var Wv=Gv(),Hv=un(Wv);const Jv=1e3*5,Kv=i((e,t="SIGTERM",n={})=>{const r=e(t);return Yv(e,t,n,r),r},"spawnedKill"),Yv=i((e,t,n,r)=>{if(!Xv(t,n,r))return;const o=ey(n),s=setTimeout(()=>{e("SIGKILL")},o);s.unref&&s.unref()},"setKillTimeout"),Xv=i((e,{forceKillAfterTimeout:t},n)=>Qv(e)&&t!==!1&&n,"shouldForceKill"),Qv=i(e=>e===LD.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),ey=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Jv;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),ty=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),ny=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),ry=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let o;const s=new Promise((u,l)=>{o=setTimeout(()=>{ny(e,n,l)},t)}),a=r.finally(()=>{clearTimeout(o)});return Promise.race([s,a])},"setupTimeout"),oy=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),ay=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const o=Hv(()=>{e.kill()});return r.finally(()=>{o()})},"setExitHandler");function Pc(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(Pc,"isStream");function Mc(e){return Pc(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(Mc,"isWritableStream");const sy=i(e=>e instanceof jD&&typeof e.then=="function","isExecaChildProcess"),Rs=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(ZD(n)),e;if(Mc(n))return e[t].pipe(n),e;if(!sy(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Mc(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),iy=i(e=>{e.stdout!==null&&(e.pipeStdout=Rs.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Rs.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Rs.bind(void 0,e,"all"))},"addPipeMethods");var Rn={exports:{}},Ns,jc;function uy(){if(jc)return Ns;jc=1;const{PassThrough:e}=hs;return Ns=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;n?s=!(r||o):r=r||"utf8",o&&(r=null);const a=new e({objectMode:s});r&&a.setEncoding(r);let u=0;const l=[];return a.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),a.getBufferedValue=()=>n?l:o?Buffer.concat(l,u):l.join(""),a.getBufferedLength=()=>u,a},"bufferStream"),Ns}i(uy,"requireBufferStream");var zc;function ly(){if(zc)return Rn.exports;zc=1;const{constants:e}=GD,t=hs,{promisify:n}=WD,r=uy(),o=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function a(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,f=r(c);return await new Promise((m,D)=>{const h=i(v=>{v&&f.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=f.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await o(l,f),m()}catch(v){h(v)}})(),f.on("data",()=>{f.getBufferedLength()>d&&h(new s)})}),f.getBufferedValue()}return i(a,"getStream"),Rn.exports=a,Rn.exports.buffer=(l,c)=>a(l,{...c,encoding:"buffer"}),Rn.exports.array=(l,c)=>a(l,{...c,array:!0}),Rn.exports.MaxBufferError=s,Rn.exports}i(ly,"requireGetStream");var cy=ly(),Lc=un(cy),Ps,qc;function dy(){if(qc)return Ps;qc=1;const{PassThrough:e}=hs;return Ps=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=o,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(a){return Array.isArray(a)?(a.forEach(r),this):(t.push(a),a.once("end",s.bind(null,a)),a.once("error",n.emit.bind(n,"error")),a.pipe(n,{end:!1}),this)}i(r,"add");function o(){return t.length==0}i(o,"isEmpty");function s(a){t=t.filter(function(u){return u!==a}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),Ps}i(dy,"requireMergeStream");var py=dy(),fy=un(py);const my=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),hy=i(({input:e,inputFile:t})=>typeof t!="string"?e:(my(e),VD(t)),"getInput"),Dy=i((e,t)=>{const n=hy(t);n!==void 0&&(Pc(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),gy=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=fy();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),Ms=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),js=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Lc(e,{encoding:t,maxBuffer:r}):Lc.buffer(e,{maxBuffer:r})},"getStreamPromise"),vy=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:o,maxBuffer:s},a)=>{const u=js(e,{encoding:r,buffer:o,maxBuffer:s}),l=js(t,{encoding:r,buffer:o,maxBuffer:s}),c=js(n,{encoding:r,buffer:o,maxBuffer:s*2});try{return await Promise.all([a,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Ms(e,u),Ms(t,l),Ms(n,c)])}},"getSpawnedResult"),yy=(async()=>{})().constructor.prototype,_y=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(yy,e)]),Uc=i((e,t)=>{for(const[n,r]of _y){const o=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:o})}},"mergePromise"),by=i(e=>new Promise((t,n)=>{e.on("exit",(r,o)=>{t({exitCode:r,signal:o})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),Zc=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),Cy=/^[\w.-]+$/,wy=/"/g,Fy=i(e=>typeof e!="string"||Cy.test(e)?e:`"${e.replace(wy,'\\"')}"`,"escapeArg"),Ey=i((e,t)=>Zc(e,t).join(" "),"joinCommand"),xy=i((e,t)=>Zc(e,t).map(n=>Fy(n)).join(" "),"getEscapedCommand"),ky=HD("execa").enabled,ea=i((e,t)=>String(e).padStart(t,"0"),"padField"),Iy=i(()=>{const e=new Date;return`${ea(e.getHours(),2)}:${ea(e.getMinutes(),2)}:${ea(e.getSeconds(),2)}.${ea(e.getMilliseconds(),3)}`},"getTimestamp"),Ay=i((e,{verbose:t})=>{t&&Le.stderr.write(`[${Iy()}] ${e}
27
+ `)},"logCommand"),$y=1e3*1e3*100,Ty=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const s=t?{...Le.env,...e}:e;return n?wv({env:s,cwd:r,execPath:o}):s},"getEnv"),Sy=i((e,t,n={})=>{const r=vv._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:$y,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||Le.cwd(),execPath:Le.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ky,...n},n.env=Ty(n),n.stdio=Zv(n),Le.platform==="win32"&&On.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),zs=i((e,t,n)=>typeof t!="string"&&!MD.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?yv(t):t,"handleOutput");function Je(e,t,n){const r=Sy(e,t,n),o=Ey(e,t),s=xy(e,t);Ay(s,r.options),oy(r.options);let a;try{a=wl.spawn(r.file,r.args,r.options)}catch(D){const h=new wl.ChildProcess,v=Promise.reject(Oc({error:D,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Uc(h,v),h}const u=by(a),l=ry(a,r.options,u),c=ay(a,r.options,l),d={isCanceled:!1};a.kill=Kv.bind(null,a.kill.bind(a)),a.cancel=ty.bind(null,a,d);const m=$c(i(async()=>{const[{error:D,exitCode:h,signal:v,timedOut:y},b,C,w]=await vy(a,r.options,c),E=zs(r.options,b),T=zs(r.options,C),O=zs(r.options,w);if(D||h!==0||v!==null){const $=Oc({error:D,exitCode:h,signal:v,stdout:E,stderr:T,all:O,command:o,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:a.killed});if(!r.options.reject)return $;throw $}return{command:o,escapedCommand:s,exitCode:0,stdout:E,stderr:T,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return Dy(a,r.options),a.all=gy(a,r.options),iy(a),Uc(a,m),a}i(Je,"execa");let dn=!0;const Nn=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let ao=0;if(Nn.process&&Nn.process.env&&Nn.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:o}=Nn.process.env;t||n||e==="0"?dn=!1:e==="1"||e==="2"||e==="3"?dn=!0:r==="dumb"?dn=!1:"CI"in Nn.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in Nn.process.env)?dn=!0:dn=process.stdout.isTTY,dn&&(process.platform==="win32"||o&&(o==="truecolor"||o==="24bit")?ao=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?ao=2:ao=1)}let Ls={enabled:dn,supportLevel:ao};function pn(e,t,n=1){const r=`\x1B[${e}m`,o=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return a=>Ls.enabled&&Ls.supportLevel>=n?r+(""+a).replace(s,r)+o:""+a}i(pn,"kolorist");const so=pn(2,22),ta=pn(30,39),Wt=pn(31,39),it=pn(32,39),na=pn(33,39),ra=pn(36,39),oa=pn(46,49);var By=Object.freeze({__proto__:null,bgCyan:oa,black:ta,cyan:ra,dim:so,green:it,options:Ls,red:Wt,yellow:na});async function Vc(e){try{return process.platform==="darwin"?await Je("pbcopy",{input:e}):process.platform==="win32"?await Je("clip",{input:e}):await Je("xclip",["-selection","clipboard"],{input:e}).catch(()=>Je("xsel",["--clipboard","--input"],{input:e})),!0}catch{return!1}}i(Vc,"copyToClipboard");var qs,Gc;function Oy(){if(Gc)return qs;Gc=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(a,u){return u?`${t}${u+1};${a+1}H`:`${t}${a+1}G`},move(a,u){let l="";return a<0?l+=`${t}${-a}D`:a>0&&(l+=`${t}${a}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((a=1)=>`${t}${a}A`,"up"),down:i((a=1)=>`${t}${a}B`,"down"),forward:i((a=1)=>`${t}${a}C`,"forward"),backward:i((a=1)=>`${t}${a}D`,"backward"),nextLine:i((a=1)=>`${t}E`.repeat(a),"nextLine"),prevLine:i((a=1)=>`${t}F`.repeat(a),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},o={up:i((a=1)=>`${t}S`.repeat(a),"up"),down:i((a=1)=>`${t}T`.repeat(a),"down")},s={screen:`${t}2J`,up:i((a=1)=>`${t}1J`.repeat(a),"up"),down:i((a=1)=>`${t}J`.repeat(a),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(a){let u="";for(let l=0;l<a;l++)u+=this.line+(l<a-1?r.up():"");return a&&(u+=r.left),u}};return qs={cursor:r,scroll:o,erase:s,beep:n},qs}i(Oy,"requireSrc");var Xe=Oy(),aa={exports:{}},Wc;function Ry(){if(Wc)return aa.exports;Wc=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),o=i((u,l,c=u)=>d=>{let f=""+d,m=f.indexOf(l,u.length);return~m?u+s(f,l,c,m)+l:u+f+l},"formatter"),s=i((u,l,c,d)=>{let f="",m=0;do f+=u.substring(m,d)+c,m=d+l.length,d=u.indexOf(l,m);while(~d);return f+u.substring(m)},"replaceClose"),a=i((u=r)=>{let l=u?o:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return aa.exports=a(),aa.exports.createColors=a,aa.exports}i(Ry,"requirePicocolors");var Ny=Ry(),L=un(Ny);function Py({onlyFirst:e=!1}={}){const 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")}i(Py,"DD");const My=Py();function Hc(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(My,"")}i(Hc,"P$1");function Jc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(Jc,"L$1");var Kc={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var o=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,a=o;return 55296<=o&&o<=56319&&56320<=s&&s<=57343&&(o&=1023,s&=1023,a=o<<10|s,a+=65536),a==12288||65281<=a&&a<=65376||65504<=a&&a<=65510?"F":a==8361||65377<=a&&a<=65470||65474<=a&&a<=65479||65482<=a&&a<=65487||65490<=a&&a<=65495||65498<=a&&a<=65500||65512<=a&&a<=65518?"H":4352<=a&&a<=4447||4515<=a&&a<=4519||4602<=a&&a<=4607||9001<=a&&a<=9002||11904<=a&&a<=11929||11931<=a&&a<=12019||12032<=a&&a<=12245||12272<=a&&a<=12283||12289<=a&&a<=12350||12353<=a&&a<=12438||12441<=a&&a<=12543||12549<=a&&a<=12589||12593<=a&&a<=12686||12688<=a&&a<=12730||12736<=a&&a<=12771||12784<=a&&a<=12830||12832<=a&&a<=12871||12880<=a&&a<=13054||13056<=a&&a<=19903||19968<=a&&a<=42124||42128<=a&&a<=42182||43360<=a&&a<=43388||44032<=a&&a<=55203||55216<=a&&a<=55238||55243<=a&&a<=55291||63744<=a&&a<=64255||65040<=a&&a<=65049||65072<=a&&a<=65106||65108<=a&&a<=65126||65128<=a&&a<=65131||110592<=a&&a<=110593||127488<=a&&a<=127490||127504<=a&&a<=127546||127552<=a&&a<=127560||127568<=a&&a<=127569||131072<=a&&a<=194367||177984<=a&&a<=196605||196608<=a&&a<=262141?"W":32<=a&&a<=126||162<=a&&a<=163||165<=a&&a<=166||a==172||a==175||10214<=a&&a<=10221||10629<=a&&a<=10630?"Na":a==161||a==164||167<=a&&a<=168||a==170||173<=a&&a<=174||176<=a&&a<=180||182<=a&&a<=186||188<=a&&a<=191||a==198||a==208||215<=a&&a<=216||222<=a&&a<=225||a==230||232<=a&&a<=234||236<=a&&a<=237||a==240||242<=a&&a<=243||247<=a&&a<=250||a==252||a==254||a==257||a==273||a==275||a==283||294<=a&&a<=295||a==299||305<=a&&a<=307||a==312||319<=a&&a<=322||a==324||328<=a&&a<=331||a==333||338<=a&&a<=339||358<=a&&a<=359||a==363||a==462||a==464||a==466||a==468||a==470||a==472||a==474||a==476||a==593||a==609||a==708||a==711||713<=a&&a<=715||a==717||a==720||728<=a&&a<=731||a==733||a==735||768<=a&&a<=879||913<=a&&a<=929||931<=a&&a<=937||945<=a&&a<=961||963<=a&&a<=969||a==1025||1040<=a&&a<=1103||a==1105||a==8208||8211<=a&&a<=8214||8216<=a&&a<=8217||8220<=a&&a<=8221||8224<=a&&a<=8226||8228<=a&&a<=8231||a==8240||8242<=a&&a<=8243||a==8245||a==8251||a==8254||a==8308||a==8319||8321<=a&&a<=8324||a==8364||a==8451||a==8453||a==8457||a==8467||a==8470||8481<=a&&a<=8482||a==8486||a==8491||8531<=a&&a<=8532||8539<=a&&a<=8542||8544<=a&&a<=8555||8560<=a&&a<=8569||a==8585||8592<=a&&a<=8601||8632<=a&&a<=8633||a==8658||a==8660||a==8679||a==8704||8706<=a&&a<=8707||8711<=a&&a<=8712||a==8715||a==8719||a==8721||a==8725||a==8730||8733<=a&&a<=8736||a==8739||a==8741||8743<=a&&a<=8748||a==8750||8756<=a&&a<=8759||8764<=a&&a<=8765||a==8776||a==8780||a==8786||8800<=a&&a<=8801||8804<=a&&a<=8807||8810<=a&&a<=8811||8814<=a&&a<=8815||8834<=a&&a<=8835||8838<=a&&a<=8839||a==8853||a==8857||a==8869||a==8895||a==8978||9312<=a&&a<=9449||9451<=a&&a<=9547||9552<=a&&a<=9587||9600<=a&&a<=9615||9618<=a&&a<=9621||9632<=a&&a<=9633||9635<=a&&a<=9641||9650<=a&&a<=9651||9654<=a&&a<=9655||9660<=a&&a<=9661||9664<=a&&a<=9665||9670<=a&&a<=9672||a==9675||9678<=a&&a<=9681||9698<=a&&a<=9701||a==9711||9733<=a&&a<=9734||a==9737||9742<=a&&a<=9743||9748<=a&&a<=9749||a==9756||a==9758||a==9792||a==9794||9824<=a&&a<=9825||9827<=a&&a<=9829||9831<=a&&a<=9834||9836<=a&&a<=9837||a==9839||9886<=a&&a<=9887||9918<=a&&a<=9919||9924<=a&&a<=9933||9935<=a&&a<=9953||a==9955||9960<=a&&a<=9983||a==10045||a==10071||10102<=a&&a<=10111||11093<=a&&a<=11097||12872<=a&&a<=12879||57344<=a&&a<=63743||65024<=a&&a<=65039||a==65533||127232<=a&&a<=127242||127248<=a&&a<=127277||127280<=a&&a<=127337||127344<=a&&a<=127386||917760<=a&&a<=917999||983040<=a&&a<=1048573||1048576<=a&&a<=1114109?"A":"N"},t.characterLength=function(r){var o=this.eastAsianWidth(r);return o=="F"||o=="W"||o=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var o=n(r),s=0,a=0;a<o.length;a++)s=s+this.characterLength(o[a]);return s},t.slice=function(r,o,s){textLen=t.length(r),o=o||0,s=s||1,o<0&&(o=textLen+o),s<0&&(s=textLen+s);for(var a="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],f=t.length(d);if(u>=o-(f==2?1:0))if(u+f<=s)a+=d;else break;u+=f}return a}})(Kc);var jy=Kc.exports;const zy=Jc(jy);var Ly=i(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},"FD");const qy=Jc(Ly);function io(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Hc(e),e.length===0))return 0;e=e.replace(qy()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const o of e){const s=o.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(zy.eastAsianWidth(o)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(io,"p");const Us=10,Yc=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),Xc=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Qc=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Te={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(Te.modifier);const Uy=Object.keys(Te.color),Zy=Object.keys(Te.bgColor);[...Uy,...Zy];function Vy(){const e=new Map;for(const[t,n]of Object.entries(Te)){for(const[r,o]of Object.entries(n))Te[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=Te[r],e.set(o[0],o[1]);Object.defineProperty(Te,t,{value:n,enumerable:!1})}return Object.defineProperty(Te,"codes",{value:e,enumerable:!1}),Te.color.close="\x1B[39m",Te.bgColor.close="\x1B[49m",Te.color.ansi=Yc(),Te.color.ansi256=Xc(),Te.color.ansi16m=Qc(),Te.bgColor.ansi=Yc(Us),Te.bgColor.ansi256=Xc(Us),Te.bgColor.ansi16m=Qc(Us),Object.defineProperties(Te,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Te.rgbToAnsi256(...Te.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Te.ansi256ToAnsi(Te.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Te.ansi256ToAnsi(Te.hexToAnsi256(t)),"value"),enumerable:!1}}),Te}i(Vy,"rD");const Gy=Vy(),sa=new Set(["\x1B","\x9B"]),Wy=39,Zs="\x07",ed="[",Hy="]",td="m",Vs=`${Hy}8;;`,nd=i(e=>`${sa.values().next().value}${ed}${e}${td}`,"z"),rd=i(e=>`${sa.values().next().value}${Vs}${e}${Zs}`,"K"),Jy=i(e=>e.split(" ").map(t=>io(t)),"aD"),Gs=i((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=io(Hc(e[e.length-1]));for(const[u,l]of r.entries()){const c=io(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),sa.has(l)&&(o=!0,s=r.slice(u+1).join("").startsWith(Vs)),o){s?l===Zs&&(o=!1,s=!1):l===td&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),Ky=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(io(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),Yy=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Jy(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let f=io(u[u.length-1]);if(c!==0&&(f>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),f=0),(f>0||n.trim===!1)&&(u[u.length-1]+=" ",f++)),n.hard&&a[c]>t){const m=t-f,D=1+Math.floor((a[c]-m-1)/t);Math.floor((a[c]-1)/t)<D&&u.push(""),Gs(u,d,t);continue}if(f+a[c]>t&&f>0&&a[c]>0){if(n.wordWrap===!1&&f<t){Gs(u,d,t);continue}u.push("")}if(f+a[c]>t&&n.wordWrap===!1){Gs(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Ky(c)));const l=[...u.join(`
28
+ `)];for(const[c,d]of l.entries()){if(r+=d,sa.has(d)){const{groups:m}=new RegExp(`(?:\\${ed}(?<code>\\d+)m|\\${Vs}(?<uri>.*)${Zs})`).exec(l.slice(c).join(""))||{groups:{}};if(m.code!==void 0){const D=Number.parseFloat(m.code);o=D===Wy?void 0:D}else m.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}const f=Gy.codes.get(Number(o));l[c+1]===`
29
+ `?(s&&(r+=rd("")),o&&f&&(r+=nd(f))):d===`
30
+ `&&(o&&f&&(r+=nd(o)),s&&(r+=rd(s)))}return r},"lD");function od(e,t,n){return String(e).normalize().replace(/\r\n/g,`
31
31
  `).split(`
32
- `).map(r=>Jy(r,t,n)).join(`
33
- `)}i(td,"Y$1");const Ky=["up","down","left","right","space","enter","cancel"],ta={actions:new Set(Ky),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function Zs(e,t){if(typeof e=="string")return ta.aliases.get(e)===t;for(const n of e)if(n!==void 0&&Zs(n,t))return!0;return!1}i(Zs,"$");function Yy(e,t){if(e===t)return;const n=e.split(`
32
+ `).map(r=>Yy(r,t,n)).join(`
33
+ `)}i(od,"Y$1");const Xy=["up","down","left","right","space","enter","cancel"],ia={actions:new Set(Xy),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function Ws(e,t){if(typeof e=="string")return ia.aliases.get(e)===t;for(const n of e)if(n!==void 0&&Ws(n,t))return!0;return!1}i(Ws,"$");function Qy(e,t){if(e===t)return;const n=e.split(`
34
34
  `),r=t.split(`
35
- `),o=[];for(let s=0;s<Math.max(n.length,r.length);s++)n[s]!==r[s]&&o.push(s);return o}i(Yy,"BD");const Xy=globalThis.process.platform.startsWith("win"),Vs=Symbol("clack:cancel");function Bn(e){return e===Vs}i(Bn,"pD");function na(e,t){const n=e;n.isTTY&&n.setRawMode(t)}i(na,"m");function Qy({input:e=bl,output:t=Cl,overwrite:n=!0,hideCursor:r=!0}={}){const o=zo.createInterface({input:e,output:t,prompt:"",tabSize:1});zo.emitKeypressEvents(e,o),e.isTTY&&e.setRawMode(!0);const s=i((a,{name:u,sequence:l})=>{const c=String(a);if(Zs([c,u,l],"cancel")){r&&t.write(Xe.cursor.show),process.exit(0);return}if(!n)return;const d=u==="return"?0:-1,f=u==="return"?-1:0;zo.moveCursor(t,d,f,()=>{zo.clearLine(t,1,()=>{e.once("keypress",s)})})},"i");return r&&t.write(Xe.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(Xe.cursor.show),e.isTTY&&!Xy&&e.setRawMode(!1),o.terminal=!1,o.close()}}i(Qy,"fD");var e0=Object.defineProperty,t0=i((e,t,n)=>t in e?e0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"vD"),ft=i((e,t,n)=>(t0(e,typeof t!="symbol"?t+"":t,n),n),"h");const yu=class yu{constructor(t,n=!0){ft(this,"input"),ft(this,"output"),ft(this,"_abortSignal"),ft(this,"rl"),ft(this,"opts"),ft(this,"_render"),ft(this,"_track",!1),ft(this,"_prevFrame",""),ft(this,"_subscribers",new Map),ft(this,"_cursor",0),ft(this,"state","initial"),ft(this,"error",""),ft(this,"value");const{input:r=bl,output:o=Cl,render:s,signal:a,...u}=t;this.opts=u,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=a,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){const r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){const r=this._subscribers.get(t)??[],o=[];for(const s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(const s of o)s()}prompt(){return new Promise((t,n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Vs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new WD;r._write=(o,s,a)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),a()},this.input.pipe(r),this.rl=xl.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),xl.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),na(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Xe.cursor.show),this.output.off("resize",this.render),na(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Xe.cursor.show),this.output.off("resize",this.render),na(this.input,!1),t(Vs)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&ta.aliases.has(n.name)&&this.emit("cursor",ta.aliases.get(n.name)),ta.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),t===" "&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),t&&this.emit("key",t.toLowerCase()),n?.name==="return"){if(this.opts.validate){const r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}Zs([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
36
- `),na(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const t=td(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
37
- `).length-1;this.output.write(Xe.cursor.move(-999,t*-1))}render(){const t=td(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Xe.cursor.hide);else{const n=Yy(this._prevFrame,t);if(this.restoreCursor(),n&&n?.length===1){const r=n[0];this.output.write(Xe.cursor.move(0,r)),this.output.write(Xe.erase.lines(1));const o=t.split(`
35
+ `),o=[];for(let s=0;s<Math.max(n.length,r.length);s++)n[s]!==r[s]&&o.push(s);return o}i(Qy,"BD");const e0=globalThis.process.platform.startsWith("win"),Hs=Symbol("clack:cancel");function Pn(e){return e===Hs}i(Pn,"pD");function ua(e,t){const n=e;n.isTTY&&n.setRawMode(t)}i(ua,"m");function t0({input:e=Fl,output:t=El,overwrite:n=!0,hideCursor:r=!0}={}){const o=Zo.createInterface({input:e,output:t,prompt:"",tabSize:1});Zo.emitKeypressEvents(e,o),e.isTTY&&e.setRawMode(!0);const s=i((a,{name:u,sequence:l})=>{const c=String(a);if(Ws([c,u,l],"cancel")){r&&t.write(Xe.cursor.show),process.exit(0);return}if(!n)return;const d=u==="return"?0:-1,f=u==="return"?-1:0;Zo.moveCursor(t,d,f,()=>{Zo.clearLine(t,1,()=>{e.once("keypress",s)})})},"i");return r&&t.write(Xe.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(Xe.cursor.show),e.isTTY&&!e0&&e.setRawMode(!1),o.terminal=!1,o.close()}}i(t0,"fD");var n0=Object.defineProperty,r0=i((e,t,n)=>t in e?n0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"vD"),mt=i((e,t,n)=>(r0(e,typeof t!="symbol"?t+"":t,n),n),"h");const Cu=class Cu{constructor(t,n=!0){mt(this,"input"),mt(this,"output"),mt(this,"_abortSignal"),mt(this,"rl"),mt(this,"opts"),mt(this,"_render"),mt(this,"_track",!1),mt(this,"_prevFrame",""),mt(this,"_subscribers",new Map),mt(this,"_cursor",0),mt(this,"state","initial"),mt(this,"error",""),mt(this,"value");const{input:r=Fl,output:o=El,render:s,signal:a,...u}=t;this.opts=u,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=a,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){const r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){const r=this._subscribers.get(t)??[],o=[];for(const s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(const s of o)s()}prompt(){return new Promise((t,n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Hs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new JD;r._write=(o,s,a)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),a()},this.input.pipe(r),this.rl=Al.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),Al.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),ua(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Xe.cursor.show),this.output.off("resize",this.render),ua(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Xe.cursor.show),this.output.off("resize",this.render),ua(this.input,!1),t(Hs)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&ia.aliases.has(n.name)&&this.emit("cursor",ia.aliases.get(n.name)),ia.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),t===" "&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),t&&this.emit("key",t.toLowerCase()),n?.name==="return"){if(this.opts.validate){const r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}Ws([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
36
+ `),ua(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const t=od(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
37
+ `).length-1;this.output.write(Xe.cursor.move(-999,t*-1))}render(){const t=od(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Xe.cursor.hide);else{const n=Qy(this._prevFrame,t);if(this.restoreCursor(),n&&n?.length===1){const r=n[0];this.output.write(Xe.cursor.move(0,r)),this.output.write(Xe.erase.lines(1));const o=t.split(`
38
38
  `);this.output.write(o[r]),this._prevFrame=t,this.output.write(Xe.cursor.move(0,o.length-r-1));return}if(n&&n?.length>1){const r=n[0];this.output.write(Xe.cursor.move(0,r)),this.output.write(Xe.erase.down());const o=t.split(`
39
39
  `).slice(r);this.output.write(o.join(`
40
- `)),this._prevFrame=t;return}this.output.write(Xe.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};i(yu,"x");let On=yu;const _u=class _u extends On{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Xe.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};i(_u,"dD");let Gs=_u;var n0=Object.defineProperty,r0=i((e,t,n)=>t in e?n0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"jD"),nd=i((e,t,n)=>(r0(e,typeof t!="symbol"?t+"":t,n),n),"U");const bu=class bu extends On{constructor({mask:t,...n}){super(n),nd(this,"valueWithCursor",""),nd(this,"_mask","\u2022"),this._mask=t??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${q.inverse(q.hidden("_"))}`;else{const r=this.masked.slice(0,this.cursor),o=this.masked.slice(this.cursor);this.valueWithCursor=`${r}${q.inverse(o[0])}${o.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};i(bu,"MD");let Ws=bu;var o0=Object.defineProperty,a0=i((e,t,n)=>t in e?o0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),rd=i((e,t,n)=>(a0(e,typeof t!="symbol"?t+"":t,n),n),"J");const Cu=class Cu extends On{constructor(t){super(t,!1),rd(this,"options"),rd(this,"cursor",0),this.options=t.options,this.cursor=this.options.findIndex(({value:n})=>n===t.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",n=>{switch(n){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}};i(Cu,"LD");let Hs=Cu;const wu=class wu extends On{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;const t=this.value.slice(0,this.cursor),[n,...r]=this.value.slice(this.cursor);return`${t}${q.inverse(n)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}};i(wu,"RD");let Js=wu;function s0(){return qe.platform!=="win32"?qe.env.TERM!=="linux":!!qe.env.CI||!!qe.env.WT_SESSION||!!qe.env.TERMINUS_SUBLIME||qe.env.ConEmuTask==="{cmd::Cmder}"||qe.env.TERM_PROGRAM==="Terminus-Sublime"||qe.env.TERM_PROGRAM==="vscode"||qe.env.TERM==="xterm-256color"||qe.env.TERM==="alacritty"||qe.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}i(s0,"ce");const Ks=s0(),Bt=i((e,t)=>Ks?e:t,"u"),i0=Bt("\u25C6","*"),od=Bt("\u25A0","x"),ad=Bt("\u25B2","x"),sd=Bt("\u25C7","o"),u0=Bt("\u250C","T"),Fe=Bt("\u2502","|"),un=Bt("\u2514","\u2014"),Ys=Bt("\u25CF",">"),Xs=Bt("\u25CB"," "),l0=Bt("\u25AA","\u2022"),ra=i(e=>{switch(e){case"initial":case"active":return q.cyan(i0);case"cancel":return q.red(od);case"error":return q.yellow(ad);case"submit":return q.green(sd)}},"b"),c0=i(e=>{const{cursor:t,options:n,style:r}=e,o=e.maxItems??Number.POSITIVE_INFINITY,s=Math.max(process.stdout.rows-4,0),a=Math.min(s,Math.max(o,5));let u=0;t>=u+a-3?u=Math.max(Math.min(t-a+3,n.length-a),0):t<u+2&&(u=Math.max(t-2,0));const l=a<n.length&&u>0,c=a<n.length&&u+a<n.length;return n.slice(u,u+a).map((d,f,h)=>{const D=f===0&&l,m=f===h.length-1&&c;return D||m?q.dim("..."):r(d,f+u===t)})},"G"),id=i(e=>new Js({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${q.gray(Fe)}
41
- ${ra(this.state)} ${e.message}
42
- `,n=e.placeholder?q.inverse(e.placeholder[0])+q.dim(e.placeholder.slice(1)):q.inverse(q.hidden("_")),r=this.value?this.valueWithCursor:n;switch(this.state){case"error":return`${t.trim()}
43
- ${q.yellow(Fe)} ${r}
44
- ${q.yellow(un)} ${q.yellow(this.error)}
45
- `;case"submit":return`${t}${q.gray(Fe)} ${q.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${q.gray(Fe)} ${q.strikethrough(q.dim(this.value??""))}${this.value?.trim()?`
46
- ${q.gray(Fe)}`:""}`;default:return`${t}${q.cyan(Fe)} ${r}
47
- ${q.cyan(un)}
48
- `}}}).prompt(),"he"),d0=i(e=>new Ws({validate:e.validate,mask:e.mask??l0,render(){const t=`${q.gray(Fe)}
49
- ${ra(this.state)} ${e.message}
40
+ `)),this._prevFrame=t;return}this.output.write(Xe.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};i(Cu,"x");let Mn=Cu;const wu=class wu extends Mn{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",n=>{this.output.write(Xe.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};i(wu,"dD");let Js=wu;var o0=Object.defineProperty,a0=i((e,t,n)=>t in e?o0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"jD"),ad=i((e,t,n)=>(a0(e,typeof t!="symbol"?t+"":t,n),n),"U");const Fu=class Fu extends Mn{constructor({mask:t,...n}){super(n),ad(this,"valueWithCursor",""),ad(this,"_mask","\u2022"),this._mask=t??"\u2022",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${L.inverse(L.hidden("_"))}`;else{const r=this.masked.slice(0,this.cursor),o=this.masked.slice(this.cursor);this.valueWithCursor=`${r}${L.inverse(o[0])}${o.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};i(Fu,"MD");let Ks=Fu;var s0=Object.defineProperty,i0=i((e,t,n)=>t in e?s0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),sd=i((e,t,n)=>(i0(e,typeof t!="symbol"?t+"":t,n),n),"J");const Eu=class Eu extends Mn{constructor(t){super(t,!1),sd(this,"options"),sd(this,"cursor",0),this.options=t.options,this.cursor=this.options.findIndex(({value:n})=>n===t.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",n=>{switch(n){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}};i(Eu,"LD");let Ys=Eu;const xu=class xu extends Mn{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;const t=this.value.slice(0,this.cursor),[n,...r]=this.value.slice(this.cursor);return`${t}${L.inverse(n)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}};i(xu,"RD");let Xs=xu;function u0(){return Le.platform!=="win32"?Le.env.TERM!=="linux":!!Le.env.CI||!!Le.env.WT_SESSION||!!Le.env.TERMINUS_SUBLIME||Le.env.ConEmuTask==="{cmd::Cmder}"||Le.env.TERM_PROGRAM==="Terminus-Sublime"||Le.env.TERM_PROGRAM==="vscode"||Le.env.TERM==="xterm-256color"||Le.env.TERM==="alacritty"||Le.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}i(u0,"ce");const Qs=u0(),Bt=i((e,t)=>Qs?e:t,"u"),l0=Bt("\u25C6","*"),id=Bt("\u25A0","x"),ud=Bt("\u25B2","x"),ld=Bt("\u25C7","o"),c0=Bt("\u250C","T"),Ee=Bt("\u2502","|"),fn=Bt("\u2514","\u2014"),ei=Bt("\u25CF",">"),ti=Bt("\u25CB"," "),d0=Bt("\u25AA","\u2022"),la=i(e=>{switch(e){case"initial":case"active":return L.cyan(l0);case"cancel":return L.red(id);case"error":return L.yellow(ud);case"submit":return L.green(ld)}},"b"),p0=i(e=>{const{cursor:t,options:n,style:r}=e,o=e.maxItems??Number.POSITIVE_INFINITY,s=Math.max(process.stdout.rows-4,0),a=Math.min(s,Math.max(o,5));let u=0;t>=u+a-3?u=Math.max(Math.min(t-a+3,n.length-a),0):t<u+2&&(u=Math.max(t-2,0));const l=a<n.length&&u>0,c=a<n.length&&u+a<n.length;return n.slice(u,u+a).map((d,f,m)=>{const D=f===0&&l,h=f===m.length-1&&c;return D||h?L.dim("..."):r(d,f+u===t)})},"G"),cd=i(e=>new Xs({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${L.gray(Ee)}
41
+ ${la(this.state)} ${e.message}
42
+ `,n=e.placeholder?L.inverse(e.placeholder[0])+L.dim(e.placeholder.slice(1)):L.inverse(L.hidden("_")),r=this.value?this.valueWithCursor:n;switch(this.state){case"error":return`${t.trim()}
43
+ ${L.yellow(Ee)} ${r}
44
+ ${L.yellow(fn)} ${L.yellow(this.error)}
45
+ `;case"submit":return`${t}${L.gray(Ee)} ${L.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${L.gray(Ee)} ${L.strikethrough(L.dim(this.value??""))}${this.value?.trim()?`
46
+ ${L.gray(Ee)}`:""}`;default:return`${t}${L.cyan(Ee)} ${r}
47
+ ${L.cyan(fn)}
48
+ `}}}).prompt(),"he"),f0=i(e=>new Ks({validate:e.validate,mask:e.mask??d0,render(){const t=`${L.gray(Ee)}
49
+ ${la(this.state)} ${e.message}
50
50
  `,n=this.valueWithCursor,r=this.masked;switch(this.state){case"error":return`${t.trim()}
51
- ${q.yellow(Fe)} ${r}
52
- ${q.yellow(un)} ${q.yellow(this.error)}
53
- `;case"submit":return`${t}${q.gray(Fe)} ${q.dim(r)}`;case"cancel":return`${t}${q.gray(Fe)} ${q.strikethrough(q.dim(r??""))}${r?`
54
- ${q.gray(Fe)}`:""}`;default:return`${t}${q.cyan(Fe)} ${n}
55
- ${q.cyan(un)}
56
- `}}}).prompt(),"ge"),p0=i(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Gs({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${q.gray(Fe)}
57
- ${ra(this.state)} ${e.message}
58
- `,o=this.value?t:n;switch(this.state){case"submit":return`${r}${q.gray(Fe)} ${q.dim(o)}`;case"cancel":return`${r}${q.gray(Fe)} ${q.strikethrough(q.dim(o))}
59
- ${q.gray(Fe)}`;default:return`${r}${q.cyan(Fe)} ${this.value?`${q.green(Ys)} ${t}`:`${q.dim(Xs)} ${q.dim(t)}`} ${q.dim("/")} ${this.value?`${q.dim(Xs)} ${q.dim(n)}`:`${q.green(Ys)} ${n}`}
60
- ${q.cyan(un)}
61
- `}}}).prompt()},"ye"),Qs=i(e=>{const t=i((n,r)=>{const o=n.label??String(n.value);switch(r){case"selected":return`${q.dim(o)}`;case"active":return`${q.green(Ys)} ${o} ${n.hint?q.dim(`(${n.hint})`):""}`;case"cancelled":return`${q.strikethrough(q.dim(o))}`;default:return`${q.dim(Xs)} ${q.dim(o)}`}},"n");return new Hs({options:e.options,initialValue:e.initialValue,render(){const n=`${q.gray(Fe)}
62
- ${ra(this.state)} ${e.message}
63
- `;switch(this.state){case"submit":return`${n}${q.gray(Fe)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${q.gray(Fe)} ${t(this.options[this.cursor],"cancelled")}
64
- ${q.gray(Fe)}`;default:return`${n}${q.cyan(Fe)} ${c0({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:i((r,o)=>t(r,o?"active":"inactive"),"style")}).join(`
65
- ${q.cyan(Fe)} `)}
66
- ${q.cyan(un)}
67
- `}}}).prompt()},"ve"),oa=i((e="")=>{process.stdout.write(`${q.gray(u0)} ${e}
68
- `)},"Ie"),Ee=i((e="")=>{process.stdout.write(`${q.gray(Fe)}
69
- ${q.gray(un)} ${e}
70
-
71
- `)},"Se");`${q.gray(Fe)}`;const Vt=i(({indicator:e="dots"}={})=>{const t=Ks?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Ks?80:120,r=process.env.CI==="true";let o,s,a=!1,u="",l,c=performance.now();const d=i(E=>{const T=E>1?"Something went wrong":"Canceled";a&&w(T,E)},"p"),f=i(()=>d(2),"v"),h=i(()=>d(1),"f"),D=i(()=>{process.on("uncaughtExceptionMonitor",f),process.on("unhandledRejection",f),process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",d)},"j"),m=i(()=>{process.removeListener("uncaughtExceptionMonitor",f),process.removeListener("unhandledRejection",f),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),process.removeListener("exit",d)},"E"),v=i(()=>{if(l===void 0)return;r&&process.stdout.write(`
51
+ ${L.yellow(Ee)} ${r}
52
+ ${L.yellow(fn)} ${L.yellow(this.error)}
53
+ `;case"submit":return`${t}${L.gray(Ee)} ${L.dim(r)}`;case"cancel":return`${t}${L.gray(Ee)} ${L.strikethrough(L.dim(r??""))}${r?`
54
+ ${L.gray(Ee)}`:""}`;default:return`${t}${L.cyan(Ee)} ${n}
55
+ ${L.cyan(fn)}
56
+ `}}}).prompt(),"ge"),m0=i(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Js({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${L.gray(Ee)}
57
+ ${la(this.state)} ${e.message}
58
+ `,o=this.value?t:n;switch(this.state){case"submit":return`${r}${L.gray(Ee)} ${L.dim(o)}`;case"cancel":return`${r}${L.gray(Ee)} ${L.strikethrough(L.dim(o))}
59
+ ${L.gray(Ee)}`;default:return`${r}${L.cyan(Ee)} ${this.value?`${L.green(ei)} ${t}`:`${L.dim(ti)} ${L.dim(t)}`} ${L.dim("/")} ${this.value?`${L.dim(ti)} ${L.dim(n)}`:`${L.green(ei)} ${n}`}
60
+ ${L.cyan(fn)}
61
+ `}}}).prompt()},"ye"),ni=i(e=>{const t=i((n,r)=>{const o=n.label??String(n.value);switch(r){case"selected":return`${L.dim(o)}`;case"active":return`${L.green(ei)} ${o} ${n.hint?L.dim(`(${n.hint})`):""}`;case"cancelled":return`${L.strikethrough(L.dim(o))}`;default:return`${L.dim(ti)} ${L.dim(o)}`}},"n");return new Ys({options:e.options,initialValue:e.initialValue,render(){const n=`${L.gray(Ee)}
62
+ ${la(this.state)} ${e.message}
63
+ `;switch(this.state){case"submit":return`${n}${L.gray(Ee)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${L.gray(Ee)} ${t(this.options[this.cursor],"cancelled")}
64
+ ${L.gray(Ee)}`;default:return`${n}${L.cyan(Ee)} ${p0({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:i((r,o)=>t(r,o?"active":"inactive"),"style")}).join(`
65
+ ${L.cyan(Ee)} `)}
66
+ ${L.cyan(fn)}
67
+ `}}}).prompt()},"ve"),ca=i((e="")=>{process.stdout.write(`${L.gray(c0)} ${e}
68
+ `)},"Ie"),be=i((e="")=>{process.stdout.write(`${L.gray(Ee)}
69
+ ${L.gray(fn)} ${e}
70
+
71
+ `)},"Se");`${L.gray(Ee)}`;const Ot=i(({indicator:e="dots"}={})=>{const t=Qs?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Qs?80:120,r=process.env.CI==="true";let o,s,a=!1,u="",l,c=performance.now();const d=i(E=>{const T=E>1?"Something went wrong":"Canceled";a&&w(T,E)},"p"),f=i(()=>d(2),"v"),m=i(()=>d(1),"f"),D=i(()=>{process.on("uncaughtExceptionMonitor",f),process.on("unhandledRejection",f),process.on("SIGINT",m),process.on("SIGTERM",m),process.on("exit",d)},"j"),h=i(()=>{process.removeListener("uncaughtExceptionMonitor",f),process.removeListener("unhandledRejection",f),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),process.removeListener("exit",d)},"E"),v=i(()=>{if(l===void 0)return;r&&process.stdout.write(`
72
72
  `);const E=l.split(`
73
- `);process.stdout.write(Xe.cursor.move(-999,E.length-1)),process.stdout.write(Xe.erase.down(E.length))},"B"),y=i(E=>E.replace(/\.+$/,""),"R"),b=i(E=>{const T=(performance.now()-E)/1e3,O=Math.floor(T/60),$=Math.floor(T%60);return O>0?`[${O}m ${$}s]`:`[${$}s]`},"O"),C=i((E="")=>{a=!0,o=Qy(),u=y(E),c=performance.now(),process.stdout.write(`${q.gray(Fe)}
74
- `);let T=0,O=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const $=q.magenta(t[T]);if(r)process.stdout.write(`${$} ${u}...`);else if(e==="timer")process.stdout.write(`${$} ${u} ${b(c)}`);else{const I=".".repeat(Math.floor(O)).slice(0,3);process.stdout.write(`${$} ${u}${I}`)}T=T+1<t.length?T+1:0,O=O<t.length?O+.125:0},n)},"H"),w=i((E="",T=0)=>{a=!1,clearInterval(s),v();const O=T===0?q.green(sd):T===1?q.red(od):q.red(ad);u=y(E??u),e==="timer"?process.stdout.write(`${O} ${u} ${b(c)}
73
+ `);process.stdout.write(Xe.cursor.move(-999,E.length-1)),process.stdout.write(Xe.erase.down(E.length))},"B"),y=i(E=>E.replace(/\.+$/,""),"R"),b=i(E=>{const T=(performance.now()-E)/1e3,O=Math.floor(T/60),$=Math.floor(T%60);return O>0?`[${O}m ${$}s]`:`[${$}s]`},"O"),C=i((E="")=>{a=!0,o=t0(),u=y(E),c=performance.now(),process.stdout.write(`${L.gray(Ee)}
74
+ `);let T=0,O=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const $=L.magenta(t[T]);if(r)process.stdout.write(`${$} ${u}...`);else if(e==="timer")process.stdout.write(`${$} ${u} ${b(c)}`);else{const I=".".repeat(Math.floor(O)).slice(0,3);process.stdout.write(`${$} ${u}${I}`)}T=T+1<t.length?T+1:0,O=O<t.length?O+.125:0},n)},"H"),w=i((E="",T=0)=>{a=!1,clearInterval(s),v();const O=T===0?L.green(ld):T===1?L.red(id):L.red(ud);u=y(E??u),e==="timer"?process.stdout.write(`${O} ${u} ${b(c)}
75
75
  `):process.stdout.write(`${O} ${u}
76
- `),m(),o()},"N");return{start:C,stop:w,message:i((E="")=>{u=y(E??u)},"message")}},"Y");var oo=Object.freeze({__proto__:null,confirm:p0,intro:oa,isCancel:Bn,outro:Ee,password:d0,select:Qs,spinner:Vt,text:id});const{version:f0}=gs,Fu=class Fu extends Error{};i(Fu,"KnownError");let pe=Fu;const ei=" ",ud=i(e=>{e instanceof Error&&!(e instanceof pe)&&(e.stack&&console.error(Ns(e.stack.split(`
76
+ `),h(),o()},"N");return{start:C,stop:w,message:i((E="")=>{u=y(E??u)},"message")}},"Y");var uo=Object.freeze({__proto__:null,confirm:m0,intro:ca,isCancel:Pn,outro:be,password:f0,select:ni,spinner:Ot,text:cd});const{version:h0}=Vt,ku=class ku extends Error{};i(ku,"KnownError");let ce=ku;const ri=" ",dd=i(e=>{e instanceof Error&&!(e instanceof ce)&&(e.stack&&console.error(so(e.stack.split(`
77
77
  `).slice(1).join(`
78
78
  `))),console.error(`
79
- ${ei}${Ns(`aicommits v${f0}`)}`),console.error(`
80
- ${ei}Please open a Bug report with the information above:`),console.error(`${ei}https://github.com/Nutlope/aicommits/issues/new/choose`))},"handleCliError"),Rn=i(e=>{process.stderr.write(`${Ps("\u2716")} ${e.message}
81
- `),ud(e),process.exit(1)},"handleCommandError"),ti=i(async()=>{const{stdout:e,failed:t}=await Je("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new pe("The current directory must be a Git repository!");return e},"assertGitRepo"),aa=i(e=>`:(exclude)${e}`,"excludeFromDiff"),ld=["package-lock.json","pnpm-lock.yaml","*.lock"],m0=i(e=>ld.some(t=>t.includes("*")?e.endsWith(".lock"):e.endsWith("/"+t)||e===t),"isLockFile"),cd=ld.map(aa),dd=i(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await Je("git",[...t,"--name-only",...e?e.map(aa):[]]);if(!n)return;const o=n.split(`
82
- `).filter(Boolean).some(l=>!m0(l));let s=[];o&&(s=[...cd]),s=[...s,...e?e.map(aa):[]];const{stdout:a}=await Je("git",[...t,"--name-only",...s]);if(!a)return;const{stdout:u}=await Je("git",[...t,...s]);return{files:a.split(`
83
- `),diff:u}},"getStagedDiff"),h0=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...cd,...t?t.map(aa):[]],{stdout:o}=await Je("git",[...n,"--",...e,...r]);return{files:e,diff:o}},"getStagedDiffForFiles"),pd=i(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var ni,fd;function D0(){if(fd)return ni;fd=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
79
+ ${ri}${so(`aicommits v${h0}`)}`),console.error(`
80
+ ${ri}Please open a Bug report with the information above:`),console.error(`${ri}https://github.com/Nutlope/aicommits/issues/new/choose`))},"handleCliError"),mn=i(e=>{process.stderr.write(`${Wt("\u2716")} ${e.message}
81
+ `),dd(e),process.exit(1)},"handleCommandError"),oi=i(async()=>{const{stdout:e,failed:t}=await Je("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new ce("The current directory must be a Git repository!");return e},"assertGitRepo"),da=i(e=>`:(exclude)${e}`,"excludeFromDiff"),pd=["package-lock.json","pnpm-lock.yaml","*.lock"],D0=i(e=>pd.some(t=>t.includes("*")?e.endsWith(".lock"):e.endsWith("/"+t)||e===t),"isLockFile"),fd=pd.map(da),md=i(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await Je("git",[...t,"--name-only",...e?e.map(da):[]]);if(!n)return;const o=n.split(`
82
+ `).filter(Boolean).some(l=>!D0(l));let s=[];o&&(s=[...fd]),s=[...s,...e?e.map(da):[]];const{stdout:a}=await Je("git",[...t,"--name-only",...s]);if(!a)return;const{stdout:u}=await Je("git",[...t,...s]);return{files:a.split(`
83
+ `),diff:u}},"getStagedDiff"),g0=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...fd,...t?t.map(da):[]],{stdout:o}=await Je("git",[...n,"--",...e,...r]);return{files:e,diff:o}},"getStagedDiffForFiles"),hd=i(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var ai,Dd;function v0(){if(Dd)return ai;Dd=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
84
84
  `:`
85
- `,n=i((l,c)=>{const d=[];let f="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const m=l[D];if(m&&Array.isArray(m))for(const v of m)f+=a(D+"[]")+h+a(v)+t;else m&&typeof m=="object"?d.push(D):f+=a(D)+h+a(m)+t}c.section&&f.length&&(f="["+a(c.section)+"]"+t+f);for(const D of d){const m=r(D).join("\\."),v=(c.section?c.section+".":"")+m,{whitespace:y}=c,b=n(l[D],{section:v,whitespace:y});f.length&&b.length&&(f+=t),f+=b}return f},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),o=i(l=>{const c=Object.create(null);let d=c,f=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(h);if(!y)continue;if(y[1]!==void 0){if(f=u(y[1]),f==="__proto__"){d=Object.create(null);continue}d=c[f]=c[f]||Object.create(null);continue}const b=u(y[2]),C=b.length>2&&b.slice(-2)==="[]",w=C?b.slice(0,-2):b;if(w==="__proto__")continue;const E=y[3]?u(y[4]):!0,T=E==="true"||E==="false"||E==="null"?JSON.parse(E):E;C&&(e.call(d,w)?Array.isArray(d[w])||(d[w]=[d[w]]):d[w]=[]),Array.isArray(d[w])?d[w].push(T):d[w]=T}const m=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const b=y.pop(),C=b.replace(/\\\./g,".");for(const w of y)w!=="__proto__"&&((!e.call(d,w)||typeof d[w]!="object")&&(d[w]=Object.create(null)),d=d[w]);d===c&&C===b||(d[C]=c[v],m.push(v))}for(const v of m)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),a=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,f="";for(let h=0,D=l.length;h<D;h++){const m=l.charAt(h);if(d)"\\;#".indexOf(m)!==-1?f+=m:f+="\\"+m,d=!1;else{if(";#".indexOf(m)!==-1)break;m==="\\"?d=!0:f+=m}}return d&&(f+="\\"),f.trim()}return l},"unsafe");return ni={parse:o,decode:o,stringify:n,encode:n,safe:a,unsafe:u},ni}i(D0,"requireIni");var g0=D0(),md=rn(g0);const ri=i(e=>He.lstat(e).then(()=>!0,()=>!1),"fileExists"),v0=["plain","conventional","gitmoji"],{hasOwnProperty:y0}=Object.prototype,oi=i((e,t)=>y0.call(e,t),"hasOwn"),Ot=i((e,t,n)=>{if(!t)throw new pe(`Invalid config property ${e}: ${n}`)},"parseAssert"),sa={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Ot("locale",!!e,"Cannot be empty"),Ot("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Ot("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("generate",t>0,"Must be greater than 0"),Ot("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Ot("type",v0.includes(e),"Invalid commit type"),e):"plain"},proxy(e){if(!(!e||e.length===0))throw new pe('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Ot("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Ot("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("max-length",t>=20,"Must be greater than 20 characters"),t}},_0={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["Qwen/Qwen3-Next-80B-A3B-Instruct","zai-org/GLM-4.5-Air-FP8","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"],requiresApiKey:!0},b0={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},C0={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},w0={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},F0={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0,headers:{"HTTP-Referer":"https://github.com/nutlope/aicommits","X-Title":"aicommits"}},E0={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},x0={name:"groq",displayName:"Groq",baseUrl:"https://api.groq.com/openai/v1",apiKeyFormat:"gsk_",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-120b","llama-3.1-8b-instant","openai/gpt-oss-20b"],requiresApiKey:!0},k0={name:"xai",displayName:"xAI",baseUrl:"https://api.x.ai/v1",apiKeyFormat:"xai-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["grok-4.1-fast","grok-4-fast","grok-code-fast-1"],requiresApiKey:!0},ao=[_0,b0,x0,k0,C0,E0,F0,w0],I0=i(()=>ao.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),A0=i((e,t)=>{if(e){const n=ao.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),ai=i(()=>bt.join(kl.homedir(),".aicommits"),"getConfigPath"),hd=i(async()=>{if(!await ri(ai()))return Object.create(null);const t=await He.readFile(ai(),"utf8");return md.parse(t)},"readConfigFile"),ln=i(async(e,t,n)=>{const r=await hd();oi(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const o={},s=t??{};for(const c of Object.keys(sa)){const d=sa[c],f=e?.[c]??s?.[c]??r[c];if(n)try{o[c]=d(f)}catch{}else o[c]=d(f)}let a,u=o.OPENAI_BASE_URL;const l=o.OPENAI_API_KEY;return!u&&l&&(u=I0(),o.OPENAI_BASE_URL=u),a=A0(u,l),{...o,model:o.OPENAI_MODEL,provider:a}},"getConfig"),si=i(async e=>{const t=await hd();for(const[n,r]of e){if(!oi(sa,n))throw new pe(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const o=sa[n](r);t[n]=o}}await He.writeFile(ai(),md.stringify(t),"utf8")},"setConfigs"),Dd=i(e=>`\u2705 ${e} (current)`,"CURRENT_LABEL_FORMAT"),$0=3600*1e3,gd=i(()=>{const e=process.platform,t=kl.homedir();if(e==="darwin")return bt.join(t,"Library","Caches","aicommits","models");if(e==="win32")return bt.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||bt.join(t,".cache");return bt.join(r,"aicommits","models")}},"getCacheDir"),T0=i(e=>{const t=HD.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),vd=i(e=>bt.join(gd(),`${e}.json`),"getCachePath"),S0=i(async e=>{const t=vd(e);try{if(!await ri(t))return null;const n=await He.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),B0=i(async(e,t)=>{try{const n=gd();await He.mkdir(n,{recursive:!0});const r=vd(e);await He.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),ii=i(async(e,t)=>{const n=T0(e),r=Date.now(),o=await S0(n);if(o&&r-o.timestamp<$0)return o.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),u=(a.data?a.data:a)||[],l={models:u};return u.length>0&&await B0(n,{data:l,timestamp:r}),l}catch(s){const a=s instanceof Error?s.message:"Request failed";return{models:[],error:a}}},"fetchModels"),O0=i(async(e,t,n)=>{const r=await ii(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let o=[];return n?.modelsFilter?o=n.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),o},"fetchAndFilterModels"),R0=i((e,t,n)=>{let r=e.map(o=>({label:o,value:o}));if(n?.defaultModels&&n.defaultModels.length>0){const o=n.defaultModels.filter(s=>r.some(a=>a.value===s));o.forEach(s=>{const a=r.findIndex(u=>u.value===s);a>=0&&r.splice(a,1)}),o.forEach((s,a)=>{const u=s===t,l=a===0;let c;u?c=`\u2705 ${s} (current)`:l?c=`\u{1F451} ${s} (default)`:c=`\u{1F525} ${s}`,r.unshift({label:c,value:s})})}if(t&&t!=="undefined"){const o=n?.defaultModels?.includes(t),s=r.findIndex(a=>a.value===t);if(s>=0&&!o){if(r[s].label=Dd(r[s].value),s>0){const[a]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,a)}}else if(s<0&&!o){const a=n?.defaultModels?.length||0;r.splice(a,0,{label:Dd(t),value:t})}}return r},"prepareModelOptions"),N0=i(async(e,t,n,r)=>{const o=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(o))return null;let s=e;o&&(s=e.filter(l=>l.toLowerCase().includes(o.toLowerCase())));let a=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${o}"):`,options:[...a,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),P0=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Bn(t)?null:t},"handleCustom"),yd=i(async(e,t,n,r,o)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const s=Vt();s.start("Fetching available models...");const a=await O0(e,t,r);s.stop(`${o||"Provider"}: ${a.length} models available`);let u=null;if(a.length>0){const{select:l,text:c,isCancel:d}=await Promise.resolve().then(function(){return oo});let f=R0(a,n,r);const h=10;f.length>h&&(f=f.slice(0,h));let D=await l({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...f,{label:"Custom model name...",value:"custom"}],initialValue:f.length>0?f[0].value:void 0});if(d(D))return null;if(D==="search"){const m=await N0(a,l,c,d);if(m===null)return null;D=m}if(D==="custom"){if(u=await P0(c),u===null)return null}else u=D}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:l,isCancel:c}=await Promise.resolve().then(function(){return oo});try{const d=await l({message:"Enter your model name:",validate:i(f=>{if(!f)return"Model name is required"},"validate")});if(c(d))return null;u=d}catch{return null}}return u},"selectModel");var M0=Object.freeze({__proto__:null,fetchModels:ii,selectModel:yd}),j0=Object.defineProperty,z0=i((e,t,n)=>t in e?j0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),_d=i((e,t,n)=>z0(e,typeof t!="symbol"?t+"":t,n),"__publicField");const Eu=class Eu{constructor(t,n){_d(this,"config"),_d(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return oo}),o=[];if(this.def.requiresApiKey){const s=this.getApiKey(),a=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(a))throw new Error("Setup cancelled");a&&o.push(["OPENAI_API_KEY",a])}if(this.name==="ollama"){const s=this.getBaseUrl(),a=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(a))throw new Error("Setup cancelled");a&&a!=="http://localhost:11434/v1"&&o.push(["OPENAI_BASE_URL",a])}return o}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await ii(t,n);if(r.error)return{models:[],error:r.error};let o;return this.def.modelsFilter?o=this.def.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),{models:o}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}getHeaders(){return this.def.headers}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(Eu,"Provider");let ui=Eu;function Nn(e){const t=e.provider,n=ao.find(r=>r.name===t);return n?new ui(n,e):null}i(Nn,"getProvider");function q0(){return ao.map(e=>({value:e.name,label:e.displayName}))}i(q0,"getAvailableProviders");function L0(e){return ao.find(n=>n.name===e)?.baseUrl||""}i(L0,"getProviderBaseUrl");var bd="vercel.ai.error",U0=Symbol.for(bd),Cd,wd,Q=(Cn=class extends(wd=Error,Cd=U0,wd){constructor({name:t,message:n,cause:r}){super(n),this[Cd]=!0,this.name=t,this.cause=r}static isInstance(t){return Cn.hasMarker(t,bd)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(Cn,"_AISDKError"),Cn),Fd="AI_APICallError",Ed=`vercel.ai.error.${Fd}`,Z0=Symbol.for(Ed),xd,kd,Be=(Kn=class extends(kd=Q,xd=Z0,kd){constructor({message:t,url:n,requestBodyValues:r,statusCode:o,responseHeaders:s,responseBody:a,cause:u,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Fd,message:t,cause:u}),this[xd]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return Q.hasMarker(t,Ed)}},i(Kn,"APICallError"),Kn),Id="AI_EmptyResponseBodyError",Ad=`vercel.ai.error.${Id}`,V0=Symbol.for(Ad),$d,Td,G0=(Yn=class extends(Td=Q,$d=V0,Td){constructor({message:t="Empty response body"}={}){super({name:Id,message:t}),this[$d]=!0}static isInstance(t){return Q.hasMarker(t,Ad)}},i(Yn,"EmptyResponseBodyError"),Yn);function so(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(so,"getErrorMessage$1");var Sd="AI_InvalidArgumentError",Bd=`vercel.ai.error.${Sd}`,W0=Symbol.for(Bd),Od,Rd,Nd=(Xn=class extends(Rd=Q,Od=W0,Rd){constructor({message:t,cause:n,argument:r}){super({name:Sd,message:t,cause:n}),this[Od]=!0,this.argument=r}static isInstance(t){return Q.hasMarker(t,Bd)}},i(Xn,"InvalidArgumentError"),Xn),Pd="AI_InvalidPromptError",Md=`vercel.ai.error.${Pd}`,H0=Symbol.for(Md),jd,zd,Gt=(Qn=class extends(zd=Q,jd=H0,zd){constructor({prompt:t,message:n,cause:r}){super({name:Pd,message:`Invalid prompt: ${n}`,cause:r}),this[jd]=!0,this.prompt=t}static isInstance(t){return Q.hasMarker(t,Md)}},i(Qn,"InvalidPromptError"),Qn),qd="AI_InvalidResponseDataError",Ld=`vercel.ai.error.${qd}`,J0=Symbol.for(Ld),Ud,Zd,io=(er=class extends(Zd=Q,Ud=J0,Zd){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:qd,message:n}),this[Ud]=!0,this.data=t}static isInstance(t){return Q.hasMarker(t,Ld)}},i(er,"InvalidResponseDataError"),er),Vd="AI_JSONParseError",Gd=`vercel.ai.error.${Vd}`,K0=Symbol.for(Gd),Wd,Hd,ia=(tr=class extends(Hd=Q,Wd=K0,Hd){constructor({text:t,cause:n}){super({name:Vd,message:`JSON parsing failed: Text: ${t}.
86
- Error message: ${so(n)}`,cause:n}),this[Wd]=!0,this.text=t}static isInstance(t){return Q.hasMarker(t,Gd)}},i(tr,"JSONParseError"),tr),Jd="AI_LoadAPIKeyError",Kd=`vercel.ai.error.${Jd}`,Y0=Symbol.for(Kd),Yd,Xd,ua=(nr=class extends(Xd=Q,Yd=Y0,Xd){constructor({message:t}){super({name:Jd,message:t}),this[Yd]=!0}static isInstance(t){return Q.hasMarker(t,Kd)}},i(nr,"LoadAPIKeyError"),nr),Qd="AI_TooManyEmbeddingValuesForCallError",ep=`vercel.ai.error.${Qd}`,X0=Symbol.for(ep),tp,np,rp=(rr=class extends(np=Q,tp=X0,np){constructor(t){super({name:Qd,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[tp]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Q.hasMarker(t,ep)}},i(rr,"TooManyEmbeddingValuesForCallError"),rr),op="AI_TypeValidationError",ap=`vercel.ai.error.${op}`,Q0=Symbol.for(ap),sp,ip,cn=(nn=class extends(ip=Q,sp=Q0,ip){constructor({value:t,cause:n,context:r}){let o="Type validation failed";if(r?.field&&(o+=` for ${r.field}`),r?.entityName||r?.entityId){o+=" (";const s=[];r.entityName&&s.push(r.entityName),r.entityId&&s.push(`id: "${r.entityId}"`),o+=s.join(", "),o+=")"}super({name:op,message:`${o}: Value: ${JSON.stringify(t)}.
87
- Error message: ${so(n)}`,cause:n}),this[sp]=!0,this.value=t,this.context=r}static isInstance(t){return Q.hasMarker(t,ap)}static wrap({value:t,cause:n,context:r}){var o,s,a;return nn.isInstance(n)&&n.value===t&&((o=n.context)==null?void 0:o.field)===r?.field&&((s=n.context)==null?void 0:s.entityName)===r?.entityName&&((a=n.context)==null?void 0:a.entityId)===r?.entityId?n:new nn({value:t,cause:n,context:r})}},i(nn,"_TypeValidationError"),nn),up="AI_UnsupportedFunctionalityError",lp=`vercel.ai.error.${up}`,e_=Symbol.for(lp),cp,dp,Qe=(or=class extends(dp=Q,cp=e_,dp){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:up,message:n}),this[cp]=!0,this.functionality=t}static isInstance(t){return Q.hasMarker(t,lp)}},i(or,"UnsupportedFunctionalityError"),or);function A(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const f in a.prototype)f in l||Object.defineProperty(l,f,{value:a.prototype[f].bind(l)});l._zod.constr=a,l._zod.def=c}i(r,"init");const o=n?.Parent??Object,u=class u extends o{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function a(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const f of d._zod.deferred)f();return d}return i(a,"_"),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(a,"name",{value:e}),a}i(A,"$constructor");const xu=class xu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(xu,"$ZodAsyncError");let dn=xu;const pp={};function Wt(e){return pp}i(Wt,"config");function fp(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}i(fp,"getEnumValues");function t_(e,t){return typeof t=="bigint"?t.toString():t}i(t_,"jsonStringifyReplacer");function li(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(li,"cached");function ci(e){return e==null}i(ci,"nullish");function di(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(di,"cleanRegex");function n_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(n_,"floatSafeRemainder$1");function De(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(De,"defineLazy");function la(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(la,"assignProp");function uo(e){return JSON.stringify(e)}i(uo,"esc");const mp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ca(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ca,"isObject");const r_=li(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function da(e){if(ca(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(ca(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(da,"isPlainObject");const o_=new Set(["string","number","symbol"]);function lo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(lo,"escapeRegex");function pn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(pn,"clone");function G(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(G,"normalizeParams");function a_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(a_,"optionalKeys");const s_={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function i_(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(i_,"pick");function u_(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(u_,"omit");function l_(e,t){if(!da(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return la(this,"shape",r),r},checks:[]};return pn(e,n)}i(l_,"extend");function c_(e,t){return pn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return la(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(c_,"merge");function d_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return pn(t,{...t._zod.def,shape:o,checks:[]})}i(d_,"partial");function p_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return pn(t,{...t._zod.def,shape:o,checks:[]})}i(p_,"required");function co(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(co,"aborted");function fn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(fn,"prefixIssues");function pa(e){return typeof e=="string"?e:e?.message}i(pa,"unwrapMessage");function Ht(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=pa(e.inst?._zod.def?.error?.(e))??pa(t?.error?.(e))??pa(n.customError?.(e))??pa(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(Ht,"finalizeIssue");function pi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(pi,"getLengthableOrigin");function po(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(po,"issue");const hp=i((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,t_,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),Dp=A("$ZodError",hp),gp=A("$ZodError",hp,{Parent:Error});function f_(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}i(f_,"flattenError");function m_(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(e),r}i(m_,"formatError");const h_=i(e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new dn;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw mp(u,o?.callee),u}return a.value},"_parse$1"),D_=i(e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw mp(u,o?.callee),u}return a.value},"_parseAsync"),vp=i(e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new dn;return s.issues.length?{success:!1,error:new(e??Dp)(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParse"),g_=vp(gp),yp=i(e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParseAsync"),v_=yp(gp),y_=/^[cC][^\s-]{8,}$/,__=/^[0-9a-z]+$/,b_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,C_=/^[0-9a-vA-V]{20}$/,w_=/^[A-Za-z0-9]{27}$/,F_=/^[a-zA-Z0-9_-]{21}$/,E_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,x_=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_p=i(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),k_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,I_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function A_(){return new RegExp(I_,"u")}i(A_,"emoji");const $_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,T_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,S_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,B_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,O_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bp=/^[A-Za-z0-9_-]*$/,R_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,N_=/^\+(?:[0-9]){6,14}[0-9]$/,Cp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",P_=new RegExp(`^${Cp}$`);function wp(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(wp,"timeSource");function M_(e){return new RegExp(`^${wp(e)}$`)}i(M_,"time$1");function j_(e){const t=wp({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Cp}T(?:${r})$`)}i(j_,"datetime$1");const z_=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),q_=/^\d+$/,L_=/^-?\d+(?:\.\d+)?/i,U_=/true|false/i,Z_=/null/i,V_=/^[^A-Z]*$/,G_=/^[^a-z]*$/,it=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Fp={number:"number",bigint:"bigint",object:"date"},Ep=A("$ZodCheckLessThan",(e,t)=>{it.init(e,t);const n=Fp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xp=A("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);const n=Fp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),W_=A("$ZodCheckMultipleOf",(e,t)=>{it.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):n_(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),H_=A("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=s_[t.format];e._zod.onattach.push(a=>{const u=a._zod.bag;u.format=t.format,u.minimum=o,u.maximum=s,n&&(u.pattern=q_)}),e._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),J_=A("$ZodCheckMaxLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ci(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=pi(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),K_=A("$ZodCheckMinLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ci(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=pi(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Y_=A("$ZodCheckLengthEquals",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ci(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=pi(o),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),fa=A("$ZodCheckStringFormat",(e,t)=>{var n,r;it.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),X_=A("$ZodCheckRegex",(e,t)=>{fa.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Q_=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=V_),fa.init(e,t)}),eb=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=G_),fa.init(e,t)}),tb=A("$ZodCheckIncludes",(e,t)=>{it.init(e,t);const n=lo(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),nb=A("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`^${lo(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),rb=A("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`.*${lo(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),ob=A("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),ku=class ku{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
85
+ `,n=i((l,c)=>{const d=[];let f="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const m=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const h=l[D];if(h&&Array.isArray(h))for(const v of h)f+=a(D+"[]")+m+a(v)+t;else h&&typeof h=="object"?d.push(D):f+=a(D)+m+a(h)+t}c.section&&f.length&&(f="["+a(c.section)+"]"+t+f);for(const D of d){const h=r(D).join("\\."),v=(c.section?c.section+".":"")+h,{whitespace:y}=c,b=n(l[D],{section:v,whitespace:y});f.length&&b.length&&(f+=t),f+=b}return f},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),o=i(l=>{const c=Object.create(null);let d=c,f=null;const m=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(m);if(!y)continue;if(y[1]!==void 0){if(f=u(y[1]),f==="__proto__"){d=Object.create(null);continue}d=c[f]=c[f]||Object.create(null);continue}const b=u(y[2]),C=b.length>2&&b.slice(-2)==="[]",w=C?b.slice(0,-2):b;if(w==="__proto__")continue;const E=y[3]?u(y[4]):!0,T=E==="true"||E==="false"||E==="null"?JSON.parse(E):E;C&&(e.call(d,w)?Array.isArray(d[w])||(d[w]=[d[w]]):d[w]=[]),Array.isArray(d[w])?d[w].push(T):d[w]=T}const h=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const b=y.pop(),C=b.replace(/\\\./g,".");for(const w of y)w!=="__proto__"&&((!e.call(d,w)||typeof d[w]!="object")&&(d[w]=Object.create(null)),d=d[w]);d===c&&C===b||(d[C]=c[v],h.push(v))}for(const v of h)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),a=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,f="";for(let m=0,D=l.length;m<D;m++){const h=l.charAt(m);if(d)"\\;#".indexOf(h)!==-1?f+=h:f+="\\"+h,d=!1;else{if(";#".indexOf(h)!==-1)break;h==="\\"?d=!0:f+=h}}return d&&(f+="\\"),f.trim()}return l},"unsafe");return ai={parse:o,decode:o,stringify:n,encode:n,safe:a,unsafe:u},ai}i(v0,"requireIni");var y0=v0(),gd=un(y0);const si=i(e=>He.lstat(e).then(()=>!0,()=>!1),"fileExists"),_0=["plain","conventional","gitmoji"],{hasOwnProperty:b0}=Object.prototype,ii=i((e,t)=>b0.call(e,t),"hasOwn"),Rt=i((e,t,n)=>{if(!t)throw new ce(`Invalid config property ${e}: ${n}`)},"parseAssert"),pa={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Rt("locale",!!e,"Cannot be empty"),Rt("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Rt("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Rt("generate",t>0,"Must be greater than 0"),Rt("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Rt("type",_0.includes(e),"Invalid commit type"),e):"plain"},proxy(e){if(!(!e||e.length===0))throw new ce('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Rt("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Rt("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Rt("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Rt("max-length",t>=20,"Must be greater than 20 characters"),t}},C0={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["Qwen/Qwen3-Next-80B-A3B-Instruct","zai-org/GLM-4.5-Air-FP8","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"],requiresApiKey:!0},w0={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},F0={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},E0={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},x0={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0,headers:{"HTTP-Referer":"https://github.com/nutlope/aicommits","X-Title":"aicommits"}},k0={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},I0={name:"groq",displayName:"Groq",baseUrl:"https://api.groq.com/openai/v1",apiKeyFormat:"gsk_",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-120b","llama-3.1-8b-instant","openai/gpt-oss-20b"],requiresApiKey:!0},A0={name:"xai",displayName:"xAI",baseUrl:"https://api.x.ai/v1",apiKeyFormat:"xai-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["grok-4.1-fast","grok-4-fast","grok-code-fast-1"],requiresApiKey:!0},lo=[C0,w0,I0,A0,F0,k0,x0,E0],$0=i(()=>lo.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),T0=i((e,t)=>{if(e){const n=lo.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),ui=i(()=>Ct.join($l.homedir(),".aicommits"),"getConfigPath"),vd=i(async()=>{if(!await si(ui()))return Object.create(null);const t=await He.readFile(ui(),"utf8");return gd.parse(t)},"readConfigFile"),hn=i(async(e,t,n)=>{const r=await vd();ii(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const o={},s=t??{};for(const c of Object.keys(pa)){const d=pa[c],f=e?.[c]??s?.[c]??r[c];if(n)try{o[c]=d(f)}catch{}else o[c]=d(f)}let a,u=o.OPENAI_BASE_URL;const l=o.OPENAI_API_KEY;return!u&&l&&(u=$0(),o.OPENAI_BASE_URL=u),a=T0(u,l),{...o,model:o.OPENAI_MODEL,provider:a}},"getConfig"),li=i(async e=>{const t=await vd();for(const[n,r]of e){if(!ii(pa,n))throw new ce(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const o=pa[n](r);t[n]=o}}await He.writeFile(ui(),gd.stringify(t),"utf8")},"setConfigs"),yd=i(e=>`\u2705 ${e} (current)`,"CURRENT_LABEL_FORMAT"),S0=3600*1e3,_d=i(()=>{const e=process.platform,t=$l.homedir();if(e==="darwin")return Ct.join(t,"Library","Caches","aicommits","models");if(e==="win32")return Ct.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||Ct.join(t,".cache");return Ct.join(r,"aicommits","models")}},"getCacheDir"),B0=i(e=>{const t=KD.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),bd=i(e=>Ct.join(_d(),`${e}.json`),"getCachePath"),O0=i(async e=>{const t=bd(e);try{if(!await si(t))return null;const n=await He.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),R0=i(async(e,t)=>{try{const n=_d();await He.mkdir(n,{recursive:!0});const r=bd(e);await He.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),ci=i(async(e,t)=>{const n=B0(e),r=Date.now(),o=await O0(n);if(o&&r-o.timestamp<S0)return o.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),u=(a.data?a.data:a)||[],l={models:u};return u.length>0&&await R0(n,{data:l,timestamp:r}),l}catch(s){const a=s instanceof Error?s.message:"Request failed";return{models:[],error:a}}},"fetchModels"),N0=i(async(e,t,n)=>{const r=await ci(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let o=[];return n?.modelsFilter?o=n.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),o},"fetchAndFilterModels"),P0=i((e,t,n)=>{let r=e.map(o=>({label:o,value:o}));if(n?.defaultModels&&n.defaultModels.length>0){const o=n.defaultModels.filter(s=>r.some(a=>a.value===s));o.forEach(s=>{const a=r.findIndex(u=>u.value===s);a>=0&&r.splice(a,1)}),o.forEach((s,a)=>{const u=s===t,l=a===0;let c;u?c=`\u2705 ${s} (current)`:l?c=`\u{1F451} ${s} (default)`:c=`\u{1F525} ${s}`,r.unshift({label:c,value:s})})}if(t&&t!=="undefined"){const o=n?.defaultModels?.includes(t),s=r.findIndex(a=>a.value===t);if(s>=0&&!o){if(r[s].label=yd(r[s].value),s>0){const[a]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,a)}}else if(s<0&&!o){const a=n?.defaultModels?.length||0;r.splice(a,0,{label:yd(t),value:t})}}return r},"prepareModelOptions"),M0=i(async(e,t,n,r)=>{const o=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(o))return null;let s=e;o&&(s=e.filter(l=>l.toLowerCase().includes(o.toLowerCase())));let a=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${o}"):`,options:[...a,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),j0=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Pn(t)?null:t},"handleCustom"),Cd=i(async(e,t,n,r,o)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const s=Ot();s.start("Fetching available models...");const a=await N0(e,t,r);s.stop(`${o||"Provider"}: ${a.length} models available`);let u=null;if(a.length>0){const{select:l,text:c,isCancel:d}=await Promise.resolve().then(function(){return uo});let f=P0(a,n,r);const m=10;f.length>m&&(f=f.slice(0,m));let D=await l({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...f,{label:"Custom model name...",value:"custom"}],initialValue:f.length>0?f[0].value:void 0});if(d(D))return null;if(D==="search"){const h=await M0(a,l,c,d);if(h===null)return null;D=h}if(D==="custom"){if(u=await j0(c),u===null)return null}else u=D}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:l,isCancel:c}=await Promise.resolve().then(function(){return uo});try{const d=await l({message:"Enter your model name:",validate:i(f=>{if(!f)return"Model name is required"},"validate")});if(c(d))return null;u=d}catch{return null}}return u},"selectModel");var z0=Object.freeze({__proto__:null,fetchModels:ci,selectModel:Cd}),L0=Object.defineProperty,q0=i((e,t,n)=>t in e?L0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),wd=i((e,t,n)=>q0(e,typeof t!="symbol"?t+"":t,n),"__publicField");const Iu=class Iu{constructor(t,n){wd(this,"config"),wd(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return uo}),o=[];if(this.def.requiresApiKey){const s=this.getApiKey(),a=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(a))throw new Error("Setup cancelled");a&&o.push(["OPENAI_API_KEY",a])}if(this.name==="ollama"){const s=this.getBaseUrl(),a=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(a))throw new Error("Setup cancelled");a&&a!=="http://localhost:11434/v1"&&o.push(["OPENAI_BASE_URL",a])}return o}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await ci(t,n);if(r.error)return{models:[],error:r.error};let o;return this.def.modelsFilter?o=this.def.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),{models:o}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}getHeaders(){return this.def.headers}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(Iu,"Provider");let di=Iu;function jn(e){const t=e.provider,n=lo.find(r=>r.name===t);return n?new di(n,e):null}i(jn,"getProvider");function U0(){return lo.map(e=>({value:e.name,label:e.displayName}))}i(U0,"getAvailableProviders");function Z0(e){return lo.find(n=>n.name===e)?.baseUrl||""}i(Z0,"getProviderBaseUrl");var Fd="vercel.ai.error",V0=Symbol.for(Fd),Ed,xd,Q=(In=class extends(xd=Error,Ed=V0,xd){constructor({name:t,message:n,cause:r}){super(n),this[Ed]=!0,this.name=t,this.cause=r}static isInstance(t){return In.hasMarker(t,Fd)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(In,"_AISDKError"),In),kd="AI_APICallError",Id=`vercel.ai.error.${kd}`,G0=Symbol.for(Id),Ad,$d,Be=(Qn=class extends($d=Q,Ad=G0,$d){constructor({message:t,url:n,requestBodyValues:r,statusCode:o,responseHeaders:s,responseBody:a,cause:u,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:kd,message:t,cause:u}),this[Ad]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return Q.hasMarker(t,Id)}},i(Qn,"APICallError"),Qn),Td="AI_EmptyResponseBodyError",Sd=`vercel.ai.error.${Td}`,W0=Symbol.for(Sd),Bd,Od,H0=(er=class extends(Od=Q,Bd=W0,Od){constructor({message:t="Empty response body"}={}){super({name:Td,message:t}),this[Bd]=!0}static isInstance(t){return Q.hasMarker(t,Sd)}},i(er,"EmptyResponseBodyError"),er);function co(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(co,"getErrorMessage$1");var Rd="AI_InvalidArgumentError",Nd=`vercel.ai.error.${Rd}`,J0=Symbol.for(Nd),Pd,Md,jd=(tr=class extends(Md=Q,Pd=J0,Md){constructor({message:t,cause:n,argument:r}){super({name:Rd,message:t,cause:n}),this[Pd]=!0,this.argument=r}static isInstance(t){return Q.hasMarker(t,Nd)}},i(tr,"InvalidArgumentError"),tr),zd="AI_InvalidPromptError",Ld=`vercel.ai.error.${zd}`,K0=Symbol.for(Ld),qd,Ud,Ht=(nr=class extends(Ud=Q,qd=K0,Ud){constructor({prompt:t,message:n,cause:r}){super({name:zd,message:`Invalid prompt: ${n}`,cause:r}),this[qd]=!0,this.prompt=t}static isInstance(t){return Q.hasMarker(t,Ld)}},i(nr,"InvalidPromptError"),nr),Zd="AI_InvalidResponseDataError",Vd=`vercel.ai.error.${Zd}`,Y0=Symbol.for(Vd),Gd,Wd,po=(rr=class extends(Wd=Q,Gd=Y0,Wd){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Zd,message:n}),this[Gd]=!0,this.data=t}static isInstance(t){return Q.hasMarker(t,Vd)}},i(rr,"InvalidResponseDataError"),rr),Hd="AI_JSONParseError",Jd=`vercel.ai.error.${Hd}`,X0=Symbol.for(Jd),Kd,Yd,fa=(or=class extends(Yd=Q,Kd=X0,Yd){constructor({text:t,cause:n}){super({name:Hd,message:`JSON parsing failed: Text: ${t}.
86
+ Error message: ${co(n)}`,cause:n}),this[Kd]=!0,this.text=t}static isInstance(t){return Q.hasMarker(t,Jd)}},i(or,"JSONParseError"),or),Xd="AI_LoadAPIKeyError",Qd=`vercel.ai.error.${Xd}`,Q0=Symbol.for(Qd),ep,tp,ma=(ar=class extends(tp=Q,ep=Q0,tp){constructor({message:t}){super({name:Xd,message:t}),this[ep]=!0}static isInstance(t){return Q.hasMarker(t,Qd)}},i(ar,"LoadAPIKeyError"),ar),np="AI_TooManyEmbeddingValuesForCallError",rp=`vercel.ai.error.${np}`,e_=Symbol.for(rp),op,ap,sp=(sr=class extends(ap=Q,op=e_,ap){constructor(t){super({name:np,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[op]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Q.hasMarker(t,rp)}},i(sr,"TooManyEmbeddingValuesForCallError"),sr),ip="AI_TypeValidationError",up=`vercel.ai.error.${ip}`,t_=Symbol.for(up),lp,cp,Dn=(on=class extends(cp=Q,lp=t_,cp){constructor({value:t,cause:n,context:r}){let o="Type validation failed";if(r?.field&&(o+=` for ${r.field}`),r?.entityName||r?.entityId){o+=" (";const s=[];r.entityName&&s.push(r.entityName),r.entityId&&s.push(`id: "${r.entityId}"`),o+=s.join(", "),o+=")"}super({name:ip,message:`${o}: Value: ${JSON.stringify(t)}.
87
+ Error message: ${co(n)}`,cause:n}),this[lp]=!0,this.value=t,this.context=r}static isInstance(t){return Q.hasMarker(t,up)}static wrap({value:t,cause:n,context:r}){var o,s,a;return on.isInstance(n)&&n.value===t&&((o=n.context)==null?void 0:o.field)===r?.field&&((s=n.context)==null?void 0:s.entityName)===r?.entityName&&((a=n.context)==null?void 0:a.entityId)===r?.entityId?n:new on({value:t,cause:n,context:r})}},i(on,"_TypeValidationError"),on),dp="AI_UnsupportedFunctionalityError",pp=`vercel.ai.error.${dp}`,n_=Symbol.for(pp),fp,mp,Qe=(ir=class extends(mp=Q,fp=n_,mp){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:dp,message:n}),this[fp]=!0,this.functionality=t}static isInstance(t){return Q.hasMarker(t,pp)}},i(ir,"UnsupportedFunctionalityError"),ir);function A(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const f in a.prototype)f in l||Object.defineProperty(l,f,{value:a.prototype[f].bind(l)});l._zod.constr=a,l._zod.def=c}i(r,"init");const o=n?.Parent??Object,u=class u extends o{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function a(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const f of d._zod.deferred)f();return d}return i(a,"_"),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(a,"name",{value:e}),a}i(A,"$constructor");const Au=class Au extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(Au,"$ZodAsyncError");let gn=Au;const hp={};function Jt(e){return hp}i(Jt,"config");function Dp(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}i(Dp,"getEnumValues");function r_(e,t){return typeof t=="bigint"?t.toString():t}i(r_,"jsonStringifyReplacer");function pi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(pi,"cached");function fi(e){return e==null}i(fi,"nullish");function mi(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(mi,"cleanRegex");function o_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(o_,"floatSafeRemainder$1");function De(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(De,"defineLazy");function ha(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(ha,"assignProp");function fo(e){return JSON.stringify(e)}i(fo,"esc");const gp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Da,"isObject");const a_=pi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ga(e){if(Da(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Da(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(ga,"isPlainObject");const s_=new Set(["string","number","symbol"]);function mo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(mo,"escapeRegex");function vn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(vn,"clone");function G(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(G,"normalizeParams");function i_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(i_,"optionalKeys");const u_={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function l_(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return vn(e,{...e._zod.def,shape:n,checks:[]})}i(l_,"pick");function c_(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return vn(e,{...e._zod.def,shape:n,checks:[]})}i(c_,"omit");function d_(e,t){if(!ga(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ha(this,"shape",r),r},checks:[]};return vn(e,n)}i(d_,"extend");function p_(e,t){return vn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ha(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(p_,"merge");function f_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return vn(t,{...t._zod.def,shape:o,checks:[]})}i(f_,"partial");function m_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return vn(t,{...t._zod.def,shape:o,checks:[]})}i(m_,"required");function ho(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(ho,"aborted");function yn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(yn,"prefixIssues");function va(e){return typeof e=="string"?e:e?.message}i(va,"unwrapMessage");function Kt(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=va(e.inst?._zod.def?.error?.(e))??va(t?.error?.(e))??va(n.customError?.(e))??va(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(Kt,"finalizeIssue");function hi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(hi,"getLengthableOrigin");function Do(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(Do,"issue");const vp=i((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,r_,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),yp=A("$ZodError",vp),_p=A("$ZodError",vp,{Parent:Error});function h_(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}i(h_,"flattenError");function D_(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(e),r}i(D_,"formatError");const g_=i(e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new gn;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Kt(l,s,Jt())));throw gp(u,o?.callee),u}return a.value},"_parse$1"),v_=i(e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Kt(l,s,Jt())));throw gp(u,o?.callee),u}return a.value},"_parseAsync"),bp=i(e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new gn;return s.issues.length?{success:!1,error:new(e??yp)(s.issues.map(a=>Kt(a,o,Jt())))}:{success:!0,data:s.value}},"_safeParse"),y_=bp(_p),Cp=i(e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Kt(a,o,Jt())))}:{success:!0,data:s.value}},"_safeParseAsync"),__=Cp(_p),b_=/^[cC][^\s-]{8,}$/,C_=/^[0-9a-z]+$/,w_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,F_=/^[0-9a-vA-V]{20}$/,E_=/^[A-Za-z0-9]{27}$/,x_=/^[a-zA-Z0-9_-]{21}$/,k_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,I_=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wp=i(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),A_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,$_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function T_(){return new RegExp($_,"u")}i(T_,"emoji");const S_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,O_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,R_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,N_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fp=/^[A-Za-z0-9_-]*$/,P_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,M_=/^\+(?:[0-9]){6,14}[0-9]$/,Ep="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",j_=new RegExp(`^${Ep}$`);function xp(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(xp,"timeSource");function z_(e){return new RegExp(`^${xp(e)}$`)}i(z_,"time$1");function L_(e){const t=xp({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ep}T(?:${r})$`)}i(L_,"datetime$1");const q_=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),U_=/^\d+$/,Z_=/^-?\d+(?:\.\d+)?/i,V_=/true|false/i,G_=/null/i,W_=/^[^A-Z]*$/,H_=/^[^a-z]*$/,ut=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),kp={number:"number",bigint:"bigint",object:"date"},Ip=A("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=kp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ap=A("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=kp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),J_=A("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):o_(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),K_=A("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=u_[t.format];e._zod.onattach.push(a=>{const u=a._zod.bag;u.format=t.format,u.minimum=o,u.maximum=s,n&&(u.pattern=U_)}),e._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),Y_=A("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=hi(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),X_=A("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=hi(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Q_=A("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=hi(o),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),ya=A("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),eb=A("$ZodCheckRegex",(e,t)=>{ya.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tb=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=W_),ya.init(e,t)}),nb=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=H_),ya.init(e,t)}),rb=A("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=mo(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),ob=A("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${mo(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),ab=A("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${mo(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),sb=A("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),$u=class $u{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
88
88
  `).filter(a=>a),o=Math.min(...r.map(a=>a.length-a.trimStart().length)),s=r.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
89
- `))}};i(ku,"Doc");let fi=ku;const ab={major:4,minor:0,patch:0},Ce=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ab;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=i((s,a,u)=>{let l=co(s),c;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new dn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(l||(l=co(s,f)))});else{if(s.issues.length===f)continue;l||(l=co(s,f))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,a)=>{const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new dn;return u.then(l=>o(l,r,a))}return o(u,r,a)}}e["~standard"]={validate:i(o=>{try{const s=g_(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return v_(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),mi=A("$ZodString",(e,t)=>{Ce.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??z_(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Se=A("$ZodStringFormat",(e,t)=>{fa.init(e,t),mi.init(e,t)}),sb=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=x_),Se.init(e,t)}),ib=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=_p(r))}else t.pattern??(t.pattern=_p());Se.init(e,t)}),ub=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=k_),Se.init(e,t)}),lb=A("$ZodURL",(e,t)=>{Se.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:R_.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),cb=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=A_()),Se.init(e,t)}),db=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=F_),Se.init(e,t)}),pb=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=y_),Se.init(e,t)}),fb=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=__),Se.init(e,t)}),mb=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=b_),Se.init(e,t)}),hb=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=C_),Se.init(e,t)}),Db=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=w_),Se.init(e,t)}),gb=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=j_(t)),Se.init(e,t)}),vb=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=P_),Se.init(e,t)}),yb=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=M_(t)),Se.init(e,t)}),_b=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=E_),Se.init(e,t)}),bb=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Cb=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=T_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),wb=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=S_),Se.init(e,t)}),Fb=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=B_),Se.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function kp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i(kp,"isValidBase64");const Eb=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=O_),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{kp(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function xb(e){if(!bp.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return kp(n)}i(xb,"isValidBase64URL");const kb=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=bp),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{xb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ib=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=N_),Se.init(e,t)});function Ab(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}i(Ab,"isValidJWT$1");const $b=A("$ZodJWT",(e,t)=>{Se.init(e,t),e._zod.check=n=>{Ab(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ip=A("$ZodNumber",(e,t)=>{Ce.init(e,t),e._zod.pattern=e._zod.bag.pattern??L_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Tb=A("$ZodNumber",(e,t)=>{H_.init(e,t),Ip.init(e,t)}),Sb=A("$ZodBoolean",(e,t)=>{Ce.init(e,t),e._zod.pattern=U_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Bb=A("$ZodNull",(e,t)=>{Ce.init(e,t),e._zod.pattern=Z_,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Ob=A("$ZodAny",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Rb=A("$ZodUnknown",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Nb=A("$ZodNever",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Ap(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(Ap,"handleArrayResult");const Pb=A("$ZodArray",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const u=o[a],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>Ap(c,n,a))):Ap(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function ma(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(ma,"handleObjectResult");function $p(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...fn(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i($p,"handleOptionalObjectResult");const Mb=A("$ZodObject",(e,t)=>{Ce.init(e,t);const n=li(()=>{const f=Object.keys(t.shape);for(const D of f)if(!(t.shape[D]instanceof Ce))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=a_(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(h)}});De(e._zod,"propValues",()=>{const f=t.shape,h={};for(const D in f){const m=f[D]._zod;if(m.values){h[D]??(h[D]=new Set);for(const v of m.values)h[D].add(v)}}return h});const r=i(f=>{const h=new fi(["shape","payload","ctx"]),D=n.value,m=i(C=>{const w=uo(C);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const C of D.keys)v[C]=`key_${y++}`;h.write("const newResult = {}");for(const C of D.keys)if(D.optionalKeys.has(C)){const w=v[C];h.write(`const ${w} = ${m(C)};`);const E=uo(C);h.write(`
89
+ `))}};i($u,"Doc");let Di=$u;const ib={major:4,minor:0,patch:0},we=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ib;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=i((s,a,u)=>{let l=ho(s),c;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&u?.async===!1)throw new gn;if(c||m instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=ho(s,f)))});else{if(s.issues.length===f)continue;l||(l=ho(s,f))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,a)=>{const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new gn;return u.then(l=>o(l,r,a))}return o(u,r,a)}}e["~standard"]={validate:i(o=>{try{const s=y_(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return __(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),gi=A("$ZodString",(e,t)=>{we.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??q_(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Se=A("$ZodStringFormat",(e,t)=>{ya.init(e,t),gi.init(e,t)}),ub=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=I_),Se.init(e,t)}),lb=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=wp(r))}else t.pattern??(t.pattern=wp());Se.init(e,t)}),cb=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=A_),Se.init(e,t)}),db=A("$ZodURL",(e,t)=>{Se.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:P_.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),pb=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=T_()),Se.init(e,t)}),fb=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=x_),Se.init(e,t)}),mb=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=b_),Se.init(e,t)}),hb=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=C_),Se.init(e,t)}),Db=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=w_),Se.init(e,t)}),gb=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=F_),Se.init(e,t)}),vb=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=E_),Se.init(e,t)}),yb=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=L_(t)),Se.init(e,t)}),_b=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=j_),Se.init(e,t)}),bb=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=z_(t)),Se.init(e,t)}),Cb=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=k_),Se.init(e,t)}),wb=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=S_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Fb=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=B_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Eb=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=O_),Se.init(e,t)}),xb=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=R_),Se.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function $p(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i($p,"isValidBase64");const kb=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=N_),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{$p(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Ib(e){if(!Fp.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return $p(n)}i(Ib,"isValidBase64URL");const Ab=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fp),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Ib(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),$b=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=M_),Se.init(e,t)});function Tb(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}i(Tb,"isValidJWT$1");const Sb=A("$ZodJWT",(e,t)=>{Se.init(e,t),e._zod.check=n=>{Tb(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Tp=A("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??Z_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Bb=A("$ZodNumber",(e,t)=>{K_.init(e,t),Tp.init(e,t)}),Ob=A("$ZodBoolean",(e,t)=>{we.init(e,t),e._zod.pattern=V_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Rb=A("$ZodNull",(e,t)=>{we.init(e,t),e._zod.pattern=G_,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Nb=A("$ZodAny",(e,t)=>{we.init(e,t),e._zod.parse=n=>n}),Pb=A("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=n=>n}),Mb=A("$ZodNever",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Sp(e,t,n){e.issues.length&&t.issues.push(...yn(n,e.issues)),t.value[n]=e.value}i(Sp,"handleArrayResult");const jb=A("$ZodArray",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const u=o[a],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>Sp(c,n,a))):Sp(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function _a(e,t,n){e.issues.length&&t.issues.push(...yn(n,e.issues)),t.value[n]=e.value}i(_a,"handleObjectResult");function Bp(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...yn(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i(Bp,"handleOptionalObjectResult");const zb=A("$ZodObject",(e,t)=>{we.init(e,t);const n=pi(()=>{const f=Object.keys(t.shape);for(const D of f)if(!(t.shape[D]instanceof we))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const m=i_(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(m)}});De(e._zod,"propValues",()=>{const f=t.shape,m={};for(const D in f){const h=f[D]._zod;if(h.values){m[D]??(m[D]=new Set);for(const v of h.values)m[D].add(v)}}return m});const r=i(f=>{const m=new Di(["shape","payload","ctx"]),D=n.value,h=i(C=>{const w=fo(C);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const C of D.keys)v[C]=`key_${y++}`;m.write("const newResult = {}");for(const C of D.keys)if(D.optionalKeys.has(C)){const w=v[C];m.write(`const ${w} = ${h(C)};`);const E=fo(C);m.write(`
90
90
  if (${w}.issues.length) {
91
91
  if (input[${E}] === undefined) {
92
92
  if (${E} in input) {
@@ -105,22 +105,22 @@ Error message: ${so(n)}`,cause:n}),this[sp]=!0,this.value=t,this.context=r}stati
105
105
  } else {
106
106
  newResult[${E}] = ${w}.value;
107
107
  }
108
- `)}else{const w=v[C];h.write(`const ${w} = ${m(C)};`),h.write(`
108
+ `)}else{const w=v[C];m.write(`const ${w} = ${h(C)};`),m.write(`
109
109
  if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
110
110
  ...iss,
111
- path: iss.path ? [${uo(C)}, ...iss.path] : [${uo(C)}]
112
- })));`),h.write(`newResult[${uo(C)}] = ${w}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const b=h.compile();return(C,w)=>b(f,C,w)},"generateFastpass");let o;const s=ca,a=!pp.jitless,l=a&&r_.value,c=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=n.value);const D=f.value;if(!s(D))return f.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),f;const m=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)o||(o=r(t.shape)),f=o(f,h);else{f.value={};const w=d.shape;for(const E of d.keys){const T=w[E],O=T._zod.run({value:D[E],issues:[]},h),$=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(I=>$?$p(I,f,E,D):ma(I,f,E))):$?$p(O,f,E,D):ma(O,f,E)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const v=[],y=d.keySet,b=c._zod,C=b.def.type;for(const w of Object.keys(D)){if(y.has(w))continue;if(C==="never"){v.push(w);continue}const E=b.run({value:D[w],issues:[]},h);E instanceof Promise?m.push(E.then(T=>ma(T,f,w))):ma(E,f,w)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),m.length?Promise.all(m).then(()=>f):f}});function Tp(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Ht(s,r,Wt())))}),t}i(Tp,"handleUnionResults");const Sp=A("$ZodUnion",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),De(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>di(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>Tp(a,n,e,r)):Tp(s,n,e,r)}}),jb=A("$ZodDiscriminatedUnion",(e,t)=>{Sp.init(e,t);const n=e._zod.parse;De(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(a)){o[u]||(o[u]=new Set);for(const c of l)o[u].add(c)}}return o});const r=li(()=>{const o=t.options,s=new Map;for(const a of o){const u=a._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!ca(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const u=r.value.get(a?.[t.discriminator]);return u?u._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),zb=A("$ZodIntersection",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Bp(n,l,c)):Bp(n,s,a)}});function hi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(da(e)&&da(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=hi(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=hi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(hi,"mergeValues$1");function Bp(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),co(e))return e;const r=hi(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(Bp,"handleIntersectionResults");const qb=A("$ZodRecord",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!da(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...fn(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...fn(l,c.issues)),n.value[l]=c.value)}let u;for(const l in o)a.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const u=t.keyType._zod.run({value:a,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>Ht(c,r,Wt())),input:a,path:[a],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...fn(a,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...fn(a,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Lb=A("$ZodEnum",(e,t)=>{Ce.init(e,t);const n=fp(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>o_.has(typeof r)).map(r=>typeof r=="string"?lo(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Ub=A("$ZodLiteral",(e,t)=>{Ce.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?lo(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),Zb=A("$ZodTransform",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new dn;return n.value=o,n}}),Vb=A("$ZodOptional",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${di(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Gb=A("$ZodNullable",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${di(n.source)}|null)$`):void 0}),De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Wb=A("$ZodDefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Op(s,t)):Op(o,t)}});function Op(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(Op,"handleDefaultResult");const Hb=A("$ZodPrefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Jb=A("$ZodNonOptional",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Rp(s,e)):Rp(o,e)}});function Rp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(Rp,"handleNonOptionalResult");const Kb=A("$ZodCatch",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>Ht(a,r,Wt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Ht(s,r,Wt()))},input:n.value}),n.issues=[]),n)}}),Yb=A("$ZodPipe",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Np(s,t,r)):Np(o,t,r)}});function Np(e,t,n){return co(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(Np,"handlePipeResult");const Xb=A("$ZodReadonly",(e,t)=>{Ce.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Pp):Pp(o)}});function Pp(e){return e.value=Object.freeze(e.value),e}i(Pp,"handleReadonlyResult");const Qb=A("$ZodLazy",(e,t)=>{Ce.init(e,t),De(e._zod,"innerType",()=>t.getter()),De(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),De(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),De(e._zod,"optin",()=>e._zod.innerType._zod.optin),De(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),eC=A("$ZodCustom",(e,t)=>{it.init(e,t),Ce.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Mp(s,n,r,e));Mp(o,n,r,e)}});function Mp(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(po(o))}}i(Mp,"handleRefineResult");const Iu=class Iu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(Iu,"$ZodRegistry");let ha=Iu;function tC(){return new ha}i(tC,"registry");const fo=tC();function nC(e,t){return new e({type:"string",...G(t)})}i(nC,"_string");function rC(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...G(t)})}i(rC,"_email");function jp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...G(t)})}i(jp,"_guid");function oC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...G(t)})}i(oC,"_uuid");function aC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(t)})}i(aC,"_uuidv4");function sC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(t)})}i(sC,"_uuidv6");function iC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(t)})}i(iC,"_uuidv7");function uC(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...G(t)})}i(uC,"_url");function lC(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...G(t)})}i(lC,"_emoji");function cC(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(t)})}i(cC,"_nanoid");function dC(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...G(t)})}i(dC,"_cuid");function pC(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(t)})}i(pC,"_cuid2");function fC(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...G(t)})}i(fC,"_ulid");function mC(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...G(t)})}i(mC,"_xid");function hC(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(t)})}i(hC,"_ksuid");function DC(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(t)})}i(DC,"_ipv4");function gC(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(t)})}i(gC,"_ipv6");function vC(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(t)})}i(vC,"_cidrv4");function yC(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(t)})}i(yC,"_cidrv6");function _C(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...G(t)})}i(_C,"_base64");function bC(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...G(t)})}i(bC,"_base64url");function CC(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...G(t)})}i(CC,"_e164");function wC(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...G(t)})}i(wC,"_jwt");function FC(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(t)})}i(FC,"_isoDateTime");function EC(e,t){return new e({type:"string",format:"date",check:"string_format",...G(t)})}i(EC,"_isoDate");function xC(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...G(t)})}i(xC,"_isoTime");function kC(e,t){return new e({type:"string",format:"duration",check:"string_format",...G(t)})}i(kC,"_isoDuration");function IC(e,t){return new e({type:"number",checks:[],...G(t)})}i(IC,"_number");function AC(e,t){return new e({type:"number",coerce:!0,checks:[],...G(t)})}i(AC,"_coercedNumber");function $C(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...G(t)})}i($C,"_int");function TC(e,t){return new e({type:"boolean",...G(t)})}i(TC,"_boolean");function SC(e,t){return new e({type:"null",...G(t)})}i(SC,"_null$1");function BC(e){return new e({type:"any"})}i(BC,"_any");function OC(e){return new e({type:"unknown"})}i(OC,"_unknown");function RC(e,t){return new e({type:"never",...G(t)})}i(RC,"_never");function zp(e,t){return new Ep({check:"less_than",...G(t),value:e,inclusive:!1})}i(zp,"_lt");function Di(e,t){return new Ep({check:"less_than",...G(t),value:e,inclusive:!0})}i(Di,"_lte");function qp(e,t){return new xp({check:"greater_than",...G(t),value:e,inclusive:!1})}i(qp,"_gt");function gi(e,t){return new xp({check:"greater_than",...G(t),value:e,inclusive:!0})}i(gi,"_gte");function Lp(e,t){return new W_({check:"multiple_of",...G(t),value:e})}i(Lp,"_multipleOf");function Up(e,t){return new J_({check:"max_length",...G(t),maximum:e})}i(Up,"_maxLength");function Da(e,t){return new K_({check:"min_length",...G(t),minimum:e})}i(Da,"_minLength");function Zp(e,t){return new Y_({check:"length_equals",...G(t),length:e})}i(Zp,"_length");function NC(e,t){return new X_({check:"string_format",format:"regex",...G(t),pattern:e})}i(NC,"_regex");function PC(e){return new Q_({check:"string_format",format:"lowercase",...G(e)})}i(PC,"_lowercase");function MC(e){return new eb({check:"string_format",format:"uppercase",...G(e)})}i(MC,"_uppercase");function jC(e,t){return new tb({check:"string_format",format:"includes",...G(t),includes:e})}i(jC,"_includes");function zC(e,t){return new nb({check:"string_format",format:"starts_with",...G(t),prefix:e})}i(zC,"_startsWith");function qC(e,t){return new rb({check:"string_format",format:"ends_with",...G(t),suffix:e})}i(qC,"_endsWith");function mo(e){return new ob({check:"overwrite",tx:e})}i(mo,"_overwrite");function LC(e){return mo(t=>t.normalize(e))}i(LC,"_normalize");function UC(){return mo(e=>e.trim())}i(UC,"_trim");function ZC(){return mo(e=>e.toLowerCase())}i(ZC,"_toLowerCase");function VC(){return mo(e=>e.toUpperCase())}i(VC,"_toUpperCase");function GC(e,t,n){return new e({type:"array",element:t,...G(n)})}i(GC,"_array");function WC(e,t,n){const r=G(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(WC,"_custom");function HC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...G(n)})}i(HC,"_refine");const Au=class Au{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??fo,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,f),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(o.type){case"string":{const m=D;m.type="string";const{minimum:v,maximum:y,format:b,patterns:C,contentEncoding:w}=t._zod.bag;if(typeof v=="number"&&(m.minLength=v),typeof y=="number"&&(m.maxLength=y),b&&(m.format=s[b]??b,m.format===""&&delete m.format),w&&(m.contentEncoding=w),C&&C.size>0){const E=[...C];E.length===1?m.pattern=E[0].source:E.length>1&&(u.schema.allOf=[...E.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{const m=D,{minimum:v,maximum:y,format:b,multipleOf:C,exclusiveMaximum:w,exclusiveMinimum:E}=t._zod.bag;typeof b=="string"&&b.includes("int")?m.type="integer":m.type="number",typeof E=="number"&&(m.exclusiveMinimum=E),typeof v=="number"&&(m.minimum=v,typeof E=="number"&&(E>=v?delete m.minimum:delete m.exclusiveMinimum)),typeof w=="number"&&(m.exclusiveMaximum=w),typeof y=="number"&&(m.maximum=y,typeof w=="number"&&(w<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof C=="number"&&(m.multipleOf=C);break}case"boolean":{const m=D;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(m.minItems=v),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const m=D;m.type="object",m.properties={};const v=o.shape;for(const C in v)m.properties[C]=this.process(v[C],{...f,path:[...f.path,"properties",C]});const y=new Set(Object.keys(v)),b=new Set([...y].filter(C=>{const w=o.shape[C]._zod;return this.io==="input"?w.optin===void 0:w.optout===void 0}));b.size>0&&(m.required=Array.from(b)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=D;m.anyOf=o.options.map((v,y)=>this.process(v,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const m=D,v=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),b=i(w=>"allOf"in w&&Object.keys(w).length===1,"isSimpleIntersection"),C=[...b(v)?v.allOf:[v],...b(y)?y.allOf:[y]];m.allOf=C;break}case"tuple":{const m=D;m.type="array";const v=o.items.map((C,w)=>this.process(C,{...f,path:[...f.path,"prefixItems",w]}));if(this.target==="draft-2020-12"?m.prefixItems=v:m.items=v,o.rest){const C=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?m.items=C:m.additionalItems=C}o.rest&&(m.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(m.minItems=y),typeof b=="number"&&(m.maxItems=b);break}case"record":{const m=D;m.type="object",m.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...f,path:[...f.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=D,v=fp(o.entries);v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),m.enum=v;break}case"literal":{const m=D,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];m.type=y===null?"null":typeof y,m.const=y}else v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),v.every(y=>typeof y=="boolean")&&(m.type="string"),v.every(y=>y===null)&&(m.type="null"),m.enum=v;break}case"file":{const m=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:C}=t._zod.bag;y!==void 0&&(v.minLength=y),b!==void 0&&(v.maxLength=b),C?C.length===1?(v.contentMediaType=C[0],Object.assign(m,v)):m.anyOf=C.map(w=>({...v,contentMediaType:w})):Object.assign(m,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,f);D.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"success":{const m=D;m.type="boolean";break}case"default":{this.process(o.innerType,f),u.ref=o.innerType,D.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),u.ref=o.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),u.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=v.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,f),u.ref=m;break}case"readonly":{this.process(o.innerType,f),u.ref=o.innerType,D.readOnly=!0;break}case"promise":{this.process(o.innerType,f),u.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,f),u.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Ze(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(C=>C);if(v)return{ref:y(v)};const b=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=b,{defId:b,ref:`${y("__shared")}#/${f}/${b}`}}if(d[1]===o)return{ref:"#"};const D=`#/${f}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:D+m}},"makeURI"),a=i(d=>{if(d[1].schema.$ref)return;const f=d[1],{ref:h,defId:D}=s(d);f.def={...f.schema},D&&(f.defId=D);const m=f.schema;for(const v in m)delete m[v];m.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const f=d[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
111
+ path: iss.path ? [${fo(C)}, ...iss.path] : [${fo(C)}]
112
+ })));`),m.write(`newResult[${fo(C)}] = ${w}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");const b=m.compile();return(C,w)=>b(f,C,w)},"generateFastpass");let o;const s=Da,a=!hp.jitless,l=a&&a_.value,c=t.catchall;let d;e._zod.parse=(f,m)=>{d??(d=n.value);const D=f.value;if(!s(D))return f.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),f;const h=[];if(a&&l&&m?.async===!1&&m.jitless!==!0)o||(o=r(t.shape)),f=o(f,m);else{f.value={};const w=d.shape;for(const E of d.keys){const T=w[E],O=T._zod.run({value:D[E],issues:[]},m),$=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?h.push(O.then(I=>$?Bp(I,f,E,D):_a(I,f,E))):$?Bp(O,f,E,D):_a(O,f,E)}}if(!c)return h.length?Promise.all(h).then(()=>f):f;const v=[],y=d.keySet,b=c._zod,C=b.def.type;for(const w of Object.keys(D)){if(y.has(w))continue;if(C==="never"){v.push(w);continue}const E=b.run({value:D[w],issues:[]},m);E instanceof Promise?h.push(E.then(T=>_a(T,f,w))):_a(E,f,w)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),h.length?Promise.all(h).then(()=>f):f}});function Op(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Kt(s,r,Jt())))}),t}i(Op,"handleUnionResults");const Rp=A("$ZodUnion",(e,t)=>{we.init(e,t),De(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),De(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>mi(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>Op(a,n,e,r)):Op(s,n,e,r)}}),Lb=A("$ZodDiscriminatedUnion",(e,t)=>{Rp.init(e,t);const n=e._zod.parse;De(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(a)){o[u]||(o[u]=new Set);for(const c of l)o[u].add(c)}}return o});const r=pi(()=>{const o=t.options,s=new Map;for(const a of o){const u=a._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!Da(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const u=r.value.get(a?.[t.discriminator]);return u?u._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),qb=A("$ZodIntersection",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Np(n,l,c)):Np(n,s,a)}});function vi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ga(e)&&ga(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=vi(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=vi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(vi,"mergeValues$1");function Np(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),ho(e))return e;const r=vi(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(Np,"handleIntersectionResults");const Ub=A("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!ga(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...yn(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...yn(l,c.issues)),n.value[l]=c.value)}let u;for(const l in o)a.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const u=t.keyType._zod.run({value:a,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>Kt(c,r,Jt())),input:a,path:[a],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...yn(a,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...yn(a,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Zb=A("$ZodEnum",(e,t)=>{we.init(e,t);const n=Dp(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>s_.has(typeof r)).map(r=>typeof r=="string"?mo(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Vb=A("$ZodLiteral",(e,t)=>{we.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?mo(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),Gb=A("$ZodTransform",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new gn;return n.value=o,n}}),Wb=A("$ZodOptional",(e,t)=>{we.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mi(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Hb=A("$ZodNullable",(e,t)=>{we.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mi(n.source)}|null)$`):void 0}),De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Jb=A("$ZodDefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Pp(s,t)):Pp(o,t)}});function Pp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(Pp,"handleDefaultResult");const Kb=A("$ZodPrefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Yb=A("$ZodNonOptional",(e,t)=>{we.init(e,t),De(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Mp(s,e)):Mp(o,e)}});function Mp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(Mp,"handleNonOptionalResult");const Xb=A("$ZodCatch",(e,t)=>{we.init(e,t),e._zod.optin="optional",De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>Kt(a,r,Jt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Kt(s,r,Jt()))},input:n.value}),n.issues=[]),n)}}),Qb=A("$ZodPipe",(e,t)=>{we.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>jp(s,t,r)):jp(o,t,r)}});function jp(e,t,n){return ho(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(jp,"handlePipeResult");const eC=A("$ZodReadonly",(e,t)=>{we.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(zp):zp(o)}});function zp(e){return e.value=Object.freeze(e.value),e}i(zp,"handleReadonlyResult");const tC=A("$ZodLazy",(e,t)=>{we.init(e,t),De(e._zod,"innerType",()=>t.getter()),De(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),De(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),De(e._zod,"optin",()=>e._zod.innerType._zod.optin),De(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),nC=A("$ZodCustom",(e,t)=>{ut.init(e,t),we.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Lp(s,n,r,e));Lp(o,n,r,e)}});function Lp(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Do(o))}}i(Lp,"handleRefineResult");const Tu=class Tu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(Tu,"$ZodRegistry");let ba=Tu;function rC(){return new ba}i(rC,"registry");const go=rC();function oC(e,t){return new e({type:"string",...G(t)})}i(oC,"_string");function aC(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...G(t)})}i(aC,"_email");function qp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...G(t)})}i(qp,"_guid");function sC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...G(t)})}i(sC,"_uuid");function iC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(t)})}i(iC,"_uuidv4");function uC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(t)})}i(uC,"_uuidv6");function lC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(t)})}i(lC,"_uuidv7");function cC(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...G(t)})}i(cC,"_url");function dC(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...G(t)})}i(dC,"_emoji");function pC(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(t)})}i(pC,"_nanoid");function fC(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...G(t)})}i(fC,"_cuid");function mC(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(t)})}i(mC,"_cuid2");function hC(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...G(t)})}i(hC,"_ulid");function DC(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...G(t)})}i(DC,"_xid");function gC(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(t)})}i(gC,"_ksuid");function vC(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(t)})}i(vC,"_ipv4");function yC(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(t)})}i(yC,"_ipv6");function _C(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(t)})}i(_C,"_cidrv4");function bC(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(t)})}i(bC,"_cidrv6");function CC(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...G(t)})}i(CC,"_base64");function wC(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...G(t)})}i(wC,"_base64url");function FC(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...G(t)})}i(FC,"_e164");function EC(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...G(t)})}i(EC,"_jwt");function xC(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(t)})}i(xC,"_isoDateTime");function kC(e,t){return new e({type:"string",format:"date",check:"string_format",...G(t)})}i(kC,"_isoDate");function IC(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...G(t)})}i(IC,"_isoTime");function AC(e,t){return new e({type:"string",format:"duration",check:"string_format",...G(t)})}i(AC,"_isoDuration");function $C(e,t){return new e({type:"number",checks:[],...G(t)})}i($C,"_number");function TC(e,t){return new e({type:"number",coerce:!0,checks:[],...G(t)})}i(TC,"_coercedNumber");function SC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...G(t)})}i(SC,"_int");function BC(e,t){return new e({type:"boolean",...G(t)})}i(BC,"_boolean");function OC(e,t){return new e({type:"null",...G(t)})}i(OC,"_null$1");function RC(e){return new e({type:"any"})}i(RC,"_any");function NC(e){return new e({type:"unknown"})}i(NC,"_unknown");function PC(e,t){return new e({type:"never",...G(t)})}i(PC,"_never");function Up(e,t){return new Ip({check:"less_than",...G(t),value:e,inclusive:!1})}i(Up,"_lt");function yi(e,t){return new Ip({check:"less_than",...G(t),value:e,inclusive:!0})}i(yi,"_lte");function Zp(e,t){return new Ap({check:"greater_than",...G(t),value:e,inclusive:!1})}i(Zp,"_gt");function _i(e,t){return new Ap({check:"greater_than",...G(t),value:e,inclusive:!0})}i(_i,"_gte");function Vp(e,t){return new J_({check:"multiple_of",...G(t),value:e})}i(Vp,"_multipleOf");function Gp(e,t){return new Y_({check:"max_length",...G(t),maximum:e})}i(Gp,"_maxLength");function Ca(e,t){return new X_({check:"min_length",...G(t),minimum:e})}i(Ca,"_minLength");function Wp(e,t){return new Q_({check:"length_equals",...G(t),length:e})}i(Wp,"_length");function MC(e,t){return new eb({check:"string_format",format:"regex",...G(t),pattern:e})}i(MC,"_regex");function jC(e){return new tb({check:"string_format",format:"lowercase",...G(e)})}i(jC,"_lowercase");function zC(e){return new nb({check:"string_format",format:"uppercase",...G(e)})}i(zC,"_uppercase");function LC(e,t){return new rb({check:"string_format",format:"includes",...G(t),includes:e})}i(LC,"_includes");function qC(e,t){return new ob({check:"string_format",format:"starts_with",...G(t),prefix:e})}i(qC,"_startsWith");function UC(e,t){return new ab({check:"string_format",format:"ends_with",...G(t),suffix:e})}i(UC,"_endsWith");function vo(e){return new sb({check:"overwrite",tx:e})}i(vo,"_overwrite");function ZC(e){return vo(t=>t.normalize(e))}i(ZC,"_normalize");function VC(){return vo(e=>e.trim())}i(VC,"_trim");function GC(){return vo(e=>e.toLowerCase())}i(GC,"_toLowerCase");function WC(){return vo(e=>e.toUpperCase())}i(WC,"_toUpperCase");function HC(e,t,n){return new e({type:"array",element:t,...G(n)})}i(HC,"_array");function JC(e,t,n){const r=G(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(JC,"_custom");function KC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...G(n)})}i(KC,"_refine");const Su=class Su{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??go,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},m=t._zod.parent;if(m)u.ref=m,this.process(m,f),this.seen.get(m).isParent=!0;else{const D=u.schema;switch(o.type){case"string":{const h=D;h.type="string";const{minimum:v,maximum:y,format:b,patterns:C,contentEncoding:w}=t._zod.bag;if(typeof v=="number"&&(h.minLength=v),typeof y=="number"&&(h.maxLength=y),b&&(h.format=s[b]??b,h.format===""&&delete h.format),w&&(h.contentEncoding=w),C&&C.size>0){const E=[...C];E.length===1?h.pattern=E[0].source:E.length>1&&(u.schema.allOf=[...E.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{const h=D,{minimum:v,maximum:y,format:b,multipleOf:C,exclusiveMaximum:w,exclusiveMinimum:E}=t._zod.bag;typeof b=="string"&&b.includes("int")?h.type="integer":h.type="number",typeof E=="number"&&(h.exclusiveMinimum=E),typeof v=="number"&&(h.minimum=v,typeof E=="number"&&(E>=v?delete h.minimum:delete h.exclusiveMinimum)),typeof w=="number"&&(h.exclusiveMaximum=w),typeof y=="number"&&(h.maximum=y,typeof w=="number"&&(w<=y?delete h.maximum:delete h.exclusiveMaximum)),typeof C=="number"&&(h.multipleOf=C);break}case"boolean":{const h=D;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const h=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(h.minItems=v),typeof y=="number"&&(h.maxItems=y),h.type="array",h.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const h=D;h.type="object",h.properties={};const v=o.shape;for(const C in v)h.properties[C]=this.process(v[C],{...f,path:[...f.path,"properties",C]});const y=new Set(Object.keys(v)),b=new Set([...y].filter(C=>{const w=o.shape[C]._zod;return this.io==="input"?w.optin===void 0:w.optout===void 0}));b.size>0&&(h.required=Array.from(b)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{const h=D;h.anyOf=o.options.map((v,y)=>this.process(v,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const h=D,v=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),b=i(w=>"allOf"in w&&Object.keys(w).length===1,"isSimpleIntersection"),C=[...b(v)?v.allOf:[v],...b(y)?y.allOf:[y]];h.allOf=C;break}case"tuple":{const h=D;h.type="array";const v=o.items.map((C,w)=>this.process(C,{...f,path:[...f.path,"prefixItems",w]}));if(this.target==="draft-2020-12"?h.prefixItems=v:h.items=v,o.rest){const C=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?h.items=C:h.additionalItems=C}o.rest&&(h.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(h.minItems=y),typeof b=="number"&&(h.maxItems=b);break}case"record":{const h=D;h.type="object",h.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...f,path:[...f.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const h=D,v=Dp(o.entries);v.every(y=>typeof y=="number")&&(h.type="number"),v.every(y=>typeof y=="string")&&(h.type="string"),h.enum=v;break}case"literal":{const h=D,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];h.type=y===null?"null":typeof y,h.const=y}else v.every(y=>typeof y=="number")&&(h.type="number"),v.every(y=>typeof y=="string")&&(h.type="string"),v.every(y=>typeof y=="boolean")&&(h.type="string"),v.every(y=>y===null)&&(h.type="null"),h.enum=v;break}case"file":{const h=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:C}=t._zod.bag;y!==void 0&&(v.minLength=y),b!==void 0&&(v.maxLength=b),C?C.length===1?(v.contentMediaType=C[0],Object.assign(h,v)):h.anyOf=C.map(w=>({...v,contentMediaType:w})):Object.assign(h,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const h=this.process(o.innerType,f);D.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"success":{const h=D;h.type="boolean";break}case"default":{this.process(o.innerType,f),u.ref=o.innerType,D.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),u.ref=o.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),u.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const h=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=v.source;break}case"pipe":{const h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,f),u.ref=h;break}case"readonly":{this.process(o.innerType,f),u.ref=o.innerType,D.readOnly=!0;break}case"promise":{this.process(o.innerType,f),u.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"lazy":{const h=t._zod.innerType;this.process(h,f),u.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Ze(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(C=>C);if(v)return{ref:y(v)};const b=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=b,{defId:b,ref:`${y("__shared")}#/${f}/${b}`}}if(d[1]===o)return{ref:"#"};const D=`#/${f}/`,h=d[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:D+h}},"makeURI"),a=i(d=>{if(d[1].schema.$ref)return;const f=d[1],{ref:m,defId:D}=s(d);f.def={...f.schema},D&&(f.defId=D);const h=f.schema;for(const v in h)delete h[v];h.$ref=m},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const f=d[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
113
113
 
114
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const f=d[1];if(t===d[0]){a(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(f.cycle){a(d);continue}if(f.count>1&&r.reused==="ref"){a(d);continue}}const u=i((d,f)=>{const h=this.seen.get(d),D=h.def??h.schema,m={...D};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){u(v,f);const y=this.seen.get(v).schema;y.$ref&&f.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,m))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,o.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const f=d[1];f.def&&f.defId&&(c[f.defId]=f.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(Au,"JSONSchemaGenerator");let ga=Au;function JC(e,t){if(e instanceof ha){const r=new ga(t),o={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=new ga(t);return n.process(e),n.emit(e,t)}i(JC,"toJSONSchema");function Ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ze(o.element,n);case"object":{for(const s in o.shape)if(Ze(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ze(s,n))return!0;return!1}case"intersection":return Ze(o.left,n)||Ze(o.right,n);case"tuple":{for(const s of o.items)if(Ze(s,n))return!0;return!!(o.rest&&Ze(o.rest,n))}case"record":return Ze(o.keyType,n)||Ze(o.valueType,n);case"map":return Ze(o.keyType,n)||Ze(o.valueType,n);case"set":return Ze(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ze(o.innerType,n);case"lazy":return Ze(o.getter(),n);case"default":return Ze(o.innerType,n);case"prefault":return Ze(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ze(o.in,n)||Ze(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}i(Ze,"isTransforming");const KC=A("ZodISODateTime",(e,t)=>{gb.init(e,t),Oe.init(e,t)});function YC(e){return FC(KC,e)}i(YC,"datetime");const XC=A("ZodISODate",(e,t)=>{vb.init(e,t),Oe.init(e,t)});function QC(e){return EC(XC,e)}i(QC,"date");const ew=A("ZodISOTime",(e,t)=>{yb.init(e,t),Oe.init(e,t)});function tw(e){return xC(ew,e)}i(tw,"time");const nw=A("ZodISODuration",(e,t)=>{_b.init(e,t),Oe.init(e,t)});function rw(e){return kC(nw,e)}i(rw,"duration");const ow=i((e,t)=>{Dp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>m_(e,n),"value")},flatten:{value:i(n=>f_(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),va=A("ZodError",ow,{Parent:Error}),aw=h_(va),sw=D_(va),iw=vp(va),Vp=yp(va),Ie=A("ZodType",(e,t)=>(Ce.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>pn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>aw(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>iw(e,n,r),e.parseAsync=async(n,r)=>sw(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Vp(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(tF(n,r)),e.superRefine=n=>e.check(nF(n)),e.overwrite=n=>e.check(mo(n)),e.optional=()=>Qp(e),e.nullable=()=>ef(e),e.nullish=()=>Qp(ef(e)),e.nonoptional=n=>Gw(e,n),e.array=()=>S(e),e.or=n=>ee([e,n]),e.and=n=>Nw(e,n),e.transform=n=>nf(e,zw(n)),e.default=n=>Uw(e,n),e.prefault=n=>Vw(e,n),e.catch=n=>Hw(e,n),e.pipe=n=>nf(e,n),e.readonly=()=>Yw(e),e.describe=n=>{const r=e.clone();return fo.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return fo.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return fo.get(e);const r=e.clone();return fo.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Gp=A("_ZodString",(e,t)=>{mi.init(e,t),Ie.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(NC(...r)),e.includes=(...r)=>e.check(jC(...r)),e.startsWith=(...r)=>e.check(zC(...r)),e.endsWith=(...r)=>e.check(qC(...r)),e.min=(...r)=>e.check(Da(...r)),e.max=(...r)=>e.check(Up(...r)),e.length=(...r)=>e.check(Zp(...r)),e.nonempty=(...r)=>e.check(Da(1,...r)),e.lowercase=r=>e.check(PC(r)),e.uppercase=r=>e.check(MC(r)),e.trim=()=>e.check(UC()),e.normalize=(...r)=>e.check(LC(...r)),e.toLowerCase=()=>e.check(ZC()),e.toUpperCase=()=>e.check(VC())}),uw=A("ZodString",(e,t)=>{mi.init(e,t),Gp.init(e,t),e.email=n=>e.check(rC(lw,n)),e.url=n=>e.check(uC(cw,n)),e.jwt=n=>e.check(wC(Ew,n)),e.emoji=n=>e.check(lC(dw,n)),e.guid=n=>e.check(jp(Wp,n)),e.uuid=n=>e.check(oC(ya,n)),e.uuidv4=n=>e.check(aC(ya,n)),e.uuidv6=n=>e.check(sC(ya,n)),e.uuidv7=n=>e.check(iC(ya,n)),e.nanoid=n=>e.check(cC(pw,n)),e.guid=n=>e.check(jp(Wp,n)),e.cuid=n=>e.check(dC(fw,n)),e.cuid2=n=>e.check(pC(mw,n)),e.ulid=n=>e.check(fC(hw,n)),e.base64=n=>e.check(_C(Cw,n)),e.base64url=n=>e.check(bC(ww,n)),e.xid=n=>e.check(mC(Dw,n)),e.ksuid=n=>e.check(hC(gw,n)),e.ipv4=n=>e.check(DC(vw,n)),e.ipv6=n=>e.check(gC(yw,n)),e.cidrv4=n=>e.check(vC(_w,n)),e.cidrv6=n=>e.check(yC(bw,n)),e.e164=n=>e.check(CC(Fw,n)),e.datetime=n=>e.check(YC(n)),e.date=n=>e.check(QC(n)),e.time=n=>e.check(tw(n)),e.duration=n=>e.check(rw(n))});function p(e){return nC(uw,e)}i(p,"string");const Oe=A("ZodStringFormat",(e,t)=>{Se.init(e,t),Gp.init(e,t)}),lw=A("ZodEmail",(e,t)=>{ub.init(e,t),Oe.init(e,t)}),Wp=A("ZodGUID",(e,t)=>{sb.init(e,t),Oe.init(e,t)}),ya=A("ZodUUID",(e,t)=>{ib.init(e,t),Oe.init(e,t)}),cw=A("ZodURL",(e,t)=>{lb.init(e,t),Oe.init(e,t)}),dw=A("ZodEmoji",(e,t)=>{cb.init(e,t),Oe.init(e,t)}),pw=A("ZodNanoID",(e,t)=>{db.init(e,t),Oe.init(e,t)}),fw=A("ZodCUID",(e,t)=>{pb.init(e,t),Oe.init(e,t)}),mw=A("ZodCUID2",(e,t)=>{fb.init(e,t),Oe.init(e,t)}),hw=A("ZodULID",(e,t)=>{mb.init(e,t),Oe.init(e,t)}),Dw=A("ZodXID",(e,t)=>{hb.init(e,t),Oe.init(e,t)}),gw=A("ZodKSUID",(e,t)=>{Db.init(e,t),Oe.init(e,t)}),vw=A("ZodIPv4",(e,t)=>{bb.init(e,t),Oe.init(e,t)}),yw=A("ZodIPv6",(e,t)=>{Cb.init(e,t),Oe.init(e,t)}),_w=A("ZodCIDRv4",(e,t)=>{wb.init(e,t),Oe.init(e,t)}),bw=A("ZodCIDRv6",(e,t)=>{Fb.init(e,t),Oe.init(e,t)}),Cw=A("ZodBase64",(e,t)=>{Eb.init(e,t),Oe.init(e,t)}),ww=A("ZodBase64URL",(e,t)=>{kb.init(e,t),Oe.init(e,t)}),Fw=A("ZodE164",(e,t)=>{Ib.init(e,t),Oe.init(e,t)}),Ew=A("ZodJWT",(e,t)=>{$b.init(e,t),Oe.init(e,t)}),vi=A("ZodNumber",(e,t)=>{Ip.init(e,t),Ie.init(e,t),e.gt=(r,o)=>e.check(qp(r,o)),e.gte=(r,o)=>e.check(gi(r,o)),e.min=(r,o)=>e.check(gi(r,o)),e.lt=(r,o)=>e.check(zp(r,o)),e.lte=(r,o)=>e.check(Di(r,o)),e.max=(r,o)=>e.check(Di(r,o)),e.int=r=>e.check(Hp(r)),e.safe=r=>e.check(Hp(r)),e.positive=r=>e.check(qp(0,r)),e.nonnegative=r=>e.check(gi(0,r)),e.negative=r=>e.check(zp(0,r)),e.nonpositive=r=>e.check(Di(0,r)),e.multipleOf=(r,o)=>e.check(Lp(r,o)),e.step=(r,o)=>e.check(Lp(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function x(e){return IC(vi,e)}i(x,"number$1");const xw=A("ZodNumberFormat",(e,t)=>{Tb.init(e,t),vi.init(e,t)});function Hp(e){return $C(xw,e)}i(Hp,"int");const kw=A("ZodBoolean",(e,t)=>{Sb.init(e,t),Ie.init(e,t)});function Re(e){return TC(kw,e)}i(Re,"boolean");const Iw=A("ZodNull",(e,t)=>{Bb.init(e,t),Ie.init(e,t)});function Jp(e){return SC(Iw,e)}i(Jp,"_null");const Aw=A("ZodAny",(e,t)=>{Ob.init(e,t),Ie.init(e,t)});function et(){return BC(Aw)}i(et,"any");const $w=A("ZodUnknown",(e,t)=>{Rb.init(e,t),Ie.init(e,t)});function ut(){return OC($w)}i(ut,"unknown");const Tw=A("ZodNever",(e,t)=>{Nb.init(e,t),Ie.init(e,t)});function Sw(e){return RC(Tw,e)}i(Sw,"never");const Bw=A("ZodArray",(e,t)=>{Pb.init(e,t),Ie.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Da(n,r)),e.nonempty=n=>e.check(Da(1,n)),e.max=(n,r)=>e.check(Up(n,r)),e.length=(n,r)=>e.check(Zp(n,r)),e.unwrap=()=>e.element});function S(e,t){return GC(Bw,e,t)}i(S,"array$1");const Kp=A("ZodObject",(e,t)=>{Mb.init(e,t),Ie.init(e,t),De(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ut()}),e.loose=()=>e.clone({...e._zod.def,catchall:ut()}),e.strict=()=>e.clone({...e._zod.def,catchall:Sw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>l_(e,n),e.merge=n=>c_(e,n),e.pick=n=>i_(e,n),e.omit=n=>u_(e,n),e.partial=(...n)=>d_(Xp,e,n[0]),e.required=(...n)=>p_(tf,e,n[0])});function g(e,t){const n={type:"object",get shape(){return la(this,"shape",{...e}),this.shape},...G(t)};return new Kp(n)}i(g,"object$1");function yi(e,t){return new Kp({type:"object",get shape(){return la(this,"shape",{...e}),this.shape},catchall:ut(),...G(t)})}i(yi,"looseObject");const Yp=A("ZodUnion",(e,t)=>{Sp.init(e,t),Ie.init(e,t),e.options=t.options});function ee(e,t){return new Yp({type:"union",options:e,...G(t)})}i(ee,"union");const Ow=A("ZodDiscriminatedUnion",(e,t)=>{Yp.init(e,t),jb.init(e,t)});function ge(e,t,n){return new Ow({type:"union",options:t,discriminator:e,...G(n)})}i(ge,"discriminatedUnion");const Rw=A("ZodIntersection",(e,t)=>{zb.init(e,t),Ie.init(e,t)});function Nw(e,t){return new Rw({type:"intersection",left:e,right:t})}i(Nw,"intersection");const Pw=A("ZodRecord",(e,t)=>{qb.init(e,t),Ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function be(e,t,n){return new Pw({type:"record",keyType:e,valueType:t,...G(n)})}i(be,"record");const _i=A("ZodEnum",(e,t)=>{Lb.init(e,t),Ie.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new _i({...t,checks:[],...G(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new _i({...t,checks:[],...G(o),entries:s})}});function se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new _i({type:"enum",entries:n,...G(t)})}i(se,"_enum");const Mw=A("ZodLiteral",(e,t)=>{Ub.init(e,t),Ie.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function F(e,t){return new Mw({type:"literal",values:Array.isArray(e)?e:[e],...G(t)})}i(F,"literal");const jw=A("ZodTransform",(e,t)=>{Zb.init(e,t),Ie.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(po(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(po(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function zw(e){return new jw({type:"transform",transform:e})}i(zw,"transform");const Xp=A("ZodOptional",(e,t)=>{Vb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Qp(e){return new Xp({type:"optional",innerType:e})}i(Qp,"optional");const qw=A("ZodNullable",(e,t)=>{Gb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ef(e){return new qw({type:"nullable",innerType:e})}i(ef,"nullable");const Lw=A("ZodDefault",(e,t)=>{Wb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Uw(e,t){return new Lw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Uw,"_default");const Zw=A("ZodPrefault",(e,t)=>{Hb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vw(e,t){return new Zw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Vw,"prefault");const tf=A("ZodNonOptional",(e,t)=>{Jb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gw(e,t){return new tf({type:"nonoptional",innerType:e,...G(t)})}i(Gw,"nonoptional");const Ww=A("ZodCatch",(e,t)=>{Kb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Hw(e,t){return new Ww({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(Hw,"_catch");const Jw=A("ZodPipe",(e,t)=>{Yb.init(e,t),Ie.init(e,t),e.in=t.in,e.out=t.out});function nf(e,t){return new Jw({type:"pipe",in:e,out:t})}i(nf,"pipe");const Kw=A("ZodReadonly",(e,t)=>{Xb.init(e,t),Ie.init(e,t)});function Yw(e){return new Kw({type:"readonly",innerType:e})}i(Yw,"readonly");const Xw=A("ZodLazy",(e,t)=>{Qb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.getter()});function bi(e){return new Xw({type:"lazy",getter:e})}i(bi,"lazy");const Ci=A("ZodCustom",(e,t)=>{eC.init(e,t),Ie.init(e,t)});function Qw(e){const t=new it({check:"custom"});return t._zod.check=e,t}i(Qw,"check");function eF(e,t){return WC(Ci,e??(()=>!0),t)}i(eF,"custom");function tF(e,t={}){return HC(Ci,e,t)}i(tF,"refine");function nF(e){const t=Qw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(po(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(po(o))}},e(n.value,n)));return t}i(nF,"superRefine");function _a(e,t={error:`Input not instance of ${e.name}`}){const n=new Ci({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...G(t)});return n._zod.bag.Class=e,n}i(_a,"_instanceof");function rF(e){return AC(vi,e)}i(rF,"number");var me;(function(e){e.assertEqual=o=>{};function t(o){}i(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}i(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(u=>typeof o[o[u]]!="number"),a={};for(const u of s)a[u]=o[u];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(me||(me={}));var rf;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(rf||(rf={}));const V=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jt=i(e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},"getParsedType"),N=me.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ya=class Ya extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(this),r}static assert(t){if(!(t instanceof Ya))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,me.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};i(Ya,"ZodError");let jt=Ya;jt.create=e=>new jt(e);const wi=i((e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===V.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,me.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${me.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${me.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${me.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:me.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case N.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case N.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,me.assertNever(e)}return{message:n}},"errorMap");let oF=wi;function aF(){return oF}i(aF,"getErrorMap");const sF=i(e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let u="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)u=c(a,{data:t,defaultError:u}).message;return{...o,path:s,message:u}},"makeIssue");function Z(e,t){const n=aF(),r=sF({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===wi?void 0:wi].filter(o=>!!o)});e.common.issues.push(r)}i(Z,"addIssueToContext");const Xa=class Xa{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return ne;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return Xa.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return ne;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}};i(Xa,"ParseStatus");let mt=Xa;const ne=Object.freeze({status:"aborted"}),ho=i(e=>({status:"dirty",value:e}),"DIRTY"),yt=i(e=>({status:"valid",value:e}),"OK"),of=i(e=>e.status==="aborted","isAborted"),af=i(e=>e.status==="dirty","isDirty"),Pn=i(e=>e.status==="valid","isValid"),ba=i(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var W;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(W||(W={}));const $u=class $u{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};i($u,"ParseInputLazyPath");let Rt=$u;const sf=i((e,t)=>{if(Pn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new jt(e.common.issues);return this._error=n,this._error}}},"handleResult");function ie(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:i((a,u)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??u.defaultError}:typeof u.data>"u"?{message:l??r??u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:l??n??u.defaultError}},"customMap"),description:o}}i(ie,"processCreateParams");const Tu=class Tu{get description(){return this._def.description}_getType(t){return Jt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new mt,ctx:{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ba(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return sf(r,o)}"~validate"(t){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:n});return Pn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Pn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(ba(o)?o:Promise.resolve(o));return sf(r,s)}refine(t,n){const r=i(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,s)=>{const a=t(o),u=i(()=>s.addIssue({code:N.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Yt({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i(n=>this["~validate"](n),"validate")}}optional(){return Pt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return qn.create(this,this._def)}or(t){return jn.create([this,t],this._def)}and(t){return zn.create(this,t,this._def)}transform(t){return new Yt({...ie(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new yo({...ie(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new xi({typeName:M.ZodBranded,type:this,...ie(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new _o({...ie(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ki.create(this,t)}readonly(){return bo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};i(Tu,"ZodType");let ce=Tu;const iF=/^c[^\s-]{8,}$/i,uF=/^[0-9a-z]+$/,lF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cF=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dF=/^[a-z0-9_-]{21}$/i,pF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fF=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,hF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Fi;const DF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,vF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,yF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_F=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",CF=new RegExp(`^${uf}$`);function lf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}i(lf,"timeRegexSource");function wF(e){return new RegExp(`^${lf(e)}$`)}i(wF,"timeRegex");function FF(e){let t=`${uf}T${lf(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}i(FF,"datetimeRegex");function EF(e,t){return!!((t==="v4"||!t)&&DF.test(e)||(t==="v6"||!t)&&vF.test(e))}i(EF,"isValidIP");function xF(e,t){if(!pF.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}i(xF,"isValidJWT");function kF(e,t){return!!((t==="v4"||!t)&&gF.test(e)||(t==="v6"||!t)&&yF.test(e))}i(kF,"isValidCidr");const bn=class bn extends ce{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.string,received:s.parsedType}),ne}const r=new mt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,u=t.data.length<s.value;(a||u)&&(o=this._getOrReturnCtx(t,o),a?Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):u&&Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")mF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"email",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Fi||(Fi=new RegExp(hF,"u")),Fi.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"emoji",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")cF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"uuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")dF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")iF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")uF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")lF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ulid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Z(o,{validation:"url",code:N.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"regex",code:N.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?FF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?CF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?wF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?fF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?EF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ip",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?xF(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"jwt",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?kF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cidr",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?_F.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?bF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):me.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:N.invalid_string,...W.errToObj(r)})}_addCheck(t){return new bn({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...W.errToObj(t)})}url(t){return this._addCheck({kind:"url",...W.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...W.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...W.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...W.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...W.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...W.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...W.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...W.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...W.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...W.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...W.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...W.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...W.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...W.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...W.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...W.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...W.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...W.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...W.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...W.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...W.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...W.errToObj(n)})}nonempty(t){return this.min(1,W.errToObj(t))}trim(){return new bn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(bn,"ZodString");let Do=bn;Do.create=e=>new Do({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...ie(e)});function IF(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(IF,"floatSafeRemainder");const Oo=class Oo extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.number,received:s.parsedType}),ne}let r;const o=new mt;for(const s of this._def.checks)s.kind==="int"?me.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?IF(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_finite,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new Oo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new Oo({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:W.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:W.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&me.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};i(Oo,"ZodNumber");let go=Oo;go.create=e=>new go({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...ie(e)});const Ro=class Ro extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let r;const o=new mt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.bigint,received:n.parsedType}),ne}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new Ro({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new Ro({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(Ro,"ZodBigInt");let Ca=Ro;Ca.create=e=>new Ca({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...ie(e)});const Su=class Su extends ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.boolean,received:r.parsedType}),ne}return yt(t.data)}};i(Su,"ZodBoolean");let wa=Su;wa.create=e=>new wa({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...ie(e)});const Qa=class Qa extends ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.date,received:s.parsedType}),ne}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_date}),ne}const r=new mt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):me.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Qa({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:W.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:W.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};i(Qa,"ZodDate");let Fa=Qa;Fa.create=e=>new Fa({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...ie(e)});const Bu=class Bu extends ce{_parse(t){if(this._getType(t)!==V.symbol){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.symbol,received:r.parsedType}),ne}return yt(t.data)}};i(Bu,"ZodSymbol");let Ea=Bu;Ea.create=e=>new Ea({typeName:M.ZodSymbol,...ie(e)});const Ou=class Ou extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.undefined,received:r.parsedType}),ne}return yt(t.data)}};i(Ou,"ZodUndefined");let xa=Ou;xa.create=e=>new xa({typeName:M.ZodUndefined,...ie(e)});const Ru=class Ru extends ce{_parse(t){if(this._getType(t)!==V.null){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.null,received:r.parsedType}),ne}return yt(t.data)}};i(Ru,"ZodNull");let ka=Ru;ka.create=e=>new ka({typeName:M.ZodNull,...ie(e)});const Nu=class Nu extends ce{constructor(){super(...arguments),this._any=!0}_parse(t){return yt(t.data)}};i(Nu,"ZodAny");let Ia=Nu;Ia.create=e=>new Ia({typeName:M.ZodAny,...ie(e)});const Pu=class Pu extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yt(t.data)}};i(Pu,"ZodUnknown");let Aa=Pu;Aa.create=e=>new Aa({typeName:M.ZodUnknown,...ie(e)});const Mu=class Mu extends ce{_parse(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.never,received:n.parsedType}),ne}};i(Mu,"ZodNever");let Nt=Mu;Nt.create=e=>new Nt({typeName:M.ZodNever,...ie(e)});const ju=class ju extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.void,received:r.parsedType}),ne}return yt(t.data)}};i(ju,"ZodVoid");let $a=ju;$a.create=e=>new $a({typeName:M.ZodVoid,...ie(e)});const Hn=class Hn extends ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==V.array)return Z(n,{code:N.invalid_type,expected:V.array,received:n.parsedType}),ne;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,u=n.data.length<o.exactLength.value;(a||u)&&(Z(n,{code:a?N.too_big:N.too_small,minimum:u?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Z(n,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Z(n,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,u)=>o.type._parseAsync(new Rt(n,a,n.path,u)))).then(a=>mt.mergeArray(r,a));const s=[...n.data].map((a,u)=>o.type._parseSync(new Rt(n,a,n.path,u)));return mt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Hn({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new Hn({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new Hn({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(t){return this.min(1,t)}};i(Hn,"ZodArray");let Kt=Hn;Kt.create=(e,t)=>new Kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ie(t)});function Mn(e){if(e instanceof Ct){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Pt.create(Mn(r))}return new Ct({...e._def,shape:i(()=>t,"shape")})}else return e instanceof Kt?new Kt({...e._def,type:Mn(e.element)}):e instanceof Pt?Pt.create(Mn(e.unwrap())):e instanceof Xt?Xt.create(Mn(e.unwrap())):e instanceof mn?mn.create(e.items.map(t=>Mn(t))):e}i(Mn,"deepPartialify");const vt=class vt extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=me.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==V.object){const c=this._getOrReturnCtx(t);return Z(c,{code:N.invalid_type,expected:V.object,received:c.parsedType}),ne}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof Nt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||u.push(c);const l=[];for(const c of a){const d=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Rt(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Nt){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of u)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(c==="strict")u.length>0&&(Z(o,{code:N.unrecognized_keys,keys:u}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of u){const f=o.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Rt(o,f,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const f=await d.key,h=await d.value;c.push({key:f,value:h,alwaysSet:d.alwaysSet})}return c}).then(c=>mt.mergeObjectSync(r,c)):mt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:i((n,r)=>{const o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:W.errToObj(t).message??o}:{message:o}},"errorMap")}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new vt({...this._def,shape:i(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:i(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new vt({...this._def,catchall:t})}pick(t){const n={};for(const r of me.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}omit(t){const n={};for(const r of me.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}deepPartial(){return Mn(this)}partial(t){const n={};for(const r of me.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new vt({...this._def,shape:i(()=>n,"shape")})}required(t){const n={};for(const r of me.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Pt;)s=s._def.innerType;n[r]=s}return new vt({...this._def,shape:i(()=>n,"shape")})}keyof(){return cf(me.objectKeys(this.shape))}};i(vt,"ZodObject");let Ct=vt;Ct.create=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strip",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)}),Ct.strictCreate=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strict",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)}),Ct.lazycreate=(e,t)=>new Ct({shape:e,unknownKeys:"strip",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)});const zu=class zu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const u of s)if(u.result.status==="valid")return u.result;for(const u of s)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const a=s.map(u=>new jt(u.ctx.common.issues));return Z(n,{code:N.invalid_union,unionErrors:a}),ne}if(i(o,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const u=a.map(l=>new jt(l));return Z(n,{code:N.invalid_union,unionErrors:u}),ne}}get options(){return this._def.options}};i(zu,"ZodUnion");let jn=zu;jn.create=(e,t)=>new jn({options:e,typeName:M.ZodUnion,...ie(t)});function Ei(e,t){const n=Jt(e),r=Jt(t);if(e===t)return{valid:!0,data:e};if(n===V.object&&r===V.object){const o=me.objectKeys(t),s=me.objectKeys(e).filter(u=>o.indexOf(u)!==-1),a={...e,...t};for(const u of s){const l=Ei(e[u],t[u]);if(!l.valid)return{valid:!1};a[u]=l.data}return{valid:!0,data:a}}else if(n===V.array&&r===V.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],u=t[s],l=Ei(a,u);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===V.date&&r===V.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}i(Ei,"mergeValues");const qu=class qu extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=i((s,a)=>{if(of(s)||of(a))return ne;const u=Ei(s.value,a.value);return u.valid?((af(s)||af(a))&&n.dirty(),{status:n.value,value:u.data}):(Z(r,{code:N.invalid_intersection_types}),ne)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};i(qu,"ZodIntersection");let zn=qu;zn.create=(e,t,n)=>new zn({left:e,right:t,typeName:M.ZodIntersection,...ie(n)});const es=class es extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.array)return Z(r,{code:N.invalid_type,expected:V.array,received:r.parsedType}),ne;if(r.data.length<this._def.items.length)return Z(r,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ne;!this._def.rest&&r.data.length>this._def.items.length&&(Z(r,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,u)=>{const l=this._def.items[u]||this._def.rest;return l?l._parse(new Rt(r,a,r.path,u)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>mt.mergeArray(n,a)):mt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new es({...this._def,rest:t})}};i(es,"ZodTuple");let mn=es;mn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mn({items:e,typeName:M.ZodTuple,rest:null,...ie(t)})};const Lu=class Lu extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.map)return Z(r,{code:N.invalid_type,expected:V.map,received:r.parsedType}),ne;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([u,l],c)=>({key:o._parse(new Rt(r,u,r.path,[c,"key"])),value:s._parse(new Rt(r,l,r.path,[c,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}}}};i(Lu,"ZodMap");let Ta=Lu;Ta.create=(e,t,n)=>new Ta({valueType:t,keyType:e,typeName:M.ZodMap,...ie(n)});const No=class No extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.set)return Z(r,{code:N.invalid_type,expected:V.set,received:r.parsedType}),ne;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Z(r,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Z(r,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return ne;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}i(a,"finalizeSet");const u=[...r.data.values()].map((l,c)=>s._parse(new Rt(r,l,r.path,c)));return r.common.async?Promise.all(u).then(l=>a(l)):a(u)}min(t,n){return new No({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new No({...this._def,maxSize:{value:t,message:W.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};i(No,"ZodSet");let Sa=No;Sa.create=(e,t)=>new Sa({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...ie(t)});const Uu=class Uu extends ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};i(Uu,"ZodLazy");let Ba=Uu;Ba.create=(e,t)=>new Ba({getter:e,typeName:M.ZodLazy,...ie(t)});const Zu=class Zu extends ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Z(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),ne}return{status:"valid",value:t.data}}get value(){return this._def.value}};i(Zu,"ZodLiteral");let Oa=Zu;Oa.create=(e,t)=>new Oa({value:e,typeName:M.ZodLiteral,...ie(t)});function cf(e,t){return new vo({values:e,typeName:M.ZodEnum,...ie(t)})}i(cf,"createZodEnum");const Po=class Po extends ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{expected:me.joinValues(r),received:n.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{received:n.data,code:N.invalid_enum_value,options:r}),ne}return yt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Po.create(t,{...this._def,...n})}exclude(t,n=this._def){return Po.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};i(Po,"ZodEnum");let vo=Po;vo.create=cf;const Vu=class Vu extends ce{_parse(t){const n=me.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==V.string&&r.parsedType!==V.number){const o=me.objectValues(n);return Z(r,{expected:me.joinValues(o),received:r.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(me.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=me.objectValues(n);return Z(r,{received:r.data,code:N.invalid_enum_value,options:o}),ne}return yt(t.data)}get enum(){return this._def.values}};i(Vu,"ZodNativeEnum");let Ra=Vu;Ra.create=(e,t)=>new Ra({values:e,typeName:M.ZodNativeEnum,...ie(t)});const Gu=class Gu extends ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==V.promise&&n.common.async===!1)return Z(n,{code:N.invalid_type,expected:V.promise,received:n.parsedType}),ne;const r=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return yt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};i(Gu,"ZodPromise");let qn=Gu;qn.create=(e,t)=>new qn({type:e,typeName:M.ZodPromise,...ie(t)});const Wu=class Wu extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i(a=>{Z(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async u=>{if(n.value==="aborted")return ne;const l=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return l.status==="aborted"?ne:l.status==="dirty"||n.value==="dirty"?ho(l.value):l});{if(n.value==="aborted")return ne;const u=this._def.schema._parseSync({data:a,path:r.path,parent:r});return u.status==="aborted"?ne:u.status==="dirty"||n.value==="dirty"?ho(u.value):u}}if(o.type==="refinement"){const a=i(u=>{const l=o.refinement(u,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u},"executeRefinement");if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value).then(()=>({status:n.value,value:u.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Pn(a))return ne;const u=o.transform(a.value,s);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Pn(a)?Promise.resolve(o.transform(a.value,s)).then(u=>({status:n.value,value:u})):ne);me.assertNever(o)}};i(Wu,"ZodEffects");let Yt=Wu;Yt.create=(e,t,n)=>new Yt({schema:e,typeName:M.ZodEffects,effect:t,...ie(n)}),Yt.createWithPreprocess=(e,t,n)=>new Yt({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...ie(n)});const Hu=class Hu extends ce{_parse(t){return this._getType(t)===V.undefined?yt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Hu,"ZodOptional");let Pt=Hu;Pt.create=(e,t)=>new Pt({innerType:e,typeName:M.ZodOptional,...ie(t)});const Ju=class Ju extends ce{_parse(t){return this._getType(t)===V.null?yt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Ju,"ZodNullable");let Xt=Ju;Xt.create=(e,t)=>new Xt({innerType:e,typeName:M.ZodNullable,...ie(t)});const Ku=class Ku extends ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};i(Ku,"ZodDefault");let yo=Ku;yo.create=(e,t)=>new yo({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ie(t)});const Yu=class Yu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ba(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};i(Yu,"ZodCatch");let _o=Yu;_o.create=(e,t)=>new _o({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ie(t)});const Xu=class Xu extends ce{_parse(t){if(this._getType(t)!==V.nan){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.nan,received:r.parsedType}),ne}return{status:"valid",value:t.data}}};i(Xu,"ZodNaN");let Na=Xu;Na.create=e=>new Na({typeName:M.ZodNaN,...ie(e)});const Qu=class Qu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};i(Qu,"ZodBranded");let xi=Qu;const ts=class ts extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return i(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ne:s.status==="dirty"?(n.dirty(),ho(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ne:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new ts({in:t,out:n,typeName:M.ZodPipeline})}};i(ts,"ZodPipeline");let ki=ts;const el=class el extends ce{_parse(t){const n=this._def.innerType._parse(t),r=i(o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return ba(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};i(el,"ZodReadonly");let bo=el;bo.create=(e,t)=>new bo({innerType:e,typeName:M.ZodReadonly,...ie(t)});var M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));const we=Do.create,Mt=go.create;Nt.create;const Qt=Kt.create,wt=Ct.create,Ii=jn.create;zn.create,mn.create;const Pa=vo.create;qn.create,Pt.create,Xt.create;const tl=class tl extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(tl,"ParseError");let Ma=tl;function Ai(e){}i(Ai,"noop");function AF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Ai,onError:n=Ai,onRetry:r=Ai,onComment:o}=e;let s="",a=!0,u,l="",c="";function d(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[b,C]=$F(`${s}${y}`);for(const w of b)f(w);s=C,a=!1}i(d,"feed");function f(v){if(v===""){D();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const b=v.slice(0,y),C=v[y+1]===" "?2:1,w=v.slice(y+C);h(b,w,v);return}h(v,"",v)}i(f,"parseLine");function h(v,y,b){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
115
- `;break;case"id":u=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?r(parseInt(y,10)):n(new Ma(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:b}));break;default:n(new Ma(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:y,line:b}));break}}i(h,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
116
- `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function m(v={}){s&&v.consume&&f(s),a=!0,u=void 0,l="",c="",s=""}return i(m,"reset"),{feed:d,reset:m}}i(AF,"createParser");function $F(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
114
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const f=d[1];if(t===d[0]){a(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(f.cycle){a(d);continue}if(f.count>1&&r.reused==="ref"){a(d);continue}}const u=i((d,f)=>{const m=this.seen.get(d),D=m.def??m.schema,h={...D};if(m.ref===null)return;const v=m.ref;if(m.ref=null,v){u(v,f);const y=this.seen.get(v).schema;y.$ref&&f.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,h))}m.isParent||this.override({zodSchema:d,jsonSchema:D,path:m.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,o.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const f=d[1];f.def&&f.defId&&(c[f.defId]=f.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(Su,"JSONSchemaGenerator");let wa=Su;function YC(e,t){if(e instanceof ba){const r=new wa(t),o={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=new wa(t);return n.process(e),n.emit(e,t)}i(YC,"toJSONSchema");function Ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ze(o.element,n);case"object":{for(const s in o.shape)if(Ze(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ze(s,n))return!0;return!1}case"intersection":return Ze(o.left,n)||Ze(o.right,n);case"tuple":{for(const s of o.items)if(Ze(s,n))return!0;return!!(o.rest&&Ze(o.rest,n))}case"record":return Ze(o.keyType,n)||Ze(o.valueType,n);case"map":return Ze(o.keyType,n)||Ze(o.valueType,n);case"set":return Ze(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ze(o.innerType,n);case"lazy":return Ze(o.getter(),n);case"default":return Ze(o.innerType,n);case"prefault":return Ze(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ze(o.in,n)||Ze(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}i(Ze,"isTransforming");const XC=A("ZodISODateTime",(e,t)=>{yb.init(e,t),Oe.init(e,t)});function QC(e){return xC(XC,e)}i(QC,"datetime");const ew=A("ZodISODate",(e,t)=>{_b.init(e,t),Oe.init(e,t)});function tw(e){return kC(ew,e)}i(tw,"date");const nw=A("ZodISOTime",(e,t)=>{bb.init(e,t),Oe.init(e,t)});function rw(e){return IC(nw,e)}i(rw,"time");const ow=A("ZodISODuration",(e,t)=>{Cb.init(e,t),Oe.init(e,t)});function aw(e){return AC(ow,e)}i(aw,"duration");const sw=i((e,t)=>{yp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>D_(e,n),"value")},flatten:{value:i(n=>h_(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),Fa=A("ZodError",sw,{Parent:Error}),iw=g_(Fa),uw=v_(Fa),lw=bp(Fa),Hp=Cp(Fa),Ie=A("ZodType",(e,t)=>(we.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>vn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>iw(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>lw(e,n,r),e.parseAsync=async(n,r)=>uw(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Hp(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(rF(n,r)),e.superRefine=n=>e.check(oF(n)),e.overwrite=n=>e.check(vo(n)),e.optional=()=>nf(e),e.nullable=()=>rf(e),e.nullish=()=>nf(rf(e)),e.nonoptional=n=>Hw(e,n),e.array=()=>S(e),e.or=n=>ee([e,n]),e.and=n=>Mw(e,n),e.transform=n=>af(e,qw(n)),e.default=n=>Vw(e,n),e.prefault=n=>Ww(e,n),e.catch=n=>Kw(e,n),e.pipe=n=>af(e,n),e.readonly=()=>Qw(e),e.describe=n=>{const r=e.clone();return go.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return go.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return go.get(e);const r=e.clone();return go.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Jp=A("_ZodString",(e,t)=>{gi.init(e,t),Ie.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(MC(...r)),e.includes=(...r)=>e.check(LC(...r)),e.startsWith=(...r)=>e.check(qC(...r)),e.endsWith=(...r)=>e.check(UC(...r)),e.min=(...r)=>e.check(Ca(...r)),e.max=(...r)=>e.check(Gp(...r)),e.length=(...r)=>e.check(Wp(...r)),e.nonempty=(...r)=>e.check(Ca(1,...r)),e.lowercase=r=>e.check(jC(r)),e.uppercase=r=>e.check(zC(r)),e.trim=()=>e.check(VC()),e.normalize=(...r)=>e.check(ZC(...r)),e.toLowerCase=()=>e.check(GC()),e.toUpperCase=()=>e.check(WC())}),cw=A("ZodString",(e,t)=>{gi.init(e,t),Jp.init(e,t),e.email=n=>e.check(aC(dw,n)),e.url=n=>e.check(cC(pw,n)),e.jwt=n=>e.check(EC(kw,n)),e.emoji=n=>e.check(dC(fw,n)),e.guid=n=>e.check(qp(Kp,n)),e.uuid=n=>e.check(sC(Ea,n)),e.uuidv4=n=>e.check(iC(Ea,n)),e.uuidv6=n=>e.check(uC(Ea,n)),e.uuidv7=n=>e.check(lC(Ea,n)),e.nanoid=n=>e.check(pC(mw,n)),e.guid=n=>e.check(qp(Kp,n)),e.cuid=n=>e.check(fC(hw,n)),e.cuid2=n=>e.check(mC(Dw,n)),e.ulid=n=>e.check(hC(gw,n)),e.base64=n=>e.check(CC(Fw,n)),e.base64url=n=>e.check(wC(Ew,n)),e.xid=n=>e.check(DC(vw,n)),e.ksuid=n=>e.check(gC(yw,n)),e.ipv4=n=>e.check(vC(_w,n)),e.ipv6=n=>e.check(yC(bw,n)),e.cidrv4=n=>e.check(_C(Cw,n)),e.cidrv6=n=>e.check(bC(ww,n)),e.e164=n=>e.check(FC(xw,n)),e.datetime=n=>e.check(QC(n)),e.date=n=>e.check(tw(n)),e.time=n=>e.check(rw(n)),e.duration=n=>e.check(aw(n))});function p(e){return oC(cw,e)}i(p,"string");const Oe=A("ZodStringFormat",(e,t)=>{Se.init(e,t),Jp.init(e,t)}),dw=A("ZodEmail",(e,t)=>{cb.init(e,t),Oe.init(e,t)}),Kp=A("ZodGUID",(e,t)=>{ub.init(e,t),Oe.init(e,t)}),Ea=A("ZodUUID",(e,t)=>{lb.init(e,t),Oe.init(e,t)}),pw=A("ZodURL",(e,t)=>{db.init(e,t),Oe.init(e,t)}),fw=A("ZodEmoji",(e,t)=>{pb.init(e,t),Oe.init(e,t)}),mw=A("ZodNanoID",(e,t)=>{fb.init(e,t),Oe.init(e,t)}),hw=A("ZodCUID",(e,t)=>{mb.init(e,t),Oe.init(e,t)}),Dw=A("ZodCUID2",(e,t)=>{hb.init(e,t),Oe.init(e,t)}),gw=A("ZodULID",(e,t)=>{Db.init(e,t),Oe.init(e,t)}),vw=A("ZodXID",(e,t)=>{gb.init(e,t),Oe.init(e,t)}),yw=A("ZodKSUID",(e,t)=>{vb.init(e,t),Oe.init(e,t)}),_w=A("ZodIPv4",(e,t)=>{wb.init(e,t),Oe.init(e,t)}),bw=A("ZodIPv6",(e,t)=>{Fb.init(e,t),Oe.init(e,t)}),Cw=A("ZodCIDRv4",(e,t)=>{Eb.init(e,t),Oe.init(e,t)}),ww=A("ZodCIDRv6",(e,t)=>{xb.init(e,t),Oe.init(e,t)}),Fw=A("ZodBase64",(e,t)=>{kb.init(e,t),Oe.init(e,t)}),Ew=A("ZodBase64URL",(e,t)=>{Ab.init(e,t),Oe.init(e,t)}),xw=A("ZodE164",(e,t)=>{$b.init(e,t),Oe.init(e,t)}),kw=A("ZodJWT",(e,t)=>{Sb.init(e,t),Oe.init(e,t)}),bi=A("ZodNumber",(e,t)=>{Tp.init(e,t),Ie.init(e,t),e.gt=(r,o)=>e.check(Zp(r,o)),e.gte=(r,o)=>e.check(_i(r,o)),e.min=(r,o)=>e.check(_i(r,o)),e.lt=(r,o)=>e.check(Up(r,o)),e.lte=(r,o)=>e.check(yi(r,o)),e.max=(r,o)=>e.check(yi(r,o)),e.int=r=>e.check(Yp(r)),e.safe=r=>e.check(Yp(r)),e.positive=r=>e.check(Zp(0,r)),e.nonnegative=r=>e.check(_i(0,r)),e.negative=r=>e.check(Up(0,r)),e.nonpositive=r=>e.check(yi(0,r)),e.multipleOf=(r,o)=>e.check(Vp(r,o)),e.step=(r,o)=>e.check(Vp(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function x(e){return $C(bi,e)}i(x,"number$1");const Iw=A("ZodNumberFormat",(e,t)=>{Bb.init(e,t),bi.init(e,t)});function Yp(e){return SC(Iw,e)}i(Yp,"int");const Aw=A("ZodBoolean",(e,t)=>{Ob.init(e,t),Ie.init(e,t)});function Re(e){return BC(Aw,e)}i(Re,"boolean");const $w=A("ZodNull",(e,t)=>{Rb.init(e,t),Ie.init(e,t)});function Xp(e){return OC($w,e)}i(Xp,"_null");const Tw=A("ZodAny",(e,t)=>{Nb.init(e,t),Ie.init(e,t)});function et(){return RC(Tw)}i(et,"any");const Sw=A("ZodUnknown",(e,t)=>{Pb.init(e,t),Ie.init(e,t)});function lt(){return NC(Sw)}i(lt,"unknown");const Bw=A("ZodNever",(e,t)=>{Mb.init(e,t),Ie.init(e,t)});function Ow(e){return PC(Bw,e)}i(Ow,"never");const Rw=A("ZodArray",(e,t)=>{jb.init(e,t),Ie.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Ca(n,r)),e.nonempty=n=>e.check(Ca(1,n)),e.max=(n,r)=>e.check(Gp(n,r)),e.length=(n,r)=>e.check(Wp(n,r)),e.unwrap=()=>e.element});function S(e,t){return HC(Rw,e,t)}i(S,"array$1");const Qp=A("ZodObject",(e,t)=>{zb.init(e,t),Ie.init(e,t),De(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:lt()}),e.loose=()=>e.clone({...e._zod.def,catchall:lt()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ow()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>d_(e,n),e.merge=n=>p_(e,n),e.pick=n=>l_(e,n),e.omit=n=>c_(e,n),e.partial=(...n)=>f_(tf,e,n[0]),e.required=(...n)=>m_(of,e,n[0])});function g(e,t){const n={type:"object",get shape(){return ha(this,"shape",{...e}),this.shape},...G(t)};return new Qp(n)}i(g,"object$1");function Ci(e,t){return new Qp({type:"object",get shape(){return ha(this,"shape",{...e}),this.shape},catchall:lt(),...G(t)})}i(Ci,"looseObject");const ef=A("ZodUnion",(e,t)=>{Rp.init(e,t),Ie.init(e,t),e.options=t.options});function ee(e,t){return new ef({type:"union",options:e,...G(t)})}i(ee,"union");const Nw=A("ZodDiscriminatedUnion",(e,t)=>{ef.init(e,t),Lb.init(e,t)});function ge(e,t,n){return new Nw({type:"union",options:t,discriminator:e,...G(n)})}i(ge,"discriminatedUnion");const Pw=A("ZodIntersection",(e,t)=>{qb.init(e,t),Ie.init(e,t)});function Mw(e,t){return new Pw({type:"intersection",left:e,right:t})}i(Mw,"intersection");const jw=A("ZodRecord",(e,t)=>{Ub.init(e,t),Ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Ce(e,t,n){return new jw({type:"record",keyType:e,valueType:t,...G(n)})}i(Ce,"record");const wi=A("ZodEnum",(e,t)=>{Zb.init(e,t),Ie.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new wi({...t,checks:[],...G(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new wi({...t,checks:[],...G(o),entries:s})}});function se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new wi({type:"enum",entries:n,...G(t)})}i(se,"_enum");const zw=A("ZodLiteral",(e,t)=>{Vb.init(e,t),Ie.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function F(e,t){return new zw({type:"literal",values:Array.isArray(e)?e:[e],...G(t)})}i(F,"literal");const Lw=A("ZodTransform",(e,t)=>{Gb.init(e,t),Ie.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Do(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(Do(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function qw(e){return new Lw({type:"transform",transform:e})}i(qw,"transform");const tf=A("ZodOptional",(e,t)=>{Wb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nf(e){return new tf({type:"optional",innerType:e})}i(nf,"optional");const Uw=A("ZodNullable",(e,t)=>{Hb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rf(e){return new Uw({type:"nullable",innerType:e})}i(rf,"nullable");const Zw=A("ZodDefault",(e,t)=>{Jb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Vw(e,t){return new Zw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Vw,"_default");const Gw=A("ZodPrefault",(e,t)=>{Kb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ww(e,t){return new Gw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Ww,"prefault");const of=A("ZodNonOptional",(e,t)=>{Yb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Hw(e,t){return new of({type:"nonoptional",innerType:e,...G(t)})}i(Hw,"nonoptional");const Jw=A("ZodCatch",(e,t)=>{Xb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Kw(e,t){return new Jw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(Kw,"_catch");const Yw=A("ZodPipe",(e,t)=>{Qb.init(e,t),Ie.init(e,t),e.in=t.in,e.out=t.out});function af(e,t){return new Yw({type:"pipe",in:e,out:t})}i(af,"pipe");const Xw=A("ZodReadonly",(e,t)=>{eC.init(e,t),Ie.init(e,t)});function Qw(e){return new Xw({type:"readonly",innerType:e})}i(Qw,"readonly");const eF=A("ZodLazy",(e,t)=>{tC.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Fi(e){return new eF({type:"lazy",getter:e})}i(Fi,"lazy");const Ei=A("ZodCustom",(e,t)=>{nC.init(e,t),Ie.init(e,t)});function tF(e){const t=new ut({check:"custom"});return t._zod.check=e,t}i(tF,"check");function nF(e,t){return JC(Ei,e??(()=>!0),t)}i(nF,"custom");function rF(e,t={}){return KC(Ei,e,t)}i(rF,"refine");function oF(e){const t=tF(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Do(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(Do(o))}},e(n.value,n)));return t}i(oF,"superRefine");function xa(e,t={error:`Input not instance of ${e.name}`}){const n=new Ei({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...G(t)});return n._zod.bag.Class=e,n}i(xa,"_instanceof");function aF(e){return TC(bi,e)}i(aF,"number");var me;(function(e){e.assertEqual=o=>{};function t(o){}i(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}i(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(u=>typeof o[o[u]]!="number"),a={};for(const u of s)a[u]=o[u];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(me||(me={}));var sf;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(sf||(sf={}));const V=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yt=i(e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},"getParsedType"),N=me.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),rs=class rs extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(this),r}static assert(t){if(!(t instanceof rs))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,me.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};i(rs,"ZodError");let zt=rs;zt.create=e=>new zt(e);const xi=i((e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===V.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,me.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${me.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${me.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${me.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:me.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case N.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case N.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,me.assertNever(e)}return{message:n}},"errorMap");let sF=xi;function iF(){return sF}i(iF,"getErrorMap");const uF=i(e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let u="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)u=c(a,{data:t,defaultError:u}).message;return{...o,path:s,message:u}},"makeIssue");function Z(e,t){const n=iF(),r=uF({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===xi?void 0:xi].filter(o=>!!o)});e.common.issues.push(r)}i(Z,"addIssueToContext");const os=class os{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return ne;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return os.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return ne;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}};i(os,"ParseStatus");let ht=os;const ne=Object.freeze({status:"aborted"}),yo=i(e=>({status:"dirty",value:e}),"DIRTY"),_t=i(e=>({status:"valid",value:e}),"OK"),uf=i(e=>e.status==="aborted","isAborted"),lf=i(e=>e.status==="dirty","isDirty"),zn=i(e=>e.status==="valid","isValid"),ka=i(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var W;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(W||(W={}));const Bu=class Bu{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};i(Bu,"ParseInputLazyPath");let Nt=Bu;const cf=i((e,t)=>{if(zn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new zt(e.common.issues);return this._error=n,this._error}}},"handleResult");function ie(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:i((a,u)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??u.defaultError}:typeof u.data>"u"?{message:l??r??u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:l??n??u.defaultError}},"customMap"),description:o}}i(ie,"processCreateParams");const Ou=class Ou{get description(){return this._def.description}_getType(t){return Yt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ht,ctx:{common:t.parent.common,data:t.data,parsedType:Yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ka(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return cf(r,o)}"~validate"(t){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yt(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:n});return zn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>zn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(ka(o)?o:Promise.resolve(o));return cf(r,s)}refine(t,n){const r=i(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,s)=>{const a=t(o),u=i(()=>s.addIssue({code:N.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Qt({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i(n=>this["~validate"](n),"validate")}}optional(){return Mt.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xt.create(this)}promise(){return Zn.create(this,this._def)}or(t){return qn.create([this,t],this._def)}and(t){return Un.create(this,t,this._def)}transform(t){return new Qt({...ie(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new wo({...ie(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Ai({typeName:M.ZodBranded,type:this,...ie(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Fo({...ie(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return $i.create(this,t)}readonly(){return Eo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};i(Ou,"ZodType");let de=Ou;const lF=/^c[^\s-]{8,}$/i,cF=/^[0-9a-z]+$/,dF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pF=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,fF=/^[a-z0-9_-]{21}$/i,mF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hF=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,DF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ki;const vF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,_F=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,bF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,CF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,df="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",FF=new RegExp(`^${df}$`);function pf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}i(pf,"timeRegexSource");function EF(e){return new RegExp(`^${pf(e)}$`)}i(EF,"timeRegex");function xF(e){let t=`${df}T${pf(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}i(xF,"datetimeRegex");function kF(e,t){return!!((t==="v4"||!t)&&vF.test(e)||(t==="v6"||!t)&&_F.test(e))}i(kF,"isValidIP");function IF(e,t){if(!mF.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}i(IF,"isValidJWT");function AF(e,t){return!!((t==="v4"||!t)&&yF.test(e)||(t==="v6"||!t)&&bF.test(e))}i(AF,"isValidCidr");const kn=class kn extends de{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.string,received:s.parsedType}),ne}const r=new ht;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,u=t.data.length<s.value;(a||u)&&(o=this._getOrReturnCtx(t,o),a?Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):u&&Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")DF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"email",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ki||(ki=new RegExp(gF,"u")),ki.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"emoji",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")pF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"uuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")fF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")lF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")cF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")dF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ulid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Z(o,{validation:"url",code:N.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"regex",code:N.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?xF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?FF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?EF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?hF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?kF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ip",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?IF(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"jwt",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?AF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cidr",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?CF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?wF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):me.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:N.invalid_string,...W.errToObj(r)})}_addCheck(t){return new kn({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...W.errToObj(t)})}url(t){return this._addCheck({kind:"url",...W.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...W.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...W.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...W.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...W.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...W.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...W.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...W.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...W.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...W.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...W.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...W.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...W.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...W.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...W.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...W.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...W.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...W.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...W.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...W.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...W.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...W.errToObj(n)})}nonempty(t){return this.min(1,W.errToObj(t))}trim(){return new kn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new kn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new kn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(kn,"ZodString");let _o=kn;_o.create=e=>new _o({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...ie(e)});function $F(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i($F,"floatSafeRemainder");const Mo=class Mo extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.number,received:s.parsedType}),ne}let r;const o=new ht;for(const s of this._def.checks)s.kind==="int"?me.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?$F(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_finite,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new Mo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new Mo({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:W.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:W.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&me.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};i(Mo,"ZodNumber");let bo=Mo;bo.create=e=>new bo({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...ie(e)});const jo=class jo extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let r;const o=new ht;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.bigint,received:n.parsedType}),ne}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new jo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new jo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(jo,"ZodBigInt");let Ia=jo;Ia.create=e=>new Ia({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...ie(e)});const Ru=class Ru extends de{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.boolean,received:r.parsedType}),ne}return _t(t.data)}};i(Ru,"ZodBoolean");let Aa=Ru;Aa.create=e=>new Aa({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...ie(e)});const as=class as extends de{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.date,received:s.parsedType}),ne}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_date}),ne}const r=new ht;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):me.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new as({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:W.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:W.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};i(as,"ZodDate");let $a=as;$a.create=e=>new $a({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...ie(e)});const Nu=class Nu extends de{_parse(t){if(this._getType(t)!==V.symbol){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.symbol,received:r.parsedType}),ne}return _t(t.data)}};i(Nu,"ZodSymbol");let Ta=Nu;Ta.create=e=>new Ta({typeName:M.ZodSymbol,...ie(e)});const Pu=class Pu extends de{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.undefined,received:r.parsedType}),ne}return _t(t.data)}};i(Pu,"ZodUndefined");let Sa=Pu;Sa.create=e=>new Sa({typeName:M.ZodUndefined,...ie(e)});const Mu=class Mu extends de{_parse(t){if(this._getType(t)!==V.null){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.null,received:r.parsedType}),ne}return _t(t.data)}};i(Mu,"ZodNull");let Ba=Mu;Ba.create=e=>new Ba({typeName:M.ZodNull,...ie(e)});const ju=class ju extends de{constructor(){super(...arguments),this._any=!0}_parse(t){return _t(t.data)}};i(ju,"ZodAny");let Oa=ju;Oa.create=e=>new Oa({typeName:M.ZodAny,...ie(e)});const zu=class zu extends de{constructor(){super(...arguments),this._unknown=!0}_parse(t){return _t(t.data)}};i(zu,"ZodUnknown");let Ra=zu;Ra.create=e=>new Ra({typeName:M.ZodUnknown,...ie(e)});const Lu=class Lu extends de{_parse(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.never,received:n.parsedType}),ne}};i(Lu,"ZodNever");let Pt=Lu;Pt.create=e=>new Pt({typeName:M.ZodNever,...ie(e)});const qu=class qu extends de{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.void,received:r.parsedType}),ne}return _t(t.data)}};i(qu,"ZodVoid");let Na=qu;Na.create=e=>new Na({typeName:M.ZodVoid,...ie(e)});const Yn=class Yn extends de{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==V.array)return Z(n,{code:N.invalid_type,expected:V.array,received:n.parsedType}),ne;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,u=n.data.length<o.exactLength.value;(a||u)&&(Z(n,{code:a?N.too_big:N.too_small,minimum:u?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Z(n,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Z(n,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,u)=>o.type._parseAsync(new Nt(n,a,n.path,u)))).then(a=>ht.mergeArray(r,a));const s=[...n.data].map((a,u)=>o.type._parseSync(new Nt(n,a,n.path,u)));return ht.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Yn({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new Yn({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new Yn({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(t){return this.min(1,t)}};i(Yn,"ZodArray");let Xt=Yn;Xt.create=(e,t)=>new Xt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ie(t)});function Ln(e){if(e instanceof wt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Mt.create(Ln(r))}return new wt({...e._def,shape:i(()=>t,"shape")})}else return e instanceof Xt?new Xt({...e._def,type:Ln(e.element)}):e instanceof Mt?Mt.create(Ln(e.unwrap())):e instanceof en?en.create(Ln(e.unwrap())):e instanceof _n?_n.create(e.items.map(t=>Ln(t))):e}i(Ln,"deepPartialify");const yt=class yt extends de{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=me.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==V.object){const c=this._getOrReturnCtx(t);return Z(c,{code:N.invalid_type,expected:V.object,received:c.parsedType}),ne}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof Pt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||u.push(c);const l=[];for(const c of a){const d=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Nt(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Pt){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of u)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(c==="strict")u.length>0&&(Z(o,{code:N.unrecognized_keys,keys:u}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of u){const f=o.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Nt(o,f,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const f=await d.key,m=await d.value;c.push({key:f,value:m,alwaysSet:d.alwaysSet})}return c}).then(c=>ht.mergeObjectSync(r,c)):ht.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new yt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:i((n,r)=>{const o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:W.errToObj(t).message??o}:{message:o}},"errorMap")}:{}})}strip(){return new yt({...this._def,unknownKeys:"strip"})}passthrough(){return new yt({...this._def,unknownKeys:"passthrough"})}extend(t){return new yt({...this._def,shape:i(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new yt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:i(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new yt({...this._def,catchall:t})}pick(t){const n={};for(const r of me.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new yt({...this._def,shape:i(()=>n,"shape")})}omit(t){const n={};for(const r of me.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new yt({...this._def,shape:i(()=>n,"shape")})}deepPartial(){return Ln(this)}partial(t){const n={};for(const r of me.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new yt({...this._def,shape:i(()=>n,"shape")})}required(t){const n={};for(const r of me.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Mt;)s=s._def.innerType;n[r]=s}return new yt({...this._def,shape:i(()=>n,"shape")})}keyof(){return ff(me.objectKeys(this.shape))}};i(yt,"ZodObject");let wt=yt;wt.create=(e,t)=>new wt({shape:i(()=>e,"shape"),unknownKeys:"strip",catchall:Pt.create(),typeName:M.ZodObject,...ie(t)}),wt.strictCreate=(e,t)=>new wt({shape:i(()=>e,"shape"),unknownKeys:"strict",catchall:Pt.create(),typeName:M.ZodObject,...ie(t)}),wt.lazycreate=(e,t)=>new wt({shape:e,unknownKeys:"strip",catchall:Pt.create(),typeName:M.ZodObject,...ie(t)});const Uu=class Uu extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const u of s)if(u.result.status==="valid")return u.result;for(const u of s)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const a=s.map(u=>new zt(u.ctx.common.issues));return Z(n,{code:N.invalid_union,unionErrors:a}),ne}if(i(o,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const u=a.map(l=>new zt(l));return Z(n,{code:N.invalid_union,unionErrors:u}),ne}}get options(){return this._def.options}};i(Uu,"ZodUnion");let qn=Uu;qn.create=(e,t)=>new qn({options:e,typeName:M.ZodUnion,...ie(t)});function Ii(e,t){const n=Yt(e),r=Yt(t);if(e===t)return{valid:!0,data:e};if(n===V.object&&r===V.object){const o=me.objectKeys(t),s=me.objectKeys(e).filter(u=>o.indexOf(u)!==-1),a={...e,...t};for(const u of s){const l=Ii(e[u],t[u]);if(!l.valid)return{valid:!1};a[u]=l.data}return{valid:!0,data:a}}else if(n===V.array&&r===V.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],u=t[s],l=Ii(a,u);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===V.date&&r===V.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}i(Ii,"mergeValues");const Zu=class Zu extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=i((s,a)=>{if(uf(s)||uf(a))return ne;const u=Ii(s.value,a.value);return u.valid?((lf(s)||lf(a))&&n.dirty(),{status:n.value,value:u.data}):(Z(r,{code:N.invalid_intersection_types}),ne)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};i(Zu,"ZodIntersection");let Un=Zu;Un.create=(e,t,n)=>new Un({left:e,right:t,typeName:M.ZodIntersection,...ie(n)});const ss=class ss extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.array)return Z(r,{code:N.invalid_type,expected:V.array,received:r.parsedType}),ne;if(r.data.length<this._def.items.length)return Z(r,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ne;!this._def.rest&&r.data.length>this._def.items.length&&(Z(r,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,u)=>{const l=this._def.items[u]||this._def.rest;return l?l._parse(new Nt(r,a,r.path,u)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>ht.mergeArray(n,a)):ht.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new ss({...this._def,rest:t})}};i(ss,"ZodTuple");let _n=ss;_n.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _n({items:e,typeName:M.ZodTuple,rest:null,...ie(t)})};const Vu=class Vu extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.map)return Z(r,{code:N.invalid_type,expected:V.map,received:r.parsedType}),ne;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([u,l],c)=>({key:o._parse(new Nt(r,u,r.path,[c,"key"])),value:s._parse(new Nt(r,l,r.path,[c,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}}}};i(Vu,"ZodMap");let Pa=Vu;Pa.create=(e,t,n)=>new Pa({valueType:t,keyType:e,typeName:M.ZodMap,...ie(n)});const zo=class zo extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.set)return Z(r,{code:N.invalid_type,expected:V.set,received:r.parsedType}),ne;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Z(r,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Z(r,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return ne;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}i(a,"finalizeSet");const u=[...r.data.values()].map((l,c)=>s._parse(new Nt(r,l,r.path,c)));return r.common.async?Promise.all(u).then(l=>a(l)):a(u)}min(t,n){return new zo({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new zo({...this._def,maxSize:{value:t,message:W.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};i(zo,"ZodSet");let Ma=zo;Ma.create=(e,t)=>new Ma({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...ie(t)});const Gu=class Gu extends de{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};i(Gu,"ZodLazy");let ja=Gu;ja.create=(e,t)=>new ja({getter:e,typeName:M.ZodLazy,...ie(t)});const Wu=class Wu extends de{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Z(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),ne}return{status:"valid",value:t.data}}get value(){return this._def.value}};i(Wu,"ZodLiteral");let za=Wu;za.create=(e,t)=>new za({value:e,typeName:M.ZodLiteral,...ie(t)});function ff(e,t){return new Co({values:e,typeName:M.ZodEnum,...ie(t)})}i(ff,"createZodEnum");const Lo=class Lo extends de{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{expected:me.joinValues(r),received:n.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{received:n.data,code:N.invalid_enum_value,options:r}),ne}return _t(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Lo.create(t,{...this._def,...n})}exclude(t,n=this._def){return Lo.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};i(Lo,"ZodEnum");let Co=Lo;Co.create=ff;const Hu=class Hu extends de{_parse(t){const n=me.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==V.string&&r.parsedType!==V.number){const o=me.objectValues(n);return Z(r,{expected:me.joinValues(o),received:r.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(me.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=me.objectValues(n);return Z(r,{received:r.data,code:N.invalid_enum_value,options:o}),ne}return _t(t.data)}get enum(){return this._def.values}};i(Hu,"ZodNativeEnum");let La=Hu;La.create=(e,t)=>new La({values:e,typeName:M.ZodNativeEnum,...ie(t)});const Ju=class Ju extends de{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==V.promise&&n.common.async===!1)return Z(n,{code:N.invalid_type,expected:V.promise,received:n.parsedType}),ne;const r=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return _t(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};i(Ju,"ZodPromise");let Zn=Ju;Zn.create=(e,t)=>new Zn({type:e,typeName:M.ZodPromise,...ie(t)});const Ku=class Ku extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i(a=>{Z(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async u=>{if(n.value==="aborted")return ne;const l=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return l.status==="aborted"?ne:l.status==="dirty"||n.value==="dirty"?yo(l.value):l});{if(n.value==="aborted")return ne;const u=this._def.schema._parseSync({data:a,path:r.path,parent:r});return u.status==="aborted"?ne:u.status==="dirty"||n.value==="dirty"?yo(u.value):u}}if(o.type==="refinement"){const a=i(u=>{const l=o.refinement(u,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u},"executeRefinement");if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value).then(()=>({status:n.value,value:u.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!zn(a))return ne;const u=o.transform(a.value,s);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>zn(a)?Promise.resolve(o.transform(a.value,s)).then(u=>({status:n.value,value:u})):ne);me.assertNever(o)}};i(Ku,"ZodEffects");let Qt=Ku;Qt.create=(e,t,n)=>new Qt({schema:e,typeName:M.ZodEffects,effect:t,...ie(n)}),Qt.createWithPreprocess=(e,t,n)=>new Qt({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...ie(n)});const Yu=class Yu extends de{_parse(t){return this._getType(t)===V.undefined?_t(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Yu,"ZodOptional");let Mt=Yu;Mt.create=(e,t)=>new Mt({innerType:e,typeName:M.ZodOptional,...ie(t)});const Xu=class Xu extends de{_parse(t){return this._getType(t)===V.null?_t(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Xu,"ZodNullable");let en=Xu;en.create=(e,t)=>new en({innerType:e,typeName:M.ZodNullable,...ie(t)});const Qu=class Qu extends de{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};i(Qu,"ZodDefault");let wo=Qu;wo.create=(e,t)=>new wo({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ie(t)});const el=class el extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ka(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new zt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new zt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};i(el,"ZodCatch");let Fo=el;Fo.create=(e,t)=>new Fo({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ie(t)});const tl=class tl extends de{_parse(t){if(this._getType(t)!==V.nan){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.nan,received:r.parsedType}),ne}return{status:"valid",value:t.data}}};i(tl,"ZodNaN");let qa=tl;qa.create=e=>new qa({typeName:M.ZodNaN,...ie(e)});const nl=class nl extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};i(nl,"ZodBranded");let Ai=nl;const is=class is extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return i(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ne:s.status==="dirty"?(n.dirty(),yo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ne:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new is({in:t,out:n,typeName:M.ZodPipeline})}};i(is,"ZodPipeline");let $i=is;const rl=class rl extends de{_parse(t){const n=this._def.innerType._parse(t),r=i(o=>(zn(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return ka(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};i(rl,"ZodReadonly");let Eo=rl;Eo.create=(e,t)=>new Eo({innerType:e,typeName:M.ZodReadonly,...ie(t)});var M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));const Fe=_o.create,jt=bo.create;Pt.create;const tn=Xt.create,Ft=wt.create,Ti=qn.create;Un.create,_n.create;const Ua=Co.create;Zn.create,Mt.create,en.create;const ol=class ol extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(ol,"ParseError");let Za=ol;function Si(e){}i(Si,"noop");function TF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Si,onError:n=Si,onRetry:r=Si,onComment:o}=e;let s="",a=!0,u,l="",c="";function d(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[b,C]=SF(`${s}${y}`);for(const w of b)f(w);s=C,a=!1}i(d,"feed");function f(v){if(v===""){D();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const b=v.slice(0,y),C=v[y+1]===" "?2:1,w=v.slice(y+C);m(b,w,v);return}m(v,"",v)}i(f,"parseLine");function m(v,y,b){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
115
+ `;break;case"id":u=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?r(parseInt(y,10)):n(new Za(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:b}));break;default:n(new Za(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:y,line:b}));break}}i(m,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
116
+ `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function h(v={}){s&&v.consume&&f(s),a=!0,u=void 0,l="",c="",s=""}return i(h,"reset"),{feed:d,reset:h}}i(TF,"createParser");function SF(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
117
117
  `,r);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){n=e.slice(r);break}else{const u=e.slice(r,a);t.push(u),r=a+1,e[r-1]==="\r"&&e[r]===`
118
- `&&r++}}return[t,n]}i($F,"splitLines");const nl=class nl extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=AF({onEvent:i(a=>{s.enqueue(a)},"onEvent"),onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}};i(nl,"EventSourceParserStream");let $i=nl;function Ne(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(Ne,"combineHeaders");function TF({tools:e=[],providerToolNames:t}){const n={},r={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];n[o.name]=s,r[s]=o.name}return{toProviderToolName:i(o=>{var s;return(s=n[o])!=null?s:o},"toProviderToolName"),toCustomToolName:i(o=>{var s;return(s=r[o])!=null?s:o},"toCustomToolName")}}i(TF,"createToolNameMapping");async function SF(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,o)=>{if(n?.aborted){o(df());return}const s=setTimeout(()=>{a(),r()},e),a=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{a(),o(df())},"onAbort");n?.addEventListener("abort",u)})}i(SF,"delay");function df(){return new DOMException("Delay was aborted","AbortError")}i(df,"createAbortError");function Ln(e){return Object.fromEntries([...e.headers])}i(Ln,"extractResponseHeaders");var{btoa:BF,atob:OF}=globalThis;function hn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=OF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(hn,"convertBase64ToUint8Array");function Un(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return BF(t)}i(Un,"convertUint8ArrayToBase64");function zt(e){return e instanceof Uint8Array?Un(e):e}i(zt,"convertToBase64");function pf(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(o,s[0]);continue}const a=n?`${o}[]`:o;for(const u of s)r.append(a,u);continue}r.append(o,s)}return r}i(pf,"convertToFormData");var ff="AI_DownloadError",mf=`vercel.ai.error.${ff}`,RF=Symbol.for(mf),hf,Df,en=(ar=class extends(Df=Q,hf=RF,Df){constructor({url:t,statusCode:n,statusText:r,cause:o,message:s=o==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${o}`}){super({name:ff,message:s,cause:o}),this[hf]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return Q.hasMarker(t,mf)}},i(ar,"DownloadError"),ar),Ti=2*1024*1024*1024;async function gf({response:e,url:t,maxBytes:n=Ti}){const r=e.headers.get("content-length");if(r!=null){const d=parseInt(r,10);if(!isNaN(d)&&d>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${d}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let u=0;try{for(;;){const{done:d,value:f}=await s.read();if(d)break;if(u+=f.length,u>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(u);let c=0;for(const d of a)l.set(d,c),c+=d.length;return l}i(gf,"readResponseWithSizeLimit");async function Si(e,t){var n,r;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new en({url:e,statusCode:o.status,statusText:o.statusText});const s=await gf({response:o,url:e,maxBytes:(n=t?.maxBytes)!=null?n:Ti}),a=(r=o.headers.get("content-type"))!=null?r:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw en.isInstance(o)?o:new en({url:e,cause:o})}}i(Si,"downloadBlob");var Co=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=i(()=>{const s=n.length,a=new Array(t);for(let u=0;u<t;u++)a[u]=n[Math.random()*s|0];return a.join("")},"generator");if(e==null)return o;if(n.includes(r))throw new Nd({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},"createIdGenerator"),Ve=Co();function vf(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(vf,"getErrorMessage");function Zn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(Zn,"isAbortError");var NF=["fetch failed","failed to fetch"],PF=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function MF(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&PF.includes(t))}i(MF,"isBunNetworkError");function yf({error:e,url:t,requestBodyValues:n}){if(Zn(e))return e;if(e instanceof TypeError&&NF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Be({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return MF(e)?new Be({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0}):e}i(yf,"handleFetchError");function Bi(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Bi,"getRuntimeEnvironmentUserAgent");function jF(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(jF,"normalizeHeaders");function Dn(e,...t){const n=new Headers(jF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Dn,"withUserAgentSuffix");var _f="4.0.15",zF=i(()=>globalThis.fetch,"getOriginalFetch"),bf=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=zF()})=>{try{const a=await s(e,{method:"GET",headers:Dn(t,`ai-sdk/provider-utils/${_f}`,Bi()),signal:o}),u=Ln(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw Zn(c)||Be.isInstance(c)?c:new Be({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Zn(l)||Be.isInstance(l))?l:new Be({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(a){throw yf({error:a,url:e,requestBodyValues:{}})}},"getFromApi");function qF(e){return e!=null}i(qF,"isNonNullable");function LF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(LF,"isUrlSupported");function UF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new ua({message:`${r} API key must be a string.`});if(typeof process>"u")throw new ua({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ua({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ua({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(UF,"loadApiKey");function wo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(wo,"loadOptionalSetting");function ZF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(ZF,"mediaTypeToExtension");var VF=/"__proto__"\s*:/,GF=/"constructor"\s*:/;function Cf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||VF.test(e)===!1&&GF.test(e)===!1?t:WF(t)}i(Cf,"_parse");function WF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}i(WF,"filter");function Oi(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Cf(e)}try{return Cf(e)}finally{Error.stackTraceLimit=t}}i(Oi,"secureJsonParse");function Ri(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=gn(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(gn):gn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(gn)),e.allOf!=null&&(e.allOf=e.allOf.map(gn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(gn));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=gn(t[n]);return e}i(Ri,"addAdditionalPropertiesToJsonSchema");function gn(e){return typeof e=="boolean"?e:Ri(e)}i(gn,"visit");var HF=Symbol("Let zodToJsonSchema decide on which parser to use"),wf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},JF=i(e=>typeof e=="string"?{...wf,name:e}:{...wf,...e},"getDefaultOptions");function ht(){return{}}i(ht,"parseAnyDef");function KF(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(s.items=_e(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(KF,"parseArrayDef");function YF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(YF,"parseBigintDef");function XF(){return{type:"boolean"}}i(XF,"parseBooleanDef");function Ff(e,t){return _e(e.type._def,t)}i(Ff,"parseBrandedDef");var QF=i((e,t)=>_e(e.innerType._def,t),"parseCatchDef");function Ef(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Ef(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return e2(e)}}i(Ef,"parseDateDef");var e2=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function t2(e,t){return{..._e(e.innerType._def,t),default:e.defaultValue()}}i(t2,"parseDefaultDef");function n2(e,t){return t.effectStrategy==="input"?_e(e.schema._def,t):ht()}i(n2,"parseEffectsDef");function r2(e){return{type:"string",enum:Array.from(e.values)}}i(r2,"parseEnumDef");var o2=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function a2(e,t){const n=[_e(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),_e(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(o2(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...u}=o;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(a2,"parseIntersectionDef");function s2(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(s2,"parseLiteralDef");var Ni=void 0,Ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(Ni===void 0&&(Ni=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ni),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function xf(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":Et(n,"email",r.message,t);break;case"format:idn-email":Et(n,"idn-email",r.message,t);break;case"pattern:zod":nt(n,Ft.email,r.message,t);break}break;case"url":Et(n,"uri",r.message,t);break;case"uuid":Et(n,"uuid",r.message,t);break;case"regex":nt(n,r.regex,r.message,t);break;case"cuid":nt(n,Ft.cuid,r.message,t);break;case"cuid2":nt(n,Ft.cuid2,r.message,t);break;case"startsWith":nt(n,RegExp(`^${Pi(r.value,t)}`),r.message,t);break;case"endsWith":nt(n,RegExp(`${Pi(r.value,t)}$`),r.message,t);break;case"datetime":Et(n,"date-time",r.message,t);break;case"date":Et(n,"date",r.message,t);break;case"time":Et(n,"time",r.message,t);break;case"duration":Et(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{nt(n,RegExp(Pi(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&Et(n,"ipv4",r.message,t),r.version!=="v4"&&Et(n,"ipv6",r.message,t);break}case"base64url":nt(n,Ft.base64url,r.message,t);break;case"jwt":nt(n,Ft.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&nt(n,Ft.ipv4Cidr,r.message,t),r.version!=="v4"&&nt(n,Ft.ipv6Cidr,r.message,t);break}case"emoji":nt(n,Ft.emoji(),r.message,t);break;case"ulid":{nt(n,Ft.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{nt(n,Ft.base64,r.message,t);break}}break}case"nanoid":nt(n,Ft.nanoid,r.message,t)}return n}i(xf,"parseStringDef");function Pi(e,t){return t.patternStrategy==="escape"?u2(e):e}i(Pi,"escapeLiteralCheckValue");var i2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function u2(e){let t="";for(let n=0;n<e.length;n++)i2.has(e[n])||(t+="\\"),t+=e[n];return t}i(u2,"escapeNonAlphaNumeric");function Et(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(Et,"addFormat");function nt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:kf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=kf(t,r)}i(nt,"addPattern");function kf(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,u=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(u){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
118
+ `&&r++}}return[t,n]}i(SF,"splitLines");const al=class al extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=TF({onEvent:i(a=>{s.enqueue(a)},"onEvent"),onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}};i(al,"EventSourceParserStream");let Bi=al;function Ne(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(Ne,"combineHeaders");function BF({tools:e=[],providerToolNames:t}){const n={},r={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];n[o.name]=s,r[s]=o.name}return{toProviderToolName:i(o=>{var s;return(s=n[o])!=null?s:o},"toProviderToolName"),toCustomToolName:i(o=>{var s;return(s=r[o])!=null?s:o},"toCustomToolName")}}i(BF,"createToolNameMapping");async function OF(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,o)=>{if(n?.aborted){o(mf());return}const s=setTimeout(()=>{a(),r()},e),a=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{a(),o(mf())},"onAbort");n?.addEventListener("abort",u)})}i(OF,"delay");function mf(){return new DOMException("Delay was aborted","AbortError")}i(mf,"createAbortError");function Vn(e){return Object.fromEntries([...e.headers])}i(Vn,"extractResponseHeaders");var{btoa:RF,atob:NF}=globalThis;function bn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=NF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(bn,"convertBase64ToUint8Array");function Gn(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return RF(t)}i(Gn,"convertUint8ArrayToBase64");function Lt(e){return e instanceof Uint8Array?Gn(e):e}i(Lt,"convertToBase64");function hf(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(o,s[0]);continue}const a=n?`${o}[]`:o;for(const u of s)r.append(a,u);continue}r.append(o,s)}return r}i(hf,"convertToFormData");var Df="AI_DownloadError",gf=`vercel.ai.error.${Df}`,PF=Symbol.for(gf),vf,yf,nn=(ur=class extends(yf=Q,vf=PF,yf){constructor({url:t,statusCode:n,statusText:r,cause:o,message:s=o==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${o}`}){super({name:Df,message:s,cause:o}),this[vf]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return Q.hasMarker(t,gf)}},i(ur,"DownloadError"),ur),Oi=2*1024*1024*1024;async function _f({response:e,url:t,maxBytes:n=Oi}){const r=e.headers.get("content-length");if(r!=null){const d=parseInt(r,10);if(!isNaN(d)&&d>n)throw new nn({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${d}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let u=0;try{for(;;){const{done:d,value:f}=await s.read();if(d)break;if(u+=f.length,u>n)throw new nn({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(u);let c=0;for(const d of a)l.set(d,c),c+=d.length;return l}i(_f,"readResponseWithSizeLimit");async function Ri(e,t){var n,r;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new nn({url:e,statusCode:o.status,statusText:o.statusText});const s=await _f({response:o,url:e,maxBytes:(n=t?.maxBytes)!=null?n:Oi}),a=(r=o.headers.get("content-type"))!=null?r:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw nn.isInstance(o)?o:new nn({url:e,cause:o})}}i(Ri,"downloadBlob");var xo=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=i(()=>{const s=n.length,a=new Array(t);for(let u=0;u<t;u++)a[u]=n[Math.random()*s|0];return a.join("")},"generator");if(e==null)return o;if(n.includes(r))throw new jd({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},"createIdGenerator"),Ve=xo();function bf(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(bf,"getErrorMessage");function Wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(Wn,"isAbortError");var MF=["fetch failed","failed to fetch"],jF=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function zF(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&jF.includes(t))}i(zF,"isBunNetworkError");function Cf({error:e,url:t,requestBodyValues:n}){if(Wn(e))return e;if(e instanceof TypeError&&MF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Be({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return zF(e)?new Be({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0}):e}i(Cf,"handleFetchError");function Ni(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Ni,"getRuntimeEnvironmentUserAgent");function LF(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(LF,"normalizeHeaders");function Cn(e,...t){const n=new Headers(LF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Cn,"withUserAgentSuffix");var wf="4.0.15",qF=i(()=>globalThis.fetch,"getOriginalFetch"),Ff=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=qF()})=>{try{const a=await s(e,{method:"GET",headers:Cn(t,`ai-sdk/provider-utils/${wf}`,Ni()),signal:o}),u=Vn(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw Wn(c)||Be.isInstance(c)?c:new Be({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Wn(l)||Be.isInstance(l))?l:new Be({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(a){throw Cf({error:a,url:e,requestBodyValues:{}})}},"getFromApi");function UF(e){return e!=null}i(UF,"isNonNullable");function ZF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(ZF,"isUrlSupported");function VF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new ma({message:`${r} API key must be a string.`});if(typeof process>"u")throw new ma({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ma({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ma({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(VF,"loadApiKey");function ko({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(ko,"loadOptionalSetting");function GF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(GF,"mediaTypeToExtension");var WF=/"__proto__"\s*:/,HF=/"constructor"\s*:/;function Ef(e){const t=JSON.parse(e);return t===null||typeof t!="object"||WF.test(e)===!1&&HF.test(e)===!1?t:JF(t)}i(Ef,"_parse");function JF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}i(JF,"filter");function Pi(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Ef(e)}try{return Ef(e)}finally{Error.stackTraceLimit=t}}i(Pi,"secureJsonParse");function Mi(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=wn(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(wn):wn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(wn)),e.allOf!=null&&(e.allOf=e.allOf.map(wn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(wn));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=wn(t[n]);return e}i(Mi,"addAdditionalPropertiesToJsonSchema");function wn(e){return typeof e=="boolean"?e:Mi(e)}i(wn,"visit");var KF=Symbol("Let zodToJsonSchema decide on which parser to use"),xf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},YF=i(e=>typeof e=="string"?{...xf,name:e}:{...xf,...e},"getDefaultOptions");function Dt(){return{}}i(Dt,"parseAnyDef");function XF(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(s.items=_e(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(XF,"parseArrayDef");function QF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(QF,"parseBigintDef");function e2(){return{type:"boolean"}}i(e2,"parseBooleanDef");function kf(e,t){return _e(e.type._def,t)}i(kf,"parseBrandedDef");var t2=i((e,t)=>_e(e.innerType._def,t),"parseCatchDef");function If(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>If(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return n2(e)}}i(If,"parseDateDef");var n2=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function r2(e,t){return{..._e(e.innerType._def,t),default:e.defaultValue()}}i(r2,"parseDefaultDef");function o2(e,t){return t.effectStrategy==="input"?_e(e.schema._def,t):Dt()}i(o2,"parseEffectsDef");function a2(e){return{type:"string",enum:Array.from(e.values)}}i(a2,"parseEnumDef");var s2=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function i2(e,t){const n=[_e(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),_e(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(s2(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...u}=o;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(i2,"parseIntersectionDef");function u2(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(u2,"parseLiteralDef");var ji=void 0,Et={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(ji===void 0&&(ji=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ji),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Af(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":xt(n,"email",r.message,t);break;case"format:idn-email":xt(n,"idn-email",r.message,t);break;case"pattern:zod":nt(n,Et.email,r.message,t);break}break;case"url":xt(n,"uri",r.message,t);break;case"uuid":xt(n,"uuid",r.message,t);break;case"regex":nt(n,r.regex,r.message,t);break;case"cuid":nt(n,Et.cuid,r.message,t);break;case"cuid2":nt(n,Et.cuid2,r.message,t);break;case"startsWith":nt(n,RegExp(`^${zi(r.value,t)}`),r.message,t);break;case"endsWith":nt(n,RegExp(`${zi(r.value,t)}$`),r.message,t);break;case"datetime":xt(n,"date-time",r.message,t);break;case"date":xt(n,"date",r.message,t);break;case"time":xt(n,"time",r.message,t);break;case"duration":xt(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{nt(n,RegExp(zi(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&xt(n,"ipv4",r.message,t),r.version!=="v4"&&xt(n,"ipv6",r.message,t);break}case"base64url":nt(n,Et.base64url,r.message,t);break;case"jwt":nt(n,Et.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&nt(n,Et.ipv4Cidr,r.message,t),r.version!=="v4"&&nt(n,Et.ipv6Cidr,r.message,t);break}case"emoji":nt(n,Et.emoji(),r.message,t);break;case"ulid":{nt(n,Et.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{xt(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{nt(n,Et.base64,r.message,t);break}}break}case"nanoid":nt(n,Et.nanoid,r.message,t)}return n}i(Af,"parseStringDef");function zi(e,t){return t.patternStrategy==="escape"?c2(e):e}i(zi,"escapeLiteralCheckValue");var l2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function c2(e){let t="";for(let n=0;n<e.length;n++)l2.has(e[n])||(t+="\\"),t+=e[n];return t}i(c2,"escapeNonAlphaNumeric");function xt(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(xt,"addFormat");function nt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:$f(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=$f(t,r)}i(nt,"addPattern");function $f(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,u=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(u){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
119
119
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
120
120
  ]))`;continue}}if(r.s&&o[c]==="."){s+=u?`${o[c]}\r
121
121
  `:`[${o[c]}\r
122
- ]`;continue}s+=o[c],o[c]==="\\"?a=!0:u&&o[c]==="]"?u=!1:!u&&o[c]==="["&&(u=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}i(kf,"stringifyRegExpWithFlags");function If(e,t){var n,r,o,s,a,u;const l={type:"object",additionalProperties:(n=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...d}=xf(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Ff(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(If,"parseRecordDef");function l2(e,t){if(t.mapStrategy==="record")return If(e,t);const n=_e(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ht(),r=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ht();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(l2,"parseMapDef");function c2(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}i(c2,"parseNativeEnumDef");function d2(){return{not:ht()}}i(d2,"parseNeverDef");function p2(){return{type:"null"}}i(p2,"parseNullDef");var Mi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function f2(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Mi&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Mi[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,u)=>u.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return m2(e,t)}i(f2,"parseUnionDef");var m2=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>_e(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function h2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Mi[e.innerType._def.typeName],"null"]};const n=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(h2,"parseNullableDef");function D2(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(D2,"parseNumberDef");function g2(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let u=o[a];if(u===void 0||u._def===void 0)continue;const l=y2(u),c=_e(u._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=v2(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(g2,"parseObjectDef");function v2(e,t){if(e.catchall._def.typeName!=="ZodNever")return _e(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(v2,"decideAdditionalProperties");function y2(e){try{return e.isOptional()}catch{return!0}}i(y2,"safeIsOptional");var _2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return _e(e.innerType._def,t);const r=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ht()},r]}:ht()},"parseOptionalDef"),b2=i((e,t)=>{if(t.pipeStrategy==="input")return _e(e.in._def,t);if(t.pipeStrategy==="output")return _e(e.out._def,t);const n=_e(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=_e(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}},"parsePipelineDef");function C2(e,t){return _e(e.type._def,t)}i(C2,"parsePromiseDef");function w2(e,t){const r={type:"array",uniqueItems:!0,items:_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(w2,"parseSetDef");function F2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:_e(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(F2,"parseTupleDef");function E2(){return{not:ht()}}i(E2,"parseUndefinedDef");function x2(){return ht()}i(x2,"parseUnknownDef");var k2=i((e,t)=>_e(e.innerType._def,t),"parseReadonlyDef"),I2=i((e,t,n)=>{switch(t){case M.ZodString:return xf(e,n);case M.ZodNumber:return D2(e);case M.ZodObject:return g2(e,n);case M.ZodBigInt:return YF(e);case M.ZodBoolean:return XF();case M.ZodDate:return Ef(e,n);case M.ZodUndefined:return E2();case M.ZodNull:return p2();case M.ZodArray:return KF(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return f2(e,n);case M.ZodIntersection:return a2(e,n);case M.ZodTuple:return F2(e,n);case M.ZodRecord:return If(e,n);case M.ZodLiteral:return s2(e);case M.ZodEnum:return r2(e);case M.ZodNativeEnum:return c2(e);case M.ZodNullable:return h2(e,n);case M.ZodOptional:return _2(e,n);case M.ZodMap:return l2(e,n);case M.ZodSet:return w2(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return C2(e,n);case M.ZodNaN:case M.ZodNever:return d2();case M.ZodEffects:return n2(e,n);case M.ZodAny:return ht();case M.ZodUnknown:return x2();case M.ZodDefault:return t2(e,n);case M.ZodBranded:return Ff(e,n);case M.ZodReadonly:return k2(e,n);case M.ZodCatch:return QF(e,n);case M.ZodPipeline:return b2(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),A2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function _e(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==HF)return l}if(o&&!n){const l=$2(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=I2(e,e.typeName,t),u=typeof a=="function"?_e(a(),t):a;if(u&&T2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(_e,"parseDef");var $2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:A2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ht()):t.$refStrategy==="seen"?ht():void 0}},"get$ref"),T2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),S2=i(e=>{const t=JF(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),B2=i((e,t)=>{var n;const r=S2(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,f])=>{var h;return{...c,[d]:(h=_e(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:ht()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=_e(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:ht(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(a.title=u);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),ji=Symbol.for("vercel.ai.schema");function K(e){let t;return()=>(t==null&&(t=e()),t)}i(K,"lazySchema");function ja(e,{validate:t}={}){return{[ji]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(ja,"jsonSchema");function O2(e){return typeof e=="object"&&e!==null&&ji in e&&e[ji]===!0&&"jsonSchema"in e&&"validate"in e}i(O2,"isSchema");function Vn(e){return e==null?ja({properties:{},additionalProperties:!1}):O2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?J(e):R2(e):e()}i(Vn,"asSchema");function R2(e){return ja(()=>Ri(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new cn({value:t,cause:n.issues})}},"validate")})}i(R2,"standardSchema");function N2(e,t){var n;const r=(n=void 0)!=null?n:!1;return ja(()=>B2(e,{$refStrategy:r?"root":"none"}),{validate:i(async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(N2,"zod3Schema");function P2(e,t){var n;const r=(n=void 0)!=null?n:!1;return ja(()=>Ri(JC(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async o=>{const s=await Vp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(P2,"zod4Schema");function M2(e){return"_zod"in e}i(M2,"isZod4Schema");function J(e,t){return M2(e)?P2(e):N2(e)}i(J,"zodSchema");async function rt({value:e,schema:t,context:n}){const r=await xt({value:e,schema:t,context:n});if(!r.success)throw cn.wrap({value:e,cause:r.error,context:n});return r.value}i(rt,"validateTypes");async function xt({value:e,schema:t,context:n}){const r=Vn(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:cn.wrap({value:e,cause:o.error,context:n}),rawValue:e}}catch(o){return{success:!1,error:cn.wrap({value:e,cause:o,context:n}),rawValue:e}}}i(xt,"safeValidateTypes");async function j2({text:e,schema:t}){try{const n=Oi(e);return t==null?n:rt({value:n,schema:t})}catch(n){throw ia.isInstance(n)||cn.isInstance(n)?n:new ia({text:e,cause:n})}}i(j2,"parseJSON");async function kt({text:e,schema:t}){try{const n=Oi(e);return t==null?{success:!0,value:n,rawValue:n}:await xt({value:n,schema:t})}catch(n){return{success:!1,error:ia.isInstance(n)?n:new ia({text:e,cause:n}),rawValue:void 0}}}i(kt,"safeParseJSON");function za(e){try{return Oi(e),!0}catch{return!1}}i(za,"isParsableJson");function Af({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new $i).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await kt({text:n,schema:t}))}}))}i(Af,"parseJsonEventStream");async function tt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await xt({value:t[e],schema:n});if(!r.success)throw new Nd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(tt,"parseProviderOptions");var z2=i(()=>globalThis.fetch,"getOriginalFetch2"),Le=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>$f({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postJsonToApi"),zi=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>$f({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postFormDataToApi"),$f=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=z2()})=>{try{const u=await a(e,{method:"POST",headers:Dn(t,`ai-sdk/provider-utils/${_f}`,Bi()),body:n.content,signal:s}),l=Ln(u);if(!u.ok){let c;try{c=await o({response:u,url:e,requestBodyValues:n.values})}catch(d){throw Zn(d)||Be.isInstance(d)?d:new Be({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Zn(c)||Be.isInstance(c))?c:new Be({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw yf({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function T8(e){return e}i(T8,"tool");function It({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(It,"createProviderToolFactoryWithOutputSchema");async function lt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(lt,"resolve");var Dt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),u=Ln(r);if(a.trim()==="")return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})};try{const l=await j2({text:a,schema:e});return{responseHeaders:u,value:new Be({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),Gn=i(e=>async({response:t})=>{const n=Ln(t);if(t.body==null)throw new G0({});return{responseHeaders:n,value:Af({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Ke=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await kt({text:o,schema:e}),a=Ln(t);if(!s.success)throw new Be({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),q2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=Ln(e);if(!e.body)throw new Be({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Be({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},"createBinaryResponseHandler");function qi(e){return e?.replace(/\/$/,"")}i(qi,"withoutTrailingSlash");function L2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(L2,"isAsyncIterable");async function*U2({execute:e,input:t,options:n}){const r=e(t,n);if(L2(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}i(U2,"executeTool");var Li,Tf;function Sf(){if(Tf)return Li;Tf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),Li=a(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),Li}i(Sf,"requireGetContext");var Ui,Bf;function Of(){if(Bf)return Ui;Bf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),Ui=a(u);const c=class c extends Error{constructor(f,h){super(f),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return Ui}i(Of,"requireTokenError");var Zi,Rf;function Z2(){if(Rf)return Zi;Rf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((h,D)=>{for(var m in D)e(h,m,{get:D[m],enumerable:!0})},"__export"),s=i((h,D,m,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==m&&e(h,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return h},"__copyProps"),a=i(h=>s(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};o(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>f,"getVercelOidcTokenSync")}),Zi=a(u);var l=Sf(),c=Of();async function d(){let h="",D;try{h=f()}catch(m){D=m}try{const[{getTokenPayload:m,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-D5yU_rYz.mjs").then(function(b){return b.t}),await import("./token-CRGQJP5l.mjs").then(function(b){return b.t})]);(!h||v(m(h)))&&(await y(),h=f())}catch(m){let v=D instanceof Error?D.message:"";throw m instanceof Error&&(v=`${v}
123
- ${m.message}`),v?new c.VercelOidcTokenError(v):m}return h}i(d,"getVercelOidcToken");function f(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return i(f,"getVercelOidcTokenSync"),Zi}i(Z2,"requireGetVercelOidcToken");var Vi,Nf;function V2(){if(Nf)return Vi;Nf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),Vi=a(u);var l=Z2(),c=Sf();return Vi}i(V2,"requireDist");var Pf=V2(),G2="vercel.ai.gateway.error",Gi=Symbol.for(G2),Mf,jf,ot=(wn=class extends(jf=Error,Mf=Gi,jf){constructor({message:t,statusCode:n=500,cause:r,generationId:o}){super(o?`${t} [${o}]`:t),this[Mf]=!0,this.statusCode=n,this.cause=r,this.generationId=o}static isInstance(t){return wn.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Gi in t&&t[Gi]===!0}},i(wn,"_GatewayError"),wn),zf="GatewayAuthenticationError",W2=`vercel.ai.gateway.error.${zf}`,qf=Symbol.for(W2),Lf,Uf,Wi=(Fn=class extends(Uf=ot,Lf=qf,Uf){constructor({message:t="Authentication failed",statusCode:n=401,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Lf]=!0,this.name=zf,this.type="authentication_error"}static isInstance(t){return ot.hasMarker(t)&&qf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let u;return t?u=`AI Gateway authentication failed: Invalid API key.
122
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:u&&o[c]==="]"?u=!1:!u&&o[c]==="["&&(u=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}i($f,"stringifyRegExpWithFlags");function Tf(e,t){var n,r,o,s,a,u;const l={type:"object",additionalProperties:(n=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...d}=Af(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=kf(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(Tf,"parseRecordDef");function d2(e,t){if(t.mapStrategy==="record")return Tf(e,t);const n=_e(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Dt(),r=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Dt();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(d2,"parseMapDef");function p2(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}i(p2,"parseNativeEnumDef");function f2(){return{not:Dt()}}i(f2,"parseNeverDef");function m2(){return{type:"null"}}i(m2,"parseNullDef");var Li={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function h2(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Li&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Li[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,u)=>u.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return D2(e,t)}i(h2,"parseUnionDef");var D2=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>_e(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function g2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Li[e.innerType._def.typeName],"null"]};const n=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(g2,"parseNullableDef");function v2(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(v2,"parseNumberDef");function y2(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let u=o[a];if(u===void 0||u._def===void 0)continue;const l=b2(u),c=_e(u._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=_2(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(y2,"parseObjectDef");function _2(e,t){if(e.catchall._def.typeName!=="ZodNever")return _e(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(_2,"decideAdditionalProperties");function b2(e){try{return e.isOptional()}catch{return!0}}i(b2,"safeIsOptional");var C2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return _e(e.innerType._def,t);const r=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Dt()},r]}:Dt()},"parseOptionalDef"),w2=i((e,t)=>{if(t.pipeStrategy==="input")return _e(e.in._def,t);if(t.pipeStrategy==="output")return _e(e.out._def,t);const n=_e(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=_e(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}},"parsePipelineDef");function F2(e,t){return _e(e.type._def,t)}i(F2,"parsePromiseDef");function E2(e,t){const r={type:"array",uniqueItems:!0,items:_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(E2,"parseSetDef");function x2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:_e(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(x2,"parseTupleDef");function k2(){return{not:Dt()}}i(k2,"parseUndefinedDef");function I2(){return Dt()}i(I2,"parseUnknownDef");var A2=i((e,t)=>_e(e.innerType._def,t),"parseReadonlyDef"),$2=i((e,t,n)=>{switch(t){case M.ZodString:return Af(e,n);case M.ZodNumber:return v2(e);case M.ZodObject:return y2(e,n);case M.ZodBigInt:return QF(e);case M.ZodBoolean:return e2();case M.ZodDate:return If(e,n);case M.ZodUndefined:return k2();case M.ZodNull:return m2();case M.ZodArray:return XF(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return h2(e,n);case M.ZodIntersection:return i2(e,n);case M.ZodTuple:return x2(e,n);case M.ZodRecord:return Tf(e,n);case M.ZodLiteral:return u2(e);case M.ZodEnum:return a2(e);case M.ZodNativeEnum:return p2(e);case M.ZodNullable:return g2(e,n);case M.ZodOptional:return C2(e,n);case M.ZodMap:return d2(e,n);case M.ZodSet:return E2(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return F2(e,n);case M.ZodNaN:case M.ZodNever:return f2();case M.ZodEffects:return o2(e,n);case M.ZodAny:return Dt();case M.ZodUnknown:return I2();case M.ZodDefault:return r2(e,n);case M.ZodBranded:return kf(e,n);case M.ZodReadonly:return A2(e,n);case M.ZodCatch:return t2(e,n);case M.ZodPipeline:return w2(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),T2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function _e(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==KF)return l}if(o&&!n){const l=S2(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=$2(e,e.typeName,t),u=typeof a=="function"?_e(a(),t):a;if(u&&B2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(_e,"parseDef");var S2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:T2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Dt()):t.$refStrategy==="seen"?Dt():void 0}},"get$ref"),B2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),O2=i(e=>{const t=YF(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),R2=i((e,t)=>{var n;const r=O2(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,f])=>{var m;return{...c,[d]:(m=_e(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?m:Dt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=_e(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:Dt(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(a.title=u);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),qi=Symbol.for("vercel.ai.schema");function K(e){let t;return()=>(t==null&&(t=e()),t)}i(K,"lazySchema");function Va(e,{validate:t}={}){return{[qi]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Va,"jsonSchema");function N2(e){return typeof e=="object"&&e!==null&&qi in e&&e[qi]===!0&&"jsonSchema"in e&&"validate"in e}i(N2,"isSchema");function Hn(e){return e==null?Va({properties:{},additionalProperties:!1}):N2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?J(e):P2(e):e()}i(Hn,"asSchema");function P2(e){return Va(()=>Mi(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new Dn({value:t,cause:n.issues})}},"validate")})}i(P2,"standardSchema");function M2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Va(()=>R2(e,{$refStrategy:r?"root":"none"}),{validate:i(async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(M2,"zod3Schema");function j2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Va(()=>Mi(YC(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async o=>{const s=await Hp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(j2,"zod4Schema");function z2(e){return"_zod"in e}i(z2,"isZod4Schema");function J(e,t){return z2(e)?j2(e):M2(e)}i(J,"zodSchema");async function rt({value:e,schema:t,context:n}){const r=await kt({value:e,schema:t,context:n});if(!r.success)throw Dn.wrap({value:e,cause:r.error,context:n});return r.value}i(rt,"validateTypes");async function kt({value:e,schema:t,context:n}){const r=Hn(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:Dn.wrap({value:e,cause:o.error,context:n}),rawValue:e}}catch(o){return{success:!1,error:Dn.wrap({value:e,cause:o,context:n}),rawValue:e}}}i(kt,"safeValidateTypes");async function L2({text:e,schema:t}){try{const n=Pi(e);return t==null?n:rt({value:n,schema:t})}catch(n){throw fa.isInstance(n)||Dn.isInstance(n)?n:new fa({text:e,cause:n})}}i(L2,"parseJSON");async function It({text:e,schema:t}){try{const n=Pi(e);return t==null?{success:!0,value:n,rawValue:n}:await kt({value:n,schema:t})}catch(n){return{success:!1,error:fa.isInstance(n)?n:new fa({text:e,cause:n}),rawValue:void 0}}}i(It,"safeParseJSON");function Ga(e){try{return Pi(e),!0}catch{return!1}}i(Ga,"isParsableJson");function Sf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Bi).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await It({text:n,schema:t}))}}))}i(Sf,"parseJsonEventStream");async function tt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await kt({value:t[e],schema:n});if(!r.success)throw new jd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(tt,"parseProviderOptions");var q2=i(()=>globalThis.fetch,"getOriginalFetch2"),qe=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Bf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postJsonToApi"),Ui=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Bf({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postFormDataToApi"),Bf=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=q2()})=>{try{const u=await a(e,{method:"POST",headers:Cn(t,`ai-sdk/provider-utils/${wf}`,Ni()),body:n.content,signal:s}),l=Vn(u);if(!u.ok){let c;try{c=await o({response:u,url:e,requestBodyValues:n.values})}catch(d){throw Wn(d)||Be.isInstance(d)?d:new Be({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Wn(c)||Be.isInstance(c))?c:new Be({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw Cf({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function M8(e){return e}i(M8,"tool");function At({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(At,"createProviderToolFactoryWithOutputSchema");async function ct(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(ct,"resolve");var gt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),u=Vn(r);if(a.trim()==="")return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})};try{const l=await L2({text:a,schema:e});return{responseHeaders:u,value:new Be({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),Jn=i(e=>async({response:t})=>{const n=Vn(t);if(t.body==null)throw new H0({});return{responseHeaders:n,value:Sf({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Ke=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await It({text:o,schema:e}),a=Vn(t);if(!s.success)throw new Be({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),U2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=Vn(e);if(!e.body)throw new Be({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Be({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},"createBinaryResponseHandler");function Zi(e){return e?.replace(/\/$/,"")}i(Zi,"withoutTrailingSlash");function Z2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(Z2,"isAsyncIterable");async function*V2({execute:e,input:t,options:n}){const r=e(t,n);if(Z2(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}i(V2,"executeTool");var Vi,Of;function Rf(){if(Of)return Vi;Of=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var m in f)e(d,m,{get:f[m],enumerable:!0})},"__export"),s=i((d,f,m,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let h of n(f))!r.call(d,h)&&h!==m&&e(d,h,{get:i(()=>f[h],"get"),enumerable:!(D=t(f,h))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),Vi=a(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),Vi}i(Rf,"requireGetContext");var Gi,Nf;function Pf(){if(Nf)return Gi;Nf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var m in f)e(d,m,{get:f[m],enumerable:!0})},"__export"),s=i((d,f,m,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let h of n(f))!r.call(d,h)&&h!==m&&e(d,h,{get:i(()=>f[h],"get"),enumerable:!(D=t(f,h))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),Gi=a(u);const c=class c extends Error{constructor(f,m){super(f),this.name="VercelOidcTokenError",this.cause=m}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return Gi}i(Pf,"requireTokenError");var Wi,Mf;function G2(){if(Mf)return Wi;Mf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((m,D)=>{for(var h in D)e(m,h,{get:D[h],enumerable:!0})},"__export"),s=i((m,D,h,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(m,y)&&y!==h&&e(m,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return m},"__copyProps"),a=i(m=>s(e({},"__esModule",{value:!0}),m),"__toCommonJS"),u={};o(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>f,"getVercelOidcTokenSync")}),Wi=a(u);var l=Rf(),c=Pf();async function d(){let m="",D;try{m=f()}catch(h){D=h}try{const[{getTokenPayload:h,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-CouME5QQ.mjs").then(function(b){return b.t}),await import("./token-KkHT_6F9.mjs").then(function(b){return b.t})]);(!m||v(h(m)))&&(await y(),m=f())}catch(h){let v=D instanceof Error?D.message:"";throw h instanceof Error&&(v=`${v}
123
+ ${h.message}`),v?new c.VercelOidcTokenError(v):h}return m}i(d,"getVercelOidcToken");function f(){const m=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!m)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return m}return i(f,"getVercelOidcTokenSync"),Wi}i(G2,"requireGetVercelOidcToken");var Hi,jf;function W2(){if(jf)return Hi;jf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var m in f)e(d,m,{get:f[m],enumerable:!0})},"__export"),s=i((d,f,m,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let h of n(f))!r.call(d,h)&&h!==m&&e(d,h,{get:i(()=>f[h],"get"),enumerable:!(D=t(f,h))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),Hi=a(u);var l=G2(),c=Rf();return Hi}i(W2,"requireDist");var zf=W2(),H2="vercel.ai.gateway.error",Ji=Symbol.for(H2),Lf,qf,ot=(An=class extends(qf=Error,Lf=Ji,qf){constructor({message:t,statusCode:n=500,cause:r,generationId:o}){super(o?`${t} [${o}]`:t),this[Lf]=!0,this.statusCode=n,this.cause=r,this.generationId=o}static isInstance(t){return An.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Ji in t&&t[Ji]===!0}},i(An,"_GatewayError"),An),Uf="GatewayAuthenticationError",J2=`vercel.ai.gateway.error.${Uf}`,Zf=Symbol.for(J2),Vf,Gf,Ki=($n=class extends(Gf=ot,Vf=Zf,Gf){constructor({message:t="Authentication failed",statusCode:n=401,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Vf]=!0,this.name=Uf,this.type="authentication_error"}static isInstance(t){return ot.hasMarker(t)&&Zf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let u;return t?u=`AI Gateway authentication failed: Invalid API key.
124
124
 
125
125
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
126
126
 
@@ -135,9 +135,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
135
135
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
136
136
 
137
137
  Option 2 - OIDC token:
138
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Fn({message:u,statusCode:o,cause:s,generationId:a})}},i(Fn,"_GatewayAuthenticationError"),Fn),Zf="GatewayInvalidRequestError",H2=`vercel.ai.gateway.error.${Zf}`,Vf=Symbol.for(H2),Gf,Wf,J2=(sr=class extends(Wf=ot,Gf=Vf,Wf){constructor({message:t="Invalid request",statusCode:n=400,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Gf]=!0,this.name=Zf,this.type="invalid_request_error"}static isInstance(t){return ot.hasMarker(t)&&Vf in t}},i(sr,"GatewayInvalidRequestError"),sr),Hf="GatewayRateLimitError",K2=`vercel.ai.gateway.error.${Hf}`,Jf=Symbol.for(K2),Kf,Yf,Y2=(ir=class extends(Yf=ot,Kf=Jf,Yf){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Kf]=!0,this.name=Hf,this.type="rate_limit_exceeded"}static isInstance(t){return ot.hasMarker(t)&&Jf in t}},i(ir,"GatewayRateLimitError"),ir),Xf="GatewayModelNotFoundError",X2=`vercel.ai.gateway.error.${Xf}`,Qf=Symbol.for(X2),Q2=K(()=>J(g({modelId:p()}))),em,tm,eE=(ur=class extends(tm=ot,em=Qf,tm){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:o,generationId:s}={}){super({message:t,statusCode:n,cause:o,generationId:s}),this[em]=!0,this.name=Xf,this.type="model_not_found",this.modelId=r}static isInstance(t){return ot.hasMarker(t)&&Qf in t}},i(ur,"GatewayModelNotFoundError"),ur),nm="GatewayInternalServerError",tE=`vercel.ai.gateway.error.${nm}`,rm=Symbol.for(tE),om,am,sm=(lr=class extends(am=ot,om=rm,am){constructor({message:t="Internal server error",statusCode:n=500,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[om]=!0,this.name=nm,this.type="internal_server_error"}static isInstance(t){return ot.hasMarker(t)&&rm in t}},i(lr,"GatewayInternalServerError"),lr),im="GatewayResponseError",nE=`vercel.ai.gateway.error.${im}`,um=Symbol.for(nE),lm,cm,rE=(cr=class extends(cm=ot,lm=um,cm){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:o,cause:s,generationId:a}={}){super({message:t,statusCode:n,cause:s,generationId:a}),this[lm]=!0,this.name=im,this.type="response_error",this.response=r,this.validationError=o}static isInstance(t){return ot.hasMarker(t)&&um in t}},i(cr,"GatewayResponseError"),cr);async function dm({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){var s;const a=await xt({value:e,schema:oE});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new rE({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r,generationId:f})}const u=a.value,l=u.error.type,c=u.error.message,d=(s=u.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Wi.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r,generationId:d});case"invalid_request_error":return new J2({message:c,statusCode:t,cause:r,generationId:d});case"rate_limit_exceeded":return new Y2({message:c,statusCode:t,cause:r,generationId:d});case"model_not_found":{const f=await xt({value:u.error.param,schema:Q2});return new eE({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:r,generationId:d})}case"internal_server_error":return new sm({message:c,statusCode:t,cause:r,generationId:d});default:return new sm({message:c,statusCode:t,cause:r,generationId:d})}}i(dm,"createGatewayErrorFromResponse");var oE=K(()=>J(g({error:g({message:p(),type:p().nullish(),param:ut().nullish(),code:ee([p(),x()]).nullish()}),generationId:p().nullish()}))),pm="GatewayTimeoutError",aE=`vercel.ai.gateway.error.${pm}`,fm=Symbol.for(aE),mm,hm,Dm=(En=class extends(hm=ot,mm=fm,hm){constructor({message:t="Request timed out",statusCode:n=408,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[mm]=!0,this.name=pm,this.type="timeout_error"}static isInstance(t){return ot.hasMarker(t)&&fm in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r,generationId:o}){const s=`Gateway request timed out: ${t}
138
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new $n({message:u,statusCode:o,cause:s,generationId:a})}},i($n,"_GatewayAuthenticationError"),$n),Wf="GatewayInvalidRequestError",K2=`vercel.ai.gateway.error.${Wf}`,Hf=Symbol.for(K2),Jf,Kf,Y2=(lr=class extends(Kf=ot,Jf=Hf,Kf){constructor({message:t="Invalid request",statusCode:n=400,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Jf]=!0,this.name=Wf,this.type="invalid_request_error"}static isInstance(t){return ot.hasMarker(t)&&Hf in t}},i(lr,"GatewayInvalidRequestError"),lr),Yf="GatewayRateLimitError",X2=`vercel.ai.gateway.error.${Yf}`,Xf=Symbol.for(X2),Qf,em,Q2=(cr=class extends(em=ot,Qf=Xf,em){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Qf]=!0,this.name=Yf,this.type="rate_limit_exceeded"}static isInstance(t){return ot.hasMarker(t)&&Xf in t}},i(cr,"GatewayRateLimitError"),cr),tm="GatewayModelNotFoundError",eE=`vercel.ai.gateway.error.${tm}`,nm=Symbol.for(eE),tE=K(()=>J(g({modelId:p()}))),rm,om,nE=(dr=class extends(om=ot,rm=nm,om){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:o,generationId:s}={}){super({message:t,statusCode:n,cause:o,generationId:s}),this[rm]=!0,this.name=tm,this.type="model_not_found",this.modelId=r}static isInstance(t){return ot.hasMarker(t)&&nm in t}},i(dr,"GatewayModelNotFoundError"),dr),am="GatewayInternalServerError",rE=`vercel.ai.gateway.error.${am}`,sm=Symbol.for(rE),im,um,lm=(pr=class extends(um=ot,im=sm,um){constructor({message:t="Internal server error",statusCode:n=500,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[im]=!0,this.name=am,this.type="internal_server_error"}static isInstance(t){return ot.hasMarker(t)&&sm in t}},i(pr,"GatewayInternalServerError"),pr),cm="GatewayResponseError",oE=`vercel.ai.gateway.error.${cm}`,dm=Symbol.for(oE),pm,fm,aE=(fr=class extends(fm=ot,pm=dm,fm){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:o,cause:s,generationId:a}={}){super({message:t,statusCode:n,cause:s,generationId:a}),this[pm]=!0,this.name=cm,this.type="response_error",this.response=r,this.validationError=o}static isInstance(t){return ot.hasMarker(t)&&dm in t}},i(fr,"GatewayResponseError"),fr);async function mm({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){var s;const a=await kt({value:e,schema:sE});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new aE({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r,generationId:f})}const u=a.value,l=u.error.type,c=u.error.message,d=(s=u.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Ki.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r,generationId:d});case"invalid_request_error":return new Y2({message:c,statusCode:t,cause:r,generationId:d});case"rate_limit_exceeded":return new Q2({message:c,statusCode:t,cause:r,generationId:d});case"model_not_found":{const f=await kt({value:u.error.param,schema:tE});return new nE({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:r,generationId:d})}case"internal_server_error":return new lm({message:c,statusCode:t,cause:r,generationId:d});default:return new lm({message:c,statusCode:t,cause:r,generationId:d})}}i(mm,"createGatewayErrorFromResponse");var sE=K(()=>J(g({error:g({message:p(),type:p().nullish(),param:lt().nullish(),code:ee([p(),x()]).nullish()}),generationId:p().nullish()}))),hm="GatewayTimeoutError",iE=`vercel.ai.gateway.error.${hm}`,Dm=Symbol.for(iE),gm,vm,ym=(Tn=class extends(vm=ot,gm=Dm,vm){constructor({message:t="Request timed out",statusCode:n=408,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[gm]=!0,this.name=hm,this.type="timeout_error"}static isInstance(t){return ot.hasMarker(t)&&Dm in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r,generationId:o}){const s=`Gateway request timed out: ${t}
139
139
 
140
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new En({message:s,statusCode:n,cause:r,generationId:o})}},i(En,"_GatewayTimeoutError"),En);function gm(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}i(gm,"isTimeoutError");async function qt(e,t){var n;return ot.isInstance(e)?e:gm(e)?Dm.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):Be.isInstance(e)?e.cause&&gm(e.cause)?Dm.createTimeoutError({originalMessage:e.message,cause:e}):await dm({response:sE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await dm({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(qt,"asGatewayError");function sE(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(sE,"extractApiCallResponse");var vm="ai-gateway-auth-method";async function vn(e){const t=await xt({value:e[vm],schema:iE});return t.success?t.value:void 0}i(vn,"parseAuthMethod");var iE=K(()=>J(ee([F("api-key"),F("oidc")]))),ym=(dr=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await bf({url:`${this.config.baseURL}/config`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(uE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await qt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await bf({url:`${t.origin}/v1/credits`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(lE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await qt(t)}}},i(dr,"GatewayFetchMetadata"),dr),uE=K(()=>J(g({models:S(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:F("v3"),provider:p(),modelId:p()}),modelType:se(["embedding","image","language","video"]).nullish()}))}))),lE=K(()=>J(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),cE=(pr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{responseHeaders:a,value:u,rawValue:l}=await Le({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Ke(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(c=>c,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:a,body:l},warnings:r}}catch(a){throw await qt(a,await vn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{value:a,responseHeaders:u}=await Le({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Gn(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(l=>l,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(a){throw await qt(a,await vn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const o=r;if(o.data instanceof Uint8Array){const s=Uint8Array.from(o.data),a=Buffer.from(s).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(pr,"GatewayLanguageModel"),pr),dE=(fr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;const a=await lt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await Le({url:this.getUrl(),headers:Ne(a,n??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{values:t,...o?{providerOptions:o}:{}},successfulResponseHandler:Ke(pE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await qt(u,await vn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(fr,"GatewayEmbeddingModel"),fr),pE=K(()=>J(g({embeddings:S(S(x())),usage:g({tokens:x()}).nullish(),providerMetadata:be(p(),be(p(),ut())).optional()}))),fE=(mr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,files:a,mask:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m;const v=await lt(this.config.headers());try{const{responseHeaders:y,value:b,rawValue:C}=await Le({url:this.getUrl(),headers:Ne(v,c??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...o&&{aspectRatio:o},...s&&{seed:s},...l&&{providerOptions:l},...a&&{files:a.map(w=>_m(w))},...u&&{mask:_m(u)}},successfulResponseHandler:Ke(gE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(w=>w,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:b.images,warnings:(f=b.warnings)!=null?f:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},...b.usage!=null&&{usage:{inputTokens:(h=b.usage.inputTokens)!=null?h:void 0,outputTokens:(D=b.usage.outputTokens)!=null?D:void 0,totalTokens:(m=b.usage.totalTokens)!=null?m:void 0}}}}catch(y){throw await qt(y,await vn(v))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(mr,"GatewayImageModel"),mr);function _m(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Un(e.data)}:e}i(_m,"maybeEncodeImageFile");var mE=g({images:S(ut()).optional()}).catchall(ut()),hE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),DE=g({inputTokens:x().nullish(),outputTokens:x().nullish(),totalTokens:x().nullish()}),gE=g({images:S(p()),warnings:S(hE).optional(),providerMetadata:be(p(),mE).optional(),usage:DE.optional()}),vE=(hr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,aspectRatio:r,resolution:o,duration:s,fps:a,seed:u,image:l,providerOptions:c,headers:d,abortSignal:f}){var h;const D=await lt(this.config.headers());try{const{responseHeaders:m,value:v}=await Le({url:this.getUrl(),headers:Ne(D,d??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:t,n,...r&&{aspectRatio:r},...o&&{resolution:o},...s&&{duration:s},...a&&{fps:a},...u&&{seed:u},...c&&{providerOptions:c},...l&&{image:yE(l)}},successfulResponseHandler:i(async({response:y,url:b,requestBodyValues:C})=>{if(y.body==null)throw new Be({message:"SSE response body is empty",url:b,requestBodyValues:C,statusCode:y.status});const E=Af({stream:y.body,schema:wE}).getReader(),{done:T,value:O}=await E.read();if(E.releaseLock(),T||!O)throw new Be({message:"SSE stream ended without a data event",url:b,requestBodyValues:C,statusCode:y.status});if(!O.success)throw new Be({message:"Failed to parse video SSE event",cause:O.error,url:b,requestBodyValues:C,statusCode:y.status});const $=O.value;if($.type==="error")throw new Be({message:$.message,statusCode:$.statusCode,url:b,requestBodyValues:C,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify($),data:{error:{message:$.message,type:$.errorType,param:$.param}}});return{value:{videos:$.videos,warnings:$.warnings,providerMetadata:$.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(y=>y,"errorToMessage")}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:(h=v.warnings)!=null?h:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:m}}}catch(m){throw await qt(m,await vn(D))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},i(hr,"GatewayVideoModel"),hr);function yE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Un(e.data)}:e}i(yE,"maybeEncodeVideoFile");var _E=g({videos:S(ut()).optional()}).catchall(ut()),bE=ee([g({type:F("url"),url:p(),mediaType:p()}),g({type:F("base64"),data:p(),mediaType:p()})]),CE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),wE=ge("type",[g({type:F("result"),videos:S(bE),warnings:S(CE).optional(),providerMetadata:be(p(),_E).optional()}),g({type:F("error"),message:p(),errorType:p(),statusCode:x(),param:ut().nullable()})]),FE=K(()=>J(wt({objective:we().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Qt(we()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Pa(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:Mt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:wt({include_domains:Qt(we()).optional().describe("List of domains to include in search results."),exclude_domains:Qt(we()).optional().describe("List of domains to exclude from search results."),after_date:we().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:wt({max_chars_per_result:Mt().optional().describe("Maximum characters per result."),max_chars_total:Mt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:wt({max_age_seconds:Mt().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),EE=K(()=>J(Ii([wt({searchId:we(),results:Qt(wt({url:we(),title:we(),excerpt:we(),publishDate:we().nullable().optional(),relevanceScore:Mt().optional()}))}),wt({error:Pa(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Mt().optional(),message:we()})]))),xE=It({id:"gateway.parallel_search",inputSchema:FE,outputSchema:EE}),kE=i((e={})=>xE(e),"parallelSearch"),IE=K(()=>J(wt({query:Ii([we(),Qt(we())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Mt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Mt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Mt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:we().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Qt(we()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Qt(we()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:we().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:we().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:we().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:we().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Pa(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),AE=K(()=>J(Ii([wt({results:Qt(wt({title:we(),url:we(),snippet:we(),date:we().optional(),lastUpdated:we().optional()})),id:we()}),wt({error:Pa(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Mt().optional(),message:we()})]))),$E=It({id:"gateway.perplexity_search",inputSchema:IE,outputSchema:AE}),TE=i((e={})=>$E(e),"perplexitySearch"),SE={parallelSearch:kE,perplexitySearch:TE};async function BE(){var e;return(e=Pf.getContext().headers)==null?void 0:e["x-vercel-id"]}i(BE,"getVercelRequestId");var OE="3.0.53",RE="0.0.1";function NE(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const u=(n=qi(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await ME(e);return Dn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":RE,[vm]:v.authMethod,...e.headers},`ai-sdk/gateway/${OE}`)}catch(v){throw Wi.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=wo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=wo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=wo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const C=await BE();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...b&&{"ai-o11y-region":b},...C&&{"ai-o11y-request-id":C}}}},"createO11yHeaders"),d=i(v=>new cE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),f=i(async()=>{var v,y,b;const C=(b=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?b:Date.now();return(!r||C-a>s)&&(a=C,r=new ym({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(w=>(o=w,w)).catch(async w=>{throw await qt(w,await vn(await l()))})),o?Promise.resolve(o):r},"getAvailableModels"),h=i(async()=>new ym({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await qt(v,await vn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=f,D.getCredits=h,D.imageModel=v=>new fE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const m=i(v=>new dE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=m,D.textEmbeddingModel=m,D.videoModel=v=>new vE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.chat=D.languageModel,D.embedding=D.embeddingModel,D.image=D.imageModel,D.video=D.videoModel,D.tools=SE,D}i(NE,"createGatewayProvider");var PE=NE();async function ME(e){const t=wo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Pf.getVercelOidcToken(),authMethod:"oidc"}}i(ME,"getGatewayAuthToken");var jE=typeof globalThis=="object"?globalThis:global,yn="1.9.0",bm=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function zE(e){var t=new Set([e]),n=new Set,r=e.match(bm);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function a(u){return t.add(u),!0}return i(a,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(bm);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||o.major!==d.major?s(l):o.major===0?o.minor===d.minor&&o.patch<=d.patch?a(l):s(l):o.minor<=d.minor?a(l):s(l)},"isCompatible2")}i(zE,"_makeCompatibilityCheck");var qE=zE(yn),LE=yn.split(".")[0],Fo=Symbol.for("opentelemetry.js.api."+LE),Eo=jE;function Hi(e,t,n,r){var o;r===void 0&&(r=!1);var s=Eo[Fo]=(o=Eo[Fo])!==null&&o!==void 0?o:{version:yn};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==yn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+yn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+yn+"."),!0}i(Hi,"registerGlobal");function xo(e){var t,n,r=(t=Eo[Fo])===null||t===void 0?void 0:t.version;if(!(!r||!qE(r)))return(n=Eo[Fo])===null||n===void 0?void 0:n[e]}i(xo,"getGlobal");function Ji(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+yn+".");var n=Eo[Fo];n&&delete n[e]}i(Ji,"unregisterGlobal");var UE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$3"),ZE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),VE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ko("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ko("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ko("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ko("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ko("verbose",this._namespace,t)},e})();function ko(e,t,n){var r=xo("diag");if(r)return n.unshift(t),r[e].apply(r,ZE([],UE(n),!1))}i(ko,"logProxy");var gt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gt||(gt={}));function GE(e,t){e<gt.NONE?e=gt.NONE:e>gt.ALL&&(e=gt.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",gt.ERROR),warn:n("warn",gt.WARN),info:n("info",gt.INFO),debug:n("debug",gt.DEBUG),verbose:n("verbose",gt.VERBOSE)}}i(GE,"createLogLevelDiagLogger");var WE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$2"),HE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),JE="diag",qa=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var u=xo("diag");if(u)return u[o].apply(u,HE([],WE(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(o,s){var a,u,l;if(s===void 0&&(s={logLevel:gt.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=xo("diag"),f=GE((u=s.logLevel)!==null&&u!==void 0?u:gt.INFO,o);if(d&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),f.warn("Current logger will overwrite one already registered from "+h)}return Hi("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){Ji(JE,n)},n.createComponentLogger=function(o){return new VE(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function KE(e){return Symbol.for(e)}i(KE,"createContextKey");var YE=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return i(e,"BaseContext2"),e})(),XE=new YE,QE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$1"),e1=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),t1=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return XE},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,e1([r],QE(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),n1=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read"),r1=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),Ki="context",o1=new t1,Yi=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Hi(Ki,t,qa.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,r1([t,n,r],n1(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return xo(Ki)||o1},e.prototype.disable=function(){this._getContextManager().disable(),Ji(Ki,qa.instance())},e})(),Xi;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Xi||(Xi={}));var Cm="0000000000000000",wm="00000000000000000000000000000000",a1={traceId:wm,spanId:Cm,traceFlags:Xi.NONE},Io=(function(){function e(t){t===void 0&&(t=a1),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),Qi=KE("OpenTelemetry Context Key SPAN");function eu(e){return e.getValue(Qi)||void 0}i(eu,"getSpan");function s1(){return eu(Yi.getInstance().active())}i(s1,"getActiveSpan");function tu(e,t){return e.setValue(Qi,t)}i(tu,"setSpan");function i1(e){return e.deleteValue(Qi)}i(i1,"deleteSpan");function u1(e,t){return tu(e,new Io(t))}i(u1,"setSpanContext");function Fm(e){var t;return(t=eu(e))===null||t===void 0?void 0:t.spanContext()}i(Fm,"getSpanContext");var l1=/^([0-9a-f]{32})$/i,c1=/^[0-9a-f]{16}$/i;function d1(e){return l1.test(e)&&e!==wm}i(d1,"isValidTraceId");function p1(e){return c1.test(e)&&e!==Cm}i(p1,"isValidSpanId");function Em(e){return d1(e.traceId)&&p1(e.spanId)}i(Em,"isSpanContextValid");function f1(e){return new Io(e)}i(f1,"wrapSpanContext");var nu=Yi.getInstance(),xm=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=nu.active());var o=!!n?.root;if(o)return new Io;var s=r&&Fm(r);return m1(s)&&Em(s)?new Io(s):new Io},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,a=r,u=o);var l=a??nu.active(),c=this.startSpan(t,s,l),d=tu(l,c);return nu.with(d,u,void 0,c)}},e})();function m1(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(m1,"isSpanContext");var h1=new xm,D1=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):h1},e})(),g1=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new xm},e})(),v1=new g1,km=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new D1(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:v1},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),La;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(La||(La={}));var Im=Yi.getInstance(),ru="trace",y1=(function(){function e(){this._proxyTracerProvider=new km,this.wrapSpanContext=f1,this.isSpanContextValid=Em,this.deleteSpan=i1,this.getSpan=eu,this.getActiveSpan=s1,this.getSpanContext=Fm,this.setSpan=tu,this.setSpanContext=u1}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Hi(ru,this._proxyTracerProvider,qa.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return xo(ru)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Ji(ru,qa.instance()),this._proxyTracerProvider=new km},e})(),_1=y1.getInstance(),b1=Object.defineProperty,C1=i((e,t)=>{for(var n in t)b1(e,n,{get:t[n],enumerable:!0})},"__export"),Am="AI_InvalidArgumentError",$m=`vercel.ai.error.${Am}`,w1=Symbol.for($m),Tm,Lt=(Dr=class extends Q{constructor({parameter:t,value:n,message:r}){super({name:Am,message:`Invalid argument for parameter ${t}: ${r}`}),this[Tm]=!0,this.parameter=t,this.value=n}static isInstance(t){return Q.hasMarker(t,$m)}},i(Dr,"InvalidArgumentError"),Dr);Tm=w1;var Sm="AI_InvalidToolApprovalError",Bm=`vercel.ai.error.${Sm}`,F1=Symbol.for(Bm),Om,E1=(gr=class extends Q{constructor({approvalId:t}){super({name:Sm,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[Om]=!0,this.approvalId=t}static isInstance(t){return Q.hasMarker(t,Bm)}},i(gr,"InvalidToolApprovalError"),gr);Om=F1;var Rm="AI_InvalidToolInputError",Nm=`vercel.ai.error.${Rm}`,x1=Symbol.for(Nm),Pm,ou=(vr=class extends Q{constructor({toolInput:t,toolName:n,cause:r,message:o=`Invalid input for tool ${n}: ${so(r)}`}){super({name:Rm,message:o,cause:r}),this[Pm]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return Q.hasMarker(t,Nm)}},i(vr,"InvalidToolInputError"),vr);Pm=x1;var Mm="AI_ToolCallNotFoundForApprovalError",jm=`vercel.ai.error.${Mm}`,k1=Symbol.for(jm),zm,qm=(yr=class extends Q{constructor({toolCallId:t,approvalId:n}){super({name:Mm,message:`Tool call "${t}" not found for approval request "${n}".`}),this[zm]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return Q.hasMarker(t,jm)}},i(yr,"ToolCallNotFoundForApprovalError"),yr);zm=k1;var Lm="AI_MissingToolResultsError",Um=`vercel.ai.error.${Lm}`,I1=Symbol.for(Um),Zm,Vm=(_r=class extends Q{constructor({toolCallIds:t}){super({name:Lm,message:`Tool result${t.length>1?"s are":" is"} missing for tool call${t.length>1?"s":""} ${t.join(", ")}.`}),this[Zm]=!0,this.toolCallIds=t}static isInstance(t){return Q.hasMarker(t,Um)}},i(_r,"MissingToolResultsError"),_r);Zm=I1;var Gm="AI_NoObjectGeneratedError",Wm=`vercel.ai.error.${Gm}`,A1=Symbol.for(Wm),Hm,tn=(br=class extends Q{constructor({message:t="No object generated.",cause:n,text:r,response:o,usage:s,finishReason:a}){super({name:Gm,message:t,cause:n}),this[Hm]=!0,this.text=r,this.response=o,this.usage=s,this.finishReason=a}static isInstance(t){return Q.hasMarker(t,Wm)}},i(br,"NoObjectGeneratedError"),br);Hm=A1;var Jm="AI_NoOutputGeneratedError",Km=`vercel.ai.error.${Jm}`,$1=Symbol.for(Km),Ym,T1=(Cr=class extends Q{constructor({message:t="No output generated.",cause:n}={}){super({name:Jm,message:t,cause:n}),this[Ym]=!0}static isInstance(t){return Q.hasMarker(t,Km)}},i(Cr,"NoOutputGeneratedError"),Cr);Ym=$1;var Xm="AI_NoSuchToolError",Qm=`vercel.ai.error.${Xm}`,S1=Symbol.for(Qm),eh,au=(wr=class extends Q{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:Xm,message:r}),this[eh]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return Q.hasMarker(t,Qm)}},i(wr,"NoSuchToolError"),wr);eh=S1;var th="AI_ToolCallRepairError",nh=`vercel.ai.error.${th}`,B1=Symbol.for(nh),rh,O1=(Fr=class extends Q{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${so(t)}`}){super({name:th,message:r,cause:t}),this[rh]=!0,this.originalError=n}static isInstance(t){return Q.hasMarker(t,nh)}},i(Fr,"ToolCallRepairError"),Fr);rh=B1;var R1=(Er=class extends Q{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Er,"UnsupportedModelVersionError"),Er),oh="AI_InvalidMessageRoleError",ah=`vercel.ai.error.${oh}`,N1=Symbol.for(ah),sh,P1=(xr=class extends Q{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:oh,message:n}),this[sh]=!0,this.role=t}static isInstance(t){return Q.hasMarker(t,ah)}},i(xr,"InvalidMessageRoleError"),xr);sh=N1;var ih="AI_RetryError",uh=`vercel.ai.error.${ih}`,M1=Symbol.for(uh),lh,ch=(kr=class extends Q{constructor({message:t,reason:n,errors:r}){super({name:ih,message:t}),this[lh]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Q.hasMarker(t,uh)}},i(kr,"RetryError"),kr);lh=M1;function j1({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let o=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(j1,"formatWarning");var z1="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",dh=!1,ph=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}dh||(dh=!0,console.info(z1));for(const n of e.warnings)console.warn(j1({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function q1({provider:e,modelId:t}){ph({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(q1,"logV2CompatibilityWarning");function L1(e){return e.specificationVersion==="v3"?e:(q1({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const o=await t.doGenerate(...r);return{...o,finishReason:fh(o.finishReason),usage:mh(o.usage)}};case"doStream":return async(...r)=>{const o=await t.doStream(...r);return{...o,stream:U1(o.stream)}};default:return t[n]}}}))}i(L1,"asLanguageModelV3");function U1(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:fh(t.finishReason),usage:mh(t.usage)});break;default:n.enqueue(t);break}}}))}i(U1,"convertV2StreamToV3");function fh(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(fh,"convertV2FinishReasonToV3");function mh(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i(mh,"convertV2UsageToV3");function hh(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new R1({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return L1(e)}return Z1().languageModel(e)}i(hh,"resolveLanguageModel");function Z1(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:PE}i(Z1,"getGlobalProvider");function Dh(e){if(e!=null)return typeof e=="number"?e:e.totalMs}i(Dh,"getTotalTimeoutMs");function V1(e){if(!(e==null||typeof e=="number"))return e.stepMs}i(V1,"getStepTimeoutMs");var G1=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],W1=i(e=>{const t=typeof e=="string"?hn(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function H1(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?W1(e):e}i(H1,"stripID3TagsIfPresent");function J1({data:e,signatures:t}){const n=H1(e),r=typeof n=="string"?hn(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}i(J1,"detectMediaType");var gh="6.0.97",K1=i(async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const s=await fetch(o,{headers:Dn({},`ai-sdk/${gh}`,Bi()),signal:n});if(!s.ok)throw new en({url:o,statusCode:s.status,statusText:s.statusText});return{data:await gf({response:s,url:o,maxBytes:t??Ti}),mediaType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw en.isInstance(s)?s:new en({url:o,cause:s})}},"download"),Y1=i((e=K1)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function X1(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(X1,"splitDataUrl");var vh=ee([p(),_a(Uint8Array),_a(ArrayBuffer),eF(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function yh(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=X1(e.toString());if(t==null||n==null)throw new Q({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(yh,"convertToLanguageModelV3DataContent");function Q1(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Un(new Uint8Array(e)):Un(e)}i(Q1,"convertDataContentToBase64String");function su(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(su,"asArray");async function e3({prompt:e,supportedUrls:t,download:n=Y1()}){const r=await n3(e.messages,n,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const d of c.content)d.type==="tool-approval-request"&&"approvalId"in d&&"toolCallId"in d&&o.set(d.approvalId,d.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const d of c.content)if(d.type==="tool-approval-response"){const f=o.get(d.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:su(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>t3({message:c,downloadedAssets:r}))],u=[];for(const c of a){if(c.role!=="tool"){u.push(c);continue}const d=u.at(-1);d?.role==="tool"?d.content.push(...c.content):u.push(c)}const l=new Set;for(const c of u)switch(c.role){case"assistant":{for(const d of c.content)d.type==="tool-call"&&!d.providerExecuted&&l.add(d.toolCallId);break}case"tool":{for(const d of c.content)d.type==="tool-result"&&l.delete(d.toolCallId);break}case"user":case"system":for(const d of s)l.delete(d);if(l.size>0)throw new Vm({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Vm({toolCallIds:Array.from(l)});return u.filter(c=>c.role!=="tool"||c.content.length>0)}i(e3,"convertToLanguageModelPrompt");function t3({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>r3(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=yh(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:_h(r.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:_h(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new P1({role:r})}}}i(t3,"convertToLanguageModelMessage");async function n3(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const u=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&LF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(n3,"downloadAssets");function r3(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=yh(r);let u=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=J1({data:l,signatures:G1}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(r3,"convertPartToLanguageModelPart");function _h(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(_h,"mapToolResultOutput");async function Ua({toolCallId:e,input:t,output:n,tool:r,errorMode:o}){return o==="text"?{type:"error-text",value:so(n)}:o==="json"?{type:"error-json",value:bh(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:bh(n)}}i(Ua,"createToolModelOutput");function bh(e){return e===void 0?null:e}i(bh,"toJSONValue");function Ch({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new Lt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Lt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Lt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Lt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new Lt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Lt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Lt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Lt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:u,seed:a}}i(Ch,"prepareCallSettings");function o3(e){return e!=null&&Object.keys(e).length>0}i(o3,"isNonEmptyObject");async function a3({tools:e,toolChoice:t,activeTools:n}){if(!o3(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),o=[];for(const[s,a]of r){const u=a.type;switch(u){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Vn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(a3,"prepareToolsAndToolChoice");var Ao=bi(()=>ee([Jp(),p(),x(),Re(),be(p(),Ao.optional()),S(Ao)])),Pe=be(p(),be(p(),Ao.optional())),wh=g({type:F("text"),text:p(),providerOptions:Pe.optional()}),s3=g({type:F("image"),image:ee([vh,_a(URL)]),mediaType:p().optional(),providerOptions:Pe.optional()}),Fh=g({type:F("file"),data:ee([vh,_a(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Pe.optional()}),i3=g({type:F("reasoning"),text:p(),providerOptions:Pe.optional()}),u3=g({type:F("tool-call"),toolCallId:p(),toolName:p(),input:ut(),providerOptions:Pe.optional(),providerExecuted:Re().optional()}),l3=ge("type",[g({type:F("text"),value:p(),providerOptions:Pe.optional()}),g({type:F("json"),value:Ao,providerOptions:Pe.optional()}),g({type:F("execution-denied"),reason:p().optional(),providerOptions:Pe.optional()}),g({type:F("error-text"),value:p(),providerOptions:Pe.optional()}),g({type:F("error-json"),value:Ao,providerOptions:Pe.optional()}),g({type:F("content"),value:S(ee([g({type:F("text"),text:p(),providerOptions:Pe.optional()}),g({type:F("media"),data:p(),mediaType:p()}),g({type:F("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:Pe.optional()}),g({type:F("file-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:F("image-data"),data:p(),mediaType:p(),providerOptions:Pe.optional()}),g({type:F("image-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("image-file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:F("custom"),providerOptions:Pe.optional()})]))})]),Eh=g({type:F("tool-result"),toolCallId:p(),toolName:p(),output:l3,providerOptions:Pe.optional()}),c3=g({type:F("tool-approval-request"),approvalId:p(),toolCallId:p()}),d3=g({type:F("tool-approval-response"),approvalId:p(),approved:Re(),reason:p().optional()}),p3=g({role:F("system"),content:p(),providerOptions:Pe.optional()}),f3=g({role:F("user"),content:ee([p(),S(ee([wh,s3,Fh]))]),providerOptions:Pe.optional()}),m3=g({role:F("assistant"),content:ee([p(),S(ee([wh,Fh,i3,u3,Eh,c3]))]),providerOptions:Pe.optional()}),h3=g({role:F("tool"),content:S(ee([Eh,d3])),providerOptions:Pe.optional()}),D3=ee([p3,f3,m3,h3]);async function g3(e){if(e.prompt==null&&e.messages==null)throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Gt({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!su(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new Gt({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Gt({prompt:e,message:"messages must not be empty"});const n=await xt({value:t,schema:S(D3)});if(!n.success)throw new Gt({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(g3,"standardizePrompt");function v3(e){if(!Wi.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new Q({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
140
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new Tn({message:s,statusCode:n,cause:r,generationId:o})}},i(Tn,"_GatewayTimeoutError"),Tn);function _m(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}i(_m,"isTimeoutError");async function qt(e,t){var n;return ot.isInstance(e)?e:_m(e)?ym.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):Be.isInstance(e)?e.cause&&_m(e.cause)?ym.createTimeoutError({originalMessage:e.message,cause:e}):await mm({response:uE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await mm({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(qt,"asGatewayError");function uE(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(uE,"extractApiCallResponse");var bm="ai-gateway-auth-method";async function Fn(e){const t=await kt({value:e[bm],schema:lE});return t.success?t.value:void 0}i(Fn,"parseAuthMethod");var lE=K(()=>J(ee([F("api-key"),F("oidc")]))),Cm=(mr=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Ff({url:`${this.config.baseURL}/config`,headers:await ct(this.config.headers()),successfulResponseHandler:Ke(cE),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await qt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await Ff({url:`${t.origin}/v1/credits`,headers:await ct(this.config.headers()),successfulResponseHandler:Ke(dE),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await qt(t)}}},i(mr,"GatewayFetchMetadata"),mr),cE=K(()=>J(g({models:S(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:F("v3"),provider:p(),modelId:p()}),modelType:se(["embedding","image","language","video"]).nullish()}))}))),dE=K(()=>J(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),pE=(hr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await ct(this.config.headers());try{const{responseHeaders:a,value:u,rawValue:l}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await ct(this.config.o11yHeaders)),body:n,successfulResponseHandler:Ke(et()),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(c=>c,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:a,body:l},warnings:r}}catch(a){throw await qt(a,await Fn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await ct(this.config.headers());try{const{value:a,responseHeaders:u}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await ct(this.config.o11yHeaders)),body:n,successfulResponseHandler:Jn(et()),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(l=>l,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(a){throw await qt(a,await Fn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const o=r;if(o.data instanceof Uint8Array){const s=Uint8Array.from(o.data),a=Buffer.from(s).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(hr,"GatewayLanguageModel"),hr),fE=(Dr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;const a=await ct(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.getUrl(),headers:Ne(a,n??{},this.getModelConfigHeaders(),await ct(this.config.o11yHeaders)),body:{values:t,...o?{providerOptions:o}:{}},successfulResponseHandler:Ke(mE),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await qt(u,await Fn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(Dr,"GatewayEmbeddingModel"),Dr),mE=K(()=>J(g({embeddings:S(S(x())),usage:g({tokens:x()}).nullish(),providerMetadata:Ce(p(),Ce(p(),lt())).optional()}))),hE=(gr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,files:a,mask:u,providerOptions:l,headers:c,abortSignal:d}){var f,m,D,h;const v=await ct(this.config.headers());try{const{responseHeaders:y,value:b,rawValue:C}=await qe({url:this.getUrl(),headers:Ne(v,c??{},this.getModelConfigHeaders(),await ct(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...o&&{aspectRatio:o},...s&&{seed:s},...l&&{providerOptions:l},...a&&{files:a.map(w=>wm(w))},...u&&{mask:wm(u)}},successfulResponseHandler:Ke(yE),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(w=>w,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:b.images,warnings:(f=b.warnings)!=null?f:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},...b.usage!=null&&{usage:{inputTokens:(m=b.usage.inputTokens)!=null?m:void 0,outputTokens:(D=b.usage.outputTokens)!=null?D:void 0,totalTokens:(h=b.usage.totalTokens)!=null?h:void 0}}}}catch(y){throw await qt(y,await Fn(v))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(gr,"GatewayImageModel"),gr);function wm(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Gn(e.data)}:e}i(wm,"maybeEncodeImageFile");var DE=g({images:S(lt()).optional()}).catchall(lt()),gE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),vE=g({inputTokens:x().nullish(),outputTokens:x().nullish(),totalTokens:x().nullish()}),yE=g({images:S(p()),warnings:S(gE).optional(),providerMetadata:Ce(p(),DE).optional(),usage:vE.optional()}),_E=(vr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,aspectRatio:r,resolution:o,duration:s,fps:a,seed:u,image:l,providerOptions:c,headers:d,abortSignal:f}){var m;const D=await ct(this.config.headers());try{const{responseHeaders:h,value:v}=await qe({url:this.getUrl(),headers:Ne(D,d??{},this.getModelConfigHeaders(),await ct(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:t,n,...r&&{aspectRatio:r},...o&&{resolution:o},...s&&{duration:s},...a&&{fps:a},...u&&{seed:u},...c&&{providerOptions:c},...l&&{image:bE(l)}},successfulResponseHandler:i(async({response:y,url:b,requestBodyValues:C})=>{if(y.body==null)throw new Be({message:"SSE response body is empty",url:b,requestBodyValues:C,statusCode:y.status});const E=Sf({stream:y.body,schema:EE}).getReader(),{done:T,value:O}=await E.read();if(E.releaseLock(),T||!O)throw new Be({message:"SSE stream ended without a data event",url:b,requestBodyValues:C,statusCode:y.status});if(!O.success)throw new Be({message:"Failed to parse video SSE event",cause:O.error,url:b,requestBodyValues:C,statusCode:y.status});const $=O.value;if($.type==="error")throw new Be({message:$.message,statusCode:$.statusCode,url:b,requestBodyValues:C,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify($),data:{error:{message:$.message,type:$.errorType,param:$.param}}});return{value:{videos:$.videos,warnings:$.warnings,providerMetadata:$.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(y=>y,"errorToMessage")}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:(m=v.warnings)!=null?m:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await qt(h,await Fn(D))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},i(vr,"GatewayVideoModel"),vr);function bE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Gn(e.data)}:e}i(bE,"maybeEncodeVideoFile");var CE=g({videos:S(lt()).optional()}).catchall(lt()),wE=ee([g({type:F("url"),url:p(),mediaType:p()}),g({type:F("base64"),data:p(),mediaType:p()})]),FE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),EE=ge("type",[g({type:F("result"),videos:S(wE),warnings:S(FE).optional(),providerMetadata:Ce(p(),CE).optional()}),g({type:F("error"),message:p(),errorType:p(),statusCode:x(),param:lt().nullable()})]),xE=K(()=>J(Ft({objective:Fe().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:tn(Fe()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Ua(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:jt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Ft({include_domains:tn(Fe()).optional().describe("List of domains to include in search results."),exclude_domains:tn(Fe()).optional().describe("List of domains to exclude from search results."),after_date:Fe().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:Ft({max_chars_per_result:jt().optional().describe("Maximum characters per result."),max_chars_total:jt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Ft({max_age_seconds:jt().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),kE=K(()=>J(Ti([Ft({searchId:Fe(),results:tn(Ft({url:Fe(),title:Fe(),excerpt:Fe(),publishDate:Fe().nullable().optional(),relevanceScore:jt().optional()}))}),Ft({error:Ua(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:jt().optional(),message:Fe()})]))),IE=At({id:"gateway.parallel_search",inputSchema:xE,outputSchema:kE}),AE=i((e={})=>IE(e),"parallelSearch"),$E=K(()=>J(Ft({query:Ti([Fe(),tn(Fe())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:jt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:jt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:jt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Fe().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:tn(Fe()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:tn(Fe()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Fe().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Fe().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Fe().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Fe().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Ua(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),TE=K(()=>J(Ti([Ft({results:tn(Ft({title:Fe(),url:Fe(),snippet:Fe(),date:Fe().optional(),lastUpdated:Fe().optional()})),id:Fe()}),Ft({error:Ua(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:jt().optional(),message:Fe()})]))),SE=At({id:"gateway.perplexity_search",inputSchema:$E,outputSchema:TE}),BE=i((e={})=>SE(e),"perplexitySearch"),OE={parallelSearch:AE,perplexitySearch:BE};async function RE(){var e;return(e=zf.getContext().headers)==null?void 0:e["x-vercel-id"]}i(RE,"getVercelRequestId");var NE="3.0.53",PE="0.0.1";function ME(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const u=(n=Zi(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await zE(e);return Cn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":PE,[bm]:v.authMethod,...e.headers},`ai-sdk/gateway/${NE}`)}catch(v){throw Ki.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=ko({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=ko({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=ko({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const C=await RE();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...b&&{"ai-o11y-region":b},...C&&{"ai-o11y-request-id":C}}}},"createO11yHeaders"),d=i(v=>new pE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),f=i(async()=>{var v,y,b;const C=(b=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?b:Date.now();return(!r||C-a>s)&&(a=C,r=new Cm({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(w=>(o=w,w)).catch(async w=>{throw await qt(w,await Fn(await l()))})),o?Promise.resolve(o):r},"getAvailableModels"),m=i(async()=>new Cm({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await qt(v,await Fn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=f,D.getCredits=m,D.imageModel=v=>new hE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const h=i(v=>new fE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=h,D.textEmbeddingModel=h,D.videoModel=v=>new _E(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.chat=D.languageModel,D.embedding=D.embeddingModel,D.image=D.imageModel,D.video=D.videoModel,D.tools=OE,D}i(ME,"createGatewayProvider");var jE=ME();async function zE(e){const t=ko({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await zf.getVercelOidcToken(),authMethod:"oidc"}}i(zE,"getGatewayAuthToken");var LE=typeof globalThis=="object"?globalThis:global,En="1.9.0",Fm=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function qE(e){var t=new Set([e]),n=new Set,r=e.match(Fm);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function a(u){return t.add(u),!0}return i(a,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(Fm);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||o.major!==d.major?s(l):o.major===0?o.minor===d.minor&&o.patch<=d.patch?a(l):s(l):o.minor<=d.minor?a(l):s(l)},"isCompatible2")}i(qE,"_makeCompatibilityCheck");var UE=qE(En),ZE=En.split(".")[0],Io=Symbol.for("opentelemetry.js.api."+ZE),Ao=LE;function Yi(e,t,n,r){var o;r===void 0&&(r=!1);var s=Ao[Io]=(o=Ao[Io])!==null&&o!==void 0?o:{version:En};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==En){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+En);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+En+"."),!0}i(Yi,"registerGlobal");function $o(e){var t,n,r=(t=Ao[Io])===null||t===void 0?void 0:t.version;if(!(!r||!UE(r)))return(n=Ao[Io])===null||n===void 0?void 0:n[e]}i($o,"getGlobal");function Xi(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+En+".");var n=Ao[Io];n&&delete n[e]}i(Xi,"unregisterGlobal");var VE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$3"),GE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),WE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return To("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return To("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return To("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return To("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return To("verbose",this._namespace,t)},e})();function To(e,t,n){var r=$o("diag");if(r)return n.unshift(t),r[e].apply(r,GE([],VE(n),!1))}i(To,"logProxy");var vt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(vt||(vt={}));function HE(e,t){e<vt.NONE?e=vt.NONE:e>vt.ALL&&(e=vt.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",vt.ERROR),warn:n("warn",vt.WARN),info:n("info",vt.INFO),debug:n("debug",vt.DEBUG),verbose:n("verbose",vt.VERBOSE)}}i(HE,"createLogLevelDiagLogger");var JE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$2"),KE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),YE="diag",Wa=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var u=$o("diag");if(u)return u[o].apply(u,KE([],JE(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(o,s){var a,u,l;if(s===void 0&&(s={logLevel:vt.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=$o("diag"),f=HE((u=s.logLevel)!==null&&u!==void 0?u:vt.INFO,o);if(d&&!s.suppressOverrideMessage){var m=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+m),f.warn("Current logger will overwrite one already registered from "+m)}return Yi("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){Xi(YE,n)},n.createComponentLogger=function(o){return new WE(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function XE(e){return Symbol.for(e)}i(XE,"createContextKey");var QE=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return i(e,"BaseContext2"),e})(),e1=new QE,t1=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$1"),n1=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),r1=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return e1},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,n1([r],t1(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),o1=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read"),a1=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),Qi="context",s1=new r1,eu=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yi(Qi,t,Wa.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,a1([t,n,r],o1(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return $o(Qi)||s1},e.prototype.disable=function(){this._getContextManager().disable(),Xi(Qi,Wa.instance())},e})(),tu;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(tu||(tu={}));var Em="0000000000000000",xm="00000000000000000000000000000000",i1={traceId:xm,spanId:Em,traceFlags:tu.NONE},So=(function(){function e(t){t===void 0&&(t=i1),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),nu=XE("OpenTelemetry Context Key SPAN");function ru(e){return e.getValue(nu)||void 0}i(ru,"getSpan");function u1(){return ru(eu.getInstance().active())}i(u1,"getActiveSpan");function ou(e,t){return e.setValue(nu,t)}i(ou,"setSpan");function l1(e){return e.deleteValue(nu)}i(l1,"deleteSpan");function c1(e,t){return ou(e,new So(t))}i(c1,"setSpanContext");function km(e){var t;return(t=ru(e))===null||t===void 0?void 0:t.spanContext()}i(km,"getSpanContext");var d1=/^([0-9a-f]{32})$/i,p1=/^[0-9a-f]{16}$/i;function f1(e){return d1.test(e)&&e!==xm}i(f1,"isValidTraceId");function m1(e){return p1.test(e)&&e!==Em}i(m1,"isValidSpanId");function Im(e){return f1(e.traceId)&&m1(e.spanId)}i(Im,"isSpanContextValid");function h1(e){return new So(e)}i(h1,"wrapSpanContext");var au=eu.getInstance(),Am=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=au.active());var o=!!n?.root;if(o)return new So;var s=r&&km(r);return D1(s)&&Im(s)?new So(s):new So},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,a=r,u=o);var l=a??au.active(),c=this.startSpan(t,s,l),d=ou(l,c);return au.with(d,u,void 0,c)}},e})();function D1(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(D1,"isSpanContext");var g1=new Am,v1=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):g1},e})(),y1=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Am},e})(),_1=new y1,$m=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new v1(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:_1},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),Ha;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ha||(Ha={}));var Tm=eu.getInstance(),su="trace",b1=(function(){function e(){this._proxyTracerProvider=new $m,this.wrapSpanContext=h1,this.isSpanContextValid=Im,this.deleteSpan=l1,this.getSpan=ru,this.getActiveSpan=u1,this.getSpanContext=km,this.setSpan=ou,this.setSpanContext=c1}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Yi(su,this._proxyTracerProvider,Wa.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return $o(su)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Xi(su,Wa.instance()),this._proxyTracerProvider=new $m},e})(),C1=b1.getInstance(),w1=Object.defineProperty,F1=i((e,t)=>{for(var n in t)w1(e,n,{get:t[n],enumerable:!0})},"__export"),Sm="AI_InvalidArgumentError",Bm=`vercel.ai.error.${Sm}`,E1=Symbol.for(Bm),Om,Ut=(yr=class extends Q{constructor({parameter:t,value:n,message:r}){super({name:Sm,message:`Invalid argument for parameter ${t}: ${r}`}),this[Om]=!0,this.parameter=t,this.value=n}static isInstance(t){return Q.hasMarker(t,Bm)}},i(yr,"InvalidArgumentError"),yr);Om=E1;var Rm="AI_InvalidToolApprovalError",Nm=`vercel.ai.error.${Rm}`,x1=Symbol.for(Nm),Pm,k1=(_r=class extends Q{constructor({approvalId:t}){super({name:Rm,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[Pm]=!0,this.approvalId=t}static isInstance(t){return Q.hasMarker(t,Nm)}},i(_r,"InvalidToolApprovalError"),_r);Pm=x1;var Mm="AI_InvalidToolInputError",jm=`vercel.ai.error.${Mm}`,I1=Symbol.for(jm),zm,iu=(br=class extends Q{constructor({toolInput:t,toolName:n,cause:r,message:o=`Invalid input for tool ${n}: ${co(r)}`}){super({name:Mm,message:o,cause:r}),this[zm]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return Q.hasMarker(t,jm)}},i(br,"InvalidToolInputError"),br);zm=I1;var Lm="AI_ToolCallNotFoundForApprovalError",qm=`vercel.ai.error.${Lm}`,A1=Symbol.for(qm),Um,Zm=(Cr=class extends Q{constructor({toolCallId:t,approvalId:n}){super({name:Lm,message:`Tool call "${t}" not found for approval request "${n}".`}),this[Um]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return Q.hasMarker(t,qm)}},i(Cr,"ToolCallNotFoundForApprovalError"),Cr);Um=A1;var Vm="AI_MissingToolResultsError",Gm=`vercel.ai.error.${Vm}`,$1=Symbol.for(Gm),Wm,Hm=(wr=class extends Q{constructor({toolCallIds:t}){super({name:Vm,message:`Tool result${t.length>1?"s are":" is"} missing for tool call${t.length>1?"s":""} ${t.join(", ")}.`}),this[Wm]=!0,this.toolCallIds=t}static isInstance(t){return Q.hasMarker(t,Gm)}},i(wr,"MissingToolResultsError"),wr);Wm=$1;var Jm="AI_NoObjectGeneratedError",Km=`vercel.ai.error.${Jm}`,T1=Symbol.for(Km),Ym,rn=(Fr=class extends Q{constructor({message:t="No object generated.",cause:n,text:r,response:o,usage:s,finishReason:a}){super({name:Jm,message:t,cause:n}),this[Ym]=!0,this.text=r,this.response=o,this.usage=s,this.finishReason=a}static isInstance(t){return Q.hasMarker(t,Km)}},i(Fr,"NoObjectGeneratedError"),Fr);Ym=T1;var Xm="AI_NoOutputGeneratedError",Qm=`vercel.ai.error.${Xm}`,S1=Symbol.for(Qm),eh,B1=(Er=class extends Q{constructor({message:t="No output generated.",cause:n}={}){super({name:Xm,message:t,cause:n}),this[eh]=!0}static isInstance(t){return Q.hasMarker(t,Qm)}},i(Er,"NoOutputGeneratedError"),Er);eh=S1;var th="AI_NoSuchToolError",nh=`vercel.ai.error.${th}`,O1=Symbol.for(nh),rh,uu=(xr=class extends Q{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:th,message:r}),this[rh]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return Q.hasMarker(t,nh)}},i(xr,"NoSuchToolError"),xr);rh=O1;var oh="AI_ToolCallRepairError",ah=`vercel.ai.error.${oh}`,R1=Symbol.for(ah),sh,N1=(kr=class extends Q{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${co(t)}`}){super({name:oh,message:r,cause:t}),this[sh]=!0,this.originalError=n}static isInstance(t){return Q.hasMarker(t,ah)}},i(kr,"ToolCallRepairError"),kr);sh=R1;var P1=(Ir=class extends Q{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Ir,"UnsupportedModelVersionError"),Ir),ih="AI_InvalidMessageRoleError",uh=`vercel.ai.error.${ih}`,M1=Symbol.for(uh),lh,j1=(Ar=class extends Q{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:ih,message:n}),this[lh]=!0,this.role=t}static isInstance(t){return Q.hasMarker(t,uh)}},i(Ar,"InvalidMessageRoleError"),Ar);lh=M1;var ch="AI_RetryError",dh=`vercel.ai.error.${ch}`,z1=Symbol.for(dh),ph,fh=($r=class extends Q{constructor({message:t,reason:n,errors:r}){super({name:ch,message:t}),this[ph]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Q.hasMarker(t,dh)}},i($r,"RetryError"),$r);ph=z1;function L1({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let o=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(L1,"formatWarning");var q1="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",mh=!1,hh=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}mh||(mh=!0,console.info(q1));for(const n of e.warnings)console.warn(L1({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function U1({provider:e,modelId:t}){hh({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(U1,"logV2CompatibilityWarning");function Z1(e){return e.specificationVersion==="v3"?e:(U1({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const o=await t.doGenerate(...r);return{...o,finishReason:Dh(o.finishReason),usage:gh(o.usage)}};case"doStream":return async(...r)=>{const o=await t.doStream(...r);return{...o,stream:V1(o.stream)}};default:return t[n]}}}))}i(Z1,"asLanguageModelV3");function V1(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:Dh(t.finishReason),usage:gh(t.usage)});break;default:n.enqueue(t);break}}}))}i(V1,"convertV2StreamToV3");function Dh(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(Dh,"convertV2FinishReasonToV3");function gh(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i(gh,"convertV2UsageToV3");function vh(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new P1({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return Z1(e)}return G1().languageModel(e)}i(vh,"resolveLanguageModel");function G1(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:jE}i(G1,"getGlobalProvider");function yh(e){if(e!=null)return typeof e=="number"?e:e.totalMs}i(yh,"getTotalTimeoutMs");function W1(e){if(!(e==null||typeof e=="number"))return e.stepMs}i(W1,"getStepTimeoutMs");var H1=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],J1=i(e=>{const t=typeof e=="string"?bn(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function K1(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?J1(e):e}i(K1,"stripID3TagsIfPresent");function Y1({data:e,signatures:t}){const n=K1(e),r=typeof n=="string"?bn(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}i(Y1,"detectMediaType");var _h="6.0.97",X1=i(async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const s=await fetch(o,{headers:Cn({},`ai-sdk/${_h}`,Ni()),signal:n});if(!s.ok)throw new nn({url:o,statusCode:s.status,statusText:s.statusText});return{data:await _f({response:s,url:o,maxBytes:t??Oi}),mediaType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw nn.isInstance(s)?s:new nn({url:o,cause:s})}},"download"),Q1=i((e=X1)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function e3(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(e3,"splitDataUrl");var bh=ee([p(),xa(Uint8Array),xa(ArrayBuffer),nF(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Ch(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=e3(e.toString());if(t==null||n==null)throw new Q({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(Ch,"convertToLanguageModelV3DataContent");function t3(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Gn(new Uint8Array(e)):Gn(e)}i(t3,"convertDataContentToBase64String");function lu(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(lu,"asArray");async function n3({prompt:e,supportedUrls:t,download:n=Q1()}){const r=await o3(e.messages,n,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const d of c.content)d.type==="tool-approval-request"&&"approvalId"in d&&"toolCallId"in d&&o.set(d.approvalId,d.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const d of c.content)if(d.type==="tool-approval-response"){const f=o.get(d.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:lu(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>r3({message:c,downloadedAssets:r}))],u=[];for(const c of a){if(c.role!=="tool"){u.push(c);continue}const d=u.at(-1);d?.role==="tool"?d.content.push(...c.content):u.push(c)}const l=new Set;for(const c of u)switch(c.role){case"assistant":{for(const d of c.content)d.type==="tool-call"&&!d.providerExecuted&&l.add(d.toolCallId);break}case"tool":{for(const d of c.content)d.type==="tool-result"&&l.delete(d.toolCallId);break}case"user":case"system":for(const d of s)l.delete(d);if(l.size>0)throw new Hm({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Hm({toolCallIds:Array.from(l)});return u.filter(c=>c.role!=="tool"||c.content.length>0)}i(n3,"convertToLanguageModelPrompt");function r3({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>a3(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=Ch(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:wh(r.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:wh(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new j1({role:r})}}}i(r3,"convertToLanguageModelMessage");async function o3(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const u=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&ZF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(o3,"downloadAssets");function a3(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=Ch(r);let u=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=Y1({data:l,signatures:H1}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(a3,"convertPartToLanguageModelPart");function wh(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(wh,"mapToolResultOutput");async function Ja({toolCallId:e,input:t,output:n,tool:r,errorMode:o}){return o==="text"?{type:"error-text",value:co(n)}:o==="json"?{type:"error-json",value:Fh(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:Fh(n)}}i(Ja,"createToolModelOutput");function Fh(e){return e===void 0?null:e}i(Fh,"toJSONValue");function Eh({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new Ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Ut({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Ut({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new Ut({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Ut({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Ut({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Ut({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:u,seed:a}}i(Eh,"prepareCallSettings");function s3(e){return e!=null&&Object.keys(e).length>0}i(s3,"isNonEmptyObject");async function i3({tools:e,toolChoice:t,activeTools:n}){if(!s3(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),o=[];for(const[s,a]of r){const u=a.type;switch(u){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Hn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(i3,"prepareToolsAndToolChoice");var Bo=Fi(()=>ee([Xp(),p(),x(),Re(),Ce(p(),Bo.optional()),S(Bo)])),Pe=Ce(p(),Ce(p(),Bo.optional())),xh=g({type:F("text"),text:p(),providerOptions:Pe.optional()}),u3=g({type:F("image"),image:ee([bh,xa(URL)]),mediaType:p().optional(),providerOptions:Pe.optional()}),kh=g({type:F("file"),data:ee([bh,xa(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Pe.optional()}),l3=g({type:F("reasoning"),text:p(),providerOptions:Pe.optional()}),c3=g({type:F("tool-call"),toolCallId:p(),toolName:p(),input:lt(),providerOptions:Pe.optional(),providerExecuted:Re().optional()}),d3=ge("type",[g({type:F("text"),value:p(),providerOptions:Pe.optional()}),g({type:F("json"),value:Bo,providerOptions:Pe.optional()}),g({type:F("execution-denied"),reason:p().optional(),providerOptions:Pe.optional()}),g({type:F("error-text"),value:p(),providerOptions:Pe.optional()}),g({type:F("error-json"),value:Bo,providerOptions:Pe.optional()}),g({type:F("content"),value:S(ee([g({type:F("text"),text:p(),providerOptions:Pe.optional()}),g({type:F("media"),data:p(),mediaType:p()}),g({type:F("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:Pe.optional()}),g({type:F("file-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("file-id"),fileId:ee([p(),Ce(p(),p())]),providerOptions:Pe.optional()}),g({type:F("image-data"),data:p(),mediaType:p(),providerOptions:Pe.optional()}),g({type:F("image-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("image-file-id"),fileId:ee([p(),Ce(p(),p())]),providerOptions:Pe.optional()}),g({type:F("custom"),providerOptions:Pe.optional()})]))})]),Ih=g({type:F("tool-result"),toolCallId:p(),toolName:p(),output:d3,providerOptions:Pe.optional()}),p3=g({type:F("tool-approval-request"),approvalId:p(),toolCallId:p()}),f3=g({type:F("tool-approval-response"),approvalId:p(),approved:Re(),reason:p().optional()}),m3=g({role:F("system"),content:p(),providerOptions:Pe.optional()}),h3=g({role:F("user"),content:ee([p(),S(ee([xh,u3,kh]))]),providerOptions:Pe.optional()}),D3=g({role:F("assistant"),content:ee([p(),S(ee([xh,kh,l3,c3,Ih,p3]))]),providerOptions:Pe.optional()}),g3=g({role:F("tool"),content:S(ee([Ih,f3])),providerOptions:Pe.optional()}),v3=ee([m3,h3,D3,g3]);async function y3(e){if(e.prompt==null&&e.messages==null)throw new Ht({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Ht({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!lu(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new Ht({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Ht({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Ht({prompt:e,message:"messages must not be empty"});const n=await kt({value:t,schema:S(v3)});if(!n.success)throw new Ht({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(y3,"standardizePrompt");function _3(e){if(!Ki.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new Q({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
141
141
 
142
142
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
143
143
 
@@ -145,14 +145,14 @@ Alternatively, you can use a provider module instead of the AI Gateway.
145
145
 
146
146
  Learn more: \x1B[34m${n}\x1B[0m
147
147
 
148
- `),{name:"GatewayAuthenticationError"})}i(v3,"wrapGatewayError");function iu({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(iu,"assembleOperationName");function y3({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,u])=>{if(a==="timeout"){const l=Dh(u);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=u;return s},{}),...Object.entries((o=n?.metadata)!=null?o:{}).reduce((s,[a,u])=>(s[`ai.telemetry.metadata.${a}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[a,u])=>(u!==void 0&&(s[`ai.request.headers.${a}`]=u),s),{})}}i(y3,"getBaseTelemetryAttributes");var _3={startSpan(){return Za},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Za);if(typeof n=="function")return n(Za);if(typeof r=="function")return r(Za)}},Za={spanContext(){return b3},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},b3={traceId:"",spanId:"",traceFlags:0};function C3({isEnabled:e=!1,tracer:t}={}){return e?t||_1.getTracer("ai"):_3}i(C3,"getTracer");async function uu({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{const a=Im.active();try{const u=await Im.with(a,()=>r(s));return o&&s.end(),u}catch(u){try{xh(s,u)}finally{s.end()}throw u}})}i(uu,"recordSpan");function xh(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:La.ERROR,message:t.message})):e.setStatus({code:La.ERROR})}i(xh,"recordErrorOnSpan");async function Wn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(n[r]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(n[r]=s);continue}n[r]=o}return n}i(Wn,"selectTelemetryAttributes");function w3(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Q1(n.data):n.data}:n)})))}i(w3,"stringifyForTelemetry");function F3(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:At(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(F3,"asLanguageModelUsage");function E3(e,t){var n,r,o,s,a,u,l,c,d,f;return{inputTokens:At(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:At((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:At((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:At((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:At(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:At((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:At((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:At(e.totalTokens,t.totalTokens),reasoningTokens:At(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:At(e.cachedInputTokens,t.cachedInputTokens)}}i(E3,"addLanguageModelUsage");function At(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i(At,"addTokenCounts");function kh(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&u?n[r]=kh(s,o):n[r]=o}return n}i(kh,"mergeObjects");function x3({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(x3,"getRetryDelayInMs");var k3=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>Ih(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function Ih(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Zn(a)||t===0)throw a;const u=vf(a),l=[...s,a],c=l.length;if(c>t)throw new ch({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Be.isInstance(a)&&a.isRetryable===!0&&c<=t)return await SF(x3({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),Ih(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new ch({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(Ih,"_retryWithExponentialBackoff");function I3({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new Lt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:k3({maxRetries:n,abortSignal:t})}}i(I3,"prepareRetries");function A3({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new E1({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new qm({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}i(A3,"collectToolApprovals");function lu(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}i(lu,"now");async function $3({toolCall:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onPreliminaryToolResult:c,onToolCallStart:d,onToolCallFinish:f}){const{toolName:h,toolCallId:D,input:m}=e,v=t?.[h];if(v?.execute==null)return;const y={stepNumber:u,model:l,toolCall:e,messages:o,abortSignal:s,functionId:r?.functionId,metadata:r?.metadata,experimental_context:a};return uu({name:"ai.toolCall",attributes:Wn({telemetry:r,attributes:{...iu({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":h,"ai.toolCall.id":D,"ai.toolCall.args":{output:i(()=>JSON.stringify(m),"output")}}}),tracer:n,fn:i(async b=>{let C;try{await d?.(y)}catch{}const w=lu();try{const T=U2({execute:v.execute.bind(v),input:m,options:{toolCallId:D,messages:o,abortSignal:s,experimental_context:a}});for await(const O of T)O.type==="preliminary"?c?.({...e,type:"tool-result",output:O.output,preliminary:!0}):C=O.output}catch(T){const O=lu()-w;try{await f?.({...y,success:!1,error:T,durationMs:O})}catch{}return xh(b,T),{type:"tool-error",toolCallId:D,toolName:h,input:m,error:T,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const E=lu()-w;try{await f?.({...y,success:!0,output:C,durationMs:E})}catch{}try{b.setAttributes(await Wn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(C),"output")}}}))}catch{}return{type:"tool-result",toolCallId:D,toolName:h,input:m,output:C,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i($3,"executeToolCall");function Ah(e){const t=e.filter(n=>n.type==="reasoning");return t.length===0?void 0:t.map(n=>n.text).join(`
149
- `)}i(Ah,"extractReasoningContent");function $h(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i($h,"extractTextContent");var T3=(Ir=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=Un(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=hn(this.base64Data)),this.uint8ArrayData}},i(Ir,"DefaultGeneratedFile"),Ir);async function S3({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i(S3,"isApprovalNeeded");var B3={};C1(B3,{array:i(()=>N3,"array"),choice:i(()=>P3,"choice"),json:i(()=>M3,"json"),object:i(()=>R3,"object"),text:i(()=>Th,"text")});function O3(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(o,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(a,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i(O3,"fixJson");async function Va(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await kt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await kt({text:O3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(Va,"parsePartialJson");var Th=i(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),R3=i(({schema:e,name:t,description:n})=>{const r=Vn(e);return{name:"object",responseFormat:lt(r.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await xt({value:a.value,schema:r});if(!u.success)throw new tn({message:"No object generated: response did not match schema.",cause:u.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:o}){const s=await Va(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},"object"),N3=i(({element:e,name:t,description:n})=>{const r=Vn(e);return{name:"array",responseFormat:lt(r.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=a.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:u,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await xt({value:l,schema:r});if(!c.success)throw new tn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:o}){const s=await Va(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const u=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of u){const d=await xt({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},"array"),P3=i(({options:e,name:t,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},o){const s=await kt({text:r});if(!s.success)throw new tn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:a,cause:"response must be an object that contains a choice value."}),text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:r}){const o=await Va(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(u=>u.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),M3=i(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const o=await kt({text:n});if(!o.success)throw new tn({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value},async parsePartialOutput({text:n}){const r=await Va(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}},createElementStreamTransform(){}}),"json");async function j3({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Sh(e);throw new au({toolName:e.toolName})}try{return await Bh({toolCall:e,tools:t})}catch(a){if(n==null||!(au.isInstance(a)||ou.isInstance(a)))throw a;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await Vn(c).jsonSchema},"inputSchema"),system:r,messages:o,error:a})}catch(l){throw new O1({cause:l,originalError:a})}if(u==null)throw a;return await Bh({toolCall:u,tools:t})}}catch(a){const u=await kt({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(j3,"parseToolCall");async function Sh(e){const t=e.input.trim()===""?{success:!0,value:{}}:await kt({text:e.input});if(t.success===!1)throw new ou({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i(Sh,"parseProviderExecutedDynamicToolCall");async function Bh({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await Sh(e);throw new au({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Vn(r.inputSchema),s=e.input.trim()===""?await xt({value:{},schema:o}):await kt({text:e.input,schema:o});if(s.success===!1)throw new ou({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Bh,"doParseToolCall");var z3=(Ar=class{constructor({stepNumber:t,model:n,functionId:r,metadata:o,experimental_context:s,content:a,finishReason:u,rawFinishReason:l,usage:c,warnings:d,request:f,response:h,providerMetadata:D}){this.stepNumber=t,this.model=n,this.functionId=r,this.metadata=o,this.experimental_context=s,this.content=a,this.finishReason=u,this.rawFinishReason=l,this.usage=c,this.warnings=d,this.request=f,this.response=h,this.providerMetadata=D}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Ar,"DefaultStepResult"),Ar);function q3(e){return({steps:t})=>t.length===e}i(q3,"stepCountIs");async function L3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(L3,"isStopConditionMet");async function U3({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Ua({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Ua({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Ua({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&n.push({role:"tool",content:o}),n}i(U3,"toResponseMessages");function Z3(...e){const t=e.filter(r=>r!=null);if(t.length===0)return;if(t.length===1)return t[0];const n=new AbortController;for(const r of t){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>{n.abort(r.reason)},{once:!0})}return n.signal}i(Z3,"mergeAbortSignals");var V3=Co({prefix:"aitxt",size:24});async function $o({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:u,timeout:l,headers:c,stopWhen:d=q3(1),experimental_output:f,output:h=f,experimental_telemetry:D,providerOptions:m,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:b,prepareStep:C=b,experimental_repairToolCall:w,experimental_download:E,experimental_context:T,experimental_include:O,_internal:{generateId:$=V3}={},experimental_onStart:I,experimental_onStepStart:re,experimental_onToolCallStart:k,experimental_onToolCallFinish:oe,onStepFinish:B,onFinish:P,...z}){const U=hh(e),R=su(d),Y=Dh(l),he=V1(l),X=he!=null?new AbortController:void 0,de=Z3(u,Y!=null?AbortSignal.timeout(Y):void 0,X?.signal),{maxRetries:fe,retry:H}=I3({maxRetries:a,abortSignal:de}),je=Ch(z),xe=Dn(c??{},`ai/${gh}`),at=y3({model:U,telemetry:D,headers:xe,settings:{...je,maxRetries:fe}}),Ae={provider:U.provider,modelId:U.modelId},j=await g3({system:r,prompt:o,messages:s});try{await I?.({model:Ae,system:r,prompt:o,messages:s,tools:t,toolChoice:n,activeTools:y,maxOutputTokens:je.maxOutputTokens,temperature:je.temperature,topP:je.topP,topK:je.topK,presencePenalty:je.presencePenalty,frequencyPenalty:je.frequencyPenalty,stopSequences:je.stopSequences,seed:je.seed,maxRetries:fe,timeout:l,headers:c,providerOptions:m,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}const te=C3(D);try{return await uu({name:"ai.generateText",attributes:Wn({telemetry:D,attributes:{...iu({operationId:"ai.generateText",telemetry:D}),...at,"ai.model.provider":U.provider,"ai.model.id":U.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:o,messages:s}),"input")}}}),tracer:te,fn:i(async Ge=>{var ve,Lr,Ur,Zr,Vr,Gr,Wr,Hr,Jr,_,L,ze,st;const xn=j.messages,Kr=[],{approvedToolApprovals:rl,deniedToolApprovals:ns}=A3({messages:xn}),ol=rl.filter(We=>!We.toolCall.providerExecuted);if(ns.length>0||ol.length>0){const We=await Oh({toolCalls:ol.map(le=>le.toolCall),tools:t,tracer:te,telemetry:D,messages:xn,abortSignal:de,experimental_context:T,stepNumber:0,model:Ae,onToolCallStart:k,onToolCallFinish:oe}),dt=[];for(const le of We){const _t=await Ua({toolCallId:le.toolCallId,input:le.input,tool:t?.[le.toolName],output:le.type==="tool-result"?le.output:le.error,errorMode:le.type==="tool-error"?"json":"none"});dt.push({type:"tool-result",toolCallId:le.toolCallId,toolName:le.toolName,output:_t})}for(const le of ns)dt.push({type:"tool-result",toolCallId:le.toolCall.toolCallId,toolName:le.toolCall.toolName,output:{type:"execution-denied",reason:le.approvalResponse.reason,...le.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:le.approvalResponse.approvalId}}}}});Kr.push({role:"tool",content:dt})}const al=[...rl,...ns].filter(We=>We.toolCall.providerExecuted);al.length>0&&Kr.push({role:"tool",content:al.map(We=>({type:"tool-approval-response",approvalId:We.approvalResponse.approvalId,approved:We.approvalResponse.approved,reason:We.approvalResponse.reason,providerExecuted:!0}))});const xD=Ch(z);let Me,Mo=[],Yr=[];const ct=[],rs=new Map;do{const We=he!=null?setTimeout(()=>X.abort(),he):void 0;try{const dt=[...xn,...Kr],le=await C?.({model:U,steps:ct,stepNumber:ct.length,messages:dt,experimental_context:T}),_t=hh((ve=le?.model)!=null?ve:U),Xr={provider:_t.provider,modelId:_t.modelId},ul=await e3({prompt:{system:(Lr=le?.system)!=null?Lr:j.system,messages:(Ur=le?.messages)!=null?Ur:dt},supportedUrls:await _t.supportedUrls,download:E});T=(Zr=le?.experimental_context)!=null?Zr:T;const ll=(Vr=le?.activeTools)!=null?Vr:y,{toolChoice:jo,tools:os}=await a3({tools:t,toolChoice:(Gr=le?.toolChoice)!=null?Gr:n,activeTools:ll}),kD=(Wr=le?.messages)!=null?Wr:dt,ID=(Hr=le?.system)!=null?Hr:j.system,cl=kh(m,le?.providerOptions);try{await re?.({stepNumber:ct.length,model:Xr,system:ID,messages:kD,tools:t,toolChoice:jo,activeTools:ll,steps:[...ct],providerOptions:cl,timeout:l,headers:c,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}Me=await H(()=>{var ue;return uu({name:"ai.generateText.doGenerate",attributes:Wn({telemetry:D,attributes:{...iu({operationId:"ai.generateText.doGenerate",telemetry:D}),...at,"ai.model.provider":_t.provider,"ai.model.id":_t.modelId,"ai.prompt.messages":{input:i(()=>w3(ul),"input")},"ai.prompt.tools":{input:i(()=>os?.map(pt=>JSON.stringify(pt)),"input")},"ai.prompt.toolChoice":{input:i(()=>jo!=null?JSON.stringify(jo):void 0,"input")},"gen_ai.system":_t.provider,"gen_ai.request.model":_t.modelId,"gen_ai.request.frequency_penalty":z.frequencyPenalty,"gen_ai.request.max_tokens":z.maxOutputTokens,"gen_ai.request.presence_penalty":z.presencePenalty,"gen_ai.request.stop_sequences":z.stopSequences,"gen_ai.request.temperature":(ue=z.temperature)!=null?ue:void 0,"gen_ai.request.top_k":z.topK,"gen_ai.request.top_p":z.topP}}),tracer:te,fn:i(async pt=>{var ss,eo,fl,ml,hl,Dl,gl,vl;const Ye=await _t.doGenerate({...xD,tools:os,toolChoice:jo,responseFormat:await h?.responseFormat,prompt:ul,providerOptions:cl,abortSignal:de,headers:xe}),kn={id:(eo=(ss=Ye.response)==null?void 0:ss.id)!=null?eo:$(),timestamp:(ml=(fl=Ye.response)==null?void 0:fl.timestamp)!=null?ml:new Date,modelId:(Dl=(hl=Ye.response)==null?void 0:hl.modelId)!=null?Dl:_t.modelId,headers:(gl=Ye.response)==null?void 0:gl.headers,body:(vl=Ye.response)==null?void 0:vl.body};return pt.setAttributes(await Wn({telemetry:D,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:i(()=>$h(Ye.content),"output")},"ai.response.reasoning":{output:i(()=>Ah(Ye.content),"output")},"ai.response.toolCalls":{output:i(()=>{const yl=Rh(Ye.content);return yl==null?void 0:JSON.stringify(yl)},"output")},"ai.response.id":kn.id,"ai.response.model":kn.modelId,"ai.response.timestamp":kn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ye.providerMetadata),"ai.usage.promptTokens":Ye.usage.inputTokens.total,"ai.usage.completionTokens":Ye.usage.outputTokens.total,"gen_ai.response.finish_reasons":[Ye.finishReason.unified],"gen_ai.response.id":kn.id,"gen_ai.response.model":kn.modelId,"gen_ai.usage.input_tokens":Ye.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ye.usage.outputTokens.total}})),{...Ye,response:kn}},"fn")})});const Qr=await Promise.all(Me.content.filter(ue=>ue.type==="tool-call").map(ue=>j3({toolCall:ue,tools:t,repairToolCall:w,system:r,messages:dt}))),as={};for(const ue of Qr){if(ue.invalid)continue;const pt=t?.[ue.toolName];pt!=null&&(pt?.onInputAvailable!=null&&await pt.onInputAvailable({input:ue.input,toolCallId:ue.toolCallId,messages:dt,abortSignal:de,experimental_context:T}),await S3({tool:pt,toolCall:ue,messages:dt,experimental_context:T})&&(as[ue.toolCallId]={type:"tool-approval-request",approvalId:$(),toolCall:ue}))}const AD=Qr.filter(ue=>ue.invalid&&ue.dynamic);Yr=[];for(const ue of AD)Yr.push({type:"tool-error",toolCallId:ue.toolCallId,toolName:ue.toolName,input:ue.input,error:vf(ue.error),dynamic:!0});Mo=Qr.filter(ue=>!ue.providerExecuted),t!=null&&Yr.push(...await Oh({toolCalls:Mo.filter(ue=>!ue.invalid&&as[ue.toolCallId]==null),tools:t,tracer:te,telemetry:D,messages:dt,abortSignal:de,experimental_context:T,stepNumber:ct.length,model:Xr,onToolCallStart:k,onToolCallFinish:oe}));for(const ue of Qr){if(!ue.providerExecuted)continue;const pt=t?.[ue.toolName];pt?.type==="provider"&&pt.supportsDeferredResults&&(Me.content.some(eo=>eo.type==="tool-result"&&eo.toolCallId===ue.toolCallId)||rs.set(ue.toolCallId,{toolName:ue.toolName}))}for(const ue of Me.content)ue.type==="tool-result"&&rs.delete(ue.toolCallId);const dl=W3({content:Me.content,toolCalls:Qr,toolOutputs:Yr,toolApprovalRequests:Object.values(as),tools:t});Kr.push(...await U3({content:dl,tools:t}));const $D=(Jr=O?.requestBody)==null||Jr?(_=Me.request)!=null?_:{}:{...Me.request,body:void 0},TD={...Me.response,messages:structuredClone(Kr),body:(L=O?.responseBody)==null||L?(ze=Me.response)==null?void 0:ze.body:void 0},SD=ct.length,pl=new z3({stepNumber:SD,model:Xr,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T,content:dl,finishReason:Me.finishReason.unified,rawFinishReason:Me.finishReason.raw,usage:F3(Me.usage),warnings:Me.warnings,providerMetadata:Me.providerMetadata,request:$D,response:TD});ph({warnings:(st=Me.warnings)!=null?st:[],provider:Xr.provider,model:Xr.modelId}),ct.push(pl),await B?.(pl)}finally{We!=null&&clearTimeout(We)}}while((Mo.length>0&&Yr.length===Mo.length||rs.size>0)&&!await L3({stopConditions:R,steps:ct}));Ge.setAttributes(await Wn({telemetry:D,attributes:{"ai.response.finishReason":Me.finishReason.unified,"ai.response.text":{output:i(()=>$h(Me.content),"output")},"ai.response.reasoning":{output:i(()=>Ah(Me.content),"output")},"ai.response.toolCalls":{output:i(()=>{const We=Rh(Me.content);return We==null?void 0:JSON.stringify(We)},"output")},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens.total,"ai.usage.completionTokens":Me.usage.outputTokens.total}}));const ye=ct[ct.length-1],sl=ct.reduce((We,dt)=>E3(We,dt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await P?.({stepNumber:ye.stepNumber,model:ye.model,functionId:ye.functionId,metadata:ye.metadata,experimental_context:ye.experimental_context,finishReason:ye.finishReason,rawFinishReason:ye.rawFinishReason,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:ct,totalUsage:sl});let il;return ye.finishReason==="stop"&&(il=await(h??Th()).parseCompleteOutput({text:ye.text},{response:ye.response,usage:ye.usage,finishReason:ye.finishReason})),new G3({steps:ct,totalUsage:sl,output:il})},"fn")})}catch(Ge){throw v3(Ge)}}i($o,"generateText");async function Oh({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d}){return(await Promise.all(e.map(async h=>$3({toolCall:h,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d})))).filter(h=>h!=null)}i(Oh,"executeTools");var G3=($r=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new T1;return this._output}},i($r,"DefaultGenerateTextResult"),$r);function Rh(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Rh,"asToolCalls");function W3({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new T3(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===a.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,error:a.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,output:a.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null)throw new qm({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(W3,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
148
+ `),{name:"GatewayAuthenticationError"})}i(_3,"wrapGatewayError");function cu({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(cu,"assembleOperationName");function b3({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,u])=>{if(a==="timeout"){const l=yh(u);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=u;return s},{}),...Object.entries((o=n?.metadata)!=null?o:{}).reduce((s,[a,u])=>(s[`ai.telemetry.metadata.${a}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[a,u])=>(u!==void 0&&(s[`ai.request.headers.${a}`]=u),s),{})}}i(b3,"getBaseTelemetryAttributes");var C3={startSpan(){return Ka},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Ka);if(typeof n=="function")return n(Ka);if(typeof r=="function")return r(Ka)}},Ka={spanContext(){return w3},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},w3={traceId:"",spanId:"",traceFlags:0};function F3({isEnabled:e=!1,tracer:t}={}){return e?t||C1.getTracer("ai"):C3}i(F3,"getTracer");async function du({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{const a=Tm.active();try{const u=await Tm.with(a,()=>r(s));return o&&s.end(),u}catch(u){try{Ah(s,u)}finally{s.end()}throw u}})}i(du,"recordSpan");function Ah(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ha.ERROR,message:t.message})):e.setStatus({code:Ha.ERROR})}i(Ah,"recordErrorOnSpan");async function Kn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(n[r]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(n[r]=s);continue}n[r]=o}return n}i(Kn,"selectTelemetryAttributes");function E3(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?t3(n.data):n.data}:n)})))}i(E3,"stringifyForTelemetry");function x3(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:$t(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(x3,"asLanguageModelUsage");function k3(e,t){var n,r,o,s,a,u,l,c,d,f;return{inputTokens:$t(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:$t((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:$t((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:$t((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:$t(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:$t((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:$t((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:$t(e.totalTokens,t.totalTokens),reasoningTokens:$t(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:$t(e.cachedInputTokens,t.cachedInputTokens)}}i(k3,"addLanguageModelUsage");function $t(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i($t,"addTokenCounts");function $h(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&u?n[r]=$h(s,o):n[r]=o}return n}i($h,"mergeObjects");function I3({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(I3,"getRetryDelayInMs");var A3=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>Th(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function Th(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Wn(a)||t===0)throw a;const u=bf(a),l=[...s,a],c=l.length;if(c>t)throw new fh({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Be.isInstance(a)&&a.isRetryable===!0&&c<=t)return await OF(I3({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),Th(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new fh({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(Th,"_retryWithExponentialBackoff");function $3({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new Ut({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:A3({maxRetries:n,abortSignal:t})}}i($3,"prepareRetries");function T3({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new k1({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new Zm({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}i(T3,"collectToolApprovals");function pu(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}i(pu,"now");async function S3({toolCall:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onPreliminaryToolResult:c,onToolCallStart:d,onToolCallFinish:f}){const{toolName:m,toolCallId:D,input:h}=e,v=t?.[m];if(v?.execute==null)return;const y={stepNumber:u,model:l,toolCall:e,messages:o,abortSignal:s,functionId:r?.functionId,metadata:r?.metadata,experimental_context:a};return du({name:"ai.toolCall",attributes:Kn({telemetry:r,attributes:{...cu({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":m,"ai.toolCall.id":D,"ai.toolCall.args":{output:i(()=>JSON.stringify(h),"output")}}}),tracer:n,fn:i(async b=>{let C;try{await d?.(y)}catch{}const w=pu();try{const T=V2({execute:v.execute.bind(v),input:h,options:{toolCallId:D,messages:o,abortSignal:s,experimental_context:a}});for await(const O of T)O.type==="preliminary"?c?.({...e,type:"tool-result",output:O.output,preliminary:!0}):C=O.output}catch(T){const O=pu()-w;try{await f?.({...y,success:!1,error:T,durationMs:O})}catch{}return Ah(b,T),{type:"tool-error",toolCallId:D,toolName:m,input:h,error:T,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const E=pu()-w;try{await f?.({...y,success:!0,output:C,durationMs:E})}catch{}try{b.setAttributes(await Kn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(C),"output")}}}))}catch{}return{type:"tool-result",toolCallId:D,toolName:m,input:h,output:C,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i(S3,"executeToolCall");function Sh(e){const t=e.filter(n=>n.type==="reasoning");return t.length===0?void 0:t.map(n=>n.text).join(`
149
+ `)}i(Sh,"extractReasoningContent");function Bh(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i(Bh,"extractTextContent");var B3=(Tr=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=Gn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=bn(this.base64Data)),this.uint8ArrayData}},i(Tr,"DefaultGeneratedFile"),Tr);async function O3({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i(O3,"isApprovalNeeded");var R3={};F1(R3,{array:i(()=>M3,"array"),choice:i(()=>j3,"choice"),json:i(()=>z3,"json"),object:i(()=>P3,"object"),text:i(()=>Oh,"text")});function N3(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(o,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(a,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i(N3,"fixJson");async function Ya(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await It({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await It({text:N3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(Ya,"parsePartialJson");var Oh=i(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),P3=i(({schema:e,name:t,description:n})=>{const r=Hn(e);return{name:"object",responseFormat:ct(r.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:o},s){const a=await It({text:o});if(!a.success)throw new rn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await kt({value:a.value,schema:r});if(!u.success)throw new rn({message:"No object generated: response did not match schema.",cause:u.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:o}){const s=await Ya(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},"object"),M3=i(({element:e,name:t,description:n})=>{const r=Hn(e);return{name:"array",responseFormat:ct(r.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:o},s){const a=await It({text:o});if(!a.success)throw new rn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=a.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new rn({message:"No object generated: response did not match schema.",cause:new Dn({value:u,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await kt({value:l,schema:r});if(!c.success)throw new rn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:o}){const s=await Ya(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const u=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of u){const d=await kt({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},"array"),j3=i(({options:e,name:t,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},o){const s=await It({text:r});if(!s.success)throw new rn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new rn({message:"No object generated: response did not match schema.",cause:new Dn({value:a,cause:"response must be an object that contains a choice value."}),text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:r}){const o=await Ya(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(u=>u.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),z3=i(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const o=await It({text:n});if(!o.success)throw new rn({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value},async parsePartialOutput({text:n}){const r=await Ya(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}},createElementStreamTransform(){}}),"json");async function L3({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Rh(e);throw new uu({toolName:e.toolName})}try{return await Nh({toolCall:e,tools:t})}catch(a){if(n==null||!(uu.isInstance(a)||iu.isInstance(a)))throw a;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await Hn(c).jsonSchema},"inputSchema"),system:r,messages:o,error:a})}catch(l){throw new N1({cause:l,originalError:a})}if(u==null)throw a;return await Nh({toolCall:u,tools:t})}}catch(a){const u=await It({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(L3,"parseToolCall");async function Rh(e){const t=e.input.trim()===""?{success:!0,value:{}}:await It({text:e.input});if(t.success===!1)throw new iu({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i(Rh,"parseProviderExecutedDynamicToolCall");async function Nh({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await Rh(e);throw new uu({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Hn(r.inputSchema),s=e.input.trim()===""?await kt({value:{},schema:o}):await It({text:e.input,schema:o});if(s.success===!1)throw new iu({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Nh,"doParseToolCall");var q3=(Sr=class{constructor({stepNumber:t,model:n,functionId:r,metadata:o,experimental_context:s,content:a,finishReason:u,rawFinishReason:l,usage:c,warnings:d,request:f,response:m,providerMetadata:D}){this.stepNumber=t,this.model=n,this.functionId=r,this.metadata=o,this.experimental_context=s,this.content=a,this.finishReason=u,this.rawFinishReason=l,this.usage=c,this.warnings=d,this.request=f,this.response=m,this.providerMetadata=D}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Sr,"DefaultStepResult"),Sr);function U3(e){return({steps:t})=>t.length===e}i(U3,"stepCountIs");async function Z3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(Z3,"isStopConditionMet");async function V3({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Ja({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Ja({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Ja({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&n.push({role:"tool",content:o}),n}i(V3,"toResponseMessages");function G3(...e){const t=e.filter(r=>r!=null);if(t.length===0)return;if(t.length===1)return t[0];const n=new AbortController;for(const r of t){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>{n.abort(r.reason)},{once:!0})}return n.signal}i(G3,"mergeAbortSignals");var W3=xo({prefix:"aitxt",size:24});async function Oo({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:u,timeout:l,headers:c,stopWhen:d=U3(1),experimental_output:f,output:m=f,experimental_telemetry:D,providerOptions:h,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:b,prepareStep:C=b,experimental_repairToolCall:w,experimental_download:E,experimental_context:T,experimental_include:O,_internal:{generateId:$=W3}={},experimental_onStart:I,experimental_onStepStart:re,experimental_onToolCallStart:k,experimental_onToolCallFinish:oe,onStepFinish:B,onFinish:P,...z}){const U=vh(e),R=lu(d),Y=yh(l),he=W1(l),X=he!=null?new AbortController:void 0,pe=G3(u,Y!=null?AbortSignal.timeout(Y):void 0,X?.signal),{maxRetries:fe,retry:H}=$3({maxRetries:a,abortSignal:pe}),je=Eh(z),xe=Cn(c??{},`ai/${_h}`),at=b3({model:U,telemetry:D,headers:xe,settings:{...je,maxRetries:fe}}),Ae={provider:U.provider,modelId:U.modelId},j=await y3({system:r,prompt:o,messages:s});try{await I?.({model:Ae,system:r,prompt:o,messages:s,tools:t,toolChoice:n,activeTools:y,maxOutputTokens:je.maxOutputTokens,temperature:je.temperature,topP:je.topP,topK:je.topK,presencePenalty:je.presencePenalty,frequencyPenalty:je.frequencyPenalty,stopSequences:je.stopSequences,seed:je.seed,maxRetries:fe,timeout:l,headers:c,providerOptions:h,stopWhen:d,output:m,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}const te=F3(D);try{return await du({name:"ai.generateText",attributes:Kn({telemetry:D,attributes:{...cu({operationId:"ai.generateText",telemetry:D}),...at,"ai.model.provider":U.provider,"ai.model.id":U.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:o,messages:s}),"input")}}}),tracer:te,fn:i(async Ge=>{var ve,Vr,Gr,Wr,Hr,Jr,Kr,Yr,Xr,_,q,ze,st;const Sn=j.messages,Qr=[],{approvedToolApprovals:sl,deniedToolApprovals:us}=T3({messages:Sn}),il=sl.filter(We=>!We.toolCall.providerExecuted);if(us.length>0||il.length>0){const We=await Ph({toolCalls:il.map(le=>le.toolCall),tools:t,tracer:te,telemetry:D,messages:Sn,abortSignal:pe,experimental_context:T,stepNumber:0,model:Ae,onToolCallStart:k,onToolCallFinish:oe}),pt=[];for(const le of We){const bt=await Ja({toolCallId:le.toolCallId,input:le.input,tool:t?.[le.toolName],output:le.type==="tool-result"?le.output:le.error,errorMode:le.type==="tool-error"?"json":"none"});pt.push({type:"tool-result",toolCallId:le.toolCallId,toolName:le.toolName,output:bt})}for(const le of us)pt.push({type:"tool-result",toolCallId:le.toolCall.toolCallId,toolName:le.toolCall.toolName,output:{type:"execution-denied",reason:le.approvalResponse.reason,...le.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:le.approvalResponse.approvalId}}}}});Qr.push({role:"tool",content:pt})}const ul=[...sl,...us].filter(We=>We.toolCall.providerExecuted);ul.length>0&&Qr.push({role:"tool",content:ul.map(We=>({type:"tool-approval-response",approvalId:We.approvalResponse.approvalId,approved:We.approvalResponse.approved,reason:We.approvalResponse.reason,providerExecuted:!0}))});const AD=Eh(z);let Me,qo=[],eo=[];const dt=[],ls=new Map;do{const We=he!=null?setTimeout(()=>X.abort(),he):void 0;try{const pt=[...Sn,...Qr],le=await C?.({model:U,steps:dt,stepNumber:dt.length,messages:pt,experimental_context:T}),bt=vh((ve=le?.model)!=null?ve:U),to={provider:bt.provider,modelId:bt.modelId},dl=await n3({prompt:{system:(Vr=le?.system)!=null?Vr:j.system,messages:(Gr=le?.messages)!=null?Gr:pt},supportedUrls:await bt.supportedUrls,download:E});T=(Wr=le?.experimental_context)!=null?Wr:T;const pl=(Hr=le?.activeTools)!=null?Hr:y,{toolChoice:Uo,tools:cs}=await i3({tools:t,toolChoice:(Jr=le?.toolChoice)!=null?Jr:n,activeTools:pl}),$D=(Kr=le?.messages)!=null?Kr:pt,TD=(Yr=le?.system)!=null?Yr:j.system,fl=$h(h,le?.providerOptions);try{await re?.({stepNumber:dt.length,model:to,system:TD,messages:$D,tools:t,toolChoice:Uo,activeTools:pl,steps:[...dt],providerOptions:fl,timeout:l,headers:c,stopWhen:d,output:m,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}Me=await H(()=>{var ue;return du({name:"ai.generateText.doGenerate",attributes:Kn({telemetry:D,attributes:{...cu({operationId:"ai.generateText.doGenerate",telemetry:D}),...at,"ai.model.provider":bt.provider,"ai.model.id":bt.modelId,"ai.prompt.messages":{input:i(()=>E3(dl),"input")},"ai.prompt.tools":{input:i(()=>cs?.map(ft=>JSON.stringify(ft)),"input")},"ai.prompt.toolChoice":{input:i(()=>Uo!=null?JSON.stringify(Uo):void 0,"input")},"gen_ai.system":bt.provider,"gen_ai.request.model":bt.modelId,"gen_ai.request.frequency_penalty":z.frequencyPenalty,"gen_ai.request.max_tokens":z.maxOutputTokens,"gen_ai.request.presence_penalty":z.presencePenalty,"gen_ai.request.stop_sequences":z.stopSequences,"gen_ai.request.temperature":(ue=z.temperature)!=null?ue:void 0,"gen_ai.request.top_k":z.topK,"gen_ai.request.top_p":z.topP}}),tracer:te,fn:i(async ft=>{var ps,ro,Dl,gl,vl,yl,_l,bl;const Ye=await bt.doGenerate({...AD,tools:cs,toolChoice:Uo,responseFormat:await m?.responseFormat,prompt:dl,providerOptions:fl,abortSignal:pe,headers:xe}),Bn={id:(ro=(ps=Ye.response)==null?void 0:ps.id)!=null?ro:$(),timestamp:(gl=(Dl=Ye.response)==null?void 0:Dl.timestamp)!=null?gl:new Date,modelId:(yl=(vl=Ye.response)==null?void 0:vl.modelId)!=null?yl:bt.modelId,headers:(_l=Ye.response)==null?void 0:_l.headers,body:(bl=Ye.response)==null?void 0:bl.body};return ft.setAttributes(await Kn({telemetry:D,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:i(()=>Bh(Ye.content),"output")},"ai.response.reasoning":{output:i(()=>Sh(Ye.content),"output")},"ai.response.toolCalls":{output:i(()=>{const Cl=Mh(Ye.content);return Cl==null?void 0:JSON.stringify(Cl)},"output")},"ai.response.id":Bn.id,"ai.response.model":Bn.modelId,"ai.response.timestamp":Bn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ye.providerMetadata),"ai.usage.promptTokens":Ye.usage.inputTokens.total,"ai.usage.completionTokens":Ye.usage.outputTokens.total,"gen_ai.response.finish_reasons":[Ye.finishReason.unified],"gen_ai.response.id":Bn.id,"gen_ai.response.model":Bn.modelId,"gen_ai.usage.input_tokens":Ye.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ye.usage.outputTokens.total}})),{...Ye,response:Bn}},"fn")})});const no=await Promise.all(Me.content.filter(ue=>ue.type==="tool-call").map(ue=>L3({toolCall:ue,tools:t,repairToolCall:w,system:r,messages:pt}))),ds={};for(const ue of no){if(ue.invalid)continue;const ft=t?.[ue.toolName];ft!=null&&(ft?.onInputAvailable!=null&&await ft.onInputAvailable({input:ue.input,toolCallId:ue.toolCallId,messages:pt,abortSignal:pe,experimental_context:T}),await O3({tool:ft,toolCall:ue,messages:pt,experimental_context:T})&&(ds[ue.toolCallId]={type:"tool-approval-request",approvalId:$(),toolCall:ue}))}const SD=no.filter(ue=>ue.invalid&&ue.dynamic);eo=[];for(const ue of SD)eo.push({type:"tool-error",toolCallId:ue.toolCallId,toolName:ue.toolName,input:ue.input,error:bf(ue.error),dynamic:!0});qo=no.filter(ue=>!ue.providerExecuted),t!=null&&eo.push(...await Ph({toolCalls:qo.filter(ue=>!ue.invalid&&ds[ue.toolCallId]==null),tools:t,tracer:te,telemetry:D,messages:pt,abortSignal:pe,experimental_context:T,stepNumber:dt.length,model:to,onToolCallStart:k,onToolCallFinish:oe}));for(const ue of no){if(!ue.providerExecuted)continue;const ft=t?.[ue.toolName];ft?.type==="provider"&&ft.supportsDeferredResults&&(Me.content.some(ro=>ro.type==="tool-result"&&ro.toolCallId===ue.toolCallId)||ls.set(ue.toolCallId,{toolName:ue.toolName}))}for(const ue of Me.content)ue.type==="tool-result"&&ls.delete(ue.toolCallId);const ml=J3({content:Me.content,toolCalls:no,toolOutputs:eo,toolApprovalRequests:Object.values(ds),tools:t});Qr.push(...await V3({content:ml,tools:t}));const BD=(Xr=O?.requestBody)==null||Xr?(_=Me.request)!=null?_:{}:{...Me.request,body:void 0},OD={...Me.response,messages:structuredClone(Qr),body:(q=O?.responseBody)==null||q?(ze=Me.response)==null?void 0:ze.body:void 0},RD=dt.length,hl=new q3({stepNumber:RD,model:to,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T,content:ml,finishReason:Me.finishReason.unified,rawFinishReason:Me.finishReason.raw,usage:x3(Me.usage),warnings:Me.warnings,providerMetadata:Me.providerMetadata,request:BD,response:OD});hh({warnings:(st=Me.warnings)!=null?st:[],provider:to.provider,model:to.modelId}),dt.push(hl),await B?.(hl)}finally{We!=null&&clearTimeout(We)}}while((qo.length>0&&eo.length===qo.length||ls.size>0)&&!await Z3({stopConditions:R,steps:dt}));Ge.setAttributes(await Kn({telemetry:D,attributes:{"ai.response.finishReason":Me.finishReason.unified,"ai.response.text":{output:i(()=>Bh(Me.content),"output")},"ai.response.reasoning":{output:i(()=>Sh(Me.content),"output")},"ai.response.toolCalls":{output:i(()=>{const We=Mh(Me.content);return We==null?void 0:JSON.stringify(We)},"output")},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens.total,"ai.usage.completionTokens":Me.usage.outputTokens.total}}));const ye=dt[dt.length-1],ll=dt.reduce((We,pt)=>k3(We,pt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await P?.({stepNumber:ye.stepNumber,model:ye.model,functionId:ye.functionId,metadata:ye.metadata,experimental_context:ye.experimental_context,finishReason:ye.finishReason,rawFinishReason:ye.rawFinishReason,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:dt,totalUsage:ll});let cl;return ye.finishReason==="stop"&&(cl=await(m??Oh()).parseCompleteOutput({text:ye.text},{response:ye.response,usage:ye.usage,finishReason:ye.finishReason})),new H3({steps:dt,totalUsage:ll,output:cl})},"fn")})}catch(Ge){throw _3(Ge)}}i(Oo,"generateText");async function Ph({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d}){return(await Promise.all(e.map(async m=>S3({toolCall:m,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d})))).filter(m=>m!=null)}i(Ph,"executeTools");var H3=(Br=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new B1;return this._output}},i(Br,"DefaultGenerateTextResult"),Br);function Mh(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Mh,"asToolCalls");function J3({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new B3(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===a.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,error:a.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,output:a.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null)throw new Zm({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(J3,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
150
150
 
151
151
  `)},flush(e){e.enqueue(`data: [DONE]
152
152
 
153
- `)}})}},Co({prefix:"aitxt",size:24}),Co({prefix:"aiobj",size:24}),Co({prefix:"aiobj",size:24});var cu=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),$t=Dt({errorSchema:cu,errorToMessage:i(e=>e.error.message,"errorToMessage")});function Nh(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}i(Nh,"getOpenAILanguageModelCapabilities");function Ph(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Ph,"convertOpenAIChatUsage");function H3({prompt:e,systemMessageMode:t="system"}){var n;const r=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:a});break}case"developer":{r.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){r.push({role:"user",content:a[0].text});break}r.push({role:"user",content:a.map((u,l)=>{var c,d,f;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${zt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:zt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:zt(u.data),format:"mp3"}};default:throw new Qe({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(f=u.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${zt(u.data)}`}}}else throw new Qe({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of a)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:o}}i(H3,"convertToOpenAIChatMessages");function du({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(du,"getResponseMetadata$1");function Mh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(Mh,"mapOpenAIFinishReason");var J3=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:F("assistant").nullish(),content:p().nullish(),tool_calls:S(g({id:p().nullish(),type:F("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:S(g({type:F("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}),index:x(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}))),K3=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),tool_calls:S(g({index:x(),id:p().nullish(),type:F("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:S(g({type:F("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:x()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}),cu]))),Y3=K(()=>J(g({logitBias:be(rF(),x()).optional(),logprobs:ee([Re(),x()]).optional(),parallelToolCalls:Re().optional(),user:p().optional(),reasoningEffort:se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:x().optional(),store:Re().optional(),metadata:be(p().max(64),p().max(512)).optional(),prediction:be(p(),et()).optional(),serviceTier:se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Re().optional(),textVerbosity:se(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:se(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));function X3({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(X3,"prepareChatTools");var Q3=(Tr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:f,toolChoice:h,providerOptions:D}){var m,v,y,b,C;const w=[],E=(m=await tt({provider:"openai",providerOptions:D,schema:Y3}))!=null?m:{},T=Nh(this.modelId),O=(v=E.forceReasoning)!=null?v:T.isReasoningModel;s!=null&&w.push({type:"unsupported",feature:"topK"});const{messages:$,warnings:I}=H3({prompt:t,systemMessageMode:(y=E.systemMessageMode)!=null?y:O?"developer":T.systemMessageMode});w.push(...I);const re=(b=E.strictJsonSchema)!=null?b:!0,k={model:this.modelId,logit_bias:E.logitBias,logprobs:E.logprobs===!0||typeof E.logprobs=="number"?!0:void 0,top_logprobs:typeof E.logprobs=="number"?E.logprobs:typeof E.logprobs=="boolean"&&E.logprobs?0:void 0,user:E.user,parallel_tool_calls:E.parallelToolCalls,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:re,name:(C=c.name)!=null?C:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:E.textVerbosity,max_completion_tokens:E.maxCompletionTokens,store:E.store,metadata:E.metadata,prediction:E.prediction,reasoning_effort:E.reasoningEffort,service_tier:E.serviceTier,prompt_cache_key:E.promptCacheKey,prompt_cache_retention:E.promptCacheRetention,safety_identifier:E.safetyIdentifier,messages:$};O?((E.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(k.temperature!=null&&(k.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,w.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,w.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,w.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,w.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),E.serviceTier==="flex"&&!T.supportsFlexProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),E.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),k.service_tier=void 0);const{tools:oe,toolChoice:B,toolWarnings:P}=X3({tools:f,toolChoice:h});return{args:{...k,tools:oe,tool_choice:B},warnings:[...w,...P]}}async doGenerate(t){var n,r,o,s,a,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:f,value:h,rawValue:D}=await Le({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:c,failedResponseHandler:$t,successfulResponseHandler:Ke(J3),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=h.choices[0],v=[],y=m.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const w of(n=m.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=w.id)!=null?r:Ve(),toolName:w.function.name,input:w.function.arguments});for(const w of(o=m.message.annotations)!=null?o:[])v.push({type:"source",sourceType:"url",id:Ve(),url:w.url_citation.url,title:w.url_citation.title});const b=(s=h.usage)==null?void 0:s.completion_tokens_details;(a=h.usage)==null||a.prompt_tokens_details;const C={openai:{}};return b?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=b?.rejected_prediction_tokens),((u=m.logprobs)==null?void 0:u.content)!=null&&(C.openai.logprobs=m.logprobs.content),{content:v,finishReason:{unified:Mh(m.finish_reason),raw:(l=m.finish_reason)!=null?l:void 0},usage:Ph(h.usage),request:{body:c},response:{...du(h),headers:f,body:D},warnings:d,providerMetadata:C}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await Le({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Gn(K3),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,f=!1;const h={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,m){var v,y,b,C,w,E,T,O,$,I,re,k,oe,B,P,z,U;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}const R=D.value;if("error"in R){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:R.error});return}if(!d){const X=du(R);Object.values(X).some(Boolean)&&(d=!0,m.enqueue({type:"response-metadata",...du(R)}))}R.usage!=null&&(c=R.usage,((v=R.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=R.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((b=R.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(C=R.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens));const Y=R.choices[0];if(Y?.finish_reason!=null&&(l={unified:Mh(Y.finish_reason),raw:Y.finish_reason}),((w=Y?.logprobs)==null?void 0:w.content)!=null&&(h.openai.logprobs=Y.logprobs.content),Y?.delta==null)return;const he=Y.delta;if(he.content!=null&&(f||(m.enqueue({type:"text-start",id:"0"}),f=!0),m.enqueue({type:"text-delta",id:"0",delta:he.content})),he.tool_calls!=null)for(const X of he.tool_calls){const de=X.index;if(u[de]==null){if(X.type!=="function")throw new io({data:X,message:"Expected 'function' type."});if(X.id==null)throw new io({data:X,message:"Expected 'id' to be a string."});if(((E=X.function)==null?void 0:E.name)==null)throw new io({data:X,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),u[de]={id:X.id,type:"function",function:{name:X.function.name,arguments:(T=X.function.arguments)!=null?T:""},hasFinished:!1};const H=u[de];((O=H.function)==null?void 0:O.name)!=null&&(($=H.function)==null?void 0:$.arguments)!=null&&(H.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),za(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(I=H.id)!=null?I:Ve(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const fe=u[de];fe.hasFinished||(((re=X.function)==null?void 0:re.arguments)!=null&&(fe.function.arguments+=(oe=(k=X.function)==null?void 0:k.arguments)!=null?oe:""),m.enqueue({type:"tool-input-delta",id:fe.id,delta:(B=X.function.arguments)!=null?B:""}),((P=fe.function)==null?void 0:P.name)!=null&&((z=fe.function)==null?void 0:z.arguments)!=null&&za(fe.function.arguments)&&(m.enqueue({type:"tool-input-end",id:fe.id}),m.enqueue({type:"tool-call",toolCallId:(U=fe.id)!=null?U:Ve(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(he.annotations!=null)for(const X of he.annotations)m.enqueue({type:"source",sourceType:"url",id:Ve(),url:X.url_citation.url,title:X.url_citation.title})},flush(D){f&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Ph(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:o},response:{headers:s}}}},i(Tr,"OpenAIChatLanguageModel"),Tr);function jh(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}i(jh,"convertOpenAICompletionUsage");function ex({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
153
+ `)}})}},xo({prefix:"aitxt",size:24}),xo({prefix:"aiobj",size:24}),xo({prefix:"aiobj",size:24});var fu=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),Tt=gt({errorSchema:fu,errorToMessage:i(e=>e.error.message,"errorToMessage")});function jh(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}i(jh,"getOpenAILanguageModelCapabilities");function zh(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(zh,"convertOpenAIChatUsage");function K3({prompt:e,systemMessageMode:t="system"}){var n;const r=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:a});break}case"developer":{r.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){r.push({role:"user",content:a[0].text});break}r.push({role:"user",content:a.map((u,l)=>{var c,d,f;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const m=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${m};base64,${Lt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Lt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Lt(u.data),format:"mp3"}};default:throw new Qe({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(f=u.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Lt(u.data)}`}}}else throw new Qe({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of a)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:o}}i(K3,"convertToOpenAIChatMessages");function mu({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(mu,"getResponseMetadata$1");function Lh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(Lh,"mapOpenAIFinishReason");var Y3=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:F("assistant").nullish(),content:p().nullish(),tool_calls:S(g({id:p().nullish(),type:F("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:S(g({type:F("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}),index:x(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}))),X3=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),tool_calls:S(g({index:x(),id:p().nullish(),type:F("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:S(g({type:F("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:x()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}),fu]))),Q3=K(()=>J(g({logitBias:Ce(aF(),x()).optional(),logprobs:ee([Re(),x()]).optional(),parallelToolCalls:Re().optional(),user:p().optional(),reasoningEffort:se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:x().optional(),store:Re().optional(),metadata:Ce(p().max(64),p().max(512)).optional(),prediction:Ce(p(),et()).optional(),serviceTier:se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Re().optional(),textVerbosity:se(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:se(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));function ex({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(ex,"prepareChatTools");var tx=(Or=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:f,toolChoice:m,providerOptions:D}){var h,v,y,b,C;const w=[],E=(h=await tt({provider:"openai",providerOptions:D,schema:Q3}))!=null?h:{},T=jh(this.modelId),O=(v=E.forceReasoning)!=null?v:T.isReasoningModel;s!=null&&w.push({type:"unsupported",feature:"topK"});const{messages:$,warnings:I}=K3({prompt:t,systemMessageMode:(y=E.systemMessageMode)!=null?y:O?"developer":T.systemMessageMode});w.push(...I);const re=(b=E.strictJsonSchema)!=null?b:!0,k={model:this.modelId,logit_bias:E.logitBias,logprobs:E.logprobs===!0||typeof E.logprobs=="number"?!0:void 0,top_logprobs:typeof E.logprobs=="number"?E.logprobs:typeof E.logprobs=="boolean"&&E.logprobs?0:void 0,user:E.user,parallel_tool_calls:E.parallelToolCalls,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:re,name:(C=c.name)!=null?C:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:E.textVerbosity,max_completion_tokens:E.maxCompletionTokens,store:E.store,metadata:E.metadata,prediction:E.prediction,reasoning_effort:E.reasoningEffort,service_tier:E.serviceTier,prompt_cache_key:E.promptCacheKey,prompt_cache_retention:E.promptCacheRetention,safety_identifier:E.safetyIdentifier,messages:$};O?((E.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(k.temperature!=null&&(k.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,w.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,w.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,w.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,w.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,w.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),E.serviceTier==="flex"&&!T.supportsFlexProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),E.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(w.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),k.service_tier=void 0);const{tools:oe,toolChoice:B,toolWarnings:P}=ex({tools:f,toolChoice:m});return{args:{...k,tools:oe,tool_choice:B},warnings:[...w,...P]}}async doGenerate(t){var n,r,o,s,a,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:f,value:m,rawValue:D}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:c,failedResponseHandler:Tt,successfulResponseHandler:Ke(Y3),abortSignal:t.abortSignal,fetch:this.config.fetch}),h=m.choices[0],v=[],y=h.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const w of(n=h.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=w.id)!=null?r:Ve(),toolName:w.function.name,input:w.function.arguments});for(const w of(o=h.message.annotations)!=null?o:[])v.push({type:"source",sourceType:"url",id:Ve(),url:w.url_citation.url,title:w.url_citation.title});const b=(s=m.usage)==null?void 0:s.completion_tokens_details;(a=m.usage)==null||a.prompt_tokens_details;const C={openai:{}};return b?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=b?.rejected_prediction_tokens),((u=h.logprobs)==null?void 0:u.content)!=null&&(C.openai.logprobs=h.logprobs.content),{content:v,finishReason:{unified:Lh(h.finish_reason),raw:(l=h.finish_reason)!=null?l:void 0},usage:zh(m.usage),request:{body:c},response:{...mu(m),headers:f,body:D},warnings:d,providerMetadata:C}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:Jn(X3),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,f=!1;const m={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,h){var v,y,b,C,w,E,T,O,$,I,re,k,oe,B,P,z,U;if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}const R=D.value;if("error"in R){l={unified:"error",raw:void 0},h.enqueue({type:"error",error:R.error});return}if(!d){const X=mu(R);Object.values(X).some(Boolean)&&(d=!0,h.enqueue({type:"response-metadata",...mu(R)}))}R.usage!=null&&(c=R.usage,((v=R.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=(y=R.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((b=R.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(C=R.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens));const Y=R.choices[0];if(Y?.finish_reason!=null&&(l={unified:Lh(Y.finish_reason),raw:Y.finish_reason}),((w=Y?.logprobs)==null?void 0:w.content)!=null&&(m.openai.logprobs=Y.logprobs.content),Y?.delta==null)return;const he=Y.delta;if(he.content!=null&&(f||(h.enqueue({type:"text-start",id:"0"}),f=!0),h.enqueue({type:"text-delta",id:"0",delta:he.content})),he.tool_calls!=null)for(const X of he.tool_calls){const pe=X.index;if(u[pe]==null){if(X.type!=="function")throw new po({data:X,message:"Expected 'function' type."});if(X.id==null)throw new po({data:X,message:"Expected 'id' to be a string."});if(((E=X.function)==null?void 0:E.name)==null)throw new po({data:X,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),u[pe]={id:X.id,type:"function",function:{name:X.function.name,arguments:(T=X.function.arguments)!=null?T:""},hasFinished:!1};const H=u[pe];((O=H.function)==null?void 0:O.name)!=null&&(($=H.function)==null?void 0:$.arguments)!=null&&(H.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),Ga(H.function.arguments)&&(h.enqueue({type:"tool-input-end",id:H.id}),h.enqueue({type:"tool-call",toolCallId:(I=H.id)!=null?I:Ve(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const fe=u[pe];fe.hasFinished||(((re=X.function)==null?void 0:re.arguments)!=null&&(fe.function.arguments+=(oe=(k=X.function)==null?void 0:k.arguments)!=null?oe:""),h.enqueue({type:"tool-input-delta",id:fe.id,delta:(B=X.function.arguments)!=null?B:""}),((P=fe.function)==null?void 0:P.name)!=null&&((z=fe.function)==null?void 0:z.arguments)!=null&&Ga(fe.function.arguments)&&(h.enqueue({type:"tool-input-end",id:fe.id}),h.enqueue({type:"tool-call",toolCallId:(U=fe.id)!=null?U:Ve(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(he.annotations!=null)for(const X of he.annotations)h.enqueue({type:"source",sourceType:"url",id:Ve(),url:X.url_citation.url,title:X.url_citation.title})},flush(D){f&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:zh(c),...m!=null?{providerMetadata:m}:{}})}})),request:{body:o},response:{headers:s}}}},i(Or,"OpenAIChatLanguageModel"),Or);function qh(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}i(qh,"convertOpenAICompletionUsage");function nx({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
154
154
 
155
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Gt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
155
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Ht({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
156
156
  ${a}
157
157
 
158
158
  `;break}case"assistant":{const a=s.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new Qe({functionality:"tool-call messages"})}}).join("");r+=`${n}:
@@ -160,9 +160,9 @@ ${a}
160
160
 
161
161
  `;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
162
162
  `,{prompt:r,stopSequences:[`
163
- ${t}:`]}}i(ex,"convertToOpenAICompletionPrompt");function zh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(zh,"getResponseMetadata2$1");function qh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(qh,"mapOpenAIFinishReason2");var tx=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(be(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}))),nx=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(be(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}),cu]))),Lh=K(()=>J(g({echo:Re().optional(),logitBias:be(p(),x()).optional(),suffix:p().optional(),user:p().optional(),logprobs:ee([Re(),x()]).optional()}))),rx=(Sr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:f,seed:h,providerOptions:D}){const m=[],v={...await tt({provider:"openai",providerOptions:D,schema:Lh}),...await tt({provider:this.providerOptionsName,providerOptions:D,schema:Lh})};s!=null&&m.push({type:"unsupported",feature:"topK"}),d?.length&&m.push({type:"unsupported",feature:"tools"}),f!=null&&m.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&m.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:b}=ex({prompt:t}),C=[...b??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:h,prompt:y,stop:C.length>0?C:void 0},warnings:m}}async doGenerate(t){var n;const{args:r,warnings:o}=await this.getArgs(t),{responseHeaders:s,value:a,rawValue:u}=await Le({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:r,failedResponseHandler:$t,successfulResponseHandler:Ke(tx),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:jh(a.usage),finishReason:{unified:qh(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...zh(a),headers:s,body:u},providerMetadata:c,warnings:o}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await Le({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Gn(nx),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:a.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:f.error});return}const D=f.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...zh(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:qh(m.finish_reason),raw:m.finish_reason}),m?.logprobs!=null&&(l.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(f){d||f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:jh(c)})}})),request:{body:o},response:{headers:s}}}},i(Sr,"OpenAICompletionLanguageModel"),Sr),ox=K(()=>J(g({dimensions:x().optional(),user:p().optional()}))),ax=K(()=>J(g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish()}))),sx=(Br=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new rp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const a=(s=await tt({provider:"openai",providerOptions:o,schema:ox}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await Le({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:$t,successfulResponseHandler:Ke(ax),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Br,"OpenAIEmbeddingModel"),Br),Uh=K(()=>J(g({created:x().nullish(),data:S(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:x().nullish(),output_tokens:x().nullish(),total_tokens:x().nullish(),input_tokens_details:g({image_tokens:x().nullish(),text_tokens:x().nullish()}).nullish()}).nullish()}))),ix={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},ux=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function lx(e){return ux.some(t=>e.startsWith(t))}i(lx,"hasDefaultResponseFormat");var cx=(Or=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=ix[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:o,size:s,aspectRatio:a,seed:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m,v,y,b,C,w,E,T;const O=[];a!=null&&O.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&O.push({type:"unsupported",feature:"seed"});const $=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date;if(n!=null){const{value:k,responseHeaders:oe}=await zi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),c),formData:pf({model:this.modelId,prompt:t,image:await Promise.all(n.map(B=>B.type==="file"?new Blob([B.data instanceof Uint8Array?new Blob([B.data],{type:B.mediaType}):new Blob([hn(B.data)],{type:B.mediaType})],{type:B.mediaType}):Si(B.url))),mask:r!=null?await dx(r):void 0,n:o,size:s,...(m=l.openai)!=null?m:{}}),failedResponseHandler:$t,successfulResponseHandler:Ke(Uh),abortSignal:d,fetch:this.config.fetch});return{images:k.data.map(B=>B.b64_json),warnings:O,usage:k.usage!=null?{inputTokens:(v=k.usage.input_tokens)!=null?v:void 0,outputTokens:(y=k.usage.output_tokens)!=null?y:void 0,totalTokens:(b=k.usage.total_tokens)!=null?b:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:oe},providerMetadata:{openai:{images:k.data.map((B,P)=>{var z,U,R,Y,he,X;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(z=k.created)!=null?z:void 0,size:(U=k.size)!=null?U:void 0,quality:(R=k.quality)!=null?R:void 0,background:(Y=k.background)!=null?Y:void 0,outputFormat:(he=k.output_format)!=null?he:void 0,...Zh((X=k.usage)==null?void 0:X.input_tokens_details,P,k.data.length)}})}}}}const{value:I,responseHeaders:re}=await Le({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:o,size:s,...(C=l.openai)!=null?C:{},...lx(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:$t,successfulResponseHandler:Ke(Uh),abortSignal:d,fetch:this.config.fetch});return{images:I.data.map(k=>k.b64_json),warnings:O,usage:I.usage!=null?{inputTokens:(w=I.usage.input_tokens)!=null?w:void 0,outputTokens:(E=I.usage.output_tokens)!=null?E:void 0,totalTokens:(T=I.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:re},providerMetadata:{openai:{images:I.data.map((k,oe)=>{var B,P,z,U,R,Y;return{...k.revised_prompt?{revisedPrompt:k.revised_prompt}:{},created:(B=I.created)!=null?B:void 0,size:(P=I.size)!=null?P:void 0,quality:(z=I.quality)!=null?z:void 0,background:(U=I.background)!=null?U:void 0,outputFormat:(R=I.output_format)!=null?R:void 0,...Zh((Y=I.usage)==null?void 0:Y.input_tokens_details,oe,I.data.length)}})}}}}},i(Or,"OpenAIImageModel"),Or);function Zh(e,t,n){if(e==null)return{};const r={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/n),s=e.image_tokens-o*(n-1);r.imageTokens=t===n-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/n),s=e.text_tokens-o*(n-1);r.textTokens=t===n-1?s:o}return r}i(Zh,"distributeTokenDetails");async function dx(e){if(!e)return;if(e.type==="url")return Si(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(dx,"fileToBlob$1");var Vh=K(()=>J(g({callId:p(),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}))),Gh=K(()=>J(g({status:se(["completed","failed"]),output:p().optional()}))),px=It({id:"openai.apply_patch",inputSchema:Vh,outputSchema:Gh}),fx=px,mx=K(()=>J(g({code:p().nullish(),containerId:p()}))),hx=K(()=>J(g({outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullish()}))),Dx=K(()=>J(g({container:ee([p(),g({fileIds:S(p()).optional()})]).optional()}))),gx=It({id:"openai.code_interpreter",inputSchema:mx,outputSchema:hx}),vx=i((e={})=>gx(e),"codeInterpreter"),Wh=g({key:p(),type:se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([p(),x(),Re(),S(p())])}),Hh=g({type:se(["and","or"]),filters:S(ee([Wh,bi(()=>Hh)]))}),yx=K(()=>J(g({vectorStoreIds:S(p()),maxNumResults:x().optional(),ranking:g({ranker:p().optional(),scoreThreshold:x().optional()}).optional(),filters:ee([Wh,Hh]).optional()}))),_x=K(()=>J(g({queries:S(p()),results:S(g({attributes:be(p(),ut()),fileId:p(),filename:p(),score:x(),text:p()})).nullable()}))),bx=It({id:"openai.file_search",inputSchema:g({}),outputSchema:_x}),Cx=K(()=>J(g({background:se(["auto","opaque","transparent"]).optional(),inputFidelity:se(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:se(["auto"]).optional(),outputCompression:x().int().min(0).max(100).optional(),outputFormat:se(["png","jpeg","webp"]).optional(),partialImages:x().int().min(0).max(3).optional(),quality:se(["auto","low","medium","high"]).optional(),size:se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),wx=K(()=>J(g({}))),Fx=K(()=>J(g({result:p()}))),Ex=It({id:"openai.image_generation",inputSchema:wx,outputSchema:Fx}),xx=i((e={})=>Ex(e),"imageGeneration"),Jh=K(()=>J(g({action:g({type:F("exec"),command:S(p()),timeoutMs:x().optional(),user:p().optional(),workingDirectory:p().optional(),env:be(p(),p()).optional()})}))),Kh=K(()=>J(g({output:p()}))),kx=It({id:"openai.local_shell",inputSchema:Jh,outputSchema:Kh}),Yh=K(()=>J(g({action:g({commands:S(p()),timeoutMs:x().optional(),maxOutputLength:x().optional()})}))),pu=K(()=>J(g({output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exitCode:x()})])}))}))),Ix=S(ge("type",[g({type:F("skillReference"),skillId:p(),version:p().optional()}),g({type:F("inline"),name:p(),description:p(),source:g({type:F("base64"),mediaType:F("application/zip"),data:p()})})])).optional(),Ax=K(()=>J(g({environment:ee([g({type:F("containerAuto"),fileIds:S(p()).optional(),memoryLimit:se(["1g","4g","16g","64g"]).optional(),networkPolicy:ge("type",[g({type:F("disabled")}),g({type:F("allowlist"),allowedDomains:S(p()),domainSecrets:S(g({domain:p(),name:p(),value:p()})).optional()})]).optional(),skills:Ix}),g({type:F("containerReference"),containerId:p()}),g({type:F("local").optional(),skills:S(g({name:p(),description:p(),path:p()})).optional()})]).optional()}))),$x=It({id:"openai.shell",inputSchema:Yh,outputSchema:pu}),Tx=K(()=>J(g({externalWebAccess:Re().optional(),filters:g({allowedDomains:S(p()).optional()}).optional(),searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Sx=K(()=>J(g({}))),Bx=K(()=>J(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).optional()}))),Ox=It({id:"openai.web_search",inputSchema:Sx,outputSchema:Bx}),Rx=i((e={})=>Ox(e),"webSearch"),Nx=K(()=>J(g({searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Px=K(()=>J(g({}))),Mx=K(()=>J(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),jx=It({id:"openai.web_search_preview",inputSchema:Px,outputSchema:Mx}),fu=bi(()=>ee([p(),x(),Re(),Jp(),S(fu),be(p(),fu)])),zx=K(()=>J(g({serverLabel:p(),allowedTools:ee([S(p()),g({readOnly:Re().optional(),toolNames:S(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:be(p(),p()).optional(),requireApproval:ee([se(["always","never"]),g({never:g({toolNames:S(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),qx=K(()=>J(g({}))),Lx=K(()=>J(g({type:F("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:ee([p(),fu]).optional()}))),Ux=It({id:"openai.mcp",inputSchema:qx,outputSchema:Lx}),Zx=i(e=>Ux(e),"mcp"),Vx={applyPatch:fx,codeInterpreter:vx,fileSearch:bx,imageGeneration:xx,localShell:kx,shell:$x,webSearchPreview:jx,webSearch:Rx,mcp:Zx};function Xh(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(o=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}i(Xh,"convertOpenAIResponsesUsage");function Qh(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(Qh,"isFileId");async function Gx({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:u=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var d,f,h,D,m,v,y,b,C,w,E,T,O;const $=[],I=[],re=new Set;for(const{role:k,content:oe}of e)switch(k){case"system":{switch(n){case"system":{$.push({role:"system",content:oe});break}case"developer":{$.push({role:"developer",content:oe});break}case"remove":{I.push({type:"other",message:"system messages are removed for this model"});break}default:{const B=n;throw new Error(`Unsupported system message mode: ${B}`)}}break}case"user":{$.push({role:"user",content:oe.map((B,P)=>{var z,U,R;switch(B.type){case"text":return{type:"input_text",text:B.text};case"file":if(B.mediaType.startsWith("image/")){const Y=B.mediaType==="image/*"?"image/jpeg":B.mediaType;return{type:"input_image",...B.data instanceof URL?{image_url:B.data.toString()}:typeof B.data=="string"&&Qh(B.data,o)?{file_id:B.data}:{image_url:`data:${Y};base64,${zt(B.data)}`},detail:(U=(z=B.providerOptions)==null?void 0:z[r])==null?void 0:U.imageDetail}}else{if(B.mediaType==="application/pdf")return B.data instanceof URL?{type:"input_file",file_url:B.data.toString()}:{type:"input_file",...typeof B.data=="string"&&Qh(B.data,o)?{file_id:B.data}:{filename:(R=B.filename)!=null?R:`part-${P}.pdf`,file_data:`data:application/pdf;base64,${zt(B.data)}`}};throw new Qe({functionality:`file part media type ${B.mediaType}`})}}})});break}case"assistant":{const B={};for(const P of oe)switch(P.type){case"text":{const z=(f=(d=P.providerOptions)==null?void 0:d[r])==null?void 0:f.itemId;if(a&&z!=null)break;if(s&&z!=null){$.push({type:"item_reference",id:z});break}$.push({role:"assistant",content:[{type:"output_text",text:P.text}],id:z});break}case"tool-call":{const z=(y=(D=(h=P.providerOptions)==null?void 0:h[r])==null?void 0:D.itemId)!=null?y:(v=(m=P.providerMetadata)==null?void 0:m[r])==null?void 0:v.itemId;if(a&&z!=null)break;if(P.providerExecuted){s&&z!=null&&$.push({type:"item_reference",id:z});break}if(s&&z!=null){$.push({type:"item_reference",id:z});break}const U=t.toProviderToolName(P.toolName);if(u&&U==="local_shell"){const R=await rt({value:P.input,schema:Jh});$.push({type:"local_shell_call",call_id:P.toolCallId,id:z,action:{type:"exec",command:R.action.command,timeout_ms:R.action.timeoutMs,user:R.action.user,working_directory:R.action.workingDirectory,env:R.action.env}});break}if(l&&U==="shell"){const R=await rt({value:P.input,schema:Yh});$.push({type:"shell_call",call_id:P.toolCallId,id:z,status:"completed",action:{commands:R.action.commands,timeout_ms:R.action.timeoutMs,max_output_length:R.action.maxOutputLength}});break}if(c&&U==="apply_patch"){const R=await rt({value:P.input,schema:Vh});$.push({type:"apply_patch_call",call_id:R.callId,id:z,status:"completed",operation:R.operation});break}$.push({type:"function_call",call_id:P.toolCallId,name:U,arguments:JSON.stringify(P.input),id:z});break}case"tool-result":{if(P.output.type==="execution-denied"||P.output.type==="json"&&typeof P.output.value=="object"&&P.output.value!=null&&"type"in P.output.value&&P.output.value.type==="execution-denied"||a)break;const z=t.toProviderToolName(P.toolName);if(l&&z==="shell"){if(P.output.type==="json"){const U=await rt({value:P.output.value,schema:pu});$.push({type:"shell_call_output",call_id:P.toolCallId,output:U.output.map(R=>({stdout:R.stdout,stderr:R.stderr,outcome:R.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:R.outcome.exitCode}}))})}break}if(s){const U=(w=(C=(b=P.providerOptions)==null?void 0:b[r])==null?void 0:C.itemId)!=null?w:P.toolCallId;$.push({type:"item_reference",id:U})}else I.push({type:"other",message:`Results for OpenAI tool ${P.toolName} are not sent to the API when store is false`});break}case"reasoning":{const z=await tt({provider:r,providerOptions:P.providerOptions,schema:Wx}),U=z?.itemId;if(a&&U!=null)break;if(U!=null){const R=B[U];if(s)R===void 0&&($.push({type:"item_reference",id:U}),B[U]={type:"reasoning",id:U,summary:[]});else{const Y=[];P.text.length>0?Y.push({type:"summary_text",text:P.text}):R!==void 0&&I.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(P)}.`}),R===void 0?(B[U]={type:"reasoning",id:U,encrypted_content:z?.reasoningEncryptedContent,summary:Y},$.push(B[U])):(R.summary.push(...Y),z?.reasoningEncryptedContent!=null&&(R.encrypted_content=z.reasoningEncryptedContent))}}else I.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(P)}.`});break}}break}case"tool":{for(const B of oe){if(B.type==="tool-approval-response"){const R=B;if(re.has(R.approvalId))continue;re.add(R.approvalId),s&&$.push({type:"item_reference",id:R.approvalId}),$.push({type:"mcp_approval_response",approval_request_id:R.approvalId,approve:R.approved});continue}const P=B.output;if(P.type==="execution-denied"&&((T=(E=P.providerOptions)==null?void 0:E.openai)==null?void 0:T.approvalId))continue;const z=t.toProviderToolName(B.toolName);if(u&&z==="local_shell"&&P.type==="json"){const R=await rt({value:P.value,schema:Kh});$.push({type:"local_shell_call_output",call_id:B.toolCallId,output:R.output});continue}if(l&&z==="shell"&&P.type==="json"){const R=await rt({value:P.value,schema:pu});$.push({type:"shell_call_output",call_id:B.toolCallId,output:R.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))});continue}if(c&&B.toolName==="apply_patch"&&P.type==="json"){const R=await rt({value:P.value,schema:Gh});$.push({type:"apply_patch_call_output",call_id:B.toolCallId,status:R.status,output:R.output});continue}let U;switch(P.type){case"text":case"error-text":U=P.value;break;case"execution-denied":U=(O=P.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(P.value);break;case"content":U=P.value.map(R=>{var Y;switch(R.type){case"text":return{type:"input_text",text:R.text};case"image-data":return{type:"input_image",image_url:`data:${R.mediaType};base64,${R.data}`};case"image-url":return{type:"input_image",image_url:R.url};case"file-data":return{type:"input_file",filename:(Y=R.filename)!=null?Y:"data",file_data:`data:${R.mediaType};base64,${R.data}`};default:{I.push({type:"other",message:`unsupported tool content part type: ${R.type}`});return}}}).filter(qF);break}$.push({type:"function_call_output",call_id:B.toolCallId,output:U})}break}default:{const B=k;throw new Error(`Unsupported role: ${B}`)}}return{input:$,warnings:I}}i(Gx,"convertToOpenAIResponsesInput");var Wx=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function eD({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}i(eD,"mapOpenAIResponseFinishReason");var Hx=K(()=>J(ee([g({type:F("response.output_text.delta"),item_id:p(),delta:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}),g({type:se(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:F("response.created"),response:g({id:p(),created_at:x(),model:p(),service_tier:p().nullish()})}),g({type:F("response.output_item.added"),output_index:x(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:F("web_search_call"),id:p(),status:p()}),g({type:F("computer_call"),id:p(),status:p()}),g({type:F("file_search_call"),id:p()}),g({type:F("image_generation_call"),id:p()}),g({type:F("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable(),status:p()}),g({type:F("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p()}),g({type:F("mcp_approval_request"),id:p()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])}),g({type:F("response.output_item.done"),output_index:x(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:F("completed")}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:be(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:F("computer_call"),id:p(),status:F("completed")}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])}),g({type:F("response.function_call_arguments.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:F("response.image_generation_call.partial_image"),item_id:p(),output_index:x(),partial_image_b64:p()}),g({type:F("response.code_interpreter_call_code.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:F("response.code_interpreter_call_code.done"),item_id:p(),output_index:x(),code:p()}),g({type:F("response.output_text.annotation.added"),annotation:ge("type",[g({type:F("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:F("file_path"),file_id:p(),index:x()})])}),g({type:F("response.reasoning_summary_part.added"),item_id:p(),summary_index:x()}),g({type:F("response.reasoning_summary_text.delta"),item_id:p(),summary_index:x(),delta:p()}),g({type:F("response.reasoning_summary_part.done"),item_id:p(),summary_index:x()}),g({type:F("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:x(),delta:p(),obfuscation:p().nullish()}),g({type:F("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:x(),diff:p()}),g({type:F("error"),sequence_number:x(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Jx=K(()=>J(g({id:p().optional(),created_at:x().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:S(ge("type",[g({type:F("message"),role:F("assistant"),id:p(),content:S(g({type:F("output_text"),text:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish(),annotations:S(ge("type",[g({type:F("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:F("file_path"),file_id:p(),index:x()})]))}))}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:be(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:F("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:F("computer_call"),id:p(),status:p().optional()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish(),summary:S(g({type:F("summary_text"),text:p()}))}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}).optional()}))),tD=20,nD=K(()=>J(g({conversation:p().nullish(),include:S(se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:ee([Re(),x().min(1).max(tD)]).optional(),maxToolCalls:x().nullish(),metadata:et().nullish(),parallelToolCalls:Re().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:se(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:se(["auto","flex","priority","default"]).nullish(),store:Re().nullish(),strictJsonSchema:Re().nullish(),textVerbosity:se(["low","medium","high"]).nullish(),truncation:se(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));async function Kx({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await rt({value:s.args,schema:yx});r.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{const a=await rt({value:s.args,schema:Ax});r.push({type:"shell",...a.environment&&{environment:Yx(a.environment)}});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await rt({value:s.args,schema:Nx});r.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await rt({value:s.args,schema:Tx});r.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await rt({value:s.args,schema:Dx});r.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await rt({value:s.args,schema:Cx});r.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await rt({value:s.args,schema:zx}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(Kx,"prepareResponsesTools");function Yx(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const n=e;return{type:"container_auto",file_ids:n.fileIds,memory_limit:n.memoryLimit,network_policy:n.networkPolicy==null?void 0:n.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:n.networkPolicy.allowedDomains,domain_secrets:n.networkPolicy.domainSecrets},skills:Xx(n.skills)}}return{type:"local",skills:e.skills}}i(Yx,"mapShellEnvironment");function Xx(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}i(Xx,"mapShellSkills");function rD(e){var t,n;const r={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;a!=null&&(r[a]=s.toolCallId)}return r}i(rD,"extractApprovalRequestIdToToolCallIdMapping");var Qx=(Rr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:o,topK:s,presencePenalty:a,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:f,toolChoice:h,responseFormat:D}){var m,v,y,b,C,w,E,T,O;const $=[],I=Nh(this.modelId);s!=null&&$.push({type:"unsupported",feature:"topK"}),l!=null&&$.push({type:"unsupported",feature:"seed"}),a!=null&&$.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&$.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&$.push({type:"unsupported",feature:"stopSequences"});const re=this.config.provider.includes("azure")?"azure":"openai";let k=await tt({provider:re,providerOptions:d,schema:nD});k==null&&re!=="openai"&&(k=await tt({provider:"openai",providerOptions:d,schema:nD}));const oe=(m=k?.forceReasoning)!=null?m:I.isReasoningModel;k?.conversation&&k?.previousResponseId&&$.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const B=TF({tools:f,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:P,warnings:z}=await Gx({prompt:c,toolNameMapping:B,systemMessageMode:(v=k?.systemMessageMode)!=null?v:oe?"developer":I.systemMessageMode,providerOptionsName:re,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=k?.store)!=null?y:!0,hasConversation:k?.conversation!=null,hasLocalShellTool:he("openai.local_shell"),hasShellTool:he("openai.shell"),hasApplyPatchTool:he("openai.apply_patch")});$.push(...z);const U=(b=k?.strictJsonSchema)!=null?b:!0;let R=k?.include;function Y(te){R==null?R=[te]:R.includes(te)||(R=[...R,te])}i(Y,"addInclude");function he(te){return f?.find(Ge=>Ge.type==="provider"&&Ge.id===te)!=null}i(he,"hasOpenAITool");const X=typeof k?.logprobs=="number"?k?.logprobs:k?.logprobs===!0?tD:void 0;X&&Y("message.output_text.logprobs");const de=(C=f?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:C.name;de&&Y("web_search_call.action.sources"),he("openai.code_interpreter")&&Y("code_interpreter_call.outputs");const fe=k?.store;fe===!1&&oe&&Y("reasoning.encrypted_content");const H={model:this.modelId,input:P,temperature:n,top_p:o,max_output_tokens:t,...(D?.type==="json"||k?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:U,name:(w=D.name)!=null?w:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...k?.textVerbosity&&{verbosity:k.textVerbosity}}},conversation:k?.conversation,max_tool_calls:k?.maxToolCalls,metadata:k?.metadata,parallel_tool_calls:k?.parallelToolCalls,previous_response_id:k?.previousResponseId,store:fe,user:k?.user,instructions:k?.instructions,service_tier:k?.serviceTier,include:R,prompt_cache_key:k?.promptCacheKey,prompt_cache_retention:k?.promptCacheRetention,safety_identifier:k?.safetyIdentifier,top_logprobs:X,truncation:k?.truncation,...oe&&(k?.reasoningEffort!=null||k?.reasoningSummary!=null)&&{reasoning:{...k?.reasoningEffort!=null&&{effort:k.reasoningEffort},...k?.reasoningSummary!=null&&{summary:k.reasoningSummary}}}};oe?k?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(H.temperature!=null&&(H.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),H.top_p!=null&&(H.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(k?.reasoningEffort!=null&&$.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),k?.reasoningSummary!=null&&$.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),k?.serviceTier==="flex"&&!I.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete H.service_tier),k?.serviceTier==="priority"&&!I.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete H.service_tier);const{tools:je,toolChoice:xe,toolWarnings:at}=await Kx({tools:f,toolChoice:h}),Ae=(O=(T=(E=f?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:E.args)==null?void 0:T.environment)==null?void 0:O.type,j=Ae==="containerAuto"||Ae==="containerReference";return{webSearchToolName:de,args:{...H,tools:je,tool_choice:xe},warnings:[...$,...at],store:fe,toolNameMapping:B,providerOptionsName:re,isShellProviderExecuted:j}}async doGenerate(t){var n,r,o,s,a,u,l,c,d,f,h,D,m,v,y,b,C,w,E,T,O,$,I,re,k;const{args:oe,warnings:B,webSearchToolName:P,toolNameMapping:z,providerOptionsName:U,isShellProviderExecuted:R}=await this.getArgs(t),Y=this.config.url({path:"/responses",modelId:this.modelId}),he=rD(t.prompt),{responseHeaders:X,value:de,rawValue:fe}=await Le({url:Y,headers:Ne(this.config.headers(),t.headers),body:oe,failedResponseHandler:$t,successfulResponseHandler:Ke(Jx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(de.error)throw new Be({message:de.error.message,url:Y,requestBodyValues:oe,statusCode:400,responseHeaders:X,responseBody:fe,isRetryable:!1});const H=[],je=[];let xe=!1;for(const j of de.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const te of j.summary)H.push({type:"reasoning",text:te.text,providerMetadata:{[U]:{itemId:j.id,reasoningEncryptedContent:(n=j.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),result:{result:j.result}});break}case"local_shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("local_shell"),input:JSON.stringify({action:j.action}),providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),input:JSON.stringify({action:{commands:j.action.commands}}),...R&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call_output":{H.push({type:"tool-result",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),result:{output:j.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const te of j.content){(o=(r=t.providerOptions)==null?void 0:r[U])!=null&&o.logprobs&&te.logprobs&&je.push(te.logprobs);const Ge={itemId:j.id,...te.annotations.length>0&&{annotations:te.annotations}};H.push({type:"text",text:te.text,providerMetadata:{[U]:Ge}});for(const ve of te.annotations)ve.type==="url_citation"?H.push({type:"source",sourceType:"url",id:(u=(a=(s=this.config).generateId)==null?void 0:a.call(s))!=null?u:Ve(),url:ve.url,title:ve.title}):ve.type==="file_citation"?H.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}}):ve.type==="container_file_citation"?H.push({type:"source",sourceType:"document",id:(D=(h=(f=this.config).generateId)==null?void 0:h.call(f))!=null?D:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,containerId:ve.container_id}}}):ve.type==="file_path"&&H.push({type:"source",sourceType:"document",id:(y=(v=(m=this.config).generateId)==null?void 0:v.call(m))!=null?y:Ve(),mediaType:"application/octet-stream",title:ve.file_id,filename:ve.file_id,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}})}break}case"function_call":{xe=!0,H.push({type:"tool-call",toolCallId:j.call_id,toolName:j.name,input:j.arguments,providerMetadata:{[U]:{itemId:j.id}}});break}case"web_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),result:aD(j.action)});break}case"mcp_call":{const te=j.approval_request_id!=null&&(b=he[j.approval_request_id])!=null?b:j.id,Ge=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:te,toolName:Ge,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-result",toolCallId:te,toolName:Ge,result:{type:"call",serverLabel:j.server_label,name:j.name,arguments:j.arguments,...j.output!=null?{output:j.output}:{},...j.error!=null?{error:j.error}:{}},providerMetadata:{[U]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const te=(C=j.approval_request_id)!=null?C:j.id,Ge=(T=(E=(w=this.config).generateId)==null?void 0:E.call(w))!=null?T:Ve(),ve=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:Ge,toolName:ve,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-approval-request",approvalId:te,toolCallId:Ge});break}case"computer_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:j.status||"completed"}});break}case"file_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),result:{queries:j.queries,results:($=(O=j.results)==null?void 0:O.map(te=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?$:null}});break}case"code_interpreter_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),input:JSON.stringify({code:j.code,containerId:j.container_id}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),result:{outputs:j.outputs}});break}case"apply_patch_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("apply_patch"),input:JSON.stringify({callId:j.call_id,operation:j.operation}),providerMetadata:{[U]:{itemId:j.id}}});break}}const at={[U]:{responseId:de.id,...je.length>0?{logprobs:je}:{},...typeof de.service_tier=="string"?{serviceTier:de.service_tier}:{}}},Ae=de.usage;return{content:H,finishReason:{unified:eD({finishReason:(I=de.incomplete_details)==null?void 0:I.reason,hasFunctionCall:xe}),raw:(k=(re=de.incomplete_details)==null?void 0:re.reason)!=null?k:void 0},usage:Xh(Ae),request:{body:oe},response:{id:de.id,timestamp:new Date(de.created_at*1e3),modelId:de.model,headers:X,body:fe},providerMetadata:at,warnings:B}}async doStream(t){const{args:n,warnings:r,webSearchToolName:o,toolNameMapping:s,store:a,providerOptionsName:u,isShellProviderExecuted:l}=await this.getArgs(t),{responseHeaders:c,value:d}=await Le({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:$t,successfulResponseHandler:Gn(Hx),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=this,h=rD(t.prompt),D=new Map;let m={unified:"other",raw:void 0},v;const y=[];let b=null;const C={},w=[];let E=!1;const T={};let O;return{stream:d.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:r})},transform($,I){var re,k,oe,B,P,z,U,R,Y,he,X,de,fe,H,je,xe,at,Ae,j,te,Ge,ve,Lr,Ur,Zr,Vr,Gr,Wr,Hr,Jr;if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){m={unified:"error",raw:void 0},I.enqueue({type:"error",error:$.error});return}const _=$.value;if(oD(_)){if(_.item.type==="function_call")C[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},I.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")C[_.output_index]={toolName:s.toCustomToolName(o??"web_search"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(o??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")C[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")C[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:L,operation:ze}=_.item;if(C[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:L,applyPatch:{hasDiff:ze.type==="delete_file",endEmitted:ze.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:L,toolName:s.toCustomToolName("apply_patch")}),ze.type==="delete_file"){const st=JSON.stringify({callId:L,operation:ze});I.enqueue({type:"tool-input-delta",id:L,delta:st}),I.enqueue({type:"tool-input-end",id:L})}else I.enqueue({type:"tool-input-delta",id:L,delta:`{"callId":"${_n(L)}","operation":{"type":"${_n(ze.type)}","path":"${_n(ze.path)}","diff":"`})}else _.item.type==="shell_call"?C[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="shell_call_output"||(_.item.type==="message"?(w.splice(0,w.length),I.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):oD(_)&&_.item.type==="reasoning"&&(T[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(re=_.item.encrypted_content)!=null?re:null}}})))}else if(tk(_)){if(_.item.type==="message")I.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...w.length>0&&{annotations:w}}}});else if(_.item.type==="function_call")C[_.output_index]=void 0,E=!0,I.enqueue({type:"tool-input-end",id:_.item.call_id}),I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),result:aD(_.item.action)});else if(_.item.type==="computer_call")C[_.output_index]=void 0,I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(oe=(k=_.item.results)==null?void 0:k.map(L=>({attributes:L.attributes,fileId:L.file_id,filename:L.filename,score:L.score,text:L.text})))!=null?oe:null}});else if(_.item.type==="code_interpreter_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){C[_.output_index]=void 0;const L=(B=_.item.approval_request_id)!=null?B:void 0,ze=L!=null&&(z=(P=D.get(L))!=null?P:h[L])!=null?z:_.item.id,st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:ze,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:ze,toolName:st,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")C[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const L=C[_.output_index];L?.applyPatch&&!L.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(L.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:_n(_.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:L.toolCallId}),L.applyPatch.endEmitted=!0),L&&_.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:L.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),C[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){C[_.output_index]=void 0;const L=(Y=(R=(U=f.config).generateId)==null?void 0:R.call(U))!=null?Y:Ve(),ze=(he=_.item.approval_request_id)!=null?he:_.item.id;D.set(ze,L);const st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:L,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:ze,toolCallId:L})}else if(_.item.type==="local_shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),result:{output:_.item.output.map(L=>({stdout:L.stdout,stderr:L.stderr,outcome:L.outcome.type==="exit"?{type:"exit",exitCode:L.outcome.exit_code}:{type:"timeout"}}))}});else if(_.item.type==="reasoning"){const L=T[_.item.id],ze=Object.entries(L.summaryParts).filter(([st,xn])=>xn==="active"||xn==="can-conclude").map(([st])=>st);for(const st of ze)I.enqueue({type:"reasoning-end",id:`${_.item.id}:${st}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(X=_.item.encrypted_content)!=null?X:null}}});delete T[_.item.id]}}else if(ok(_)){const L=C[_.output_index];L!=null&&I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:_.delta})}else if(uk(_)){const L=C[_.output_index];L?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:_n(_.delta)}),L.applyPatch.hasDiff=!0)}else if(lk(_)){const L=C[_.output_index];L?.applyPatch&&!L.applyPatch.endEmitted&&(L.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:_n(_.diff)}),L.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:L.toolCallId}),L.applyPatch.endEmitted=!0)}else if(ak(_))I.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(sk(_)){const L=C[_.output_index];L!=null&&I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:_n(_.delta)})}else if(ik(_)){const L=C[_.output_index];L!=null&&(I.enqueue({type:"tool-input-delta",id:L.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:L.toolCallId}),I.enqueue({type:"tool-call",toolCallId:L.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:L.codeInterpreter.containerId}),providerExecuted:!0}))}else if(rk(_))b=_.response.id,I.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(ek(_))I.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(fe=(de=t.providerOptions)==null?void 0:de[u])!=null&&fe.logprobs&&_.logprobs&&y.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const L=T[_.item_id];L.summaryParts[_.summary_index]="active";for(const ze of Object.keys(L.summaryParts))L.summaryParts[ze]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${ze}`,providerMetadata:{[u]:{itemId:_.item_id}}}),L.summaryParts[ze]="concluded");I.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(je=(H=T[_.item_id])==null?void 0:H.encryptedContent)!=null?je:null}}})}}else _.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?a?(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),T[_.item_id].summaryParts[_.summary_index]="concluded"):T[_.item_id].summaryParts[_.summary_index]="can-conclude":nk(_)?(m={unified:eD({finishReason:(xe=_.response.incomplete_details)==null?void 0:xe.reason,hasFunctionCall:E}),raw:(Ae=(at=_.response.incomplete_details)==null?void 0:at.reason)!=null?Ae:void 0},v=_.response.usage,typeof _.response.service_tier=="string"&&(O=_.response.service_tier)):ck(_)?(w.push(_.annotation),_.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(Ge=(te=(j=f.config).generateId)==null?void 0:te.call(j))!=null?Ge:Ve(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Ur=(Lr=(ve=f.config).generateId)==null?void 0:Lr.call(ve))!=null?Ur:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}}):_.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Gr=(Vr=(Zr=f.config).generateId)==null?void 0:Vr.call(Zr))!=null?Gr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,containerId:_.annotation.container_id}}}):_.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Jr=(Hr=(Wr=f.config).generateId)==null?void 0:Hr.call(Wr))!=null?Jr:Ve(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}})):dk(_)&&I.enqueue({type:"error",error:_})},flush($){const I={[u]:{responseId:b,...y.length>0?{logprobs:y}:{},...O!==void 0?{serviceTier:O}:{}}};$.enqueue({type:"finish",finishReason:m,usage:Xh(v),providerMetadata:I})}})),request:{body:n},response:{headers:c}}}},i(Rr,"OpenAIResponsesLanguageModel"),Rr);function ek(e){return e.type==="response.output_text.delta"}i(ek,"isTextDeltaChunk");function tk(e){return e.type==="response.output_item.done"}i(tk,"isResponseOutputItemDoneChunk");function nk(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(nk,"isResponseFinishedChunk");function rk(e){return e.type==="response.created"}i(rk,"isResponseCreatedChunk");function ok(e){return e.type==="response.function_call_arguments.delta"}i(ok,"isResponseFunctionCallArgumentsDeltaChunk");function ak(e){return e.type==="response.image_generation_call.partial_image"}i(ak,"isResponseImageGenerationCallPartialImageChunk");function sk(e){return e.type==="response.code_interpreter_call_code.delta"}i(sk,"isResponseCodeInterpreterCallCodeDeltaChunk");function ik(e){return e.type==="response.code_interpreter_call_code.done"}i(ik,"isResponseCodeInterpreterCallCodeDoneChunk");function uk(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(uk,"isResponseApplyPatchCallOperationDiffDeltaChunk");function lk(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(lk,"isResponseApplyPatchCallOperationDiffDoneChunk");function oD(e){return e.type==="response.output_item.added"}i(oD,"isResponseOutputItemAddedChunk");function ck(e){return e.type==="response.output_text.annotation.added"}i(ck,"isResponseAnnotationAddedChunk");function dk(e){return e.type==="error"}i(dk,"isErrorChunk");function aD(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(aD,"mapWebSearchOutput");function _n(e){return JSON.stringify(e).slice(1,-1)}i(_n,"escapeJSONDelta");var pk=K(()=>J(g({instructions:p().nullish(),speed:x().min(.25).max(4).default(1).nullish()}))),fk=(Nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:o,instructions:s,language:a,providerOptions:u}){const l=[],c=await tt({provider:"openai",providerOptions:u,schema:pk}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:o,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const f={};for(const h in f){const D=f[h];D!==void 0&&(d[h]=D)}}return a&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,o;const s=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{requestBody:a,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await Le({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:a,failedResponseHandler:$t,successfulResponseHandler:q2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(a)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(Nr,"OpenAISpeechModel"),Nr),mk=K(()=>J(g({text:p(),language:p().nullish(),duration:x().nullish(),words:S(g({word:p(),start:x(),end:x()})).nullish(),segments:S(g({id:x(),seek:x(),start:x(),end:x(),text:p(),tokens:S(x()),temperature:x(),avg_logprob:x(),compression_ratio:x(),no_speech_prob:x()})).nullish()}))),hk=K(()=>J(g({include:S(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:x().min(0).max(1).default(0).optional(),timestampGranularities:S(se(["word","segment"])).default(["segment"]).optional()}))),sD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Dk=(Pr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const o=[],s=await tt({provider:"openai",providerOptions:r,schema:hk}),a=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([hn(t)]);a.append("model",this.modelId);const l=ZF(n);if(a.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,f]of Object.entries(c))if(f!=null)if(Array.isArray(f))for(const h of f)a.append(`${d}[]`,String(h));else a.append(d,String(f))}return{formData:a,warnings:o}}async doGenerate(t){var n,r,o,s,a,u,l,c;const d=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{formData:f,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:m,rawValue:v}=await zi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),formData:f,failedResponseHandler:$t,successfulResponseHandler:Ke(mk),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in sD?sD[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(b=>({text:b.text,startSecond:b.start,endSecond:b.end})))!=null?u:(a=D.words)==null?void 0:a.map(b=>({text:b.word,startSecond:b.start,endSecond:b.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:m,body:v}}}},i(Pr,"OpenAITranscriptionModel"),Pr),gk="3.0.30";function Ga(e={}){var t,n;const r=(t=qi(wo({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=i(()=>Dn({Authorization:`Bearer ${UF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${gk}`),"getHeaders"),a=i(v=>new Q3(v,{provider:`${o}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new rx(v,{provider:`${o}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new sx(v,{provider:`${o}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new cx(v,{provider:`${o}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new Dk(v,{provider:`${o}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),f=i(v=>new fk(v,{provider:`${o}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),h=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new Qx(v,{provider:`${o}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),m=i(function(v){return h(v)},"provider");return m.specificationVersion="v3",m.languageModel=h,m.chat=a,m.completion=u,m.responses=D,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=d,m.transcriptionModel=d,m.speech=f,m.speechModel=f,m.tools=Vx,m}i(Ga,"createOpenAI"),Ga();var vk=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),To={errorSchema:vk,errorToMessage:i(e=>e.error.message,"errorToMessage")};function iD(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(iD,"convertOpenAICompatibleChatUsage");function So(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(So,"getOpenAIMetadata");function yk(e){switch(e){case"audio/wav":return"wav";case"audio/mp3":case"audio/mpeg":return"mp3";default:return null}}i(yk,"getAudioFormat");function _k(e){var t,n,r;const o=[];for(const{role:s,content:a,...u}of e){const l=So({...u});switch(s){case"system":{o.push({role:"system",content:a,...l});break}case"user":{if(a.length===1&&a[0].type==="text"){o.push({role:"user",content:a[0].text,...So(a[0])});break}o.push({role:"user",content:a.map(c=>{var d;const f=So(c);switch(c.type){case"text":return{type:"text",text:c.text,...f};case"file":{if(c.mediaType.startsWith("image/")){const h=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"image_url",image_url:{url:c.data instanceof URL?c.data.toString():`data:${h};base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("audio/")){if(c.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});const h=yk(c.mediaType);if(h===null)throw new Qe({functionality:`audio media type ${c.mediaType}`});return{type:"input_audio",input_audio:{data:zt(c.data),format:h},...f}}if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:{filename:(d=c.filename)!=null?d:"document.pdf",file_data:`data:application/pdf;base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("text/"))return{type:"text",text:c.data instanceof URL?c.data.toString():typeof c.data=="string"?c.data:new TextDecoder().decode(c.data),...f};throw new Qe({functionality:`file part media type ${c.mediaType}`})}}}),...l});break}case"assistant":{let c="",d="";const f=[];for(const h of a){const D=So(h);switch(h.type){case"text":{c+=h.text;break}case"reasoning":{d+=h.text;break}case"tool-call":{const m=(n=(t=h.providerOptions)==null?void 0:t.google)==null?void 0:n.thoughtSignature;f.push({id:h.toolCallId,type:"function",function:{name:h.toolName,arguments:JSON.stringify(h.input)},...D,...m?{extra_content:{google:{thought_signature:String(m)}}}:{}});break}}}o.push({role:"assistant",content:c,...d.length>0?{reasoning_content:d}:{},tool_calls:f.length>0?f:void 0,...l});break}case"tool":{for(const c of a){if(c.type==="tool-approval-response")continue;const d=c.output;let f;switch(d.type){case"text":case"error-text":f=d.value;break;case"execution-denied":f=(r=d.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":f=JSON.stringify(d.value);break}const h=So(c);o.push({role:"tool",tool_call_id:c.toolCallId,content:f,...h})}break}default:{const c=s;throw new Error(`Unsupported role: ${c}`)}}}return o}i(_k,"convertToOpenAICompatibleChatMessages");function uD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(uD,"getResponseMetadata");function lD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(lD,"mapOpenAICompatibleFinishReason");var Wa=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional(),strictJsonSchema:Re().optional()});function bk({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(bk,"prepareTools");var Ck=(Mr=class{constructor(t,n){this.specificationVersion="v3";var r,o;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:To;this.chunkSchema=Ek(s.errorSchema),this.failedResponseHandler=Dt(s),this.supportsStructuredOutputs=(o=n.supportsStructuredOutputs)!=null?o:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}transformRequestBody(t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,t))!=null?o:t}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:f,toolChoice:h,tools:D}){var m,v,y,b,C;const w=[],E=await tt({provider:"openai-compatible",providerOptions:l,schema:Wa});E!=null&&w.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const T=Object.assign(E??{},(m=await tt({provider:"openaiCompatible",providerOptions:l,schema:Wa}))!=null?m:{},(v=await tt({provider:this.providerOptionsName,providerOptions:l,schema:Wa}))!=null?v:{}),O=(y=T?.strictJsonSchema)!=null?y:!0;s!=null&&w.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:I,toolWarnings:re}=bk({tools:D,toolChoice:h});return{args:{model:this.modelId,user:T.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,strict:O,name:(b=d.name)!=null?b:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:f,...Object.fromEntries(Object.entries((C=l?.[this.providerOptionsName])!=null?C:{}).filter(([k])=>!Object.keys(Wa.shape).includes(k))),reasoning_effort:T.reasoningEffort,verbosity:T.textVerbosity,messages:_k(t),tools:$,tool_choice:I},warnings:[...w,...re]}}async doGenerate(t){var n,r,o,s,a,u,l,c;const{args:d,warnings:f}=await this.getArgs({...t}),h=this.transformRequestBody(d),D=JSON.stringify(h),{responseHeaders:m,value:v,rawValue:y}=await Le({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:h,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(wk),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=v.choices[0],C=[],w=b.message.content;w!=null&&w.length>0&&C.push({type:"text",text:w});const E=(n=b.message.reasoning_content)!=null?n:b.message.reasoning;if(E!=null&&E.length>0&&C.push({type:"reasoning",text:E}),b.message.tool_calls!=null)for(const $ of b.message.tool_calls){const I=(o=(r=$.extra_content)==null?void 0:r.google)==null?void 0:o.thought_signature;C.push({type:"tool-call",toolCallId:(s=$.id)!=null?s:Ve(),toolName:$.function.name,input:$.function.arguments,...I?{providerMetadata:{[this.providerOptionsName]:{thoughtSignature:I}}}:{}})}const T={[this.providerOptionsName]:{},...await((u=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:u.call(a,{parsedBody:y}))},O=(l=v.usage)==null?void 0:l.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(T[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(T[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:C,finishReason:{unified:lD(b.finish_reason),raw:(c=b.finish_reason)!=null?c:void 0},usage:iD(v.usage),providerMetadata:T,request:{body:D},response:{...uD(v),headers:m,body:y},warnings:f}}async doStream(t){var n;const{args:r,warnings:o}=await this.getArgs({...t}),s=this.transformRequestBody({...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0}),a=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await Le({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Gn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},f,h=!0;const D=this.providerOptionsName;let m=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:o})},transform(y,b){var C,w,E,T,O,$,I,re,k,oe,B,P,z,U,R,Y,he,X;if(t.includeRawChunks&&b.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.error});return}if(a?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.value.error.message});return}const de=y.value;h&&(h=!1,b.enqueue({type:"response-metadata",...uD(de)})),de.usage!=null&&(f=de.usage);const fe=de.choices[0];if(fe?.finish_reason!=null&&(d={unified:lD(fe.finish_reason),raw:(C=fe.finish_reason)!=null?C:void 0}),fe?.delta==null)return;const H=fe.delta,je=(w=H.reasoning_content)!=null?w:H.reasoning;if(je&&(m||(b.enqueue({type:"reasoning-start",id:"reasoning-0"}),m=!0),b.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:je})),H.content&&(m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1),v||(b.enqueue({type:"text-start",id:"txt-0"}),v=!0),b.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null){m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1);for(const xe of H.tool_calls){const at=(E=xe.index)!=null?E:c.length;if(c[at]==null){if(xe.id==null)throw new io({data:xe,message:"Expected 'id' to be a string."});if(((T=xe.function)==null?void 0:T.name)==null)throw new io({data:xe,message:"Expected 'function.name' to be a string."});b.enqueue({type:"tool-input-start",id:xe.id,toolName:xe.function.name}),c[at]={id:xe.id,type:"function",function:{name:xe.function.name,arguments:(O=xe.function.arguments)!=null?O:""},hasFinished:!1,thoughtSignature:(re=(I=($=xe.extra_content)==null?void 0:$.google)==null?void 0:I.thought_signature)!=null?re:void 0};const j=c[at];((k=j.function)==null?void 0:k.name)!=null&&((oe=j.function)==null?void 0:oe.arguments)!=null&&(j.function.arguments.length>0&&b.enqueue({type:"tool-input-delta",id:j.id,delta:j.function.arguments}),za(j.function.arguments)&&(b.enqueue({type:"tool-input-end",id:j.id}),b.enqueue({type:"tool-call",toolCallId:(B=j.id)!=null?B:Ve(),toolName:j.function.name,input:j.function.arguments,...j.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:j.thoughtSignature}}}:{}}),j.hasFinished=!0));continue}const Ae=c[at];Ae.hasFinished||(((P=xe.function)==null?void 0:P.arguments)!=null&&(Ae.function.arguments+=(U=(z=xe.function)==null?void 0:z.arguments)!=null?U:""),b.enqueue({type:"tool-input-delta",id:Ae.id,delta:(R=xe.function.arguments)!=null?R:""}),((Y=Ae.function)==null?void 0:Y.name)!=null&&((he=Ae.function)==null?void 0:he.arguments)!=null&&za(Ae.function.arguments)&&(b.enqueue({type:"tool-input-end",id:Ae.id}),b.enqueue({type:"tool-call",toolCallId:(X=Ae.id)!=null?X:Ve(),toolName:Ae.function.name,input:Ae.function.arguments,...Ae.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:Ae.thoughtSignature}}}:{}}),Ae.hasFinished=!0))}}},flush(y){var b,C,w,E,T;m&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const $ of c.filter(I=>!I.hasFinished))y.enqueue({type:"tool-input-end",id:$.id}),y.enqueue({type:"tool-call",toolCallId:(b=$.id)!=null?b:Ve(),toolName:$.function.name,input:$.function.arguments,...$.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:$.thoughtSignature}}}:{}});const O={[D]:{},...a?.buildMetadata()};((C=f?.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens)!=null&&(O[D].acceptedPredictionTokens=(w=f?.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens),((E=f?.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens)!=null&&(O[D].rejectedPredictionTokens=(T=f?.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:iD(f),providerMetadata:O})}})),request:{body:s},response:{headers:u}}}},i(Mr,"OpenAICompatibleChatLanguageModel"),Mr),cD=yi({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish(),wk=yi({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:F("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({id:p().nullish(),function:g({name:p(),arguments:p()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}),finish_reason:p().nullish()})),usage:cD}),Fk=yi({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({index:x().nullish(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:cD}),Ek=i(e=>ee([Fk,e]),"createOpenAICompatibleChatChunkSchema");function dD(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:o,text:o,reasoning:void 0},raw:e}}i(dD,"convertOpenAICompatibleCompletionUsage");function xk({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
163
+ ${t}:`]}}i(nx,"convertToOpenAICompletionPrompt");function Uh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(Uh,"getResponseMetadata2$1");function Zh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(Zh,"mapOpenAIFinishReason2");var rx=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(Ce(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}))),ox=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(Ce(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}),fu]))),Vh=K(()=>J(g({echo:Re().optional(),logitBias:Ce(p(),x()).optional(),suffix:p().optional(),user:p().optional(),logprobs:ee([Re(),x()]).optional()}))),ax=(Rr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:f,seed:m,providerOptions:D}){const h=[],v={...await tt({provider:"openai",providerOptions:D,schema:Vh}),...await tt({provider:this.providerOptionsName,providerOptions:D,schema:Vh})};s!=null&&h.push({type:"unsupported",feature:"topK"}),d?.length&&h.push({type:"unsupported",feature:"tools"}),f!=null&&h.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:b}=nx({prompt:t}),C=[...b??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:m,prompt:y,stop:C.length>0?C:void 0},warnings:h}}async doGenerate(t){var n;const{args:r,warnings:o}=await this.getArgs(t),{responseHeaders:s,value:a,rawValue:u}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:Ke(rx),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:qh(a.usage),finishReason:{unified:Zh(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...Uh(a),headers:s,body:u},providerMetadata:c,warnings:o}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:Jn(ox),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:a.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,m){if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:f.error});return}const D=f.value;if("error"in D){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}d&&(d=!1,m.enqueue({type:"response-metadata",...Uh(D)}),m.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const h=D.choices[0];h?.finish_reason!=null&&(u={unified:Zh(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(l.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&m.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(f){d||f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:qh(c)})}})),request:{body:o},response:{headers:s}}}},i(Rr,"OpenAICompletionLanguageModel"),Rr),sx=K(()=>J(g({dimensions:x().optional(),user:p().optional()}))),ix=K(()=>J(g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish()}))),ux=(Nr=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new sp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const a=(s=await tt({provider:"openai",providerOptions:o,schema:sx}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:Tt,successfulResponseHandler:Ke(ix),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Nr,"OpenAIEmbeddingModel"),Nr),Gh=K(()=>J(g({created:x().nullish(),data:S(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:x().nullish(),output_tokens:x().nullish(),total_tokens:x().nullish(),input_tokens_details:g({image_tokens:x().nullish(),text_tokens:x().nullish()}).nullish()}).nullish()}))),lx={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},cx=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function dx(e){return cx.some(t=>e.startsWith(t))}i(dx,"hasDefaultResponseFormat");var px=(Pr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=lx[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:o,size:s,aspectRatio:a,seed:u,providerOptions:l,headers:c,abortSignal:d}){var f,m,D,h,v,y,b,C,w,E,T;const O=[];a!=null&&O.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&O.push({type:"unsupported",feature:"seed"});const $=(D=(m=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:m.call(f))!=null?D:new Date;if(n!=null){const{value:k,responseHeaders:oe}=await Ui({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),c),formData:hf({model:this.modelId,prompt:t,image:await Promise.all(n.map(B=>B.type==="file"?new Blob([B.data instanceof Uint8Array?new Blob([B.data],{type:B.mediaType}):new Blob([bn(B.data)],{type:B.mediaType})],{type:B.mediaType}):Ri(B.url))),mask:r!=null?await fx(r):void 0,n:o,size:s,...(h=l.openai)!=null?h:{}}),failedResponseHandler:Tt,successfulResponseHandler:Ke(Gh),abortSignal:d,fetch:this.config.fetch});return{images:k.data.map(B=>B.b64_json),warnings:O,usage:k.usage!=null?{inputTokens:(v=k.usage.input_tokens)!=null?v:void 0,outputTokens:(y=k.usage.output_tokens)!=null?y:void 0,totalTokens:(b=k.usage.total_tokens)!=null?b:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:oe},providerMetadata:{openai:{images:k.data.map((B,P)=>{var z,U,R,Y,he,X;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(z=k.created)!=null?z:void 0,size:(U=k.size)!=null?U:void 0,quality:(R=k.quality)!=null?R:void 0,background:(Y=k.background)!=null?Y:void 0,outputFormat:(he=k.output_format)!=null?he:void 0,...Wh((X=k.usage)==null?void 0:X.input_tokens_details,P,k.data.length)}})}}}}const{value:I,responseHeaders:re}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:o,size:s,...(C=l.openai)!=null?C:{},...dx(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tt,successfulResponseHandler:Ke(Gh),abortSignal:d,fetch:this.config.fetch});return{images:I.data.map(k=>k.b64_json),warnings:O,usage:I.usage!=null?{inputTokens:(w=I.usage.input_tokens)!=null?w:void 0,outputTokens:(E=I.usage.output_tokens)!=null?E:void 0,totalTokens:(T=I.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:re},providerMetadata:{openai:{images:I.data.map((k,oe)=>{var B,P,z,U,R,Y;return{...k.revised_prompt?{revisedPrompt:k.revised_prompt}:{},created:(B=I.created)!=null?B:void 0,size:(P=I.size)!=null?P:void 0,quality:(z=I.quality)!=null?z:void 0,background:(U=I.background)!=null?U:void 0,outputFormat:(R=I.output_format)!=null?R:void 0,...Wh((Y=I.usage)==null?void 0:Y.input_tokens_details,oe,I.data.length)}})}}}}},i(Pr,"OpenAIImageModel"),Pr);function Wh(e,t,n){if(e==null)return{};const r={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/n),s=e.image_tokens-o*(n-1);r.imageTokens=t===n-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/n),s=e.text_tokens-o*(n-1);r.textTokens=t===n-1?s:o}return r}i(Wh,"distributeTokenDetails");async function fx(e){if(!e)return;if(e.type==="url")return Ri(e.url);const t=e.data instanceof Uint8Array?e.data:bn(e.data);return new Blob([t],{type:e.mediaType})}i(fx,"fileToBlob$1");var Hh=K(()=>J(g({callId:p(),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}))),Jh=K(()=>J(g({status:se(["completed","failed"]),output:p().optional()}))),mx=At({id:"openai.apply_patch",inputSchema:Hh,outputSchema:Jh}),hx=mx,Dx=K(()=>J(g({code:p().nullish(),containerId:p()}))),gx=K(()=>J(g({outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullish()}))),vx=K(()=>J(g({container:ee([p(),g({fileIds:S(p()).optional()})]).optional()}))),yx=At({id:"openai.code_interpreter",inputSchema:Dx,outputSchema:gx}),_x=i((e={})=>yx(e),"codeInterpreter"),Kh=g({key:p(),type:se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([p(),x(),Re(),S(p())])}),Yh=g({type:se(["and","or"]),filters:S(ee([Kh,Fi(()=>Yh)]))}),bx=K(()=>J(g({vectorStoreIds:S(p()),maxNumResults:x().optional(),ranking:g({ranker:p().optional(),scoreThreshold:x().optional()}).optional(),filters:ee([Kh,Yh]).optional()}))),Cx=K(()=>J(g({queries:S(p()),results:S(g({attributes:Ce(p(),lt()),fileId:p(),filename:p(),score:x(),text:p()})).nullable()}))),wx=At({id:"openai.file_search",inputSchema:g({}),outputSchema:Cx}),Fx=K(()=>J(g({background:se(["auto","opaque","transparent"]).optional(),inputFidelity:se(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:se(["auto"]).optional(),outputCompression:x().int().min(0).max(100).optional(),outputFormat:se(["png","jpeg","webp"]).optional(),partialImages:x().int().min(0).max(3).optional(),quality:se(["auto","low","medium","high"]).optional(),size:se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Ex=K(()=>J(g({}))),xx=K(()=>J(g({result:p()}))),kx=At({id:"openai.image_generation",inputSchema:Ex,outputSchema:xx}),Ix=i((e={})=>kx(e),"imageGeneration"),Xh=K(()=>J(g({action:g({type:F("exec"),command:S(p()),timeoutMs:x().optional(),user:p().optional(),workingDirectory:p().optional(),env:Ce(p(),p()).optional()})}))),Qh=K(()=>J(g({output:p()}))),Ax=At({id:"openai.local_shell",inputSchema:Xh,outputSchema:Qh}),eD=K(()=>J(g({action:g({commands:S(p()),timeoutMs:x().optional(),maxOutputLength:x().optional()})}))),hu=K(()=>J(g({output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exitCode:x()})])}))}))),$x=S(ge("type",[g({type:F("skillReference"),skillId:p(),version:p().optional()}),g({type:F("inline"),name:p(),description:p(),source:g({type:F("base64"),mediaType:F("application/zip"),data:p()})})])).optional(),Tx=K(()=>J(g({environment:ee([g({type:F("containerAuto"),fileIds:S(p()).optional(),memoryLimit:se(["1g","4g","16g","64g"]).optional(),networkPolicy:ge("type",[g({type:F("disabled")}),g({type:F("allowlist"),allowedDomains:S(p()),domainSecrets:S(g({domain:p(),name:p(),value:p()})).optional()})]).optional(),skills:$x}),g({type:F("containerReference"),containerId:p()}),g({type:F("local").optional(),skills:S(g({name:p(),description:p(),path:p()})).optional()})]).optional()}))),Sx=At({id:"openai.shell",inputSchema:eD,outputSchema:hu}),Bx=K(()=>J(g({externalWebAccess:Re().optional(),filters:g({allowedDomains:S(p()).optional()}).optional(),searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Ox=K(()=>J(g({}))),Rx=K(()=>J(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).optional()}))),Nx=At({id:"openai.web_search",inputSchema:Ox,outputSchema:Rx}),Px=i((e={})=>Nx(e),"webSearch"),Mx=K(()=>J(g({searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),jx=K(()=>J(g({}))),zx=K(()=>J(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),Lx=At({id:"openai.web_search_preview",inputSchema:jx,outputSchema:zx}),Du=Fi(()=>ee([p(),x(),Re(),Xp(),S(Du),Ce(p(),Du)])),qx=K(()=>J(g({serverLabel:p(),allowedTools:ee([S(p()),g({readOnly:Re().optional(),toolNames:S(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:Ce(p(),p()).optional(),requireApproval:ee([se(["always","never"]),g({never:g({toolNames:S(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Ux=K(()=>J(g({}))),Zx=K(()=>J(g({type:F("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:ee([p(),Du]).optional()}))),Vx=At({id:"openai.mcp",inputSchema:Ux,outputSchema:Zx}),Gx=i(e=>Vx(e),"mcp"),Wx={applyPatch:hx,codeInterpreter:_x,fileSearch:wx,imageGeneration:Ix,localShell:Ax,shell:Sx,webSearchPreview:Lx,webSearch:Px,mcp:Gx};function tD(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(o=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}i(tD,"convertOpenAIResponsesUsage");function nD(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(nD,"isFileId");async function Hx({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:u=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var d,f,m,D,h,v,y,b,C,w,E,T,O;const $=[],I=[],re=new Set;for(const{role:k,content:oe}of e)switch(k){case"system":{switch(n){case"system":{$.push({role:"system",content:oe});break}case"developer":{$.push({role:"developer",content:oe});break}case"remove":{I.push({type:"other",message:"system messages are removed for this model"});break}default:{const B=n;throw new Error(`Unsupported system message mode: ${B}`)}}break}case"user":{$.push({role:"user",content:oe.map((B,P)=>{var z,U,R;switch(B.type){case"text":return{type:"input_text",text:B.text};case"file":if(B.mediaType.startsWith("image/")){const Y=B.mediaType==="image/*"?"image/jpeg":B.mediaType;return{type:"input_image",...B.data instanceof URL?{image_url:B.data.toString()}:typeof B.data=="string"&&nD(B.data,o)?{file_id:B.data}:{image_url:`data:${Y};base64,${Lt(B.data)}`},detail:(U=(z=B.providerOptions)==null?void 0:z[r])==null?void 0:U.imageDetail}}else{if(B.mediaType==="application/pdf")return B.data instanceof URL?{type:"input_file",file_url:B.data.toString()}:{type:"input_file",...typeof B.data=="string"&&nD(B.data,o)?{file_id:B.data}:{filename:(R=B.filename)!=null?R:`part-${P}.pdf`,file_data:`data:application/pdf;base64,${Lt(B.data)}`}};throw new Qe({functionality:`file part media type ${B.mediaType}`})}}})});break}case"assistant":{const B={};for(const P of oe)switch(P.type){case"text":{const z=(f=(d=P.providerOptions)==null?void 0:d[r])==null?void 0:f.itemId;if(a&&z!=null)break;if(s&&z!=null){$.push({type:"item_reference",id:z});break}$.push({role:"assistant",content:[{type:"output_text",text:P.text}],id:z});break}case"tool-call":{const z=(y=(D=(m=P.providerOptions)==null?void 0:m[r])==null?void 0:D.itemId)!=null?y:(v=(h=P.providerMetadata)==null?void 0:h[r])==null?void 0:v.itemId;if(a&&z!=null)break;if(P.providerExecuted){s&&z!=null&&$.push({type:"item_reference",id:z});break}if(s&&z!=null){$.push({type:"item_reference",id:z});break}const U=t.toProviderToolName(P.toolName);if(u&&U==="local_shell"){const R=await rt({value:P.input,schema:Xh});$.push({type:"local_shell_call",call_id:P.toolCallId,id:z,action:{type:"exec",command:R.action.command,timeout_ms:R.action.timeoutMs,user:R.action.user,working_directory:R.action.workingDirectory,env:R.action.env}});break}if(l&&U==="shell"){const R=await rt({value:P.input,schema:eD});$.push({type:"shell_call",call_id:P.toolCallId,id:z,status:"completed",action:{commands:R.action.commands,timeout_ms:R.action.timeoutMs,max_output_length:R.action.maxOutputLength}});break}if(c&&U==="apply_patch"){const R=await rt({value:P.input,schema:Hh});$.push({type:"apply_patch_call",call_id:R.callId,id:z,status:"completed",operation:R.operation});break}$.push({type:"function_call",call_id:P.toolCallId,name:U,arguments:JSON.stringify(P.input),id:z});break}case"tool-result":{if(P.output.type==="execution-denied"||P.output.type==="json"&&typeof P.output.value=="object"&&P.output.value!=null&&"type"in P.output.value&&P.output.value.type==="execution-denied"||a)break;const z=t.toProviderToolName(P.toolName);if(l&&z==="shell"){if(P.output.type==="json"){const U=await rt({value:P.output.value,schema:hu});$.push({type:"shell_call_output",call_id:P.toolCallId,output:U.output.map(R=>({stdout:R.stdout,stderr:R.stderr,outcome:R.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:R.outcome.exitCode}}))})}break}if(s){const U=(w=(C=(b=P.providerOptions)==null?void 0:b[r])==null?void 0:C.itemId)!=null?w:P.toolCallId;$.push({type:"item_reference",id:U})}else I.push({type:"other",message:`Results for OpenAI tool ${P.toolName} are not sent to the API when store is false`});break}case"reasoning":{const z=await tt({provider:r,providerOptions:P.providerOptions,schema:Jx}),U=z?.itemId;if(a&&U!=null)break;if(U!=null){const R=B[U];if(s)R===void 0&&($.push({type:"item_reference",id:U}),B[U]={type:"reasoning",id:U,summary:[]});else{const Y=[];P.text.length>0?Y.push({type:"summary_text",text:P.text}):R!==void 0&&I.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(P)}.`}),R===void 0?(B[U]={type:"reasoning",id:U,encrypted_content:z?.reasoningEncryptedContent,summary:Y},$.push(B[U])):(R.summary.push(...Y),z?.reasoningEncryptedContent!=null&&(R.encrypted_content=z.reasoningEncryptedContent))}}else I.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(P)}.`});break}}break}case"tool":{for(const B of oe){if(B.type==="tool-approval-response"){const R=B;if(re.has(R.approvalId))continue;re.add(R.approvalId),s&&$.push({type:"item_reference",id:R.approvalId}),$.push({type:"mcp_approval_response",approval_request_id:R.approvalId,approve:R.approved});continue}const P=B.output;if(P.type==="execution-denied"&&((T=(E=P.providerOptions)==null?void 0:E.openai)==null?void 0:T.approvalId))continue;const z=t.toProviderToolName(B.toolName);if(u&&z==="local_shell"&&P.type==="json"){const R=await rt({value:P.value,schema:Qh});$.push({type:"local_shell_call_output",call_id:B.toolCallId,output:R.output});continue}if(l&&z==="shell"&&P.type==="json"){const R=await rt({value:P.value,schema:hu});$.push({type:"shell_call_output",call_id:B.toolCallId,output:R.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))});continue}if(c&&B.toolName==="apply_patch"&&P.type==="json"){const R=await rt({value:P.value,schema:Jh});$.push({type:"apply_patch_call_output",call_id:B.toolCallId,status:R.status,output:R.output});continue}let U;switch(P.type){case"text":case"error-text":U=P.value;break;case"execution-denied":U=(O=P.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(P.value);break;case"content":U=P.value.map(R=>{var Y;switch(R.type){case"text":return{type:"input_text",text:R.text};case"image-data":return{type:"input_image",image_url:`data:${R.mediaType};base64,${R.data}`};case"image-url":return{type:"input_image",image_url:R.url};case"file-data":return{type:"input_file",filename:(Y=R.filename)!=null?Y:"data",file_data:`data:${R.mediaType};base64,${R.data}`};default:{I.push({type:"other",message:`unsupported tool content part type: ${R.type}`});return}}}).filter(UF);break}$.push({type:"function_call_output",call_id:B.toolCallId,output:U})}break}default:{const B=k;throw new Error(`Unsupported role: ${B}`)}}return{input:$,warnings:I}}i(Hx,"convertToOpenAIResponsesInput");var Jx=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function rD({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}i(rD,"mapOpenAIResponseFinishReason");var Kx=K(()=>J(ee([g({type:F("response.output_text.delta"),item_id:p(),delta:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}),g({type:se(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:F("response.created"),response:g({id:p(),created_at:x(),model:p(),service_tier:p().nullish()})}),g({type:F("response.output_item.added"),output_index:x(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:F("web_search_call"),id:p(),status:p()}),g({type:F("computer_call"),id:p(),status:p()}),g({type:F("file_search_call"),id:p()}),g({type:F("image_generation_call"),id:p()}),g({type:F("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable(),status:p()}),g({type:F("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p()}),g({type:F("mcp_approval_request"),id:p()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])}),g({type:F("response.output_item.done"),output_index:x(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:F("completed")}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:Ce(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:Ce(p(),p()).optional()})}),g({type:F("computer_call"),id:p(),status:F("completed")}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:Ce(p(),lt()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])}),g({type:F("response.function_call_arguments.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:F("response.image_generation_call.partial_image"),item_id:p(),output_index:x(),partial_image_b64:p()}),g({type:F("response.code_interpreter_call_code.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:F("response.code_interpreter_call_code.done"),item_id:p(),output_index:x(),code:p()}),g({type:F("response.output_text.annotation.added"),annotation:ge("type",[g({type:F("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:F("file_path"),file_id:p(),index:x()})])}),g({type:F("response.reasoning_summary_part.added"),item_id:p(),summary_index:x()}),g({type:F("response.reasoning_summary_text.delta"),item_id:p(),summary_index:x(),delta:p()}),g({type:F("response.reasoning_summary_part.done"),item_id:p(),summary_index:x()}),g({type:F("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:x(),delta:p(),obfuscation:p().nullish()}),g({type:F("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:x(),diff:p()}),g({type:F("error"),sequence_number:x(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Yx=K(()=>J(g({id:p().optional(),created_at:x().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:S(ge("type",[g({type:F("message"),role:F("assistant"),id:p(),content:S(g({type:F("output_text"),text:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish(),annotations:S(ge("type",[g({type:F("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:F("file_path"),file_id:p(),index:x()})]))}))}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:S(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:Ce(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:Ce(p(),p()).optional()})}),g({type:F("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:F("computer_call"),id:p(),status:p().optional()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish(),summary:S(g({type:F("summary_text"),text:p()}))}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:Ce(p(),lt()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:x()})])}))})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}).optional()}))),oD=20,aD=K(()=>J(g({conversation:p().nullish(),include:S(se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:ee([Re(),x().min(1).max(oD)]).optional(),maxToolCalls:x().nullish(),metadata:et().nullish(),parallelToolCalls:Re().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:se(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:se(["auto","flex","priority","default"]).nullish(),store:Re().nullish(),strictJsonSchema:Re().nullish(),textVerbosity:se(["low","medium","high"]).nullish(),truncation:se(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));async function Xx({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await rt({value:s.args,schema:bx});r.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{const a=await rt({value:s.args,schema:Tx});r.push({type:"shell",...a.environment&&{environment:Qx(a.environment)}});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await rt({value:s.args,schema:Mx});r.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await rt({value:s.args,schema:Bx});r.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await rt({value:s.args,schema:vx});r.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await rt({value:s.args,schema:Fx});r.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await rt({value:s.args,schema:qx}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(Xx,"prepareResponsesTools");function Qx(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const n=e;return{type:"container_auto",file_ids:n.fileIds,memory_limit:n.memoryLimit,network_policy:n.networkPolicy==null?void 0:n.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:n.networkPolicy.allowedDomains,domain_secrets:n.networkPolicy.domainSecrets},skills:ek(n.skills)}}return{type:"local",skills:e.skills}}i(Qx,"mapShellEnvironment");function ek(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}i(ek,"mapShellSkills");function sD(e){var t,n;const r={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;a!=null&&(r[a]=s.toolCallId)}return r}i(sD,"extractApprovalRequestIdToToolCallIdMapping");var tk=(Mr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:o,topK:s,presencePenalty:a,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:f,toolChoice:m,responseFormat:D}){var h,v,y,b,C,w,E,T,O;const $=[],I=jh(this.modelId);s!=null&&$.push({type:"unsupported",feature:"topK"}),l!=null&&$.push({type:"unsupported",feature:"seed"}),a!=null&&$.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&$.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&$.push({type:"unsupported",feature:"stopSequences"});const re=this.config.provider.includes("azure")?"azure":"openai";let k=await tt({provider:re,providerOptions:d,schema:aD});k==null&&re!=="openai"&&(k=await tt({provider:"openai",providerOptions:d,schema:aD}));const oe=(h=k?.forceReasoning)!=null?h:I.isReasoningModel;k?.conversation&&k?.previousResponseId&&$.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const B=BF({tools:f,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:P,warnings:z}=await Hx({prompt:c,toolNameMapping:B,systemMessageMode:(v=k?.systemMessageMode)!=null?v:oe?"developer":I.systemMessageMode,providerOptionsName:re,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=k?.store)!=null?y:!0,hasConversation:k?.conversation!=null,hasLocalShellTool:he("openai.local_shell"),hasShellTool:he("openai.shell"),hasApplyPatchTool:he("openai.apply_patch")});$.push(...z);const U=(b=k?.strictJsonSchema)!=null?b:!0;let R=k?.include;function Y(te){R==null?R=[te]:R.includes(te)||(R=[...R,te])}i(Y,"addInclude");function he(te){return f?.find(Ge=>Ge.type==="provider"&&Ge.id===te)!=null}i(he,"hasOpenAITool");const X=typeof k?.logprobs=="number"?k?.logprobs:k?.logprobs===!0?oD:void 0;X&&Y("message.output_text.logprobs");const pe=(C=f?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:C.name;pe&&Y("web_search_call.action.sources"),he("openai.code_interpreter")&&Y("code_interpreter_call.outputs");const fe=k?.store;fe===!1&&oe&&Y("reasoning.encrypted_content");const H={model:this.modelId,input:P,temperature:n,top_p:o,max_output_tokens:t,...(D?.type==="json"||k?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:U,name:(w=D.name)!=null?w:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...k?.textVerbosity&&{verbosity:k.textVerbosity}}},conversation:k?.conversation,max_tool_calls:k?.maxToolCalls,metadata:k?.metadata,parallel_tool_calls:k?.parallelToolCalls,previous_response_id:k?.previousResponseId,store:fe,user:k?.user,instructions:k?.instructions,service_tier:k?.serviceTier,include:R,prompt_cache_key:k?.promptCacheKey,prompt_cache_retention:k?.promptCacheRetention,safety_identifier:k?.safetyIdentifier,top_logprobs:X,truncation:k?.truncation,...oe&&(k?.reasoningEffort!=null||k?.reasoningSummary!=null)&&{reasoning:{...k?.reasoningEffort!=null&&{effort:k.reasoningEffort},...k?.reasoningSummary!=null&&{summary:k.reasoningSummary}}}};oe?k?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(H.temperature!=null&&(H.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),H.top_p!=null&&(H.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(k?.reasoningEffort!=null&&$.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),k?.reasoningSummary!=null&&$.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),k?.serviceTier==="flex"&&!I.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete H.service_tier),k?.serviceTier==="priority"&&!I.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete H.service_tier);const{tools:je,toolChoice:xe,toolWarnings:at}=await Xx({tools:f,toolChoice:m}),Ae=(O=(T=(E=f?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:E.args)==null?void 0:T.environment)==null?void 0:O.type,j=Ae==="containerAuto"||Ae==="containerReference";return{webSearchToolName:pe,args:{...H,tools:je,tool_choice:xe},warnings:[...$,...at],store:fe,toolNameMapping:B,providerOptionsName:re,isShellProviderExecuted:j}}async doGenerate(t){var n,r,o,s,a,u,l,c,d,f,m,D,h,v,y,b,C,w,E,T,O,$,I,re,k;const{args:oe,warnings:B,webSearchToolName:P,toolNameMapping:z,providerOptionsName:U,isShellProviderExecuted:R}=await this.getArgs(t),Y=this.config.url({path:"/responses",modelId:this.modelId}),he=sD(t.prompt),{responseHeaders:X,value:pe,rawValue:fe}=await qe({url:Y,headers:Ne(this.config.headers(),t.headers),body:oe,failedResponseHandler:Tt,successfulResponseHandler:Ke(Yx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(pe.error)throw new Be({message:pe.error.message,url:Y,requestBodyValues:oe,statusCode:400,responseHeaders:X,responseBody:fe,isRetryable:!1});const H=[],je=[];let xe=!1;for(const j of pe.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const te of j.summary)H.push({type:"reasoning",text:te.text,providerMetadata:{[U]:{itemId:j.id,reasoningEncryptedContent:(n=j.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),result:{result:j.result}});break}case"local_shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("local_shell"),input:JSON.stringify({action:j.action}),providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),input:JSON.stringify({action:{commands:j.action.commands}}),...R&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call_output":{H.push({type:"tool-result",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),result:{output:j.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const te of j.content){(o=(r=t.providerOptions)==null?void 0:r[U])!=null&&o.logprobs&&te.logprobs&&je.push(te.logprobs);const Ge={itemId:j.id,...te.annotations.length>0&&{annotations:te.annotations}};H.push({type:"text",text:te.text,providerMetadata:{[U]:Ge}});for(const ve of te.annotations)ve.type==="url_citation"?H.push({type:"source",sourceType:"url",id:(u=(a=(s=this.config).generateId)==null?void 0:a.call(s))!=null?u:Ve(),url:ve.url,title:ve.title}):ve.type==="file_citation"?H.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}}):ve.type==="container_file_citation"?H.push({type:"source",sourceType:"document",id:(D=(m=(f=this.config).generateId)==null?void 0:m.call(f))!=null?D:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,containerId:ve.container_id}}}):ve.type==="file_path"&&H.push({type:"source",sourceType:"document",id:(y=(v=(h=this.config).generateId)==null?void 0:v.call(h))!=null?y:Ve(),mediaType:"application/octet-stream",title:ve.file_id,filename:ve.file_id,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}})}break}case"function_call":{xe=!0,H.push({type:"tool-call",toolCallId:j.call_id,toolName:j.name,input:j.arguments,providerMetadata:{[U]:{itemId:j.id}}});break}case"web_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),result:uD(j.action)});break}case"mcp_call":{const te=j.approval_request_id!=null&&(b=he[j.approval_request_id])!=null?b:j.id,Ge=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:te,toolName:Ge,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-result",toolCallId:te,toolName:Ge,result:{type:"call",serverLabel:j.server_label,name:j.name,arguments:j.arguments,...j.output!=null?{output:j.output}:{},...j.error!=null?{error:j.error}:{}},providerMetadata:{[U]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const te=(C=j.approval_request_id)!=null?C:j.id,Ge=(T=(E=(w=this.config).generateId)==null?void 0:E.call(w))!=null?T:Ve(),ve=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:Ge,toolName:ve,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-approval-request",approvalId:te,toolCallId:Ge});break}case"computer_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:j.status||"completed"}});break}case"file_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),result:{queries:j.queries,results:($=(O=j.results)==null?void 0:O.map(te=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?$:null}});break}case"code_interpreter_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),input:JSON.stringify({code:j.code,containerId:j.container_id}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),result:{outputs:j.outputs}});break}case"apply_patch_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("apply_patch"),input:JSON.stringify({callId:j.call_id,operation:j.operation}),providerMetadata:{[U]:{itemId:j.id}}});break}}const at={[U]:{responseId:pe.id,...je.length>0?{logprobs:je}:{},...typeof pe.service_tier=="string"?{serviceTier:pe.service_tier}:{}}},Ae=pe.usage;return{content:H,finishReason:{unified:rD({finishReason:(I=pe.incomplete_details)==null?void 0:I.reason,hasFunctionCall:xe}),raw:(k=(re=pe.incomplete_details)==null?void 0:re.reason)!=null?k:void 0},usage:tD(Ae),request:{body:oe},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:X,body:fe},providerMetadata:at,warnings:B}}async doStream(t){const{args:n,warnings:r,webSearchToolName:o,toolNameMapping:s,store:a,providerOptionsName:u,isShellProviderExecuted:l}=await this.getArgs(t),{responseHeaders:c,value:d}=await qe({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:Tt,successfulResponseHandler:Jn(Kx),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=this,m=sD(t.prompt),D=new Map;let h={unified:"other",raw:void 0},v;const y=[];let b=null;const C={},w=[];let E=!1;const T={};let O;return{stream:d.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:r})},transform($,I){var re,k,oe,B,P,z,U,R,Y,he,X,pe,fe,H,je,xe,at,Ae,j,te,Ge,ve,Vr,Gr,Wr,Hr,Jr,Kr,Yr,Xr;if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){h={unified:"error",raw:void 0},I.enqueue({type:"error",error:$.error});return}const _=$.value;if(iD(_)){if(_.item.type==="function_call")C[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},I.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")C[_.output_index]={toolName:s.toCustomToolName(o??"web_search"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(o??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")C[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")C[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:q,operation:ze}=_.item;if(C[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:q,applyPatch:{hasDiff:ze.type==="delete_file",endEmitted:ze.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:q,toolName:s.toCustomToolName("apply_patch")}),ze.type==="delete_file"){const st=JSON.stringify({callId:q,operation:ze});I.enqueue({type:"tool-input-delta",id:q,delta:st}),I.enqueue({type:"tool-input-end",id:q})}else I.enqueue({type:"tool-input-delta",id:q,delta:`{"callId":"${xn(q)}","operation":{"type":"${xn(ze.type)}","path":"${xn(ze.path)}","diff":"`})}else _.item.type==="shell_call"?C[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="shell_call_output"||(_.item.type==="message"?(w.splice(0,w.length),I.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):iD(_)&&_.item.type==="reasoning"&&(T[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(re=_.item.encrypted_content)!=null?re:null}}})))}else if(rk(_)){if(_.item.type==="message")I.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...w.length>0&&{annotations:w}}}});else if(_.item.type==="function_call")C[_.output_index]=void 0,E=!0,I.enqueue({type:"tool-input-end",id:_.item.call_id}),I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),result:uD(_.item.action)});else if(_.item.type==="computer_call")C[_.output_index]=void 0,I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(oe=(k=_.item.results)==null?void 0:k.map(q=>({attributes:q.attributes,fileId:q.file_id,filename:q.filename,score:q.score,text:q.text})))!=null?oe:null}});else if(_.item.type==="code_interpreter_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){C[_.output_index]=void 0;const q=(B=_.item.approval_request_id)!=null?B:void 0,ze=q!=null&&(z=(P=D.get(q))!=null?P:m[q])!=null?z:_.item.id,st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:ze,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:ze,toolName:st,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")C[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const q=C[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(q.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:xn(_.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0),q&&_.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),C[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){C[_.output_index]=void 0;const q=(Y=(R=(U=f.config).generateId)==null?void 0:R.call(U))!=null?Y:Ve(),ze=(he=_.item.approval_request_id)!=null?he:_.item.id;D.set(ze,q);const st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:q,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:ze,toolCallId:q})}else if(_.item.type==="local_shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),result:{output:_.item.output.map(q=>({stdout:q.stdout,stderr:q.stderr,outcome:q.outcome.type==="exit"?{type:"exit",exitCode:q.outcome.exit_code}:{type:"timeout"}}))}});else if(_.item.type==="reasoning"){const q=T[_.item.id],ze=Object.entries(q.summaryParts).filter(([st,Sn])=>Sn==="active"||Sn==="can-conclude").map(([st])=>st);for(const st of ze)I.enqueue({type:"reasoning-end",id:`${_.item.id}:${st}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(X=_.item.encrypted_content)!=null?X:null}}});delete T[_.item.id]}}else if(sk(_)){const q=C[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_.delta})}else if(ck(_)){const q=C[_.output_index];q?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:xn(_.delta)}),q.applyPatch.hasDiff=!0)}else if(dk(_)){const q=C[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&(q.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:xn(_.diff)}),q.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0)}else if(ik(_))I.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(uk(_)){const q=C[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:xn(_.delta)})}else if(lk(_)){const q=C[_.output_index];q!=null&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:q.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ak(_))b=_.response.id,I.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(nk(_))I.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(fe=(pe=t.providerOptions)==null?void 0:pe[u])!=null&&fe.logprobs&&_.logprobs&&y.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const q=T[_.item_id];q.summaryParts[_.summary_index]="active";for(const ze of Object.keys(q.summaryParts))q.summaryParts[ze]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${ze}`,providerMetadata:{[u]:{itemId:_.item_id}}}),q.summaryParts[ze]="concluded");I.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(je=(H=T[_.item_id])==null?void 0:H.encryptedContent)!=null?je:null}}})}}else _.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?a?(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),T[_.item_id].summaryParts[_.summary_index]="concluded"):T[_.item_id].summaryParts[_.summary_index]="can-conclude":ok(_)?(h={unified:rD({finishReason:(xe=_.response.incomplete_details)==null?void 0:xe.reason,hasFunctionCall:E}),raw:(Ae=(at=_.response.incomplete_details)==null?void 0:at.reason)!=null?Ae:void 0},v=_.response.usage,typeof _.response.service_tier=="string"&&(O=_.response.service_tier)):pk(_)?(w.push(_.annotation),_.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(Ge=(te=(j=f.config).generateId)==null?void 0:te.call(j))!=null?Ge:Ve(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Gr=(Vr=(ve=f.config).generateId)==null?void 0:Vr.call(ve))!=null?Gr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}}):_.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Jr=(Hr=(Wr=f.config).generateId)==null?void 0:Hr.call(Wr))!=null?Jr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,containerId:_.annotation.container_id}}}):_.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Xr=(Yr=(Kr=f.config).generateId)==null?void 0:Yr.call(Kr))!=null?Xr:Ve(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}})):fk(_)&&I.enqueue({type:"error",error:_})},flush($){const I={[u]:{responseId:b,...y.length>0?{logprobs:y}:{},...O!==void 0?{serviceTier:O}:{}}};$.enqueue({type:"finish",finishReason:h,usage:tD(v),providerMetadata:I})}})),request:{body:n},response:{headers:c}}}},i(Mr,"OpenAIResponsesLanguageModel"),Mr);function nk(e){return e.type==="response.output_text.delta"}i(nk,"isTextDeltaChunk");function rk(e){return e.type==="response.output_item.done"}i(rk,"isResponseOutputItemDoneChunk");function ok(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(ok,"isResponseFinishedChunk");function ak(e){return e.type==="response.created"}i(ak,"isResponseCreatedChunk");function sk(e){return e.type==="response.function_call_arguments.delta"}i(sk,"isResponseFunctionCallArgumentsDeltaChunk");function ik(e){return e.type==="response.image_generation_call.partial_image"}i(ik,"isResponseImageGenerationCallPartialImageChunk");function uk(e){return e.type==="response.code_interpreter_call_code.delta"}i(uk,"isResponseCodeInterpreterCallCodeDeltaChunk");function lk(e){return e.type==="response.code_interpreter_call_code.done"}i(lk,"isResponseCodeInterpreterCallCodeDoneChunk");function ck(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(ck,"isResponseApplyPatchCallOperationDiffDeltaChunk");function dk(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(dk,"isResponseApplyPatchCallOperationDiffDoneChunk");function iD(e){return e.type==="response.output_item.added"}i(iD,"isResponseOutputItemAddedChunk");function pk(e){return e.type==="response.output_text.annotation.added"}i(pk,"isResponseAnnotationAddedChunk");function fk(e){return e.type==="error"}i(fk,"isErrorChunk");function uD(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(uD,"mapWebSearchOutput");function xn(e){return JSON.stringify(e).slice(1,-1)}i(xn,"escapeJSONDelta");var mk=K(()=>J(g({instructions:p().nullish(),speed:x().min(.25).max(4).default(1).nullish()}))),hk=(jr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:o,instructions:s,language:a,providerOptions:u}){const l=[],c=await tt({provider:"openai",providerOptions:u,schema:mk}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:o,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const f={};for(const m in f){const D=f[m];D!==void 0&&(d[m]=D)}}return a&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,o;const s=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{requestBody:a,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await qe({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:a,failedResponseHandler:Tt,successfulResponseHandler:U2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(a)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(jr,"OpenAISpeechModel"),jr),Dk=K(()=>J(g({text:p(),language:p().nullish(),duration:x().nullish(),words:S(g({word:p(),start:x(),end:x()})).nullish(),segments:S(g({id:x(),seek:x(),start:x(),end:x(),text:p(),tokens:S(x()),temperature:x(),avg_logprob:x(),compression_ratio:x(),no_speech_prob:x()})).nullish()}))),gk=K(()=>J(g({include:S(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:x().min(0).max(1).default(0).optional(),timestampGranularities:S(se(["word","segment"])).default(["segment"]).optional()}))),lD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},vk=(zr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const o=[],s=await tt({provider:"openai",providerOptions:r,schema:gk}),a=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([bn(t)]);a.append("model",this.modelId);const l=GF(n);if(a.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,f]of Object.entries(c))if(f!=null)if(Array.isArray(f))for(const m of f)a.append(`${d}[]`,String(m));else a.append(d,String(f))}return{formData:a,warnings:o}}async doGenerate(t){var n,r,o,s,a,u,l,c;const d=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{formData:f,warnings:m}=await this.getArgs(t),{value:D,responseHeaders:h,rawValue:v}=await Ui({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),formData:f,failedResponseHandler:Tt,successfulResponseHandler:Ke(Dk),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in lD?lD[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(b=>({text:b.text,startSecond:b.start,endSecond:b.end})))!=null?u:(a=D.words)==null?void 0:a.map(b=>({text:b.word,startSecond:b.start,endSecond:b.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:m,response:{timestamp:d,modelId:this.modelId,headers:h,body:v}}}},i(zr,"OpenAITranscriptionModel"),zr),yk="3.0.30";function Xa(e={}){var t,n;const r=(t=Zi(ko({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=i(()=>Cn({Authorization:`Bearer ${VF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${yk}`),"getHeaders"),a=i(v=>new tx(v,{provider:`${o}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new ax(v,{provider:`${o}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new ux(v,{provider:`${o}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new px(v,{provider:`${o}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new vk(v,{provider:`${o}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),f=i(v=>new hk(v,{provider:`${o}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),m=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new tk(v,{provider:`${o}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),h=i(function(v){return m(v)},"provider");return h.specificationVersion="v3",h.languageModel=m,h.chat=a,h.completion=u,h.responses=D,h.embedding=l,h.embeddingModel=l,h.textEmbedding=l,h.textEmbeddingModel=l,h.image=c,h.imageModel=c,h.transcription=d,h.transcriptionModel=d,h.speech=f,h.speechModel=f,h.tools=Wx,h}i(Xa,"createOpenAI"),Xa();var _k=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),Ro={errorSchema:_k,errorToMessage:i(e=>e.error.message,"errorToMessage")};function cD(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(cD,"convertOpenAICompatibleChatUsage");function No(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(No,"getOpenAIMetadata");function bk(e){switch(e){case"audio/wav":return"wav";case"audio/mp3":case"audio/mpeg":return"mp3";default:return null}}i(bk,"getAudioFormat");function Ck(e){var t,n,r;const o=[];for(const{role:s,content:a,...u}of e){const l=No({...u});switch(s){case"system":{o.push({role:"system",content:a,...l});break}case"user":{if(a.length===1&&a[0].type==="text"){o.push({role:"user",content:a[0].text,...No(a[0])});break}o.push({role:"user",content:a.map(c=>{var d;const f=No(c);switch(c.type){case"text":return{type:"text",text:c.text,...f};case"file":{if(c.mediaType.startsWith("image/")){const m=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"image_url",image_url:{url:c.data instanceof URL?c.data.toString():`data:${m};base64,${Lt(c.data)}`},...f}}if(c.mediaType.startsWith("audio/")){if(c.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});const m=bk(c.mediaType);if(m===null)throw new Qe({functionality:`audio media type ${c.mediaType}`});return{type:"input_audio",input_audio:{data:Lt(c.data),format:m},...f}}if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:{filename:(d=c.filename)!=null?d:"document.pdf",file_data:`data:application/pdf;base64,${Lt(c.data)}`},...f}}if(c.mediaType.startsWith("text/"))return{type:"text",text:c.data instanceof URL?c.data.toString():typeof c.data=="string"?c.data:new TextDecoder().decode(c.data),...f};throw new Qe({functionality:`file part media type ${c.mediaType}`})}}}),...l});break}case"assistant":{let c="",d="";const f=[];for(const m of a){const D=No(m);switch(m.type){case"text":{c+=m.text;break}case"reasoning":{d+=m.text;break}case"tool-call":{const h=(n=(t=m.providerOptions)==null?void 0:t.google)==null?void 0:n.thoughtSignature;f.push({id:m.toolCallId,type:"function",function:{name:m.toolName,arguments:JSON.stringify(m.input)},...D,...h?{extra_content:{google:{thought_signature:String(h)}}}:{}});break}}}o.push({role:"assistant",content:c,...d.length>0?{reasoning_content:d}:{},tool_calls:f.length>0?f:void 0,...l});break}case"tool":{for(const c of a){if(c.type==="tool-approval-response")continue;const d=c.output;let f;switch(d.type){case"text":case"error-text":f=d.value;break;case"execution-denied":f=(r=d.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":f=JSON.stringify(d.value);break}const m=No(c);o.push({role:"tool",tool_call_id:c.toolCallId,content:f,...m})}break}default:{const c=s;throw new Error(`Unsupported role: ${c}`)}}}return o}i(Ck,"convertToOpenAICompatibleChatMessages");function dD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(dD,"getResponseMetadata");function pD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(pD,"mapOpenAICompatibleFinishReason");var Qa=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional(),strictJsonSchema:Re().optional()});function wk({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(wk,"prepareTools");var Fk=(Lr=class{constructor(t,n){this.specificationVersion="v3";var r,o;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:Ro;this.chunkSchema=kk(s.errorSchema),this.failedResponseHandler=gt(s),this.supportsStructuredOutputs=(o=n.supportsStructuredOutputs)!=null?o:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}transformRequestBody(t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,t))!=null?o:t}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:f,toolChoice:m,tools:D}){var h,v,y,b,C;const w=[],E=await tt({provider:"openai-compatible",providerOptions:l,schema:Qa});E!=null&&w.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const T=Object.assign(E??{},(h=await tt({provider:"openaiCompatible",providerOptions:l,schema:Qa}))!=null?h:{},(v=await tt({provider:this.providerOptionsName,providerOptions:l,schema:Qa}))!=null?v:{}),O=(y=T?.strictJsonSchema)!=null?y:!0;s!=null&&w.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:I,toolWarnings:re}=wk({tools:D,toolChoice:m});return{args:{model:this.modelId,user:T.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,strict:O,name:(b=d.name)!=null?b:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:f,...Object.fromEntries(Object.entries((C=l?.[this.providerOptionsName])!=null?C:{}).filter(([k])=>!Object.keys(Qa.shape).includes(k))),reasoning_effort:T.reasoningEffort,verbosity:T.textVerbosity,messages:Ck(t),tools:$,tool_choice:I},warnings:[...w,...re]}}async doGenerate(t){var n,r,o,s,a,u,l,c;const{args:d,warnings:f}=await this.getArgs({...t}),m=this.transformRequestBody(d),D=JSON.stringify(m),{responseHeaders:h,value:v,rawValue:y}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:m,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(Ek),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=v.choices[0],C=[],w=b.message.content;w!=null&&w.length>0&&C.push({type:"text",text:w});const E=(n=b.message.reasoning_content)!=null?n:b.message.reasoning;if(E!=null&&E.length>0&&C.push({type:"reasoning",text:E}),b.message.tool_calls!=null)for(const $ of b.message.tool_calls){const I=(o=(r=$.extra_content)==null?void 0:r.google)==null?void 0:o.thought_signature;C.push({type:"tool-call",toolCallId:(s=$.id)!=null?s:Ve(),toolName:$.function.name,input:$.function.arguments,...I?{providerMetadata:{[this.providerOptionsName]:{thoughtSignature:I}}}:{}})}const T={[this.providerOptionsName]:{},...await((u=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:u.call(a,{parsedBody:y}))},O=(l=v.usage)==null?void 0:l.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(T[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(T[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:C,finishReason:{unified:pD(b.finish_reason),raw:(c=b.finish_reason)!=null?c:void 0},usage:cD(v.usage),providerMetadata:T,request:{body:D},response:{...dD(v),headers:h,body:y},warnings:f}}async doStream(t){var n;const{args:r,warnings:o}=await this.getArgs({...t}),s=this.transformRequestBody({...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0}),a=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Jn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},f,m=!0;const D=this.providerOptionsName;let h=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:o})},transform(y,b){var C,w,E,T,O,$,I,re,k,oe,B,P,z,U,R,Y,he,X;if(t.includeRawChunks&&b.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.error});return}if(a?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.value.error.message});return}const pe=y.value;m&&(m=!1,b.enqueue({type:"response-metadata",...dD(pe)})),pe.usage!=null&&(f=pe.usage);const fe=pe.choices[0];if(fe?.finish_reason!=null&&(d={unified:pD(fe.finish_reason),raw:(C=fe.finish_reason)!=null?C:void 0}),fe?.delta==null)return;const H=fe.delta,je=(w=H.reasoning_content)!=null?w:H.reasoning;if(je&&(h||(b.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),b.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:je})),H.content&&(h&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),h=!1),v||(b.enqueue({type:"text-start",id:"txt-0"}),v=!0),b.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null){h&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),h=!1);for(const xe of H.tool_calls){const at=(E=xe.index)!=null?E:c.length;if(c[at]==null){if(xe.id==null)throw new po({data:xe,message:"Expected 'id' to be a string."});if(((T=xe.function)==null?void 0:T.name)==null)throw new po({data:xe,message:"Expected 'function.name' to be a string."});b.enqueue({type:"tool-input-start",id:xe.id,toolName:xe.function.name}),c[at]={id:xe.id,type:"function",function:{name:xe.function.name,arguments:(O=xe.function.arguments)!=null?O:""},hasFinished:!1,thoughtSignature:(re=(I=($=xe.extra_content)==null?void 0:$.google)==null?void 0:I.thought_signature)!=null?re:void 0};const j=c[at];((k=j.function)==null?void 0:k.name)!=null&&((oe=j.function)==null?void 0:oe.arguments)!=null&&(j.function.arguments.length>0&&b.enqueue({type:"tool-input-delta",id:j.id,delta:j.function.arguments}),Ga(j.function.arguments)&&(b.enqueue({type:"tool-input-end",id:j.id}),b.enqueue({type:"tool-call",toolCallId:(B=j.id)!=null?B:Ve(),toolName:j.function.name,input:j.function.arguments,...j.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:j.thoughtSignature}}}:{}}),j.hasFinished=!0));continue}const Ae=c[at];Ae.hasFinished||(((P=xe.function)==null?void 0:P.arguments)!=null&&(Ae.function.arguments+=(U=(z=xe.function)==null?void 0:z.arguments)!=null?U:""),b.enqueue({type:"tool-input-delta",id:Ae.id,delta:(R=xe.function.arguments)!=null?R:""}),((Y=Ae.function)==null?void 0:Y.name)!=null&&((he=Ae.function)==null?void 0:he.arguments)!=null&&Ga(Ae.function.arguments)&&(b.enqueue({type:"tool-input-end",id:Ae.id}),b.enqueue({type:"tool-call",toolCallId:(X=Ae.id)!=null?X:Ve(),toolName:Ae.function.name,input:Ae.function.arguments,...Ae.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:Ae.thoughtSignature}}}:{}}),Ae.hasFinished=!0))}}},flush(y){var b,C,w,E,T;h&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const $ of c.filter(I=>!I.hasFinished))y.enqueue({type:"tool-input-end",id:$.id}),y.enqueue({type:"tool-call",toolCallId:(b=$.id)!=null?b:Ve(),toolName:$.function.name,input:$.function.arguments,...$.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:$.thoughtSignature}}}:{}});const O={[D]:{},...a?.buildMetadata()};((C=f?.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens)!=null&&(O[D].acceptedPredictionTokens=(w=f?.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens),((E=f?.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens)!=null&&(O[D].rejectedPredictionTokens=(T=f?.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:cD(f),providerMetadata:O})}})),request:{body:s},response:{headers:u}}}},i(Lr,"OpenAICompatibleChatLanguageModel"),Lr),fD=Ci({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish(),Ek=Ci({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:F("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({id:p().nullish(),function:g({name:p(),arguments:p()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}),finish_reason:p().nullish()})),usage:fD}),xk=Ci({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({index:x().nullish(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:fD}),kk=i(e=>ee([xk,e]),"createOpenAICompatibleChatChunkSchema");function mD(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:o,text:o,reasoning:void 0},raw:e}}i(mD,"convertOpenAICompatibleCompletionUsage");function Ik({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
164
164
 
165
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Gt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
165
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Ht({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
166
166
  ${a}
167
167
 
168
168
  `;break}case"assistant":{const a=s.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new Qe({functionality:"tool-call messages"})}}).join("");r+=`${n}:
@@ -170,39 +170,40 @@ ${a}
170
170
 
171
171
  `;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
172
172
  `,{prompt:r,stopSequences:[`
173
- ${t}:`]}}i(xk,"convertToOpenAICompatibleCompletionPrompt");function pD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(pD,"getResponseMetadata2");function fD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(fD,"mapOpenAICompatibleFinishReason2");var kk=g({echo:Re().optional(),logitBias:be(p(),x()).optional(),suffix:p().optional(),user:p().optional()}),Ik=(jr=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const o=(r=n.errorStructure)!=null?r:To;this.chunkSchema=$k(o.errorSchema),this.failedResponseHandler=Dt(o)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:f,tools:h,toolChoice:D}){var m;const v=[],y=(m=await tt({provider:this.providerOptionsName,providerOptions:f,schema:kk}))!=null?m:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),h?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:C}=xk({prompt:t}),w=[...C??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:d,...f?.[this.providerOptionsName],prompt:b,stop:w.length>0?w:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:o,value:s,rawValue:a}=await Le({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(Ak),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:dD(s.usage),finishReason:{unified:fD(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...pD(s),headers:o,body:a},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await Le({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Gn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,f){var h;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...pD(D)}),f.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:fD(m.finish_reason),raw:(h=m.finish_reason)!=null?h:void 0}),m?.text!=null&&f.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:dD(l)})}})),request:{body:o},response:{headers:s}}}},i(jr,"OpenAICompatibleCompletionLanguageModel"),jr),mD=g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}),Ak=g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p()})),usage:mD.nullish()}),$k=i(e=>ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x()})),usage:mD.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),mu=g({dimensions:x().optional(),user:p().optional()}),Tk=(zr=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s,a,u;const l=[],c=await tt({provider:"openai-compatible",providerOptions:o,schema:mu});c!=null&&l.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const d=Object.assign(c??{},(s=await tt({provider:"openaiCompatible",providerOptions:o,schema:mu}))!=null?s:{},(a=await tt({provider:this.providerOptionsName,providerOptions:o,schema:mu}))!=null?a:{});if(t.length>this.maxEmbeddingsPerCall)throw new rp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:f,value:h,rawValue:D}=await Le({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:d.dimensions,user:d.user},failedResponseHandler:Dt((u=this.config.errorStructure)!=null?u:To),successfulResponseHandler:Ke(Sk),abortSignal:r,fetch:this.config.fetch});return{warnings:l,embeddings:h.data.map(m=>m.embedding),usage:h.usage?{tokens:h.usage.prompt_tokens}:void 0,providerMetadata:h.providerMetadata,response:{headers:f,body:D}}}},i(zr,"OpenAICompatibleEmbeddingModel"),zr),Sk=g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish(),providerMetadata:be(p(),be(p(),et())).optional()}),Bk=(qr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}get providerOptionsKey(){return this.config.provider.split(".")[0].trim()}getArgs(t){return{...t[this.providerOptionsKey],...t[Ok(this.providerOptionsKey)]}}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,providerOptions:a,headers:u,abortSignal:l,files:c,mask:d}){var f,h,D,m,v;const y=[];o!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported",feature:"seed"});const b=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date,C=this.getArgs(a);if(c!=null&&c.length>0){const{value:T,responseHeaders:O}=await zi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),u),formData:pf({model:this.modelId,prompt:t,image:await Promise.all(c.map($=>DD($))),mask:d!=null?await DD(d):void 0,n,size:r,...C}),failedResponseHandler:Dt((m=this.config.errorStructure)!=null?m:To),successfulResponseHandler:Ke(hD),abortSignal:l,fetch:this.config.fetch});return{images:T.data.map($=>$.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:O}}}const{value:w,responseHeaders:E}=await Le({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...C,response_format:"b64_json"},failedResponseHandler:Dt((v=this.config.errorStructure)!=null?v:To),successfulResponseHandler:Ke(hD),abortSignal:l,fetch:this.config.fetch});return{images:w.data.map(T=>T.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:E}}}},i(qr,"OpenAICompatibleImageModel"),qr),hD=g({data:S(g({b64_json:p()}))});async function DD(e){if(e.type==="url")return Si(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(DD,"fileToBlob");function Ok(e){return e.replace(/[_-]([a-z])/g,t=>t[1].toUpperCase())}i(Ok,"toCamelCase");var Rk="2.0.30";function hu(e){const t=qi(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},o=i(()=>Dn(r,`ai-sdk/openai-compatible/${Rk}`),"getHeaders"),s=i(h=>({provider:`${n}.${h}`,url:i(({path:D})=>{const m=new URL(`${t}${D}`);return e.queryParams&&(m.search=new URLSearchParams(e.queryParams).toString()),m.toString()},"url"),headers:o,fetch:e.fetch}),"getCommonModelConfig"),a=i(h=>u(h),"createLanguageModel"),u=i(h=>new Ck(h,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs,transformRequestBody:e.transformRequestBody,metadataExtractor:e.metadataExtractor}),"createChatModel"),l=i(h=>new Ik(h,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(h=>new Tk(h,{...s("embedding")}),"createEmbeddingModel"),d=i(h=>new Bk(h,s("image")),"createImageModel"),f=i(h=>a(h),"provider");return f.specificationVersion="v3",f.languageModel=a,f.chatModel=u,f.completionModel=l,f.embeddingModel=c,f.textEmbeddingModel=c,f.imageModel=d,f}i(hu,"createOpenAICompatible");const Nk={plain:"<commit message>",conventional:`<type>[optional (<scope>)]: <commit message>
174
- The commit message subject must start with a lowercase letter`,gitmoji:":emoji: <commit message>"},Pk=i(e=>`The output response must be in format:
175
- ${Nk[e]}`,"specifyCommitFormat"),Mk={plain:"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff. IMPORTANT: The type MUST be lowercase (e.g., "feat", not "Feat" or "FEAT"):
173
+ ${t}:`]}}i(Ik,"convertToOpenAICompatibleCompletionPrompt");function hD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(hD,"getResponseMetadata2");function DD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(DD,"mapOpenAICompatibleFinishReason2");var Ak=g({echo:Re().optional(),logitBias:Ce(p(),x()).optional(),suffix:p().optional(),user:p().optional()}),$k=(qr=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const o=(r=n.errorStructure)!=null?r:Ro;this.chunkSchema=Sk(o.errorSchema),this.failedResponseHandler=gt(o)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:f,tools:m,toolChoice:D}){var h;const v=[],y=(h=await tt({provider:this.providerOptionsName,providerOptions:f,schema:Ak}))!=null?h:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),m?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:C}=Ik({prompt:t}),w=[...C??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:d,...f?.[this.providerOptionsName],prompt:b,stop:w.length>0?w:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:o,value:s,rawValue:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(Tk),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:mD(s.usage),finishReason:{unified:DD(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...hD(s),headers:o,body:a},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Jn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,f){var m;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...hD(D)}),f.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const h=D.choices[0];h?.finish_reason!=null&&(u={unified:DD(h.finish_reason),raw:(m=h.finish_reason)!=null?m:void 0}),h?.text!=null&&f.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:mD(l)})}})),request:{body:o},response:{headers:s}}}},i(qr,"OpenAICompatibleCompletionLanguageModel"),qr),gD=g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}),Tk=g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p()})),usage:gD.nullish()}),Sk=i(e=>ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x()})),usage:gD.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),gu=g({dimensions:x().optional(),user:p().optional()}),Bk=(Ur=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s,a,u;const l=[],c=await tt({provider:"openai-compatible",providerOptions:o,schema:gu});c!=null&&l.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const d=Object.assign(c??{},(s=await tt({provider:"openaiCompatible",providerOptions:o,schema:gu}))!=null?s:{},(a=await tt({provider:this.providerOptionsName,providerOptions:o,schema:gu}))!=null?a:{});if(t.length>this.maxEmbeddingsPerCall)throw new sp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:f,value:m,rawValue:D}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:d.dimensions,user:d.user},failedResponseHandler:gt((u=this.config.errorStructure)!=null?u:Ro),successfulResponseHandler:Ke(Ok),abortSignal:r,fetch:this.config.fetch});return{warnings:l,embeddings:m.data.map(h=>h.embedding),usage:m.usage?{tokens:m.usage.prompt_tokens}:void 0,providerMetadata:m.providerMetadata,response:{headers:f,body:D}}}},i(Ur,"OpenAICompatibleEmbeddingModel"),Ur),Ok=g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish(),providerMetadata:Ce(p(),Ce(p(),et())).optional()}),Rk=(Zr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}get providerOptionsKey(){return this.config.provider.split(".")[0].trim()}getArgs(t){return{...t[this.providerOptionsKey],...t[Nk(this.providerOptionsKey)]}}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,providerOptions:a,headers:u,abortSignal:l,files:c,mask:d}){var f,m,D,h,v;const y=[];o!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported",feature:"seed"});const b=(D=(m=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:m.call(f))!=null?D:new Date,C=this.getArgs(a);if(c!=null&&c.length>0){const{value:T,responseHeaders:O}=await Ui({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),u),formData:hf({model:this.modelId,prompt:t,image:await Promise.all(c.map($=>yD($))),mask:d!=null?await yD(d):void 0,n,size:r,...C}),failedResponseHandler:gt((h=this.config.errorStructure)!=null?h:Ro),successfulResponseHandler:Ke(vD),abortSignal:l,fetch:this.config.fetch});return{images:T.data.map($=>$.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:O}}}const{value:w,responseHeaders:E}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...C,response_format:"b64_json"},failedResponseHandler:gt((v=this.config.errorStructure)!=null?v:Ro),successfulResponseHandler:Ke(vD),abortSignal:l,fetch:this.config.fetch});return{images:w.data.map(T=>T.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:E}}}},i(Zr,"OpenAICompatibleImageModel"),Zr),vD=g({data:S(g({b64_json:p()}))});async function yD(e){if(e.type==="url")return Ri(e.url);const t=e.data instanceof Uint8Array?e.data:bn(e.data);return new Blob([t],{type:e.mediaType})}i(yD,"fileToBlob");function Nk(e){return e.replace(/[_-]([a-z])/g,t=>t[1].toUpperCase())}i(Nk,"toCamelCase");var Pk="2.0.30";function vu(e){const t=Zi(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},o=i(()=>Cn(r,`ai-sdk/openai-compatible/${Pk}`),"getHeaders"),s=i(m=>({provider:`${n}.${m}`,url:i(({path:D})=>{const h=new URL(`${t}${D}`);return e.queryParams&&(h.search=new URLSearchParams(e.queryParams).toString()),h.toString()},"url"),headers:o,fetch:e.fetch}),"getCommonModelConfig"),a=i(m=>u(m),"createLanguageModel"),u=i(m=>new Fk(m,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs,transformRequestBody:e.transformRequestBody,metadataExtractor:e.metadataExtractor}),"createChatModel"),l=i(m=>new $k(m,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(m=>new Bk(m,{...s("embedding")}),"createEmbeddingModel"),d=i(m=>new Rk(m,s("image")),"createImageModel"),f=i(m=>a(m),"provider");return f.specificationVersion="v3",f.languageModel=a,f.chatModel=u,f.completionModel=l,f.embeddingModel=c,f.textEmbeddingModel=c,f.imageModel=d,f}i(vu,"createOpenAICompatible");const Mk={plain:"<commit message>",conventional:`<type>[optional (<scope>)]: <commit message>
174
+ The commit message subject must start with a lowercase letter`,gitmoji:":emoji: <commit message>"},jk=i(e=>`The output response must be in format:
175
+ ${Mk[e]}`,"specifyCommitFormat"),zk={plain:"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff. IMPORTANT: The type MUST be lowercase (e.g., "feat", not "Feat" or "FEAT"):
176
176
  ${JSON.stringify({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that improves code structure without changing functionality (renaming, restructuring classes/methods, extracting functions, etc)",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to our CI configuration files and scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"},null,2)}`,gitmoji:`Choose an emoji from the emoji-to-description JSON below that best describes the git diff:
177
- ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},jk=i((e,t,n,r)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",r,Mk[n],Pk(n)].filter(Boolean).join(`
178
- `),"generatePrompt"),Ha=i(()=>!process.stdin.isTTY||!process.stdout.isTTY,"isHeadless"),Bo=i(()=>!!(process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI),"isInteractive"),zk=i(()=>!!(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&!Ha(),"shouldLogDebug"),qk=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),Du=i(e=>qk(e).trim().split(`
179
- `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),gD=i(e=>Array.from(new Set(e)),"deduplicateMessages"),vD=i(async(e,t,n,r,o)=>{const s=new AbortController,a=setTimeout(()=>s.abort(),o);try{const u=await $o({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500,abortSignal:s.signal});return clearTimeout(a),Du(u.text)}catch(u){throw clearTimeout(a),u}},"shortenCommitMessage"),gu=i(async(e,t,n,r,o,s,a,u,l,c,d)=>{zk()&&(console.log("Diff being sent to AI:"),console.log(o));try{const f=e==="https://api.openai.com/v1"?Ga({apiKey:t}):hu({name:"custom",apiKey:t,baseURL:e,headers:d}),h=new AbortController,D=setTimeout(()=>h.abort(),l),m=Array.from({length:s},()=>$o({model:f(n),system:jk(r,a,u,c),prompt:o,temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:h.signal})),v=await(async()=>{try{return await Promise.all(m)}finally{clearTimeout(D)}})();let y=v.map(E=>E.text),b=gD(y.map(E=>Du(E)));const C=3;for(let E=0;E<C;E++){let T=!1;const O=await Promise.all(b.map(async $=>{if($.length<=a)return $;T=!0;try{return await vD(f,n,$,a,l)}catch{return $}}));if(b=gD(O),!T)break}const w={prompt_tokens:v.reduce((E,T)=>E+(T.usage.promptTokens||0),0),completion_tokens:v.reduce((E,T)=>E+(T.usage.completionTokens||0),0),total_tokens:v.reduce((E,T)=>E+(T.usage.totalTokens||0),0)};return{messages:b,usage:w}}catch(f){const h=f;if(h.code==="ENOTFOUND")throw new pe(`Error connecting to ${h.hostname} (${h.syscall}). Are you connected to the internet?`);if(h.status===429){const D=h.headers?.get("x-ratelimit-reset");let m="Rate limit exceeded";if(D){const v=parseInt(D),y=Date.now(),b=v-y,C=Math.ceil(b/1e3);if(C>0){let w;if(C<60)w=`${C} second${C===1?"":"s"}`;else if(C<3600){const E=Math.ceil(C/60);w=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(C/3600);w=`${E} hour${E===1?"":"s"}`}m+=`. Retry in ${w}.`}}throw new pe(m)}throw h}},"generateCommitMessage"),Lk=i(async(e,t,n,r,o,s,a,u,l,c)=>{try{const d=t==="https://api.openai.com/v1"?Ga({apiKey:n}):hu({name:"custom",apiKey:n,baseURL:t,headers:c}),f=new AbortController,h=setTimeout(()=>f.abort(),u),m=await $o({model:d(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
177
+ ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},Lk=i((e,t,n,r)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",r,zk[n],jk(n)].filter(Boolean).join(`
178
+ `),"generatePrompt"),es=i(()=>!process.stdin.isTTY||!process.stdout.isTTY,"isHeadless"),Po=i(()=>!!(process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI),"isInteractive"),qk=i(()=>!!(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&!es(),"shouldLogDebug"),Uk=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),yu=i(e=>Uk(e).trim().split(`
179
+ `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),_D=i(e=>Array.from(new Set(e)),"deduplicateMessages"),bD=i(async(e,t,n,r,o)=>{const s=new AbortController,a=setTimeout(()=>s.abort(),o);try{const u=await Oo({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500,abortSignal:s.signal});return clearTimeout(a),yu(u.text)}catch(u){throw clearTimeout(a),u}},"shortenCommitMessage"),_u=i(async({baseUrl:e,apiKey:t,model:n,locale:r,diff:o,completions:s,maxLength:a,type:u,timeout:l,customPrompt:c,headers:d})=>{qk()&&(console.log("Diff being sent to AI:"),console.log(o));try{const f=e==="https://api.openai.com/v1"?Xa({apiKey:t}):vu({name:"custom",apiKey:t,baseURL:e,headers:d}),m=new AbortController,D=setTimeout(()=>m.abort(),l),h=Array.from({length:s},()=>Oo({model:f(n),system:Lk(r,a,u,c),prompt:o,temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:m.signal})),v=await(async()=>{try{return await Promise.all(h)}finally{clearTimeout(D)}})();let y=v.map(E=>E.text),b=_D(y.map(E=>yu(E)));const C=3;for(let E=0;E<C;E++){let T=!1;const O=await Promise.all(b.map(async $=>{if($.length<=a)return $;T=!0;try{return await bD(f,n,$,a,l)}catch{return $}}));if(b=_D(O),!T)break}const w={prompt_tokens:v.reduce((E,T)=>E+(T.usage.promptTokens||0),0),completion_tokens:v.reduce((E,T)=>E+(T.usage.completionTokens||0),0),total_tokens:v.reduce((E,T)=>E+(T.usage.totalTokens||0),0)};return{messages:b,usage:w}}catch(f){const m=f;if(m.name==="AbortError"||m.message?.includes("aborted")||m.message?.includes("This operation was aborted"))throw new ce(`Request timed out after ${l/1e3} seconds. The API took too long to respond. Try again or use a different model.`);if(m.code==="ENOTFOUND")throw new ce(`Error connecting to ${m.hostname} (${m.syscall}). Are you connected to the internet?`);if(m.status===429){const D=m.headers?.get("x-ratelimit-reset");let h="Rate limit exceeded";if(D){const v=parseInt(D),y=Date.now(),b=v-y,C=Math.ceil(b/1e3);if(C>0){let w;if(C<60)w=`${C} second${C===1?"":"s"}`;else if(C<3600){const E=Math.ceil(C/60);w=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(C/3600);w=`${E} hour${E===1?"":"s"}`}h+=`. Retry in ${w}.`}}throw new ce(h)}throw m}},"generateCommitMessage"),Zk=i(async({messages:e,baseUrl:t,apiKey:n,model:r,locale:o,maxLength:s,type:a,timeout:u,customPrompt:l,headers:c})=>{try{const d=t==="https://api.openai.com/v1"?Xa({apiKey:n}):vu({name:"custom",apiKey:n,baseURL:t,headers:c}),f=new AbortController,m=setTimeout(()=>f.abort(),u),h=await Oo({model:d(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
180
180
 
181
181
  Input: Several commit messages separated by newlines.
182
182
  Output: A single commit message starting with type like 'feat:' or 'fix:'.
183
183
 
184
184
  Do not add thanks, explanations, or any text outside the commit message.`,prompt:e.join(`
185
- `),temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:f.signal});clearTimeout(h);let v=Du(m.text);if(v.length>s)try{v=await vD(d,r,v,s,u)}catch{}return{messages:[v],usage:m.usage}}catch(d){throw d}},"combineCommitMessages"),Uk=i(async(e,t)=>{const{select:n,confirm:r,isCancel:o}=await Promise.resolve().then(function(){return oo}),{dim:s}=await Promise.resolve().then(function(){return Ty});if(e.length===1){const[u]=e;if(t)return u;if(!Bo())throw new pe("Interactive terminal required for commit message confirmation. Use --yes flag to skip confirmation.");console.log(`
185
+ `),temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:f.signal});clearTimeout(m);let v=yu(h.text);if(v.length>s)try{v=await bD(d,r,v,s,u)}catch{}return{messages:[v],usage:h.usage}}catch(d){const f=d;throw f.name==="AbortError"||f.message?.includes("aborted")||f.message?.includes("This operation was aborted")?new ce(`Request timed out after ${u/1e3} seconds. The API took too long to respond. Try again or use a different model.`):f}},"combineCommitMessages"),Vk=i(async(e,t)=>{const{select:n,confirm:r,isCancel:o}=await Promise.resolve().then(function(){return uo}),{dim:s}=await Promise.resolve().then(function(){return By});if(e.length===1){const[u]=e;if(t)return u;if(!Po())throw new ce("Interactive terminal required for commit message confirmation. Use --yes flag to skip confirmation.");console.log(`
186
186
  \x1B[1m${u}\x1B[0m
187
- `);const l=await r({message:"Use this commit message?"});return l&&!o(l)?u:null}if(t)return e[0];if(!Bo())throw new pe("Interactive terminal required for commit message selection. Use --yes flag to skip selection and use the first message.");const a=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(u=>({label:u,value:u}))});return o(a)?null:a},"getCommitMessage");var Zk=i(async(e,t,n,r,o,s,a,u,l)=>(async()=>{const c=Ha();c||oa(Xo(Yo(" aicommits "))),await ti(),n&&await Je("git",["add","--update"]);const d=await dd(t);if(!d)throw new pe("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");if(!c){const I=Vt();d.files.length<=10?(I.start("Detecting staged files"),I.stop(`\u{1F4C1} ${pd(d.files)}:
187
+ `);const l=await r({message:"Use this commit message?"});return l&&!o(l)?u:null}if(t)return e[0];if(!Po())throw new ce("Interactive terminal required for commit message selection. Use --yes flag to skip selection and use the first message.");const a=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(u=>({label:u,value:u}))});return o(a)?null:a},"getCommitMessage");var Gk=i(async(e,t,n,r,o,s,a,u,l)=>(async()=>{const c=es();c||ca(oa(ta(" aicommits "))),await oi(),n&&await Je("git",["add","--update"]);const d=await md(t);if(!d)throw new ce("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");if(!c){const I=Ot();d.files.length<=10?(I.start("Detecting staged files"),I.stop(`\u{1F4C1} ${hd(d.files)}:
188
188
  ${d.files.map(re=>` ${re}`).join(`
189
- `)}`)):(I.start("Detecting staged files"),I.stop(`\u{1F4C1} ${pd(d.files)}`))}const{env:f}=process,h=await ln({generate:e?.toString(),type:r?.toString()}),D=Nn(h);if(!D){if(c)throw new pe("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),Ee("Setup required. Please run: aicommits setup");return}const m=h.timeout||(D.name==="ollama"?3e4:1e4),v=D.validateConfig();if(!v.valid)throw new pe(`Provider configuration issues: ${v.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);h.model=h.OPENAI_MODEL||D.getDefaultModel();const y=50,b=10;let C=!1;d.files.length>y&&(C=!0);const w=c?null:Vt();w&&w.start(`\u{1F50D} Analyzing changes in ${d.files.length} file${d.files.length===1?"":"s"}`);const E=Date.now();let T,O;try{const I=D.getBaseUrl(),re=D.getApiKey()||"",k=D.getHeaders();if(C){const oe=[];for(let U=0;U<d.files.length;U+=b)oe.push(d.files.slice(U,U+b));const B=[];let P={prompt_tokens:0,completion_tokens:0,total_tokens:0};for(const U of oe){const R=await h0(U,t);if(R&&R.diff){let he=R.diff;he.length>3e4&&(he=he.substring(0,3e4)+`
189
+ `)}`)):(I.start("Detecting staged files"),I.stop(`\u{1F4C1} ${hd(d.files)}`))}const{env:f}=process,m=await hn({generate:e?.toString(),type:r?.toString()}),D=jn(m);if(!D){if(c)throw new ce("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),be("Setup required. Please run: aicommits setup");return}const h=m.timeout||(D.name==="ollama"?3e4:1e4),v=D.validateConfig();if(!v.valid)throw new ce(`Provider configuration issues: ${v.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);m.model=m.OPENAI_MODEL||D.getDefaultModel();const y=50,b=10;let C=!1;d.files.length>y&&(C=!0);const w=c?null:Ot();w&&w.start(`\u{1F50D} Analyzing changes in ${d.files.length} file${d.files.length===1?"":"s"}`);const E=Date.now();let T,O;try{const I=D.getBaseUrl(),re=D.getApiKey()||"",k=D.getHeaders();if(C){const oe=[];for(let U=0;U<d.files.length;U+=b)oe.push(d.files.slice(U,U+b));const B=[];let P={prompt_tokens:0,completion_tokens:0,total_tokens:0};for(const U of oe){const R=await g0(U,t);if(R&&R.diff){let he=R.diff;he.length>3e4&&(he=he.substring(0,3e4)+`
190
190
 
191
- [Diff truncated due to size]`);const X=await gu(I,re,h.model,h.locale,he,h.generate,h["max-length"],h.type,m,u,k);B.push(...X.messages),X.usage&&(P.prompt_tokens+=X.usage.prompt_tokens||X.usage.promptTokens||0,P.completion_tokens+=X.usage.completion_tokens||X.usage.completionTokens||0,P.total_tokens+=X.usage.total_tokens||X.usage.totalTokens||0)}}const z=await Lk(B,I,re,h.model,h.locale,h["max-length"],h.type,m,u,k);T=z.messages,z.usage&&(P.prompt_tokens+=z.usage.prompt_tokens||z.usage.promptTokens||0,P.completion_tokens+=z.usage.completion_tokens||z.usage.completionTokens||0,P.total_tokens+=z.usage.total_tokens||z.usage.totalTokens||0),O=P}else{let B=d.diff;B.length>3e4&&(B=B.substring(0,3e4)+`
191
+ [Diff truncated due to size]`);const X=await _u({baseUrl:I,apiKey:re,model:m.model,locale:m.locale,diff:he,completions:m.generate,maxLength:m["max-length"],type:m.type,timeout:h,customPrompt:u,headers:k});B.push(...X.messages),X.usage&&(P.prompt_tokens+=X.usage.prompt_tokens||X.usage.promptTokens||0,P.completion_tokens+=X.usage.completion_tokens||X.usage.completionTokens||0,P.total_tokens+=X.usage.total_tokens||X.usage.totalTokens||0)}}const z=await Zk({messages:B,baseUrl:I,apiKey:re,model:m.model,locale:m.locale,maxLength:m["max-length"],type:m.type,timeout:h,customPrompt:u,headers:k});T=z.messages,z.usage&&(P.prompt_tokens+=z.usage.prompt_tokens||z.usage.promptTokens||0,P.completion_tokens+=z.usage.completion_tokens||z.usage.completionTokens||0,P.total_tokens+=z.usage.total_tokens||z.usage.totalTokens||0),O=P}else{let B=d.diff;B.length>3e4&&(B=B.substring(0,3e4)+`
192
192
 
193
- [Diff truncated due to size]`);const P=await gu(I,re,h.model,h.locale,B,h.generate,h["max-length"],h.type,m,u,k);T=P.messages,O=P.usage}}finally{if(w){const I=Date.now()-E;let re="";if(O?.total_tokens){const k=O.total_tokens,oe=k>=1e3?`${(k/1e3).toFixed(0)}k`:k.toString(),B=Math.round(k/(I/1e3));re=`, ${oe} tokens (${B} tokens/s)`}w.stop(`\u2705 Changes analyzed in ${(I/1e3).toFixed(1)}s${re}`)}}if(T.length===0)throw new pe("No commit messages were generated. Try again.");if(c){const I=T[0];console.log(I);return}const $=await Uk(T,o);if(!$){Ee("Commit cancelled");return}if(s){await Lc($)&&Ee(`${St("\u2714")} Message copied to clipboard`);return}try{const I=["-m",$];a&&I.push("--no-verify"),await Je("git",["commit",...I,...l],{stdio:"inherit",cleanup:!0,timeout:1e4}),Ee(`${St("\u2714")} Successfully committed!`)}catch(I){if(I.timedOut){const re=await Lc($);Ee(re?`${Ms("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${Ms("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw I}})().catch(Rn),"aicommits");const[Ja,Vk]=process.argv.slice(2);var Gk=i(()=>(async()=>{if(!Ja)throw new pe('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(Vk)return;const e=await dd();if(!e)return;const t=Ha();t||oa(Xo(Yo(" aicommits ")));const n=await ln({}),r=Nn(n);if(!r)throw new pe("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const o=r.validateConfig();if(!o.valid)throw new pe(`Provider configuration issues: ${o.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const s=r.getBaseUrl(),a=r.getApiKey()||"",u=r.getHeaders(),l=n.timeout||(r.name==="ollama"?3e4:1e4);let c=n.OPENAI_MODEL||r.getDefaultModel();const d=t?null:Vt();d?.start("The AI is analyzing your changes");let f;try{f=(await gu(s,a,c,n.locale,e.diff,n.generate,n["max-length"],n.type,l,void 0,u)).messages}finally{d?.stop("Changes analyzed")}const D=await He.readFile(Ja,"utf8")!=="",m=f.length>1;let v="";D&&(v=`# \u{1F916} AI generated commit${m?"s":""}
194
- `),m?(D&&(v+=`# Select one of the following messages by uncommenting:
193
+ [Diff truncated due to size]`);const P=await _u({baseUrl:I,apiKey:re,model:m.model,locale:m.locale,diff:B,completions:m.generate,maxLength:m["max-length"],type:m.type,timeout:h,customPrompt:u,headers:k});T=P.messages,O=P.usage}}finally{if(w){const I=Date.now()-E;w.stop(`\u2705 Changes analyzed in ${(I/1e3).toFixed(1)}s`)}}if(T.length===0)throw new ce("No commit messages were generated. Try again.");if(c){const I=T[0];console.log(I);return}const $=await Vk(T,o);if(!$){be("Commit cancelled");return}if(s){await Vc($)&&be(`${it("\u2714")} Message copied to clipboard`);return}try{const I=["-m",$];a&&I.push("--no-verify"),await Je("git",["commit",...I,...l],{stdio:"inherit",cleanup:!0,timeout:1e4}),be(`${it("\u2714")} Successfully committed!`)}catch(I){if(I.timedOut){const re=await Vc($);be(re?`${na("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${na("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw I.exitCode!==void 0&&(be(`${Wt("\u2718")} Commit failed. This may be due to pre-commit hooks.`),console.error(` ${so("Use")} --no-verify ${so("to bypass pre-commit hooks")}`),process.exit(1)),I}})().catch(mn),"aicommits");const[ts,Wk]=process.argv.slice(2);var Hk=i(()=>(async()=>{if(!ts)throw new ce('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(Wk)return;const e=await md();if(!e)return;const t=es();t||ca(oa(ta(" aicommits ")));const n=await hn({}),r=jn(n);if(!r)throw new ce("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const o=r.validateConfig();if(!o.valid)throw new ce(`Provider configuration issues: ${o.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const s=r.getBaseUrl(),a=r.getApiKey()||"",u=r.getHeaders(),l=n.timeout||(r.name==="ollama"?3e4:1e4);let c=n.OPENAI_MODEL||r.getDefaultModel();const d=t?null:Ot();d?.start("The AI is analyzing your changes");let f;try{f=(await _u({baseUrl:s,apiKey:a,model:c,locale:n.locale,diff:e.diff,completions:n.generate,maxLength:n["max-length"],type:n.type,timeout:l,headers:u})).messages}finally{d?.stop("Changes analyzed")}const D=await He.readFile(ts,"utf8")!=="",h=f.length>1;let v="";D&&(v=`# \u{1F916} AI generated commit${h?"s":""}
194
+ `),h?(D&&(v+=`# Select one of the following messages by uncommenting:
195
195
  `),v+=`
196
196
  ${f.map(C=>`# ${C}`).join(`
197
197
  `)}`):(D&&(v+=`# Edit the message below and commit:
198
198
  `),v+=`
199
199
  ${f[0]}
200
- `);const y=await He.readFile(Ja,"utf8"),b=v+`
201
- `+y;await He.writeFile(Ja,b),t||Ee(`${St("\u2714")} Saved commit message!`)})().catch(Rn),"prepareCommitMessageHook"),Wk=An({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await ln({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await ln({},{},!0),o=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(oi(r,s)){const a=r[s],u=o.includes(s)?`${String(a).substring(0,4)}****`:String(a);console.log(`${s}=${u}`)}return}if(t==="set"){await si(n.map(r=>r.split("=")));return}throw new pe(`Invalid mode: ${t}`)})().catch(Rn)}),Hk=An({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{if(!Bo())throw new pe("Interactive terminal required for setup. Run `aicommits setup` in a terminal.");let t=await ln();const n=q0(),r=await Qs({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Bn(r)){Ee("Setup cancelled");return}const o=r;let s="";if(o==="custom"){const D=await id({message:"Enter your custom API endpoint:",validate:i(m=>{if(!m)return"Endpoint is required";try{new URL(m)}catch{return"Invalid URL format"}},"validate")});if(Bn(D)){Ee("Setup cancelled");return}s=D}let a=s||L0(o);t.OPENAI_BASE_URL=a,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=Nn({...t,provider:o});if(!u){Ee("Invalid provider selected");return}try{const D=await u.setup();for(const[m,v]of D)t[m]=v}catch(D){if(D instanceof Error&&D.message==="Setup cancelled"){Ee("Setup cancelled");return}throw D}if(u=Nn({...t,provider:o}),!u){Ee("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){Ee(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return M0}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{Ee("Model selection cancelled.");return}const f=await Qs({message:"Choose commit message format:",options:[{value:"plain",label:"Plain - Simple format without structure"},{value:"conventional",label:"Conventional - Standard conventional commits"},{value:"gitmoji",label:"Gitmoji - Using emojis for commit types"}],initialValue:"plain"});if(Bn(f)){Ee("Setup cancelled");return}t.type=f;const h=Object.entries(t).filter(([D,m])=>D!=="provider"&&D!=="model"&&m!==void 0&&m!==""&&typeof m=="string");await si(h),Ee(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(Rn)}),Jk=An({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{if(!Bo())throw new pe("Interactive terminal required for model selection.");const e=await ln();if(!e.provider){Ee("No provider configured. Run `aicommits setup` first.");return}const t=Nn(e);if(!t){Ee("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}const n=e.OPENAI_MODEL,r=t.validateConfig();if(!r.valid){Ee(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const o=await yd(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition(),t.displayName);o?(await si([["OPENAI_MODEL",o]]),Ee(`\u2705 Model updated to: ${o}`)):Ee("Model selection cancelled")})().catch(Rn)});const yD="prepare-commit-msg",_D=`.git/hooks/${yD}`,Ka=JD(new URL("cli.mjs",import.meta.url)),bD=process.argv[1].replace(/\\/g,"/").endsWith(`/${_D}`),CD=process.platform==="win32",wD=`
200
+ `);const y=await He.readFile(ts,"utf8"),b=v+`
201
+ `+y;await He.writeFile(ts,b),t||be(`${it("\u2714")} Saved commit message!`)})().catch(mn),"prepareCommitMessageHook"),Jk=sn({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await hn({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await hn({},{},!0),o=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(ii(r,s)){const a=r[s],u=o.includes(s)?`${String(a).substring(0,4)}****`:String(a);console.log(`${s}=${u}`)}return}if(t==="set"){await li(n.map(r=>r.split("=")));return}throw new ce(`Invalid mode: ${t}`)})().catch(mn)}),Kk=sn({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{if(!Po())throw new ce("Interactive terminal required for setup. Run `aicommits setup` in a terminal.");let t=await hn();const n=U0(),r=await ni({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Pn(r)){be("Setup cancelled");return}const o=r;let s="";if(o==="custom"){const D=await cd({message:"Enter your custom API endpoint:",validate:i(h=>{if(!h)return"Endpoint is required";try{new URL(h)}catch{return"Invalid URL format"}},"validate")});if(Pn(D)){be("Setup cancelled");return}s=D}let a=s||Z0(o);t.OPENAI_BASE_URL=a,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=jn({...t,provider:o});if(!u){be("Invalid provider selected");return}try{const D=await u.setup();for(const[h,v]of D)t[h]=v}catch(D){if(D instanceof Error&&D.message==="Setup cancelled"){be("Setup cancelled");return}throw D}if(u=jn({...t,provider:o}),!u){be("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){be(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return z0}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{be("Model selection cancelled.");return}const f=await ni({message:"Choose commit message format:",options:[{value:"plain",label:"Plain - Simple format without structure"},{value:"conventional",label:"Conventional - Standard conventional commits"},{value:"gitmoji",label:"Gitmoji - Using emojis for commit types"}],initialValue:"plain"});if(Pn(f)){be("Setup cancelled");return}t.type=f;const m=Object.entries(t).filter(([D,h])=>D!=="provider"&&D!=="model"&&h!==void 0&&h!==""&&typeof h=="string");await li(m),be(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(mn)}),Yk=sn({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{if(!Po())throw new ce("Interactive terminal required for model selection.");const e=await hn();if(!e.provider){be("No provider configured. Run `aicommits setup` first.");return}const t=jn(e);if(!t){be("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}const n=e.OPENAI_MODEL,r=t.validateConfig();if(!r.valid){be(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const o=await Cd(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition(),t.displayName);o?(await li([["OPENAI_MODEL",o]]),be(`\u2705 Model updated to: ${o}`)):be("Model selection cancelled")})().catch(mn)});const CD="prepare-commit-msg",wD=`.git/hooks/${CD}`,ns=YD(new URL("cli.mjs",import.meta.url)),FD=process.argv[1].replace(/\\/g,"/").endsWith(`/${wD}`),ED=process.platform==="win32",xD=`
202
202
  #!/usr/bin/env node
203
- import(${JSON.stringify(KD(Ka))})
204
- `.trim();var Kk=An({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await ti(),{installUninstall:n}=e._,r=bt.join(t,_D),o=await ri(r);if(n==="install"){if(o){if(await He.realpath(r).catch(()=>{})===Ka){console.warn("The hook is already installed");return}throw new pe(`A different ${yD} hook seems to be installed. Please remove it before installing aicommits.`)}await He.mkdir(bt.dirname(r),{recursive:!0}),CD?await He.writeFile(r,wD):(await He.symlink(Ka,r,"file"),await He.chmod(r,493)),console.log(`${St("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(CD){if(await He.readFile(r,"utf8")!==wD){console.warn("Hook is not installed");return}}else if(await He.realpath(r)!==Ka){console.warn("Hook is not installed");return}await He.rm(r),console.log(`${St("\u2714")} Hook uninstalled`);return}throw new pe(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${Ps("\u2716")} ${t.message}`),ud(t),process.exit(1)})});function Yk(e){const t=e.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(t)return{provider:"github",owner:t[1],repo:t[2]};const n=e.match(/gitlab\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(n)return{provider:"gitlab",owner:n[1],repo:n[2]};const r=e.match(/bitbucket\.org[\/:]([^\/]+)\/([^\/\.]+)/);if(r)return{provider:"bitbucket",owner:r[1],repo:r[2]};const o=e.match(/dev\.azure\.com[\/:]([^\/]+)\/([^\/\.]+)|vs-internal\.visualstudio\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(o)return{provider:"azure",owner:o[1]||o[3],repo:o[2]||o[4]};throw new pe(`Unsupported git provider. Supported: GitHub, GitLab, Bitbucket, Azure DevOps.
205
- Remote URL: ${e}`)}i(Yk,"parseRemoteUrl");function Xk(e,t,n,r,o,s,a){const u=encodeURIComponent(s),l=encodeURIComponent(a);switch(e){case"github":return`https://github.com/${t}/${n}/compare/${r}...${o}?expand=1&title=${u}&body=${l}`;case"gitlab":return`https://gitlab.com/${t}/${n}/-/merge_requests/new?merge_request[source_branch]=${encodeURIComponent(o)}&merge_request[target_branch]=${encodeURIComponent(r)}&merge_request[title]=${u}&merge_request[description]=${l}`;case"bitbucket":return`https://bitbucket.org/${t}/${n}/pull-requests/new?source=${encodeURIComponent(o)}&dest=${encodeURIComponent(r)}&title=${u}&description=${l}`;case"azure":return`https://dev.azure.com/${t}/${n}/_git/${n}/pullrequestcreate?sourceRef=${encodeURIComponent(o)}&targetRef=${encodeURIComponent(r)}&title=${u}&description=${l}`}}i(Xk,"getPrUrl");var Qk=An({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff"}},()=>{(async()=>{if(!Bo())throw new pe("Interactive terminal required for PR creation.");oa(Xo(Yo(" aicommits pr "))),await ti();const{stdout:e}=await Je("git",["branch","--show-current"]);if(!e.trim())throw new pe("Not on a branch");const{stdout:t}=await Je("git",["remote","get-url","origin"]),n=Yk(t),{provider:r,owner:o,repo:s}=n;let a="main";try{const{stdout:B}=await Je("git",["symbolic-ref","refs/remotes/origin/HEAD"]);a=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===a)throw new pe("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let u;try{const{stdout:B}=await Je("git",["diff",`origin/${a}..HEAD`]);u=B}catch{throw new pe(`Could not get diff from origin/${a}`)}if(!u)throw new pe("No changes to create PR from");const l=u.split(`
203
+ import(${JSON.stringify(XD(ns))})
204
+ `.trim();var Xk=sn({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await oi(),{installUninstall:n}=e._,r=Ct.join(t,wD),o=await si(r);if(n==="install"){if(o){if(await He.realpath(r).catch(()=>{})===ns){console.warn("The hook is already installed");return}throw new ce(`A different ${CD} hook seems to be installed. Please remove it before installing aicommits.`)}await He.mkdir(Ct.dirname(r),{recursive:!0}),ED?await He.writeFile(r,xD):(await He.symlink(ns,r,"file"),await He.chmod(r,493)),console.log(`${it("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(ED){if(await He.readFile(r,"utf8")!==xD){console.warn("Hook is not installed");return}}else if(await He.realpath(r)!==ns){console.warn("Hook is not installed");return}await He.rm(r),console.log(`${it("\u2714")} Hook uninstalled`);return}throw new ce(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${Wt("\u2716")} ${t.message}`),dd(t),process.exit(1)})});function Qk(e){const t=e.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(t)return{provider:"github",owner:t[1],repo:t[2]};const n=e.match(/gitlab\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(n)return{provider:"gitlab",owner:n[1],repo:n[2]};const r=e.match(/bitbucket\.org[\/:]([^\/]+)\/([^\/\.]+)/);if(r)return{provider:"bitbucket",owner:r[1],repo:r[2]};const o=e.match(/dev\.azure\.com[\/:]([^\/]+)\/([^\/\.]+)|vs-internal\.visualstudio\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(o)return{provider:"azure",owner:o[1]||o[3],repo:o[2]||o[4]};throw new ce(`Unsupported git provider. Supported: GitHub, GitLab, Bitbucket, Azure DevOps.
205
+ Remote URL: ${e}`)}i(Qk,"parseRemoteUrl");function e8(e,t,n,r,o,s,a){const u=encodeURIComponent(s),l=encodeURIComponent(a);switch(e){case"github":return`https://github.com/${t}/${n}/compare/${r}...${o}?expand=1&title=${u}&body=${l}`;case"gitlab":return`https://gitlab.com/${t}/${n}/-/merge_requests/new?merge_request[source_branch]=${encodeURIComponent(o)}&merge_request[target_branch]=${encodeURIComponent(r)}&merge_request[title]=${u}&merge_request[description]=${l}`;case"bitbucket":return`https://bitbucket.org/${t}/${n}/pull-requests/new?source=${encodeURIComponent(o)}&dest=${encodeURIComponent(r)}&title=${u}&description=${l}`;case"azure":return`https://dev.azure.com/${t}/${n}/_git/${n}/pullrequestcreate?sourceRef=${encodeURIComponent(o)}&targetRef=${encodeURIComponent(r)}&title=${u}&description=${l}`}}i(e8,"getPrUrl");var t8=sn({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff"}},()=>{(async()=>{if(!Po())throw new ce("Interactive terminal required for PR creation.");ca(oa(ta(" aicommits pr "))),await oi();const{stdout:e}=await Je("git",["branch","--show-current"]);if(!e.trim())throw new ce("Not on a branch");const{stdout:t}=await Je("git",["remote","get-url","origin"]),n=Qk(t),{provider:r,owner:o,repo:s}=n;let a="main";try{const{stdout:B}=await Je("git",["symbolic-ref","refs/remotes/origin/HEAD"]);a=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===a)throw new ce("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let u;try{const{stdout:B}=await Je("git",["diff",`origin/${a}..HEAD`]);u=B}catch{throw new ce(`Could not get diff from origin/${a}`)}if(!u)throw new ce("No changes to create PR from");const l=u.split(`
206
206
  `).filter(B=>B.startsWith("diff --git")).length,c=3e4;u.length>c&&(u=u.substring(0,c)+`
207
207
 
208
- [Diff truncated due to size]`);const d=await ln(),f=await Nn(d);if(!f)throw new pe("No provider configured");let h=f.getBaseUrl();if(!h||h==="")throw new pe("Base URL not configured. Please run `aicommits setup` to configure your provider.");h.endsWith("/v1")||(h+="/v1");const D=f.getApiKey();if(!D)throw new pe("API key not configured. Please run `aicommits setup` to configure your provider.");const m=h==="https://api.openai.com/v1"?Ga({apiKey:D}):hu({name:"custom",apiKey:D,baseURL:h}),v=Vt();v.start(`Generating PR title and description (${l} files changed)`);const y=Date.now(),C=(await $o({model:m(d.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:u,maxRetries:2})).text,E=(await $o({model:m(d.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:u,maxRetries:2})).text,T=Date.now(),O=Math.round((T-y)/1e3);v.stop(`Generated PR content for ${l} files in ${O}s`),console.log(`${St("Title:")} ${C.replace(/\n/g," ")}`),console.log(`${St("Body:")} ${E.length>100?E.substring(0,100)+"...":E}`);const{text:$}=await Promise.resolve().then(function(){return oo}),I=await $({message:"Press Enter to push and open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Bn(I)){Ee("PR creation cancelled");return}const re=Vt();re.start(`Pushing branch to ${r}`);try{await Je("git",["push","-u","origin",e.trim()]),re.stop(`Branch pushed to ${r}`)}catch(B){throw re.stop("Failed to push branch"),new pe(`Failed to push branch: ${B instanceof Error?B.message:String(B)}`)}const k=Xk(r,o,s,a,e.trim(),C,E),oe=Vt();oe.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Je(B,[k]),oe.stop("PR creation page opened in browser"),Ee(St("PR creation page opened! Please review and submit the PR."))}catch{oe.stop("Failed to open browser"),Ee(`${St("PR URL:")} ${k}`),Ee("Please open the URL above in your browser to create the PR.")}})().catch(e=>{Rn(e)})});const e8=VD(wl);function FD(e){const n=e.replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z]+)(?:\.(\d+))?)?$/);if(!n)return{major:0,minor:0,patch:0,prerelease:null,prereleaseNum:0};const[,r,o,s,a,u]=n;return{major:parseInt(r,10),minor:parseInt(o,10),patch:parseInt(s,10),prerelease:a||null,prereleaseNum:u?parseInt(u,10):0}}i(FD,"parseVersion");function t8(e,t){const n=FD(e),r=FD(t);return n.major!==r.major?n.major>r.major?1:-1:n.minor!==r.minor?n.minor>r.minor?1:-1:n.patch!==r.patch?n.patch>r.patch?1:-1:!n.prerelease&&r.prerelease?1:n.prerelease&&!r.prerelease?-1:!n.prerelease&&!r.prerelease?0:n.prereleaseNum!==r.prereleaseNum?n.prereleaseNum>r.prereleaseNum?1:-1:0}i(t8,"compareVersions");async function n8(e,t){try{const n=await fetch(`https://registry.npmjs.org/${e}/${t}`,{headers:{Accept:"application/json"}});return n.ok&&(await n.json()).version||null}catch{return null}}i(n8,"fetchLatestVersion");async function r8(e){try{const{stdout:t}=await e8(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(r8,"checkIfGlobalInstallation");async function o8(e,t){return new Promise((n,r)=>{const o=wl(`npm install -g ${e}@${t}`,{timeout:12e4,env:{...process.env,NPM_CONFIG_PROGRESS:"false"}});o.on("error",r),o.on("exit",s=>{s===0||s===null?n():r(new Error(`npm install exited with code ${s}`))})})}i(o8,"runBackgroundUpdate");async function a8(e){const{pkg:t,distTag:n="latest",headless:r=!1}=e;if(r||t.version==="0.0.0-semantic-release"||t.version.includes("semantic-release"))return;const o=t.version.includes("-")?"develop":n;(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&(console.log(`[auto-update] Current version: ${t.version}`),console.log(`[auto-update] Checking ${o} tag...`));const s=await n8(t.name,o);if(!s){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] Could not fetch latest version");return}if((process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log(`[auto-update] Latest version: ${s}`),t8(t.version,s)>=0){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] No update needed");return}if(console.log(`Updating aicommits from v${t.version} to v${s}...`),!await r8(t.name)){console.log("Note: aicommits is installed locally. Auto-update skipped for local installations.");return}try{await o8(t.name,o),console.log(`\u2713 aicommits updated to v${s}`),console.log("Please restart aic to use the new version.")}catch{console.log("Auto-update failed. You can manually update with:"),console.log(` npm install -g aicommits@${o}`)}}i(a8,"checkAndAutoUpdate"),globalThis.AI_SDK_LOG_WARNINGS=!1;const{description:s8,version:vu}=gs;if(!bD&&!Ha()&&vu!=="0.0.0-semantic-release"){const e=vu.includes("-")?"develop":"latest";a8({pkg:gs,distTag:e,headless:!1})}const ED=process.argv.slice(2);pc({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: plain). Supports plain, conventional, and gitmoji",alias:"t"},yes:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},prompt:{type:String,description:"Custom prompt to guide the LLM behavior (e.g., specific language, style instructions)",alias:"p"},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[Wk,Hk,Jk,Kk,Qk],help:{description:s8},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(vu),process.exit(0)),bD?Gk():Zk(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.yes,e.flags.clipboard,e.flags.noVerify,e.flags.prompt,ED)},ED);export{rn as g,Of as r};
208
+ [Diff truncated due to size]`);const d=await hn(),f=await jn(d);if(!f)throw new ce("No provider configured");let m=f.getBaseUrl();if(!m||m==="")throw new ce("Base URL not configured. Please run `aicommits setup` to configure your provider.");m.endsWith("/v1")||(m+="/v1");const D=f.getApiKey();if(!D)throw new ce("API key not configured. Please run `aicommits setup` to configure your provider.");const h=m==="https://api.openai.com/v1"?Xa({apiKey:D}):vu({name:"custom",apiKey:D,baseURL:m}),v=Ot();v.start(`Generating PR title and description (${l} files changed)`);const y=Date.now(),C=(await Oo({model:h(d.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:u,maxRetries:2})).text,E=(await Oo({model:h(d.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:u,maxRetries:2})).text,T=Date.now(),O=Math.round((T-y)/1e3);v.stop(`Generated PR content for ${l} files in ${O}s`),console.log(`${it("Title:")} ${C.replace(/\n/g," ")}`),console.log(`${it("Body:")} ${E.length>100?E.substring(0,100)+"...":E}`);const{text:$}=await Promise.resolve().then(function(){return uo}),I=await $({message:"Press Enter to push and open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Pn(I)){be("PR creation cancelled");return}const re=Ot();re.start(`Pushing branch to ${r}`);try{await Je("git",["push","-u","origin",e.trim()]),re.stop(`Branch pushed to ${r}`)}catch(B){throw re.stop("Failed to push branch"),new ce(`Failed to push branch: ${B instanceof Error?B.message:String(B)}`)}const k=e8(r,o,s,a,e.trim(),C,E),oe=Ot();oe.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Je(B,[k]),oe.stop("PR creation page opened in browser"),be(it("PR creation page opened! Please review and submit the PR."))}catch{oe.stop("Failed to open browser"),be(`${it("PR URL:")} ${k}`),be("Please open the URL above in your browser to create the PR.")}})().catch(e=>{mn(e)})});const n8=Il(fs);function r8(e){return e==="0.0.0-semantic-release"||e.includes("semantic-release")?"latest":e.includes("-")?"develop":"latest"}i(r8,"getDistTag");function o8(e){try{const t=an("npm root -g",{encoding:"utf8"}).trim(),{execPath:n}=process;if(n.includes(t)||n.includes("/usr/local")||n.includes("/usr/bin"))return{name:"npm",updateCommand:`npm install -g aicommits@${e}`}}catch{}try{if(an("pnpm --version",{stdio:"ignore"}),an("pnpm list -g aicommits",{encoding:"utf8"}).includes("aicommits"))return{name:"pnpm",updateCommand:`pnpm add -g aicommits@${e}`}}catch{}try{if(an("yarn --version",{stdio:"ignore"}),an("yarn global list",{encoding:"utf8"}).includes("aicommits"))return{name:"yarn",updateCommand:`yarn global add aicommits@${e}`}}catch{}try{an("bun --version",{stdio:"ignore"});const t=an("bun pm bin -g",{encoding:"utf8"});if(process.execPath.includes("bun")||t.includes("aicommits"))return{name:"bun",updateCommand:`bun add -g aicommits@${e}`}}catch{}return{name:"npm",updateCommand:`npm install -g aicommits@${e}`}}i(o8,"detectPackageManager");async function a8(e){try{const t=await fetch(`https://registry.npmjs.org/aicommits/${e}`,{headers:{Accept:"application/json"}});return t.ok&&(await t.json()).version||null}catch{return null}}i(a8,"getLatestVersion");var s8=sn({name:"update",description:"Update aicommits to the latest version",help:{description:"Check for updates and install the latest version using your package manager"}},()=>{(async()=>{const e=r8(Vt.version),t=o8(e);console.log(`${ra("\u2139")} Current version: ${Vt.version}`),console.log(`${ra("\u2139")} Package manager detected: ${t.name}`),e!=="latest"&&console.log(`${ra("\u2139")} Using '${e}' distribution tag`);const n=Ot();n.start("Checking for updates...");const r=await a8(e);if(!r)throw n.stop("Could not check for updates",1),new ce("Failed to fetch latest version from npm registry");if(r===Vt.version){n.stop(`${it("\u2714")} Already on the latest version (${Vt.version})`);return}n.stop(`${it("\u2714")} Update available: v${Vt.version} \u2192 v${r}`);const o=Ot();o.start(`Updating via ${t.name}...`);try{await n8(t.updateCommand,{timeout:12e4}),o.stop(`${it("\u2714")} Successfully updated to v${r}`),be(`${it("\u2714")} Update complete! Run 'aic --version' to verify.`)}catch(s){o.stop(`${Wt("\u2718")} Update failed`,1),s.stderr?.includes("permission")||s.message?.includes("permission")?(console.error(`${Wt("\u2718")} Permission denied. Try running with sudo:`),console.error(` sudo ${t.updateCommand}`)):s.stderr?.includes("EACCES")?(console.error(`${Wt("\u2718")} Permission denied. Try running with sudo:`),console.error(` sudo ${t.updateCommand}`)):(console.error(`${Wt("\u2718")} Error: ${s.message||"Unknown error"}`),console.error(`
209
+ ${na("You can manually update with:")}`),console.error(` ${t.updateCommand}`)),process.exit(1)}})().catch(mn)});const i8=Il(fs);function kD(e){const n=e.replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z]+)(?:\.(\d+))?)?$/);if(!n)return{major:0,minor:0,patch:0,prerelease:null,prereleaseNum:0};const[,r,o,s,a,u]=n;return{major:parseInt(r,10),minor:parseInt(o,10),patch:parseInt(s,10),prerelease:a||null,prereleaseNum:u?parseInt(u,10):0}}i(kD,"parseVersion");function u8(e,t){const n=kD(e),r=kD(t);return n.major!==r.major?n.major>r.major?1:-1:n.minor!==r.minor?n.minor>r.minor?1:-1:n.patch!==r.patch?n.patch>r.patch?1:-1:!n.prerelease&&r.prerelease?1:n.prerelease&&!r.prerelease?-1:!n.prerelease&&!r.prerelease?0:n.prereleaseNum!==r.prereleaseNum?n.prereleaseNum>r.prereleaseNum?1:-1:0}i(u8,"compareVersions");async function l8(e,t){try{const n=await fetch(`https://registry.npmjs.org/${e}/${t}`,{headers:{Accept:"application/json"}});return n.ok&&(await n.json()).version||null}catch{return null}}i(l8,"fetchLatestVersion");async function c8(e){try{const{stdout:t}=await i8(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(c8,"checkIfGlobalInstallation");async function d8(e,t){return new Promise((n,r)=>{const o=fs(`npm install -g ${e}@${t}`,{timeout:12e4,env:{...process.env,NPM_CONFIG_PROGRESS:"false"}});o.on("error",r),o.on("exit",s=>{s===0||s===null?n():r(new Error(`npm install exited with code ${s}`))})})}i(d8,"runBackgroundUpdate");async function p8(e){const{pkg:t,distTag:n="latest",headless:r=!1}=e;if(r||t.version==="0.0.0-semantic-release"||t.version.includes("semantic-release"))return;const o=t.version.includes("-")?"develop":n;(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&(console.log(`[auto-update] Current version: ${t.version}`),console.log(`[auto-update] Checking ${o} tag...`));const s=await l8(t.name,o);if(!s){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] Could not fetch latest version");return}if((process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log(`[auto-update] Latest version: ${s}`),u8(t.version,s)>=0){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] No update needed");return}if(console.log(`Updating aicommits from v${t.version} to v${s}...`),!await c8(t.name)){console.log("Note: aicommits is installed locally. Auto-update skipped for local installations.");return}try{await d8(t.name,o),console.log(`\u2713 aicommits updated to v${s}`),console.log("Please restart aic to use the new version.")}catch{console.log("Auto-update failed. You can manually update with:"),console.log(` npm install -g aicommits@${o}`)}}i(p8,"checkAndAutoUpdate"),globalThis.AI_SDK_LOG_WARNINGS=!1;const{description:f8,version:bu}=Vt;if(!FD&&!es()&&bu!=="0.0.0-semantic-release"){const e=bu.includes("-")?"develop":"latest";p8({pkg:Vt,distTag:e,headless:!1})}const ID=process.argv.slice(2);hc({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: plain). Supports plain, conventional, and gitmoji",alias:"t"},yes:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},prompt:{type:String,description:"Custom prompt to guide the LLM behavior (e.g., specific language, style instructions)",alias:"p"},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[Jk,Kk,Yk,Xk,t8,s8],help:{description:f8},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(bu),process.exit(0)),FD?Hk():Gk(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.yes,e.flags.clipboard,e.flags.noVerify,e.flags.prompt,ID)},ID);export{un as g,Pf as r};