aicommits 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/cli-fXLbQukQ.mjs +223 -0
- package/dist/cli.mjs +1 -1
- package/dist/{token-CguVX0Ch.mjs → token-CkJSeVBK.mjs} +1 -1
- package/dist/{token-util-BHa3nm6u.mjs → token-util-C6r3rt16.mjs} +1 -1
- package/dist/{token-util-BSE6QSDg.mjs → token-util-JRYE6X6v.mjs} +1 -1
- package/package.json +1 -1
- package/dist/cli-C6nkjKMe.mjs +0 -209
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
var MD=Object.defineProperty;var i=(e,t)=>MD(e,"name",{value:t,configurable:!0});var Qn,In,er,tr,nr,rr,or,ar,sr,ir,on,ur,lr,An,$n,cr,dr,pr,fr,mr,Tn,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,Vr;import jD from"tty";import{Buffer as zD}from"node:buffer";import On from"node:path";import wl,{ChildProcess as LD}from"node:child_process";import Le,{stdin as Fl,stdout as El}from"node:process";import qD,{exec as hs,execSync as an}from"child_process";import Ct from"path";import Ds from"fs";import{fileURLToPath as xl}from"node:url";import UD,{constants as kl}from"node:os";import ZD from"assert";import VD from"events";import{createWriteStream as GD,createReadStream as WD}from"node:fs";import HD from"buffer";import gs from"stream";import JD,{promisify as Il}from"util";import{debuglog as KD}from"node:util";import*as Vo from"node:readline";import Al from"node:readline";import{Writable as YD}from"node:stream";import Je from"fs/promises";import $l from"os";import XD from"crypto";import{fileURLToPath as QD,pathToFileURL as eg}from"url";var tg=Object.defineProperty,Ue=i((e,t)=>tg(e,"name",{value:t,configurable:!0}),"a");const ng="known-flag",rg="unknown-flag",og="argument",ag=/\B([A-Z])/g,sg=Ue(e=>e.replaceAll(ag,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:ig}=Object.prototype,ao=Ue((e,t)=>ig.call(e,t),"hasOwn"),vs=Ue(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:vs(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"),ug=/[\s.:=]/,lg=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(ug);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),ys=Ue((e,t,n)=>{if(ao(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),cg=Ue(e=>{const t={};for(const n in e){if(!ao(e,n))continue;lg(n);const r=e[n],o=[[],...vs(r),r];ys(t,n,o);const s=sg(n);if(n!==s&&ys(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`);ys(t,a,o)}}return t},"createRegistry"),dg=Ue((e,t)=>{const n={};for(const r in e){if(!ao(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"),Go="--",pg=3,fg=/^-{1,2}\w/,Bl=Ue(e=>{if(!fg.test(e))return;const t=!e.startsWith(Go);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===Go){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"),mg=Ue((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],o=cg(e),s={},a=[];return a[Go]=[],Ol(t,{onFlag(u,l,c){const d=(c.length===pg||u.length>1)&&ao(o,u);if(!n?.(d?ng:rg,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)}ao(s,u)||(s[u]=[]),s[u].push(l===void 0?!0:l),r.push(c)}},onArgument:Ue((u,l,c)=>{n?.(og,t[l[0]])||(a.push(...u),c?(a[Go]=u,t.splice(l[0])):r.push(l))},"onArgument")}),Rl(t,r),{flags:dg(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]=vs(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 hg=Object.defineProperty,ie=i((e,t)=>hg(e,"name",{value:t,configurable:!0}),"n");const Dg=ie(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"),ie(Nl,"ansiRegex");const gg=Nl();function _s(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(gg,"")}i(_s,"w$2"),ie(_s,"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"),ie(Pl,"isAmbiguous");function Ml(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}i(Ml,"z$2"),ie(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"),ie(jl,"isWide");function zl(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}i(zl,"Z$1"),ie(zl,"validate");function Ll(e,{ambiguousAsWide:t=!1}={}){return zl(e),Ml(e)||jl(e)||t&&Pl(e)?2:1}i(Ll,"V$3"),ie(Ll,"eastAsianWidth");var vg=ie(()=>/[#*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 yg=new Intl.Segmenter,_g=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=_s(e)),e.length===0)return 0;let o=0;const s={ambiguousAsWide:!n};for(const{segment:a}of yg.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)&&!_g.test(a)){if(vg().test(a)){o+=2;continue}o+=Ll(u,s)}}return o}i(Zt,"d$2"),ie(Zt,"stringWidth");const ql=ie(e=>Math.max(...e.split(`
|
|
2
|
+
`).map(t=>Zt(t))),"getLongestLineWidth"),bg=ie(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:""},Cg=ie((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"),wg=ie((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=ie(()=>Object.assign([],{columns:0}),"makeRow"),Fg=ie((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"),Eg=ie((e,t,n)=>{const r=Cg(n,t);return wg(r,e),Fg(r,e)},"computeColumnWidths"),bs=10,Gl=ie((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),Wl=ie((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),Hl=ie((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 xg=Object.keys($e.color),kg=Object.keys($e.bgColor);[...xg,...kg];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(bs),$e.bgColor.ansi256=Wl(bs),$e.bgColor.ansi16m=Hl(bs),Object.defineProperties($e,{rgbToAnsi256:{value:ie((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:ie(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:ie(t=>$e.rgbToAnsi256(...$e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:ie(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:ie((t,n,r)=>$e.ansi256ToAnsi($e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:ie(t=>$e.ansi256ToAnsi($e.hexToAnsi256(t)),"value"),enumerable:!1}}),$e}i(Jl,"FD$1"),ie(Jl,"assembleStyles");const Ig=Jl(),Wo=new Set(["\x1B","\x9B"]),Ag=39,Cs="\x07",Kl="[",$g="]",Yl="m",Ho=`${$g}8;;`,Xl=ie(e=>`${Wo.values().next().value}${Kl}${e}${Yl}`,"wrapAnsiCode"),Ql=ie(e=>`${Wo.values().next().value}${Ho}${e}${Cs}`,"wrapAnsiHyperlink"),Tg=ie(e=>e.split(" ").map(t=>Zt(t)),"wordLengths"),ws=ie((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=Zt(_s(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),Wo.has(l)&&(o=!0,s=r.slice(u+1,u+1+Ho.length).join("")===Ho),o){s?l===Cs&&(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"),Sg=ie(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"),Bg=ie((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Tg(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(""),ws(u,m,t);continue}if(D+a[f]>t&&D>0&&a[f]>0){if(n.wordWrap===!1&&D<t){ws(u,m,t);continue}u.push("")}if(D+a[f]>t&&n.wordWrap===!1){ws(u,m,t);continue}u[u.length-1]+=m}n.trim!==!1&&(u=u.map(f=>Sg(f)));const l=u.join(`
|
|
3
|
+
`),c=[...l];let d=0;for(const[f,m]of c.entries()){if(r+=m,Wo.has(m)){const{groups:h}=new RegExp(`(?:\\${Kl}(?<code>\\d+)m|\\${Ho}(?<uri>.*)${Cs})`).exec(l.slice(d))||{groups:{}};if(h.code!==void 0){const v=Number.parseFloat(h.code);o=v===Ag?void 0:v}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const D=Ig.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
|
+
`,`
|
|
7
|
+
`).split(`
|
|
8
|
+
`).map(r=>Bg(r,t,n)).join(`
|
|
9
|
+
`)}i(ec,"BD$1"),ie(ec,"wrapAnsi");const tc=ie(e=>Array.from({length:e}).fill(""),"emptyLines"),Og=ie((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
|
+
`))}return n.join(`
|
|
12
|
+
`)},"renderRow"),Rg=ie((e,t)=>{if(!e||e.length===0)return"";const n=bg(e),r=n.length;if(r===0)return"";const{stdoutColumns:o,columns:s}=Dg(t);if(s.length>r)throw new Error(`${s.length} columns defined, but only ${r} columns found`);const a=Eg(o,s,n);return e.map(u=>Og(a,u)).join(`
|
|
13
|
+
`)},"terminalColumns"),Ng=["<",">","=",">=","<="],Pg=ie(e=>{if(!Ng.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),Mg=ie(e=>{const t=Object.keys(e).map(n=>{const[r,o]=n.split(" ");Pg(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 jg=Object.defineProperty,ke=i((e,t)=>jg(e,"name",{value:t,configurable:!0}),"s");const zg=ke(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),Lg=ke(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),qg={"> 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:`--${Lg(n)}`,aliasesEnabled:t,aliasFormatted:o?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:qg}}}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 Ug=ke(e=>[ac,sc,ic,uc,lc,cc,dc].map(t=>t(e)).filter(Boolean),"generateHelp"),Zg=jD.WriteStream.prototype.hasColors(),pc=(Qn=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)}
|
|
19
|
+
`:"")+(n?this.indentText({text:this.render(n),spaces:r}):"")}
|
|
20
|
+
`}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return Rg(t.map(o=>o.map(s=>this.render(s))),r?Mg(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(Qn,"_z"),Qn);ke(pc,"Renderers");let Vg=pc;const Fs=ke(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:St}=JSON,Gg=/[|\\{}()[\]^$+*?.]/;function Jo(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(Gg);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(Jo,"b$1"),ke(Jo,"parseParameters");function Ko(e,t,n,r){for(let o=0;o<t.length;o+=1){const{name:s,required:a,spread:u}=t[o],l=zg(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(Ko,"v"),ke(Ko,"mapParametersToArguments");function fc(e){return e===void 0||e!==!1}i(fc,"G$2"),ke(fc,"helpEnabled");function Es(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=mg(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 Vg,f=u&&a?.render?a.render:v=>d.render(v),m=ke(v=>{const y=Ug({...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),Ko(w,Jo(v),y,m),Ko(w,Jo(C),E,m)}else Ko(w,Jo(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(Es,"j"),ke(Es,"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||!Fs(e.name)))throw new Error(`Invalid script name: ${St(e.name)}`);const r=n[0];if(e.commands&&r&&Fs(r)){const o=mc(r,e.commands);if(o)return Es(o.options.name,{...o.options,parent:e},o.callback,n.slice(1))}return Es(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(!Fs(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 Wg="aicommits",Hg="3.1.0",Jg="Writes your git commit messages for you with AI",Kg=["ai","git","commit","code changes"],Yg="MIT",Xg={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},Qg="Hassan El Mghari (@nutlope)",ev="module",tv=["dist"],nv={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},rv={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},ov={"@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"},av={branches:["develop"]},Vt={name:Wg,version:Hg,description:Jg,keywords:Kg,license:Yg,repository:Xg,author:Qg,type:ev,files:tv,bin:nv,scripts:rv,devDependencies:ov,release:av},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:{}},xs,Dc;function sv(){if(Dc)return xs;Dc=1,xs=r,r.sync=o;var e=Ds;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"),xs}i(sv,"requireWindows");var ks,gc;function iv(){if(gc)return ks;gc=1,ks=t,t.sync=n;var e=Ds;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"),ks}i(iv,"requireMode");var Is,vc;function uv(){if(vc)return Is;vc=1;var e;process.platform==="win32"||Gt.TESTING_WINDOWS?e=sv():e=iv(),Is=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"),Is}i(uv,"requireIsexe");var As,yc;function lv(){if(yc)return As;yc=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=Ct,n=e?";":":",r=uv(),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),A=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+O:O;C(y(A,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},(A,I)=>{if(!A&&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 As=a,a.sync=u,As}i(lv,"requireWhich");var Yo={exports:{}},_c;function cv(){if(_c)return Yo.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 Yo.exports=e,Yo.exports.default=e,Yo.exports}i(cv,"requirePathKey");var $s,bc;function dv(){if(bc)return $s;bc=1;const e=Ct,t=lv(),n=cv();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"),$s=o,$s}i(dv,"requireResolveCommand");var Xo={},Cc;function pv(){if(Cc)return Xo;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"),Xo.command=t,Xo.argument=n,Xo}i(pv,"require_escape");var Ts,wc;function fv(){return wc||(wc=1,Ts=/^#!(.*)/),Ts}i(fv,"requireShebangRegex");var Ss,Fc;function mv(){if(Fc)return Ss;Fc=1;const e=fv();return Ss=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"),Ss}i(mv,"requireShebangCommand");var Bs,Ec;function hv(){if(Ec)return Bs;Ec=1;const e=Ds,t=mv();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"),Bs=n,Bs}i(hv,"requireReadShebang");var Os,xc;function Dv(){if(xc)return Os;xc=1;const e=Ct,t=dv(),n=pv(),r=hv(),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"),Os=c,Os}i(Dv,"requireParse");var Rs,kc;function gv(){if(kc)return Rs;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"),Rs={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:o,notFoundError:t},Rs}i(gv,"requireEnoent");var Ic;function vv(){if(Ic)return ln.exports;Ic=1;const e=qD,t=Dv(),n=gv();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(vv,"requireCrossSpawn");var yv=vv(),_v=un(yv);function bv(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(bv,"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 Cv=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&&wv(u,a),o&&Fv(u,r,a),[...u,t].join(On.delimiter)},"npmRunPath"),wv=i((e,t)=>{let n;for(;n!==t;)e.push(On.join(t,"node_modules/.bin")),n=t,t=On.resolve(t,"..")},"applyPreferLocal"),Fv=i((e,t,n)=>{const r=t instanceof URL?xl(t):t;e.push(On.resolve(n,r,".."))},"applyExecPath"),Ev=i(({env:e=Le.env,...t}={})=>{e={...e};const n=Ac({env:e});return t.path=e[n],e[n]=Cv(t),e},"npmRunPathEnv"),xv=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);!kv(o,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),kv=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"),Iv=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),Av=i((e,t)=>`/* Wrapped ${e}*/
|
|
24
|
+
${t}`,"wrappedToString"),$v=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Tv=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Sv=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,o=Av.bind(null,r,t.toString());Object.defineProperty(o,"name",Tv),Object.defineProperty(e,"toString",{...$v,value:o})},"changeToString");function Bv(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const o of Reflect.ownKeys(t))xv(e,t,o,n);return Iv(e,t),Sv(e,t,r),e}i(Bv,"mimicFunction");const Qo=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(Qo.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 Bv(s,e),Qo.set(s,r),s},"onetime");$c.callCount=e=>{if(!Qo.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Qo.get(e)};const Ov=i(()=>{const e=Sc-Tc+1;return Array.from({length:e},Rv)},"getRealtimeSignals"),Rv=i((e,t)=>({name:`SIGRT${t+1}`,number:Tc+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),Tc=34,Sc=64,Nv=[{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=Ov();return[...Nv,...e].map(Pv)},"getSignals"),Pv=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"),Mv=i(()=>{const e=Bc();return Object.fromEntries(e.map(jv))},"getSignalsByName"),jv=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"),zv=Mv(),Lv=i(()=>{const e=Bc(),t=Sc+1,n=Array.from({length:t},(r,o)=>qv(o,e));return Object.assign({},...n)},"getSignalsByNumber"),qv=i((e,t)=>{const n=Uv(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"),Uv=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");Lv();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"),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:zv[o].description,h=r&&r.code,y=`Command ${Zv({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
|
+
${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=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"),ea=["stdin","stdout","stderr"],Vv=i(e=>ea.some(t=>e[t]!==void 0),"hasAlias"),Gv=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return ea.map(r=>e[r]);if(Vv(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ea.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,ea.length);return Array.from({length:n},(r,o)=>t[o])},"normalizeStdio");var cn={exports:{}},Ns={exports:{}},Rc;function Wv(){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")})(Ns)),Ns.exports}i(Wv,"requireSignals");var Nc;function Hv(){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=ZD,r=Wv(),o=/^win/i.test(e.platform),s=VD;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(Hv,"requireSignalExit");var Jv=Hv(),Kv=un(Jv);const Yv=1e3*5,Xv=i((e,t="SIGTERM",n={})=>{const r=e(t);return Qv(e,t,n,r),r},"spawnedKill"),Qv=i((e,t,n,r)=>{if(!ey(t,n,r))return;const o=ny(n),s=setTimeout(()=>{e("SIGKILL")},o);s.unref&&s.unref()},"setKillTimeout"),ey=i((e,{forceKillAfterTimeout:t},n)=>ty(e)&&t!==!1&&n,"shouldForceKill"),ty=i(e=>e===UD.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),ny=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Yv;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"),ry=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),oy=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),ay=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(()=>{oy(e,n,l)},t)}),a=r.finally(()=>{clearTimeout(o)});return Promise.race([s,a])},"setupTimeout"),sy=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"),iy=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const o=Kv(()=>{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 uy=i(e=>e instanceof LD&&typeof e.then=="function","isExecaChildProcess"),Ps=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(GD(n)),e;if(Mc(n))return e[t].pipe(n),e;if(!uy(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"),ly=i(e=>{e.stdout!==null&&(e.pipeStdout=Ps.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Ps.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Ps.bind(void 0,e,"all"))},"addPipeMethods");var Rn={exports:{}},Ms,jc;function cy(){if(jc)return Ms;jc=1;const{PassThrough:e}=gs;return Ms=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"),Ms}i(cy,"requireBufferStream");var zc;function dy(){if(zc)return Rn.exports;zc=1;const{constants:e}=HD,t=gs,{promisify:n}=JD,r=cy(),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(dy,"requireGetStream");var py=dy(),Lc=un(py),js,qc;function fy(){if(qc)return js;qc=1;const{PassThrough:e}=gs;return js=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"),js}i(fy,"requireMergeStream");var my=fy(),hy=un(my);const Dy=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),gy=i(({input:e,inputFile:t})=>typeof t!="string"?e:(Dy(e),WD(t)),"getInput"),vy=i((e,t)=>{const n=gy(t);n!==void 0&&(Pc(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),yy=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=hy();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),zs=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),Ls=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"),_y=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:o,maxBuffer:s},a)=>{const u=Ls(e,{encoding:r,buffer:o,maxBuffer:s}),l=Ls(t,{encoding:r,buffer:o,maxBuffer:s}),c=Ls(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},zs(e,u),zs(t,l),zs(n,c)])}},"getSpawnedResult"),by=(async()=>{})().constructor.prototype,Cy=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(by,e)]),Uc=i((e,t)=>{for(const[n,r]of Cy){const o=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:o})}},"mergePromise"),wy=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"),Fy=/^[\w.-]+$/,Ey=/"/g,xy=i(e=>typeof e!="string"||Fy.test(e)?e:`"${e.replace(Ey,'\\"')}"`,"escapeArg"),ky=i((e,t)=>Zc(e,t).join(" "),"joinCommand"),Iy=i((e,t)=>Zc(e,t).map(n=>xy(n)).join(" "),"getEscapedCommand"),Ay=KD("execa").enabled,ta=i((e,t)=>String(e).padStart(t,"0"),"padField"),$y=i(()=>{const e=new Date;return`${ta(e.getHours(),2)}:${ta(e.getMinutes(),2)}:${ta(e.getSeconds(),2)}.${ta(e.getMilliseconds(),3)}`},"getTimestamp"),Ty=i((e,{verbose:t})=>{t&&Le.stderr.write(`[${$y()}] ${e}
|
|
27
|
+
`)},"logCommand"),Sy=1e3*1e3*100,By=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const s=t?{...Le.env,...e}:e;return n?Ev({env:s,cwd:r,execPath:o}):s},"getEnv"),Oy=i((e,t,n={})=>{const r=_v._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:Sy,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:Ay,...n},n.env=By(n),n.stdio=Gv(n),Le.platform==="win32"&&On.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),qs=i((e,t,n)=>typeof t!="string"&&!zD.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?bv(t):t,"handleOutput");function He(e,t,n){const r=Oy(e,t,n),o=ky(e,t),s=Iy(e,t);Ty(s,r.options),sy(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=wy(a),l=ay(a,r.options,u),c=iy(a,r.options,l),d={isCanceled:!1};a.kill=Xv.bind(null,a.kill.bind(a)),a.cancel=ry.bind(null,a,d);const m=$c(i(async()=>{const[{error:D,exitCode:h,signal:v,timedOut:y},b,C,w]=await _y(a,r.options,c),E=qs(r.options,b),T=qs(r.options,C),O=qs(r.options,w);if(D||h!==0||v!==null){const A=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 A;throw A}return{command:o,escapedCommand:s,exitCode:0,stdout:E,stderr:T,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return vy(a,r.options),a.all=yy(a,r.options),ly(a),Uc(a,m),a}i(He,"execa");let dn=!0;const Nn=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let so=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")?so=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?so=2:so=1)}let Us={enabled:dn,supportLevel:so};function pn(e,t,n=1){const r=`\x1B[${e}m`,o=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return a=>Us.enabled&&Us.supportLevel>=n?r+(""+a).replace(s,r)+o:""+a}i(pn,"kolorist");const io=pn(2,22),na=pn(30,39),Wt=pn(31,39),it=pn(32,39),ra=pn(33,39),oa=pn(36,39),aa=pn(46,49);var Ry=Object.freeze({__proto__:null,bgCyan:aa,black:na,cyan:oa,dim:io,green:it,options:Us,red:Wt,yellow:ra});async function Vc(e){try{if(process.platform==="darwin")await He("pbcopy",{input:e});else if(process.platform==="win32")await He("clip",{input:e});else{const t={input:e,stdio:["pipe","ignore","ignore"]};try{await He("wl-copy",t)}catch{try{await He("xclip",["-selection","clipboard"],t)}catch{await He("xsel",["--clipboard","--input"],t)}}}return!0}catch{return!1}}i(Vc,"copyToClipboard");var Zs,Gc;function Ny(){if(Gc)return Zs;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 Zs={cursor:r,scroll:o,erase:s,beep:n},Zs}i(Ny,"requireSrc");var Xe=Ny(),sa={exports:{}},Wc;function Py(){if(Wc)return sa.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 sa.exports=a(),sa.exports.createColors=a,sa.exports}i(Py,"requirePicocolors");var My=Py(),q=un(My);function jy({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(jy,"DD");const zy=jy();function Hc(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(zy,"")}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 Ly=Kc.exports;const qy=Jc(Ly);var Uy=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=Jc(Uy);function uo(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Hc(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(qy.eastAsianWidth(o)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(uo,"p");const Vs=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 Vy=Object.keys(Te.color),Gy=Object.keys(Te.bgColor);[...Vy,...Gy];function Wy(){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(Vs),Te.bgColor.ansi256=Xc(Vs),Te.bgColor.ansi16m=Qc(Vs),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(Wy,"rD");const Hy=Wy(),ia=new Set(["\x1B","\x9B"]),Jy=39,Gs="\x07",ed="[",Ky="]",td="m",Ws=`${Ky}8;;`,nd=i(e=>`${ia.values().next().value}${ed}${e}${td}`,"z"),rd=i(e=>`${ia.values().next().value}${Ws}${e}${Gs}`,"K"),Yy=i(e=>e.split(" ").map(t=>uo(t)),"aD"),Hs=i((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=uo(Hc(e[e.length-1]));for(const[u,l]of r.entries()){const c=uo(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),ia.has(l)&&(o=!0,s=r.slice(u+1).join("").startsWith(Ws)),o){s?l===Gs&&(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"),Xy=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(uo(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),Qy=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Yy(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=uo(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(""),Hs(u,d,t);continue}if(f+a[c]>t&&f>0&&a[c]>0){if(n.wordWrap===!1&&f<t){Hs(u,d,t);continue}u.push("")}if(f+a[c]>t&&n.wordWrap===!1){Hs(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Xy(c)));const l=[...u.join(`
|
|
28
|
+
`)];for(const[c,d]of l.entries()){if(r+=d,ia.has(d)){const{groups:m}=new RegExp(`(?:\\${ed}(?<code>\\d+)m|\\${Ws}(?<uri>.*)${Gs})`).exec(l.slice(c).join(""))||{groups:{}};if(m.code!==void 0){const D=Number.parseFloat(m.code);o=D===Jy?void 0:D}else m.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}const f=Hy.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
|
+
`).split(`
|
|
32
|
+
`).map(r=>Qy(r,t,n)).join(`
|
|
33
|
+
`)}i(od,"Y$1");const e0=["up","down","left","right","space","enter","cancel"],ua={actions:new Set(e0),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function Js(e,t){if(typeof e=="string")return ua.aliases.get(e)===t;for(const n of e)if(n!==void 0&&Js(n,t))return!0;return!1}i(Js,"$");function t0(e,t){if(e===t)return;const n=e.split(`
|
|
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(t0,"BD");const n0=globalThis.process.platform.startsWith("win"),Ks=Symbol("clack:cancel");function Pn(e){return e===Ks}i(Pn,"pD");function la(e,t){const n=e;n.isTTY&&n.setRawMode(t)}i(la,"m");function r0({input:e=Fl,output:t=El,overwrite:n=!0,hideCursor:r=!0}={}){const o=Vo.createInterface({input:e,output:t,prompt:"",tabSize:1});Vo.emitKeypressEvents(e,o),e.isTTY&&e.setRawMode(!0);const s=i((a,{name:u,sequence:l})=>{const c=String(a);if(Js([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;Vo.moveCursor(t,d,f,()=>{Vo.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&&!n0&&e.setRawMode(!1),o.terminal=!1,o.close()}}i(r0,"fD");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,"vD"),mt=i((e,t,n)=>(a0(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(Ks);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new YD;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),la(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),la(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Xe.cursor.show),this.output.off("resize",this.render),la(this.input,!1),t(Ks)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&ua.aliases.has(n.name)&&this.emit("cursor",ua.aliases.get(n.name)),ua.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")}Js([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
|
+
`),la(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=t0(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
|
+
`);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
|
+
`).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(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 Ys=wu;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,"jD"),ad=i((e,t,n)=>(i0(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}${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(Fu,"MD");let Xs=Fu;var u0=Object.defineProperty,l0=i((e,t,n)=>t in e?u0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),sd=i((e,t,n)=>(l0(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 Qs=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}${q.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 ei=xu;function c0(){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(c0,"ce");const ti=c0(),Bt=i((e,t)=>ti?e:t,"u"),d0=Bt("\u25C6","*"),id=Bt("\u25A0","x"),ud=Bt("\u25B2","x"),ld=Bt("\u25C7","o"),p0=Bt("\u250C","T"),Ee=Bt("\u2502","|"),fn=Bt("\u2514","\u2014"),ni=Bt("\u25CF",">"),ri=Bt("\u25CB"," "),f0=Bt("\u25AA","\u2022"),ca=i(e=>{switch(e){case"initial":case"active":return q.cyan(d0);case"cancel":return q.red(id);case"error":return q.yellow(ud);case"submit":return q.green(ld)}},"b"),m0=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?q.dim("..."):r(d,f+u===t)})},"G"),cd=i(e=>new ei({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${q.gray(Ee)}
|
|
41
|
+
${ca(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(Ee)} ${r}
|
|
44
|
+
${q.yellow(fn)} ${q.yellow(this.error)}
|
|
45
|
+
`;case"submit":return`${t}${q.gray(Ee)} ${q.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${q.gray(Ee)} ${q.strikethrough(q.dim(this.value??""))}${this.value?.trim()?`
|
|
46
|
+
${q.gray(Ee)}`:""}`;default:return`${t}${q.cyan(Ee)} ${r}
|
|
47
|
+
${q.cyan(fn)}
|
|
48
|
+
`}}}).prompt(),"he"),h0=i(e=>new Xs({validate:e.validate,mask:e.mask??f0,render(){const t=`${q.gray(Ee)}
|
|
49
|
+
${ca(this.state)} ${e.message}
|
|
50
|
+
`,n=this.valueWithCursor,r=this.masked;switch(this.state){case"error":return`${t.trim()}
|
|
51
|
+
${q.yellow(Ee)} ${r}
|
|
52
|
+
${q.yellow(fn)} ${q.yellow(this.error)}
|
|
53
|
+
`;case"submit":return`${t}${q.gray(Ee)} ${q.dim(r)}`;case"cancel":return`${t}${q.gray(Ee)} ${q.strikethrough(q.dim(r??""))}${r?`
|
|
54
|
+
${q.gray(Ee)}`:""}`;default:return`${t}${q.cyan(Ee)} ${n}
|
|
55
|
+
${q.cyan(fn)}
|
|
56
|
+
`}}}).prompt(),"ge"),D0=i(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Ys({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${q.gray(Ee)}
|
|
57
|
+
${ca(this.state)} ${e.message}
|
|
58
|
+
`,o=this.value?t:n;switch(this.state){case"submit":return`${r}${q.gray(Ee)} ${q.dim(o)}`;case"cancel":return`${r}${q.gray(Ee)} ${q.strikethrough(q.dim(o))}
|
|
59
|
+
${q.gray(Ee)}`;default:return`${r}${q.cyan(Ee)} ${this.value?`${q.green(ni)} ${t}`:`${q.dim(ri)} ${q.dim(t)}`} ${q.dim("/")} ${this.value?`${q.dim(ri)} ${q.dim(n)}`:`${q.green(ni)} ${n}`}
|
|
60
|
+
${q.cyan(fn)}
|
|
61
|
+
`}}}).prompt()},"ye"),oi=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(ni)} ${o} ${n.hint?q.dim(`(${n.hint})`):""}`;case"cancelled":return`${q.strikethrough(q.dim(o))}`;default:return`${q.dim(ri)} ${q.dim(o)}`}},"n");return new Qs({options:e.options,initialValue:e.initialValue,render(){const n=`${q.gray(Ee)}
|
|
62
|
+
${ca(this.state)} ${e.message}
|
|
63
|
+
`;switch(this.state){case"submit":return`${n}${q.gray(Ee)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${q.gray(Ee)} ${t(this.options[this.cursor],"cancelled")}
|
|
64
|
+
${q.gray(Ee)}`;default:return`${n}${q.cyan(Ee)} ${m0({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:i((r,o)=>t(r,o?"active":"inactive"),"style")}).join(`
|
|
65
|
+
${q.cyan(Ee)} `)}
|
|
66
|
+
${q.cyan(fn)}
|
|
67
|
+
`}}}).prompt()},"ve"),da=i((e="")=>{process.stdout.write(`${q.gray(p0)} ${e}
|
|
68
|
+
`)},"Ie"),be=i((e="")=>{process.stdout.write(`${q.gray(Ee)}
|
|
69
|
+
${q.gray(fn)} ${e}
|
|
70
|
+
|
|
71
|
+
`)},"Se");`${q.gray(Ee)}`;const Ot=i(({indicator:e="dots"}={})=>{const t=ti?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=ti?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
|
+
`);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),A=Math.floor(T%60);return O>0?`[${O}m ${A}s]`:`[${A}s]`},"O"),C=i((E="")=>{a=!0,o=r0(),u=y(E),c=performance.now(),process.stdout.write(`${q.gray(Ee)}
|
|
74
|
+
`);let T=0,O=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const A=q.magenta(t[T]);if(r)process.stdout.write(`${A} ${u}...`);else if(e==="timer")process.stdout.write(`${A} ${u} ${b(c)}`);else{const I=".".repeat(Math.floor(O)).slice(0,3);process.stdout.write(`${A} ${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(ld):T===1?q.red(id):q.red(ud);u=y(E??u),e==="timer"?process.stdout.write(`${O} ${u} ${b(c)}
|
|
75
|
+
`):process.stdout.write(`${O} ${u}
|
|
76
|
+
`),h(),o()},"N");return{start:C,stop:w,message:i((E="")=>{u=y(E??u)},"message")}},"Y");var lo=Object.freeze({__proto__:null,confirm:D0,intro:da,isCancel:Pn,outro:be,password:h0,select:oi,spinner:Ot,text:cd});const{version:g0}=Vt,ku=class ku extends Error{};i(ku,"KnownError");let le=ku;const ai=" ",dd=i(e=>{e instanceof Error&&!(e instanceof le)&&(e.stack&&console.error(io(e.stack.split(`
|
|
77
|
+
`).slice(1).join(`
|
|
78
|
+
`))),console.error(`
|
|
79
|
+
${ai}${io(`aicommits v${g0}`)}`),console.error(`
|
|
80
|
+
${ai}Please open a Bug report with the information above:`),console.error(`${ai}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"),si=i(async()=>{const{stdout:e,failed:t}=await He("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new le("The current directory must be a Git repository!");return e},"assertGitRepo"),pa=i(e=>`:(exclude)${e}`,"excludeFromDiff"),pd=["package-lock.json","pnpm-lock.yaml","*.lock"],v0=i(e=>pd.some(t=>t.includes("*")?e.endsWith(".lock"):e.endsWith("/"+t)||e===t),"isLockFile"),fd=pd.map(pa),md=i(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await He("git",[...t,"--name-only",...e?e.map(pa):[]]);if(!n)return;const o=n.split(`
|
|
82
|
+
`).filter(Boolean).some(l=>!v0(l));let s=[];o&&(s=[...fd]),s=[...s,...e?e.map(pa):[]];const{stdout:a}=await He("git",[...t,"--name-only",...s]);if(!a)return;const{stdout:u}=await He("git",[...t,...s]);return{files:a.split(`
|
|
83
|
+
`),diff:u}},"getStagedDiff"),y0=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...fd,...t?t.map(pa):[]],{stdout:o}=await He("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 ii,Dd;function _0(){if(Dd)return ii;Dd=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
|
|
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 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 ii={parse:o,decode:o,stringify:n,encode:n,safe:a,unsafe:u},ii}i(_0,"requireIni");var b0=_0(),gd=un(b0);const ui=i(e=>Je.lstat(e).then(()=>!0,()=>!1),"fileExists"),C0=["plain","conventional","gitmoji","subject+body"],{hasOwnProperty:w0}=Object.prototype,li=i((e,t)=>w0.call(e,t),"hasOwn"),Rt=i((e,t,n)=>{if(!t)throw new le(`Invalid config property ${e}: ${n}`)},"parseAssert"),fa={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",C0.includes(e),"Invalid commit type"),e):"plain"},proxy(e){if(!(!e||e.length===0))throw new le('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}},F0={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},E0={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},x0={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.id||t.name).map(t=>t.id||t.name),"modelsFilter"),defaultModels:["qwen3.5:4b","llama3.2:latest"],requiresApiKey:!1,cacheModels:!1,isLocal:!0},k0={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},I0={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"}},A0={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,cacheModels:!1,isLocal:!0},$0={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},T0={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},co=[F0,E0,$0,T0,x0,A0,I0,k0],S0=i(()=>co.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),B0=i((e,t)=>{if(e){const n=co.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"),ci=i(()=>Ct.join($l.homedir(),".aicommits"),"getConfigPath"),vd=i(async()=>{if(!await ui(ci()))return Object.create(null);const t=await Je.readFile(ci(),"utf8");return gd.parse(t)},"readConfigFile"),hn=i(async(e,t,n)=>{const r=await vd();li(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const o={},s=t??{};for(const c of Object.keys(fa)){const d=fa[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=S0(),o.OPENAI_BASE_URL=u),a=B0(u,l),{...o,model:o.OPENAI_MODEL,provider:a}},"getConfig"),di=i(async e=>{const t=await vd();for(const[n,r]of e){if(!li(fa,n))throw new le(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const o=fa[n](r);t[n]=o}}await Je.writeFile(ci(),gd.stringify(t),"utf8")},"setConfigs"),yd=i(e=>`\u2705 ${e} (current)`,"CURRENT_LABEL_FORMAT"),O0=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"),R0=i(e=>{const t=XD.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),bd=i(e=>Ct.join(_d(),`${e}.json`),"getCachePath"),N0=i(async e=>{const t=bd(e);try{if(!await ui(t))return null;const n=await Je.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),P0=i(async(e,t)=>{try{const n=_d();await Je.mkdir(n,{recursive:!0});const r=bd(e);await Je.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),pi=i(async e=>{const{baseUrl:t,apiKey:n="",cacheModels:r=!0}=e,o=R0(t),s=Date.now();if(r){const a=await N0(o);if(a&&s-a.timestamp<O0)return a.data}try{const a=await fetch(`${t}/models`,{headers:{Authorization:`Bearer ${n}`}});if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);const u=await a.json(),l=(u.data?u.data:u)||[],c={models:l};return r&&l.length>0&&await P0(o,{data:c,timestamp:s}),c}catch(a){const u=a instanceof Error?a.message:"Request failed";return{models:[],error:u}}},"fetchModels"),M0=i(async(e,t,n)=>{const r=await pi({baseUrl:e,apiKey:t,cacheModels:n?.cacheModels});r.error&&console.error(`Failed to fetch models: ${r.error}`);let o=[];const s=Array.isArray(r.models)?r.models:[];return n?.modelsFilter?o=n.modelsFilter(s):o=s.map(a=>a.id||a.name).filter(Boolean),o},"fetchAndFilterModels"),j0=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"),z0=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"),L0=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 M0(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 lo});let f=j0(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 z0(a,l,c,d);if(h===null)return null;D=h}if(D==="custom"){if(u=await L0(c),u===null)return null}else u=D}else{if(r?.isLocal)return console.log(`No models found on ${o||"local provider"}. Please download a model first, then run \`aicommits model\` to select it.`),null;console.log("Could not fetch available models. Please specify a model name manually.");const{text:l,isCancel:c}=await Promise.resolve().then(function(){return lo});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 q0=Object.freeze({__proto__:null,fetchModels:pi,selectModel:Cd}),U0=Object.defineProperty,Z0=i((e,t,n)=>t in e?U0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),wd=i((e,t,n)=>Z0(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 lo}),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 pi({baseUrl:t,apiKey:n,cacheModels:this.def.cacheModels});if(r.error)return{models:[],error:r.error};const o=Array.isArray(r.models)?r.models:[];let s;return this.def.modelsFilter?s=this.def.modelsFilter(o):s=o.map(a=>a.id||a.name).filter(Boolean),{models:s}}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 fi=Iu;function jn(e){const t=e.provider,n=co.find(r=>r.name===t);return n?new fi(n,e):null}i(jn,"getProvider");function V0(){return co.map(e=>({value:e.name,label:e.displayName}))}i(V0,"getAvailableProviders");function G0(e){return co.find(n=>n.name===e)?.baseUrl||""}i(G0,"getProviderBaseUrl");var Fd="vercel.ai.error",W0=Symbol.for(Fd),Ed,xd,X=(In=class extends(xd=Error,Ed=W0,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}`,H0=Symbol.for(Id),Ad,$d,Be=(er=class extends($d=X,Ad=H0,$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 X.hasMarker(t,Id)}},i(er,"APICallError"),er),Td="AI_EmptyResponseBodyError",Sd=`vercel.ai.error.${Td}`,J0=Symbol.for(Sd),Bd,Od,K0=(tr=class extends(Od=X,Bd=J0,Od){constructor({message:t="Empty response body"}={}){super({name:Td,message:t}),this[Bd]=!0}static isInstance(t){return X.hasMarker(t,Sd)}},i(tr,"EmptyResponseBodyError"),tr);function po(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(po,"getErrorMessage$1");var Rd="AI_InvalidArgumentError",Nd=`vercel.ai.error.${Rd}`,Y0=Symbol.for(Nd),Pd,Md,jd=(nr=class extends(Md=X,Pd=Y0,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 X.hasMarker(t,Nd)}},i(nr,"InvalidArgumentError"),nr),zd="AI_InvalidPromptError",Ld=`vercel.ai.error.${zd}`,X0=Symbol.for(Ld),qd,Ud,Ht=(rr=class extends(Ud=X,qd=X0,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 X.hasMarker(t,Ld)}},i(rr,"InvalidPromptError"),rr),Zd="AI_InvalidResponseDataError",Vd=`vercel.ai.error.${Zd}`,Q0=Symbol.for(Vd),Gd,Wd,fo=(or=class extends(Wd=X,Gd=Q0,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 X.hasMarker(t,Vd)}},i(or,"InvalidResponseDataError"),or),Hd="AI_JSONParseError",Jd=`vercel.ai.error.${Hd}`,e_=Symbol.for(Jd),Kd,Yd,ma=(ar=class extends(Yd=X,Kd=e_,Yd){constructor({text:t,cause:n}){super({name:Hd,message:`JSON parsing failed: Text: ${t}.
|
|
86
|
+
Error message: ${po(n)}`,cause:n}),this[Kd]=!0,this.text=t}static isInstance(t){return X.hasMarker(t,Jd)}},i(ar,"JSONParseError"),ar),Xd="AI_LoadAPIKeyError",Qd=`vercel.ai.error.${Xd}`,t_=Symbol.for(Qd),ep,tp,ha=(sr=class extends(tp=X,ep=t_,tp){constructor({message:t}){super({name:Xd,message:t}),this[ep]=!0}static isInstance(t){return X.hasMarker(t,Qd)}},i(sr,"LoadAPIKeyError"),sr),np="AI_TooManyEmbeddingValuesForCallError",rp=`vercel.ai.error.${np}`,n_=Symbol.for(rp),op,ap,sp=(ir=class extends(ap=X,op=n_,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 X.hasMarker(t,rp)}},i(ir,"TooManyEmbeddingValuesForCallError"),ir),ip="AI_TypeValidationError",up=`vercel.ai.error.${ip}`,r_=Symbol.for(up),lp,cp,Dn=(on=class extends(cp=X,lp=r_,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: ${po(n)}`,cause:n}),this[lp]=!0,this.value=t,this.context=r}static isInstance(t){return X.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}`,o_=Symbol.for(pp),fp,mp,Qe=(ur=class extends(mp=X,fp=o_,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 X.hasMarker(t,pp)}},i(ur,"UnsupportedFunctionalityError"),ur);function $(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($,"$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 a_(e,t){return typeof t=="bigint"?t.toString():t}i(a_,"jsonStringifyReplacer");function mi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(mi,"cached");function hi(e){return e==null}i(hi,"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 s_(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(s_,"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 Da(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(Da,"assignProp");function mo(e){return JSON.stringify(e)}i(mo,"esc");const gp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function ga(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ga,"isObject");const i_=mi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function va(e){if(ga(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(ga(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(va,"isPlainObject");const u_=new Set(["string","number","symbol"]);function ho(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(ho,"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 l_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(l_,"optionalKeys");const c_={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 d_(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(d_,"pick");function p_(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(p_,"omit");function f_(e,t){if(!va(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 Da(this,"shape",r),r},checks:[]};return vn(e,n)}i(f_,"extend");function m_(e,t){return vn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Da(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(m_,"merge");function h_(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(h_,"partial");function D_(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(D_,"required");function Do(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(Do,"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 ya(e){return typeof e=="string"?e:e?.message}i(ya,"unwrapMessage");function Kt(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=ya(e.inst?._zod.def?.error?.(e))??ya(t?.error?.(e))??ya(n.customError?.(e))??ya(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 gi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(gi,"getLengthableOrigin");function go(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(go,"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,a_,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),yp=$("$ZodError",vp),_p=$("$ZodError",vp,{Parent:Error});function g_(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(g_,"flattenError");function v_(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(v_,"formatError");const y_=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"),__=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"),b_=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"),C_=Cp(_p),w_=/^[cC][^\s-]{8,}$/,F_=/^[0-9a-z]+$/,E_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,x_=/^[0-9a-vA-V]{20}$/,k_=/^[A-Za-z0-9]{27}$/,I_=/^[a-zA-Z0-9_-]{21}$/,A_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$_=/^([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"),T_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,S_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function B_(){return new RegExp(S_,"u")}i(B_,"emoji");const 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])$/,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})$/,N_=/^((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])$/,P_=/^(([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])$/,M_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fp=/^[A-Za-z0-9_-]*$/,j_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,z_=/^\+(?:[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])))",L_=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 q_(e){return new RegExp(`^${xp(e)}$`)}i(q_,"time$1");function U_(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(U_,"datetime$1");const Z_=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),V_=/^\d+$/,G_=/^-?\d+(?:\.\d+)?/i,W_=/true|false/i,H_=/null/i,J_=/^[^A-Z]*$/,K_=/^[^a-z]*$/,ut=$("$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=$("$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=$("$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})}}),Y_=$("$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):s_(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})}}),X_=$("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=c_[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=V_)}),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})}}),Q_=$("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!hi(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=gi(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),eb=$("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!hi(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=gi(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tb=$("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!hi(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=gi(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})}}),_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=()=>{})}),nb=$("$ZodCheckRegex",(e,t)=>{_a.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})}}),rb=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=J_),_a.init(e,t)}),ob=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=K_),_a.init(e,t)}),ab=$("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=ho(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})}}),sb=$("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${ho(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})}}),ib=$("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${ho(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})}}),ub=$("$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
|
+
`).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($u,"Doc");let vi=$u;const lb={major:4,minor:0,patch:0},we=$("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lb;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=Do(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=Do(s,f)))});else{if(s.issues.length===f)continue;l||(l=Do(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=b_(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return C_(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),yi=$("$ZodString",(e,t)=>{we.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=$("$ZodStringFormat",(e,t)=>{_a.init(e,t),yi.init(e,t)}),cb=$("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=$_),Se.init(e,t)}),db=$("$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)}),pb=$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=T_),Se.init(e,t)}),fb=$("$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:j_.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})}}}),mb=$("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=B_()),Se.init(e,t)}),hb=$("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=I_),Se.init(e,t)}),Db=$("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=w_),Se.init(e,t)}),gb=$("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=F_),Se.init(e,t)}),vb=$("$ZodULID",(e,t)=>{t.pattern??(t.pattern=E_),Se.init(e,t)}),yb=$("$ZodXID",(e,t)=>{t.pattern??(t.pattern=x_),Se.init(e,t)}),_b=$("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=k_),Se.init(e,t)}),bb=$("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=U_(t)),Se.init(e,t)}),Cb=$("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=L_),Se.init(e,t)}),wb=$("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=q_(t)),Se.init(e,t)}),Fb=$("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=A_),Se.init(e,t)}),Eb=$("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=O_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),xb=$("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=R_),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})}}}),kb=$("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=N_),Se.init(e,t)}),Ib=$("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=P_),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 Ab=$("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=M_),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 $b(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($b,"isValidBase64URL");const Tb=$("$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=>{$b(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Sb=$("$ZodE164",(e,t)=>{t.pattern??(t.pattern=z_),Se.init(e,t)});function Bb(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(Bb,"isValidJWT$1");const Ob=$("$ZodJWT",(e,t)=>{Se.init(e,t),e._zod.check=n=>{Bb(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Tp=$("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??G_,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}}),Rb=$("$ZodNumber",(e,t)=>{X_.init(e,t),Tp.init(e,t)}),Nb=$("$ZodBoolean",(e,t)=>{we.init(e,t),e._zod.pattern=W_,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}}),Pb=$("$ZodNull",(e,t)=>{we.init(e,t),e._zod.pattern=H_,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}}),Mb=$("$ZodAny",(e,t)=>{we.init(e,t),e._zod.parse=n=>n}),jb=$("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=n=>n}),zb=$("$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 Lb=$("$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 ba(e,t,n){e.issues.length&&t.issues.push(...yn(n,e.issues)),t.value[n]=e.value}i(ba,"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 qb=$("$ZodObject",(e,t)=>{we.init(e,t);const n=mi(()=>{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=l_(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 vi(["shape","payload","ctx"]),D=n.value,h=i(C=>{const w=mo(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=mo(C);m.write(`
|
|
90
|
+
if (${w}.issues.length) {
|
|
91
|
+
if (input[${E}] === undefined) {
|
|
92
|
+
if (${E} in input) {
|
|
93
|
+
newResult[${E}] = undefined;
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
payload.issues = payload.issues.concat(
|
|
97
|
+
${w}.issues.map((iss) => ({
|
|
98
|
+
...iss,
|
|
99
|
+
path: iss.path ? [${E}, ...iss.path] : [${E}],
|
|
100
|
+
}))
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
} else if (${w}.value === undefined) {
|
|
104
|
+
if (${E} in input) newResult[${E}] = undefined;
|
|
105
|
+
} else {
|
|
106
|
+
newResult[${E}] = ${w}.value;
|
|
107
|
+
}
|
|
108
|
+
`)}else{const w=v[C];m.write(`const ${w} = ${h(C)};`),m.write(`
|
|
109
|
+
if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
|
|
110
|
+
...iss,
|
|
111
|
+
path: iss.path ? [${mo(C)}, ...iss.path] : [${mo(C)}]
|
|
112
|
+
})));`),m.write(`newResult[${mo(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=ga,a=!hp.jitless,l=a&&i_.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),A=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?h.push(O.then(I=>A?Bp(I,f,E,D):ba(I,f,E))):A?Bp(O,f,E,D):ba(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=>ba(T,f,w))):ba(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=$("$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=>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=>Op(a,n,e,r)):Op(s,n,e,r)}}),Ub=$("$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=mi(()=>{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(!ga(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=$("$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 _i(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(va(e)&&va(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=_i(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=_i(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(_i,"mergeValues$1");function Np(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Do(e))return e;const r=_i(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 Vb=$("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!va(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}}),Gb=$("$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=>u_.has(typeof r)).map(r=>typeof r=="string"?ho(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}}),Wb=$("$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"?ho(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}}),Hb=$("$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}}),Jb=$("$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(`^(${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)}),Kb=$("$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(`^(${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)}),Yb=$("$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 Xb=$("$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))}),Qb=$("$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 eC=$("$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)}}),tC=$("$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 Do(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(jp,"handlePipeResult");const nC=$("$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 rC=$("$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)}),oC=$("$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(go(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 Ca=Tu;function aC(){return new Ca}i(aC,"registry");const vo=aC();function sC(e,t){return new e({type:"string",...G(t)})}i(sC,"_string");function iC(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...G(t)})}i(iC,"_email");function qp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...G(t)})}i(qp,"_guid");function uC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...G(t)})}i(uC,"_uuid");function lC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(t)})}i(lC,"_uuidv4");function cC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(t)})}i(cC,"_uuidv6");function dC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(t)})}i(dC,"_uuidv7");function pC(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...G(t)})}i(pC,"_url");function fC(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...G(t)})}i(fC,"_emoji");function mC(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(t)})}i(mC,"_nanoid");function hC(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...G(t)})}i(hC,"_cuid");function DC(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(t)})}i(DC,"_cuid2");function gC(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...G(t)})}i(gC,"_ulid");function vC(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...G(t)})}i(vC,"_xid");function yC(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(t)})}i(yC,"_ksuid");function _C(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(t)})}i(_C,"_ipv4");function bC(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(t)})}i(bC,"_ipv6");function CC(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(t)})}i(CC,"_cidrv4");function wC(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(t)})}i(wC,"_cidrv6");function FC(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...G(t)})}i(FC,"_base64");function EC(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...G(t)})}i(EC,"_base64url");function xC(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...G(t)})}i(xC,"_e164");function kC(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...G(t)})}i(kC,"_jwt");function IC(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(t)})}i(IC,"_isoDateTime");function AC(e,t){return new e({type:"string",format:"date",check:"string_format",...G(t)})}i(AC,"_isoDate");function $C(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...G(t)})}i($C,"_isoTime");function TC(e,t){return new e({type:"string",format:"duration",check:"string_format",...G(t)})}i(TC,"_isoDuration");function SC(e,t){return new e({type:"number",checks:[],...G(t)})}i(SC,"_number");function BC(e,t){return new e({type:"number",coerce:!0,checks:[],...G(t)})}i(BC,"_coercedNumber");function OC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...G(t)})}i(OC,"_int");function RC(e,t){return new e({type:"boolean",...G(t)})}i(RC,"_boolean");function NC(e,t){return new e({type:"null",...G(t)})}i(NC,"_null$1");function PC(e){return new e({type:"any"})}i(PC,"_any");function MC(e){return new e({type:"unknown"})}i(MC,"_unknown");function jC(e,t){return new e({type:"never",...G(t)})}i(jC,"_never");function Up(e,t){return new Ip({check:"less_than",...G(t),value:e,inclusive:!1})}i(Up,"_lt");function bi(e,t){return new Ip({check:"less_than",...G(t),value:e,inclusive:!0})}i(bi,"_lte");function Zp(e,t){return new Ap({check:"greater_than",...G(t),value:e,inclusive:!1})}i(Zp,"_gt");function Ci(e,t){return new Ap({check:"greater_than",...G(t),value:e,inclusive:!0})}i(Ci,"_gte");function Vp(e,t){return new Y_({check:"multiple_of",...G(t),value:e})}i(Vp,"_multipleOf");function Gp(e,t){return new Q_({check:"max_length",...G(t),maximum:e})}i(Gp,"_maxLength");function wa(e,t){return new eb({check:"min_length",...G(t),minimum:e})}i(wa,"_minLength");function Wp(e,t){return new tb({check:"length_equals",...G(t),length:e})}i(Wp,"_length");function zC(e,t){return new nb({check:"string_format",format:"regex",...G(t),pattern:e})}i(zC,"_regex");function LC(e){return new rb({check:"string_format",format:"lowercase",...G(e)})}i(LC,"_lowercase");function qC(e){return new ob({check:"string_format",format:"uppercase",...G(e)})}i(qC,"_uppercase");function UC(e,t){return new ab({check:"string_format",format:"includes",...G(t),includes:e})}i(UC,"_includes");function ZC(e,t){return new sb({check:"string_format",format:"starts_with",...G(t),prefix:e})}i(ZC,"_startsWith");function VC(e,t){return new ib({check:"string_format",format:"ends_with",...G(t),suffix:e})}i(VC,"_endsWith");function yo(e){return new ub({check:"overwrite",tx:e})}i(yo,"_overwrite");function GC(e){return yo(t=>t.normalize(e))}i(GC,"_normalize");function WC(){return yo(e=>e.trim())}i(WC,"_trim");function HC(){return yo(e=>e.toLowerCase())}i(HC,"_toLowerCase");function JC(){return yo(e=>e.toUpperCase())}i(JC,"_toUpperCase");function KC(e,t,n){return new e({type:"array",element:t,...G(n)})}i(KC,"_array");function YC(e,t,n){const r=G(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(YC,"_custom");function XC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...G(n)})}i(XC,"_refine");const Su=class Su{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??vo,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
|
+
|
|
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 Fa=Su;function QC(e,t){if(e instanceof Ca){const r=new Fa(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 Fa(t);return n.process(e),n.emit(e,t)}i(QC,"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 ew=$("ZodISODateTime",(e,t)=>{bb.init(e,t),Oe.init(e,t)});function tw(e){return IC(ew,e)}i(tw,"datetime");const nw=$("ZodISODate",(e,t)=>{Cb.init(e,t),Oe.init(e,t)});function rw(e){return AC(nw,e)}i(rw,"date");const ow=$("ZodISOTime",(e,t)=>{wb.init(e,t),Oe.init(e,t)});function aw(e){return $C(ow,e)}i(aw,"time");const sw=$("ZodISODuration",(e,t)=>{Fb.init(e,t),Oe.init(e,t)});function iw(e){return TC(sw,e)}i(iw,"duration");const uw=i((e,t)=>{yp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>v_(e,n),"value")},flatten:{value:i(n=>g_(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"),Ea=$("ZodError",uw,{Parent:Error}),lw=y_(Ea),cw=__(Ea),dw=bp(Ea),Hp=Cp(Ea),Ie=$("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)=>lw(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>dw(e,n,r),e.parseAsync=async(n,r)=>cw(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(a2(n,r)),e.superRefine=n=>e.check(s2(n)),e.overwrite=n=>e.check(yo(n)),e.optional=()=>nf(e),e.nullable=()=>rf(e),e.nullish=()=>nf(rf(e)),e.nonoptional=n=>Kw(e,n),e.array=()=>S(e),e.or=n=>Q([e,n]),e.and=n=>zw(e,n),e.transform=n=>af(e,Zw(n)),e.default=n=>Ww(e,n),e.prefault=n=>Jw(e,n),e.catch=n=>Xw(e,n),e.pipe=n=>af(e,n),e.readonly=()=>t2(e),e.describe=n=>{const r=e.clone();return vo.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return vo.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return vo.get(e);const r=e.clone();return vo.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Jp=$("_ZodString",(e,t)=>{yi.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(zC(...r)),e.includes=(...r)=>e.check(UC(...r)),e.startsWith=(...r)=>e.check(ZC(...r)),e.endsWith=(...r)=>e.check(VC(...r)),e.min=(...r)=>e.check(wa(...r)),e.max=(...r)=>e.check(Gp(...r)),e.length=(...r)=>e.check(Wp(...r)),e.nonempty=(...r)=>e.check(wa(1,...r)),e.lowercase=r=>e.check(LC(r)),e.uppercase=r=>e.check(qC(r)),e.trim=()=>e.check(WC()),e.normalize=(...r)=>e.check(GC(...r)),e.toLowerCase=()=>e.check(HC()),e.toUpperCase=()=>e.check(JC())}),pw=$("ZodString",(e,t)=>{yi.init(e,t),Jp.init(e,t),e.email=n=>e.check(iC(fw,n)),e.url=n=>e.check(pC(mw,n)),e.jwt=n=>e.check(kC(Aw,n)),e.emoji=n=>e.check(fC(hw,n)),e.guid=n=>e.check(qp(Kp,n)),e.uuid=n=>e.check(uC(xa,n)),e.uuidv4=n=>e.check(lC(xa,n)),e.uuidv6=n=>e.check(cC(xa,n)),e.uuidv7=n=>e.check(dC(xa,n)),e.nanoid=n=>e.check(mC(Dw,n)),e.guid=n=>e.check(qp(Kp,n)),e.cuid=n=>e.check(hC(gw,n)),e.cuid2=n=>e.check(DC(vw,n)),e.ulid=n=>e.check(gC(yw,n)),e.base64=n=>e.check(FC(xw,n)),e.base64url=n=>e.check(EC(kw,n)),e.xid=n=>e.check(vC(_w,n)),e.ksuid=n=>e.check(yC(bw,n)),e.ipv4=n=>e.check(_C(Cw,n)),e.ipv6=n=>e.check(bC(ww,n)),e.cidrv4=n=>e.check(CC(Fw,n)),e.cidrv6=n=>e.check(wC(Ew,n)),e.e164=n=>e.check(xC(Iw,n)),e.datetime=n=>e.check(tw(n)),e.date=n=>e.check(rw(n)),e.time=n=>e.check(aw(n)),e.duration=n=>e.check(iw(n))});function p(e){return sC(pw,e)}i(p,"string");const Oe=$("ZodStringFormat",(e,t)=>{Se.init(e,t),Jp.init(e,t)}),fw=$("ZodEmail",(e,t)=>{pb.init(e,t),Oe.init(e,t)}),Kp=$("ZodGUID",(e,t)=>{cb.init(e,t),Oe.init(e,t)}),xa=$("ZodUUID",(e,t)=>{db.init(e,t),Oe.init(e,t)}),mw=$("ZodURL",(e,t)=>{fb.init(e,t),Oe.init(e,t)}),hw=$("ZodEmoji",(e,t)=>{mb.init(e,t),Oe.init(e,t)}),Dw=$("ZodNanoID",(e,t)=>{hb.init(e,t),Oe.init(e,t)}),gw=$("ZodCUID",(e,t)=>{Db.init(e,t),Oe.init(e,t)}),vw=$("ZodCUID2",(e,t)=>{gb.init(e,t),Oe.init(e,t)}),yw=$("ZodULID",(e,t)=>{vb.init(e,t),Oe.init(e,t)}),_w=$("ZodXID",(e,t)=>{yb.init(e,t),Oe.init(e,t)}),bw=$("ZodKSUID",(e,t)=>{_b.init(e,t),Oe.init(e,t)}),Cw=$("ZodIPv4",(e,t)=>{Eb.init(e,t),Oe.init(e,t)}),ww=$("ZodIPv6",(e,t)=>{xb.init(e,t),Oe.init(e,t)}),Fw=$("ZodCIDRv4",(e,t)=>{kb.init(e,t),Oe.init(e,t)}),Ew=$("ZodCIDRv6",(e,t)=>{Ib.init(e,t),Oe.init(e,t)}),xw=$("ZodBase64",(e,t)=>{Ab.init(e,t),Oe.init(e,t)}),kw=$("ZodBase64URL",(e,t)=>{Tb.init(e,t),Oe.init(e,t)}),Iw=$("ZodE164",(e,t)=>{Sb.init(e,t),Oe.init(e,t)}),Aw=$("ZodJWT",(e,t)=>{Ob.init(e,t),Oe.init(e,t)}),wi=$("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(Ci(r,o)),e.min=(r,o)=>e.check(Ci(r,o)),e.lt=(r,o)=>e.check(Up(r,o)),e.lte=(r,o)=>e.check(bi(r,o)),e.max=(r,o)=>e.check(bi(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(Ci(0,r)),e.negative=r=>e.check(Up(0,r)),e.nonpositive=r=>e.check(bi(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 SC(wi,e)}i(x,"number$1");const $w=$("ZodNumberFormat",(e,t)=>{Rb.init(e,t),wi.init(e,t)});function Yp(e){return OC($w,e)}i(Yp,"int");const Tw=$("ZodBoolean",(e,t)=>{Nb.init(e,t),Ie.init(e,t)});function Re(e){return RC(Tw,e)}i(Re,"boolean");const Sw=$("ZodNull",(e,t)=>{Pb.init(e,t),Ie.init(e,t)});function Xp(e){return NC(Sw,e)}i(Xp,"_null");const Bw=$("ZodAny",(e,t)=>{Mb.init(e,t),Ie.init(e,t)});function et(){return PC(Bw)}i(et,"any");const Ow=$("ZodUnknown",(e,t)=>{jb.init(e,t),Ie.init(e,t)});function lt(){return MC(Ow)}i(lt,"unknown");const Rw=$("ZodNever",(e,t)=>{zb.init(e,t),Ie.init(e,t)});function Nw(e){return jC(Rw,e)}i(Nw,"never");const Pw=$("ZodArray",(e,t)=>{Lb.init(e,t),Ie.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(wa(n,r)),e.nonempty=n=>e.check(wa(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 KC(Pw,e,t)}i(S,"array$1");const Qp=$("ZodObject",(e,t)=>{qb.init(e,t),Ie.init(e,t),De(e,"shape",()=>t.shape),e.keyof=()=>ue(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:Nw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>f_(e,n),e.merge=n=>m_(e,n),e.pick=n=>d_(e,n),e.omit=n=>p_(e,n),e.partial=(...n)=>h_(tf,e,n[0]),e.required=(...n)=>D_(of,e,n[0])});function g(e,t){const n={type:"object",get shape(){return Da(this,"shape",{...e}),this.shape},...G(t)};return new Qp(n)}i(g,"object$1");function Fi(e,t){return new Qp({type:"object",get shape(){return Da(this,"shape",{...e}),this.shape},catchall:lt(),...G(t)})}i(Fi,"looseObject");const ef=$("ZodUnion",(e,t)=>{Rp.init(e,t),Ie.init(e,t),e.options=t.options});function Q(e,t){return new ef({type:"union",options:e,...G(t)})}i(Q,"union");const Mw=$("ZodDiscriminatedUnion",(e,t)=>{ef.init(e,t),Ub.init(e,t)});function ge(e,t,n){return new Mw({type:"union",options:t,discriminator:e,...G(n)})}i(ge,"discriminatedUnion");const jw=$("ZodIntersection",(e,t)=>{Zb.init(e,t),Ie.init(e,t)});function zw(e,t){return new jw({type:"intersection",left:e,right:t})}i(zw,"intersection");const Lw=$("ZodRecord",(e,t)=>{Vb.init(e,t),Ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Ce(e,t,n){return new Lw({type:"record",keyType:e,valueType:t,...G(n)})}i(Ce,"record");const Ei=$("ZodEnum",(e,t)=>{Gb.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 Ei({...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 Ei({...t,checks:[],...G(o),entries:s})}});function ue(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ei({type:"enum",entries:n,...G(t)})}i(ue,"_enum");const qw=$("ZodLiteral",(e,t)=>{Wb.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 qw({type:"literal",values:Array.isArray(e)?e:[e],...G(t)})}i(F,"literal");const Uw=$("ZodTransform",(e,t)=>{Hb.init(e,t),Ie.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(go(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(go(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 Uw({type:"transform",transform:e})}i(Zw,"transform");const tf=$("ZodOptional",(e,t)=>{Jb.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 Vw=$("ZodNullable",(e,t)=>{Kb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rf(e){return new Vw({type:"nullable",innerType:e})}i(rf,"nullable");const Gw=$("ZodDefault",(e,t)=>{Yb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ww(e,t){return new Gw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Ww,"_default");const Hw=$("ZodPrefault",(e,t)=>{Xb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Jw(e,t){return new Hw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Jw,"prefault");const of=$("ZodNonOptional",(e,t)=>{Qb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Kw(e,t){return new of({type:"nonoptional",innerType:e,...G(t)})}i(Kw,"nonoptional");const Yw=$("ZodCatch",(e,t)=>{eC.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Xw(e,t){return new Yw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(Xw,"_catch");const Qw=$("ZodPipe",(e,t)=>{tC.init(e,t),Ie.init(e,t),e.in=t.in,e.out=t.out});function af(e,t){return new Qw({type:"pipe",in:e,out:t})}i(af,"pipe");const e2=$("ZodReadonly",(e,t)=>{nC.init(e,t),Ie.init(e,t)});function t2(e){return new e2({type:"readonly",innerType:e})}i(t2,"readonly");const n2=$("ZodLazy",(e,t)=>{rC.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.getter()});function xi(e){return new n2({type:"lazy",getter:e})}i(xi,"lazy");const ki=$("ZodCustom",(e,t)=>{oC.init(e,t),Ie.init(e,t)});function r2(e){const t=new ut({check:"custom"});return t._zod.check=e,t}i(r2,"check");function o2(e,t){return YC(ki,e??(()=>!0),t)}i(o2,"custom");function a2(e,t={}){return XC(ki,e,t)}i(a2,"refine");function s2(e){const t=r2(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(go(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(go(o))}},e(n.value,n)));return t}i(s2,"superRefine");function ka(e,t={error:`Input not instance of ${e.name}`}){const n=new ki({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...G(t)});return n._zod.bag.Class=e,n}i(ka,"_instanceof");function i2(e){return BC(wi,e)}i(i2,"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"]),as=class as 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 as))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(as,"ZodError");let zt=as;zt.create=e=>new zt(e);const Ii=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 u2=Ii;function l2(){return u2}i(l2,"getErrorMap");const c2=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=l2(),r=c2({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ii?void 0:Ii].filter(o=>!!o)});e.common.issues.push(r)}i(Z,"addIssueToContext");const ss=class ss{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 te;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 ss.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 te;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(ss,"ParseStatus");let ht=ss;const te=Object.freeze({status:"aborted"}),_o=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"),Ia=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 ce(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(ce,"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(Ia(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(Ia(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:P.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({...ce(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Fo({...ce(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new Ti({typeName:P.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Eo({...ce(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Si.create(this,t)}readonly(){return xo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};i(Ou,"ZodType");let fe=Ou;const d2=/^c[^\s-]{8,}$/i,p2=/^[0-9a-z]+$/,f2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,m2=/^[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,h2=/^[a-z0-9_-]{21}$/i,D2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,g2=/^[-+]?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)?)??$/,v2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,y2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ai;const _2=/^(?:(?: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])$/,b2=/^(?:(?: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])$/,C2=/^(([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]))$/,w2=/^(([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])$/,F2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,E2=/^([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])))",x2=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 k2(e){return new RegExp(`^${pf(e)}$`)}i(k2,"timeRegex");function I2(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(I2,"datetimeRegex");function A2(e,t){return!!((t==="v4"||!t)&&_2.test(e)||(t==="v6"||!t)&&C2.test(e))}i(A2,"isValidIP");function $2(e,t){if(!D2.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($2,"isValidJWT");function T2(e,t){return!!((t==="v4"||!t)&&b2.test(e)||(t==="v6"||!t)&&w2.test(e))}i(T2,"isValidCidr");const kn=class kn extends fe{_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}),te}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")v2.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")Ai||(Ai=new RegExp(y2,"u")),Ai.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")m2.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")h2.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")d2.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")p2.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")f2.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"?I2(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"?x2.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?k2(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"?g2.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?A2(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"?$2(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"?T2(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"?F2.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?E2.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 bo=kn;bo.create=e=>new bo({checks:[],typeName:P.ZodString,coerce:e?.coerce??!1,...ce(e)});function S2(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(S2,"floatSafeRemainder");const jo=class jo extends fe{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}),te}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"?S2(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 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]})}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(jo,"ZodNumber");let Co=jo;Co.create=e=>new Co({checks:[],typeName:P.ZodNumber,coerce:e?.coerce||!1,...ce(e)});const zo=class zo extends fe{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}),te}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 zo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new zo({...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(zo,"ZodBigInt");let Aa=zo;Aa.create=e=>new Aa({checks:[],typeName:P.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});const Ru=class Ru extends fe{_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}),te}return _t(t.data)}};i(Ru,"ZodBoolean");let $a=Ru;$a.create=e=>new $a({typeName:P.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});const is=class is extends fe{_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}),te}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_date}),te}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 is({...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(is,"ZodDate");let Ta=is;Ta.create=e=>new Ta({checks:[],coerce:e?.coerce||!1,typeName:P.ZodDate,...ce(e)});const Nu=class Nu extends fe{_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}),te}return _t(t.data)}};i(Nu,"ZodSymbol");let Sa=Nu;Sa.create=e=>new Sa({typeName:P.ZodSymbol,...ce(e)});const Pu=class Pu extends fe{_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}),te}return _t(t.data)}};i(Pu,"ZodUndefined");let Ba=Pu;Ba.create=e=>new Ba({typeName:P.ZodUndefined,...ce(e)});const Mu=class Mu extends fe{_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}),te}return _t(t.data)}};i(Mu,"ZodNull");let Oa=Mu;Oa.create=e=>new Oa({typeName:P.ZodNull,...ce(e)});const ju=class ju extends fe{constructor(){super(...arguments),this._any=!0}_parse(t){return _t(t.data)}};i(ju,"ZodAny");let Ra=ju;Ra.create=e=>new Ra({typeName:P.ZodAny,...ce(e)});const zu=class zu extends fe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return _t(t.data)}};i(zu,"ZodUnknown");let Na=zu;Na.create=e=>new Na({typeName:P.ZodUnknown,...ce(e)});const Lu=class Lu extends fe{_parse(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.never,received:n.parsedType}),te}};i(Lu,"ZodNever");let Pt=Lu;Pt.create=e=>new Pt({typeName:P.ZodNever,...ce(e)});const qu=class qu extends fe{_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}),te}return _t(t.data)}};i(qu,"ZodVoid");let Pa=qu;Pa.create=e=>new Pa({typeName:P.ZodVoid,...ce(e)});const Xn=class Xn extends fe{_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}),te;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 Xn({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new Xn({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new Xn({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(t){return this.min(1,t)}};i(Xn,"ZodArray");let Xt=Xn;Xt.create=(e,t)=>new Xt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...ce(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 fe{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}),te}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:P.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:P.ZodObject,...ce(t)}),wt.strictCreate=(e,t)=>new wt({shape:i(()=>e,"shape"),unknownKeys:"strict",catchall:Pt.create(),typeName:P.ZodObject,...ce(t)}),wt.lazycreate=(e,t)=>new wt({shape:e,unknownKeys:"strip",catchall:Pt.create(),typeName:P.ZodObject,...ce(t)});const Uu=class Uu extends fe{_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}),te}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}),te}}get options(){return this._def.options}};i(Uu,"ZodUnion");let qn=Uu;qn.create=(e,t)=>new qn({options:e,typeName:P.ZodUnion,...ce(t)});function $i(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=$i(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=$i(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($i,"mergeValues");const Zu=class Zu extends fe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=i((s,a)=>{if(uf(s)||uf(a))return te;const u=$i(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}),te)},"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:P.ZodIntersection,...ce(n)});const us=class us extends fe{_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}),te;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"}),te;!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 us({...this._def,rest:t})}};i(us,"ZodTuple");let _n=us;_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:P.ZodTuple,rest:null,...ce(t)})};const Vu=class Vu extends fe{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}),te;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 te;(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 te;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}}}};i(Vu,"ZodMap");let Ma=Vu;Ma.create=(e,t,n)=>new Ma({valueType:t,keyType:e,typeName:P.ZodMap,...ce(n)});const Lo=class Lo extends fe{_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}),te;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 te;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 Lo({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new Lo({...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(Lo,"ZodSet");let ja=Lo;ja.create=(e,t)=>new ja({valueType:e,minSize:null,maxSize:null,typeName:P.ZodSet,...ce(t)});const Gu=class Gu extends fe{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 za=Gu;za.create=(e,t)=>new za({getter:e,typeName:P.ZodLazy,...ce(t)});const Wu=class Wu extends fe{_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}),te}return{status:"valid",value:t.data}}get value(){return this._def.value}};i(Wu,"ZodLiteral");let La=Wu;La.create=(e,t)=>new La({value:e,typeName:P.ZodLiteral,...ce(t)});function ff(e,t){return new wo({values:e,typeName:P.ZodEnum,...ce(t)})}i(ff,"createZodEnum");const qo=class qo extends fe{_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}),te}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}),te}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 qo.create(t,{...this._def,...n})}exclude(t,n=this._def){return qo.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};i(qo,"ZodEnum");let wo=qo;wo.create=ff;const Hu=class Hu extends fe{_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}),te}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}),te}return _t(t.data)}get enum(){return this._def.values}};i(Hu,"ZodNativeEnum");let qa=Hu;qa.create=(e,t)=>new qa({values:e,typeName:P.ZodNativeEnum,...ce(t)});const Ju=class Ju extends fe{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}),te;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:P.ZodPromise,...ce(t)});const Ku=class Ku extends fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.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 te;const l=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return l.status==="aborted"?te:l.status==="dirty"||n.value==="dirty"?_o(l.value):l});{if(n.value==="aborted")return te;const u=this._def.schema._parseSync({data:a,path:r.path,parent:r});return u.status==="aborted"?te:u.status==="dirty"||n.value==="dirty"?_o(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"?te:(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"?te:(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 te;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})):te);me.assertNever(o)}};i(Ku,"ZodEffects");let Qt=Ku;Qt.create=(e,t,n)=>new Qt({schema:e,typeName:P.ZodEffects,effect:t,...ce(n)}),Qt.createWithPreprocess=(e,t,n)=>new Qt({schema:t,effect:{type:"preprocess",transform:e},typeName:P.ZodEffects,...ce(n)});const Yu=class Yu extends fe{_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:P.ZodOptional,...ce(t)});const Xu=class Xu extends fe{_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:P.ZodNullable,...ce(t)});const Qu=class Qu extends fe{_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 Fo=Qu;Fo.create=(e,t)=>new Fo({innerType:e,typeName:P.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});const el=class el extends fe{_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 Ia(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 Eo=el;Eo.create=(e,t)=>new Eo({innerType:e,typeName:P.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});const tl=class tl extends fe{_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}),te}return{status:"valid",value:t.data}}};i(tl,"ZodNaN");let Ua=tl;Ua.create=e=>new Ua({typeName:P.ZodNaN,...ce(e)});const nl=class nl extends fe{_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 Ti=nl;const ls=class ls extends fe{_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"?te:s.status==="dirty"?(n.dirty(),_o(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"?te: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 ls({in:t,out:n,typeName:P.ZodPipeline})}};i(ls,"ZodPipeline");let Si=ls;const rl=class rl extends fe{_parse(t){const n=this._def.innerType._parse(t),r=i(o=>(zn(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return Ia(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};i(rl,"ZodReadonly");let xo=rl;xo.create=(e,t)=>new xo({innerType:e,typeName:P.ZodReadonly,...ce(t)});var P;(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"})(P||(P={}));const Fe=bo.create,jt=Co.create;Pt.create;const tn=Xt.create,Ft=wt.create,Bi=qn.create;Un.create,_n.create;const Za=wo.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 Va=ol;function Oi(e){}i(Oi,"noop");function B2(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=Oi,onError:n=Oi,onRetry:r=Oi,onComment:o}=e;let s="",a=!0,u,l="",c="";function d(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[b,C]=O2(`${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 Va(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:b}));break;default:n(new Va(`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(B2,"createParser");function O2(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
|
|
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(O2,"splitLines");const al=class al extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=B2({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 Ri=al;function Ne(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(Ne,"combineHeaders");function R2({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(R2,"createToolNameMapping");async function N2(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(N2,"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:P2,atob:M2}=globalThis;function bn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=M2(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 P2(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}`,j2=Symbol.for(gf),vf,yf,nn=(lr=class extends(yf=X,vf=j2,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 X.hasMarker(t,gf)}},i(lr,"DownloadError"),lr),Ni=2*1024*1024*1024;async function _f({response:e,url:t,maxBytes:n=Ni}){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 Pi(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:Ni}),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(Pi,"downloadBlob");var ko=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=ko();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 z2=["fetch failed","failed to fetch"],L2=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function q2(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&L2.includes(t))}i(q2,"isBunNetworkError");function Cf({error:e,url:t,requestBodyValues:n}){if(Wn(e))return e;if(e instanceof TypeError&&z2.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 q2(e)?new Be({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0}):e}i(Cf,"handleFetchError");function Mi(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(Mi,"getRuntimeEnvironmentUserAgent");function U2(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(U2,"normalizeHeaders");function Cn(e,...t){const n=new Headers(U2(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",Z2=i(()=>globalThis.fetch,"getOriginalFetch"),Ff=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=Z2()})=>{try{const a=await s(e,{method:"GET",headers:Cn(t,`ai-sdk/provider-utils/${wf}`,Mi()),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 V2(e){return e!=null}i(V2,"isNonNullable");function G2({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(G2,"isUrlSupported");function W2({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new ha({message:`${r} API key must be a string.`});if(typeof process>"u")throw new ha({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 ha({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ha({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(W2,"loadApiKey");function Io({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(Io,"loadOptionalSetting");function H2(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(H2,"mediaTypeToExtension");var J2=/"__proto__"\s*:/,K2=/"constructor"\s*:/;function Ef(e){const t=JSON.parse(e);return t===null||typeof t!="object"||J2.test(e)===!1&&K2.test(e)===!1?t:Y2(t)}i(Ef,"_parse");function Y2(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(Y2,"filter");function ji(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Ef(e)}try{return Ef(e)}finally{Error.stackTraceLimit=t}}i(ji,"secureJsonParse");function zi(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(zi,"addAdditionalPropertiesToJsonSchema");function wn(e){return typeof e=="boolean"?e:zi(e)}i(wn,"visit");var X2=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"},Q2=i(e=>typeof e=="string"?{...xf,name:e}:{...xf,...e},"getDefaultOptions");function Dt(){return{}}i(Dt,"parseAnyDef");function eF(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)!==P.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(eF,"parseArrayDef");function tF(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(tF,"parseBigintDef");function nF(){return{type:"boolean"}}i(nF,"parseBooleanDef");function kf(e,t){return _e(e.type._def,t)}i(kf,"parseBrandedDef");var rF=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 oF(e)}}i(If,"parseDateDef");var oF=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 aF(e,t){return{..._e(e.innerType._def,t),default:e.defaultValue()}}i(aF,"parseDefaultDef");function sF(e,t){return t.effectStrategy==="input"?_e(e.schema._def,t):Dt()}i(sF,"parseEffectsDef");function iF(e){return{type:"string",enum:Array.from(e.values)}}i(iF,"parseEnumDef");var uF=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function lF(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(uF(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(lF,"parseIntersectionDef");function cF(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(cF,"parseLiteralDef");var Li=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(()=>(Li===void 0&&(Li=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Li),"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(`^${qi(r.value,t)}`),r.message,t);break;case"endsWith":nt(n,RegExp(`${qi(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(qi(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 qi(e,t){return t.patternStrategy==="escape"?pF(e):e}i(qi,"escapeLiteralCheckValue");var dF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pF(e){let t="";for(let n=0;n<e.length;n++)dF.has(e[n])||(t+="\\"),t+=e[n];return t}i(pF,"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
|
+
]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
|
|
120
|
+
]))`;continue}}if(r.s&&o[c]==="."){s+=u?`${o[c]}\r
|
|
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($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)===P.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)===P.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===P.ZodBranded&&e.keyType._def.type._def.typeName===P.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 fF(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(fF,"parseMapDef");function mF(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(mF,"parseNativeEnumDef");function hF(){return{not:Dt()}}i(hF,"parseNeverDef");function DF(){return{type:"null"}}i(DF,"parseNullDef");var Ui={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gF(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ui&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Ui[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 vF(e,t)}i(gF,"parseUnionDef");var vF=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 yF(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ui[e.innerType._def.typeName],"null"]};const n=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(yF,"parseNullableDef");function _F(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(_F,"parseNumberDef");function bF(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=wF(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=CF(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(bF,"parseObjectDef");function CF(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(CF,"decideAdditionalProperties");function wF(e){try{return e.isOptional()}catch{return!0}}i(wF,"safeIsOptional");var FF=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"),EF=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 xF(e,t){return _e(e.type._def,t)}i(xF,"parsePromiseDef");function kF(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(kF,"parseSetDef");function IF(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(IF,"parseTupleDef");function AF(){return{not:Dt()}}i(AF,"parseUndefinedDef");function $F(){return Dt()}i($F,"parseUnknownDef");var TF=i((e,t)=>_e(e.innerType._def,t),"parseReadonlyDef"),SF=i((e,t,n)=>{switch(t){case P.ZodString:return Af(e,n);case P.ZodNumber:return _F(e);case P.ZodObject:return bF(e,n);case P.ZodBigInt:return tF(e);case P.ZodBoolean:return nF();case P.ZodDate:return If(e,n);case P.ZodUndefined:return AF();case P.ZodNull:return DF();case P.ZodArray:return eF(e,n);case P.ZodUnion:case P.ZodDiscriminatedUnion:return gF(e,n);case P.ZodIntersection:return lF(e,n);case P.ZodTuple:return IF(e,n);case P.ZodRecord:return Tf(e,n);case P.ZodLiteral:return cF(e);case P.ZodEnum:return iF(e);case P.ZodNativeEnum:return mF(e);case P.ZodNullable:return yF(e,n);case P.ZodOptional:return FF(e,n);case P.ZodMap:return fF(e,n);case P.ZodSet:return kF(e,n);case P.ZodLazy:return()=>e.getter()._def;case P.ZodPromise:return xF(e,n);case P.ZodNaN:case P.ZodNever:return hF();case P.ZodEffects:return sF(e,n);case P.ZodAny:return Dt();case P.ZodUnknown:return $F();case P.ZodDefault:return aF(e,n);case P.ZodBranded:return kf(e,n);case P.ZodReadonly:return TF(e,n);case P.ZodCatch:return rF(e,n);case P.ZodPipeline:return EF(e,n);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),BF=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!==X2)return l}if(o&&!n){const l=OF(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=SF(e,e.typeName,t),u=typeof a=="function"?_e(a(),t):a;if(u&&RF(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 OF=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:BF(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"),RF=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),NF=i(e=>{const t=Q2(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"),PF=i((e,t)=>{var n;const r=NF(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"),Zi=Symbol.for("vercel.ai.schema");function Y(e){let t;return()=>(t==null&&(t=e()),t)}i(Y,"lazySchema");function Ga(e,{validate:t}={}){return{[Zi]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Ga,"jsonSchema");function MF(e){return typeof e=="object"&&e!==null&&Zi in e&&e[Zi]===!0&&"jsonSchema"in e&&"validate"in e}i(MF,"isSchema");function Hn(e){return e==null?Ga({properties:{},additionalProperties:!1}):MF(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?K(e):jF(e):e()}i(Hn,"asSchema");function jF(e){return Ga(()=>zi(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(jF,"standardSchema");function zF(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ga(()=>PF(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(zF,"zod3Schema");function LF(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ga(()=>zi(QC(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(LF,"zod4Schema");function qF(e){return"_zod"in e}i(qF,"isZod4Schema");function K(e,t){return qF(e)?LF(e):zF(e)}i(K,"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 UF({text:e,schema:t}){try{const n=ji(e);return t==null?n:rt({value:n,schema:t})}catch(n){throw ma.isInstance(n)||Dn.isInstance(n)?n:new ma({text:e,cause:n})}}i(UF,"parseJSON");async function It({text:e,schema:t}){try{const n=ji(e);return t==null?{success:!0,value:n,rawValue:n}:await kt({value:n,schema:t})}catch(n){return{success:!1,error:ma.isInstance(n)?n:new ma({text:e,cause:n}),rawValue:void 0}}}i(It,"safeParseJSON");function Wa(e){try{return ji(e),!0}catch{return!1}}i(Wa,"isParsableJson");function Sf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ri).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 ZF=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"),Vi=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=ZF()})=>{try{const u=await a(e,{method:"POST",headers:Cn(t,`ai-sdk/provider-utils/${wf}`,Mi()),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 q8(e){return e}i(q8,"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 UF({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 K0({});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"),VF=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 Gi(e){return e?.replace(/\/$/,"")}i(Gi,"withoutTrailingSlash");function GF(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(GF,"isAsyncIterable");async function*WF({execute:e,input:t,options:n}){const r=e(t,n);if(GF(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(WF,"executeTool");var Wi,Of;function Rf(){if(Of)return Wi;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")}),Wi=a(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),Wi}i(Rf,"requireGetContext");var Hi,Nf;function Pf(){if(Nf)return Hi;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")}),Hi=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 Hi}i(Pf,"requireTokenError");var Ji,Mf;function HF(){if(Mf)return Ji;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")}),Ji=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-C6r3rt16.mjs").then(function(b){return b.t}),await import("./token-CkJSeVBK.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"),Ji}i(HF,"requireGetVercelOidcToken");var Ki,jf;function JF(){if(jf)return Ki;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")}),Ki=a(u);var l=HF(),c=Rf();return Ki}i(JF,"requireDist");var zf=JF(),KF="vercel.ai.gateway.error",Yi=Symbol.for(KF),Lf,qf,ot=(An=class extends(qf=Error,Lf=Yi,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&&Yi in t&&t[Yi]===!0}},i(An,"_GatewayError"),An),Uf="GatewayAuthenticationError",YF=`vercel.ai.gateway.error.${Uf}`,Zf=Symbol.for(YF),Vf,Gf,Xi=($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
|
+
|
|
125
|
+
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
126
|
+
|
|
127
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?u=`AI Gateway authentication failed: Invalid OIDC token.
|
|
128
|
+
|
|
129
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
130
|
+
|
|
131
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:u=`AI Gateway authentication failed: No authentication provided.
|
|
132
|
+
|
|
133
|
+
Option 1 - API key:
|
|
134
|
+
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
135
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
136
|
+
|
|
137
|
+
Option 2 - OIDC token:
|
|
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",XF=`vercel.ai.gateway.error.${Wf}`,Hf=Symbol.for(XF),Jf,Kf,QF=(cr=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(cr,"GatewayInvalidRequestError"),cr),Yf="GatewayRateLimitError",eE=`vercel.ai.gateway.error.${Yf}`,Xf=Symbol.for(eE),Qf,em,tE=(dr=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(dr,"GatewayRateLimitError"),dr),tm="GatewayModelNotFoundError",nE=`vercel.ai.gateway.error.${tm}`,nm=Symbol.for(nE),rE=Y(()=>K(g({modelId:p()}))),rm,om,oE=(pr=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(pr,"GatewayModelNotFoundError"),pr),am="GatewayInternalServerError",aE=`vercel.ai.gateway.error.${am}`,sm=Symbol.for(aE),im,um,lm=(fr=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(fr,"GatewayInternalServerError"),fr),cm="GatewayResponseError",sE=`vercel.ai.gateway.error.${cm}`,dm=Symbol.for(sE),pm,fm,iE=(mr=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(mr,"GatewayResponseError"),mr);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:uE});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new iE({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 Xi.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r,generationId:d});case"invalid_request_error":return new QF({message:c,statusCode:t,cause:r,generationId:d});case"rate_limit_exceeded":return new tE({message:c,statusCode:t,cause:r,generationId:d});case"model_not_found":{const f=await kt({value:u.error.param,schema:rE});return new oE({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 uE=Y(()=>K(g({error:g({message:p(),type:p().nullish(),param:lt().nullish(),code:Q([p(),x()]).nullish()}),generationId:p().nullish()}))),hm="GatewayTimeoutError",lE=`vercel.ai.gateway.error.${hm}`,Dm=Symbol.for(lE),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
|
+
|
|
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:cE(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 cE(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(cE,"extractApiCallResponse");var bm="ai-gateway-auth-method";async function Fn(e){const t=await kt({value:e[bm],schema:dE});return t.success?t.value:void 0}i(Fn,"parseAuthMethod");var dE=Y(()=>K(Q([F("api-key"),F("oidc")]))),Cm=(hr=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(pE),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(fE),failedResponseHandler:gt({errorSchema:et(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await qt(t)}}},i(hr,"GatewayFetchMetadata"),hr),pE=Y(()=>K(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:ue(["embedding","image","language","video"]).nullish()}))}))),fE=Y(()=>K(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),mE=(Dr=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(Dr,"GatewayLanguageModel"),Dr),hE=(gr=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(DE),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(gr,"GatewayEmbeddingModel"),gr),DE=Y(()=>K(g({embeddings:S(S(x())),usage:g({tokens:x()}).nullish(),providerMetadata:Ce(p(),Ce(p(),lt())).optional()}))),gE=(vr=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(bE),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(vr,"GatewayImageModel"),vr);function wm(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Gn(e.data)}:e}i(wm,"maybeEncodeImageFile");var vE=g({images:S(lt()).optional()}).catchall(lt()),yE=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()})]),_E=g({inputTokens:x().nullish(),outputTokens:x().nullish(),totalTokens:x().nullish()}),bE=g({images:S(p()),warnings:S(yE).optional(),providerMetadata:Ce(p(),vE).optional(),usage:_E.optional()}),CE=(yr=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:wE(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:kE}).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 A=O.value;if(A.type==="error")throw new Be({message:A.message,statusCode:A.statusCode,url:b,requestBodyValues:C,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify(A),data:{error:{message:A.message,type:A.errorType,param:A.param}}});return{value:{videos:A.videos,warnings:A.warnings,providerMetadata:A.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(yr,"GatewayVideoModel"),yr);function wE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Gn(e.data)}:e}i(wE,"maybeEncodeVideoFile");var FE=g({videos:S(lt()).optional()}).catchall(lt()),EE=Q([g({type:F("url"),url:p(),mediaType:p()}),g({type:F("base64"),data:p(),mediaType:p()})]),xE=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()})]),kE=ge("type",[g({type:F("result"),videos:S(EE),warnings:S(xE).optional(),providerMetadata:Ce(p(),FE).optional()}),g({type:F("error"),message:p(),errorType:p(),statusCode:x(),param:lt().nullable()})]),IE=Y(()=>K(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:Za(["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.")}))),AE=Y(()=>K(Bi([Ft({searchId:Fe(),results:tn(Ft({url:Fe(),title:Fe(),excerpt:Fe(),publishDate:Fe().nullable().optional(),relevanceScore:jt().optional()}))}),Ft({error:Za(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:jt().optional(),message:Fe()})]))),$E=At({id:"gateway.parallel_search",inputSchema:IE,outputSchema:AE}),TE=i((e={})=>$E(e),"parallelSearch"),SE=Y(()=>K(Ft({query:Bi([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:Za(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),BE=Y(()=>K(Bi([Ft({results:tn(Ft({title:Fe(),url:Fe(),snippet:Fe(),date:Fe().optional(),lastUpdated:Fe().optional()})),id:Fe()}),Ft({error:Za(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:jt().optional(),message:Fe()})]))),OE=At({id:"gateway.perplexity_search",inputSchema:SE,outputSchema:BE}),RE=i((e={})=>OE(e),"perplexitySearch"),NE={parallelSearch:TE,perplexitySearch:RE};async function PE(){var e;return(e=zf.getContext().headers)==null?void 0:e["x-vercel-id"]}i(PE,"getVercelRequestId");var ME="3.0.53",jE="0.0.1";function zE(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=Gi(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await qE(e);return Cn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":jE,[bm]:v.authMethod,...e.headers},`ai-sdk/gateway/${ME}`)}catch(v){throw Xi.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=Io({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Io({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=Io({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const C=await PE();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 mE(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 gE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const h=i(v=>new hE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=h,D.textEmbeddingModel=h,D.videoModel=v=>new CE(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=NE,D}i(zE,"createGatewayProvider");var LE=zE();async function qE(e){const t=Io({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await zf.getVercelOidcToken(),authMethod:"oidc"}}i(qE,"getGatewayAuthToken");var UE=typeof globalThis=="object"?globalThis:global,En="1.9.0",Fm=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function ZE(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(ZE,"_makeCompatibilityCheck");var VE=ZE(En),GE=En.split(".")[0],Ao=Symbol.for("opentelemetry.js.api."+GE),$o=UE;function Qi(e,t,n,r){var o;r===void 0&&(r=!1);var s=$o[Ao]=(o=$o[Ao])!==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(Qi,"registerGlobal");function To(e){var t,n,r=(t=$o[Ao])===null||t===void 0?void 0:t.version;if(!(!r||!VE(r)))return(n=$o[Ao])===null||n===void 0?void 0:n[e]}i(To,"getGlobal");function eu(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+En+".");var n=$o[Ao];n&&delete n[e]}i(eu,"unregisterGlobal");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$3"),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$3"),JE=(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 So("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return So("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return So("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return So("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return So("verbose",this._namespace,t)},e})();function So(e,t,n){var r=To("diag");if(r)return n.unshift(t),r[e].apply(r,HE([],WE(n),!1))}i(So,"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 KE(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(KE,"createLogLevelDiagLogger");var YE=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"),XE=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"),QE="diag",Ha=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var u=To("diag");if(u)return u[o].apply(u,XE([],YE(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=To("diag"),f=KE((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 Qi("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){eu(QE,n)},n.createComponentLogger=function(o){return new JE(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 e1(e){return Symbol.for(e)}i(e1,"createContextKey");var t1=(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})(),n1=new t1,r1=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"),o1=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"),a1=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return n1},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,o1([r],r1(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),s1=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"),i1=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"),tu="context",u1=new a1,nu=(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 Qi(tu,t,Ha.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,i1([t,n,r],s1(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return To(tu)||u1},e.prototype.disable=function(){this._getContextManager().disable(),eu(tu,Ha.instance())},e})(),ru;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ru||(ru={}));var Em="0000000000000000",xm="00000000000000000000000000000000",l1={traceId:xm,spanId:Em,traceFlags:ru.NONE},Bo=(function(){function e(t){t===void 0&&(t=l1),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})(),ou=e1("OpenTelemetry Context Key SPAN");function au(e){return e.getValue(ou)||void 0}i(au,"getSpan");function c1(){return au(nu.getInstance().active())}i(c1,"getActiveSpan");function su(e,t){return e.setValue(ou,t)}i(su,"setSpan");function d1(e){return e.deleteValue(ou)}i(d1,"deleteSpan");function p1(e,t){return su(e,new Bo(t))}i(p1,"setSpanContext");function km(e){var t;return(t=au(e))===null||t===void 0?void 0:t.spanContext()}i(km,"getSpanContext");var f1=/^([0-9a-f]{32})$/i,m1=/^[0-9a-f]{16}$/i;function h1(e){return f1.test(e)&&e!==xm}i(h1,"isValidTraceId");function D1(e){return m1.test(e)&&e!==Em}i(D1,"isValidSpanId");function Im(e){return h1(e.traceId)&&D1(e.spanId)}i(Im,"isSpanContextValid");function g1(e){return new Bo(e)}i(g1,"wrapSpanContext");var iu=nu.getInstance(),Am=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=iu.active());var o=!!n?.root;if(o)return new Bo;var s=r&&km(r);return v1(s)&&Im(s)?new Bo(s):new Bo},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??iu.active(),c=this.startSpan(t,s,l),d=su(l,c);return iu.with(d,u,void 0,c)}},e})();function v1(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(v1,"isSpanContext");var y1=new Am,_1=(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):y1},e})(),b1=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Am},e})(),C1=new b1,$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 _1(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:C1},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})(),Ja;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ja||(Ja={}));var Tm=nu.getInstance(),uu="trace",w1=(function(){function e(){this._proxyTracerProvider=new $m,this.wrapSpanContext=g1,this.isSpanContextValid=Im,this.deleteSpan=d1,this.getSpan=au,this.getActiveSpan=c1,this.getSpanContext=km,this.setSpan=su,this.setSpanContext=p1}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Qi(uu,this._proxyTracerProvider,Ha.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return To(uu)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){eu(uu,Ha.instance()),this._proxyTracerProvider=new $m},e})(),F1=w1.getInstance(),E1=Object.defineProperty,x1=i((e,t)=>{for(var n in t)E1(e,n,{get:t[n],enumerable:!0})},"__export"),Sm="AI_InvalidArgumentError",Bm=`vercel.ai.error.${Sm}`,k1=Symbol.for(Bm),Om,Ut=(_r=class extends X{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 X.hasMarker(t,Bm)}},i(_r,"InvalidArgumentError"),_r);Om=k1;var Rm="AI_InvalidToolApprovalError",Nm=`vercel.ai.error.${Rm}`,I1=Symbol.for(Nm),Pm,A1=(br=class extends X{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 X.hasMarker(t,Nm)}},i(br,"InvalidToolApprovalError"),br);Pm=I1;var Mm="AI_InvalidToolInputError",jm=`vercel.ai.error.${Mm}`,$1=Symbol.for(jm),zm,lu=(Cr=class extends X{constructor({toolInput:t,toolName:n,cause:r,message:o=`Invalid input for tool ${n}: ${po(r)}`}){super({name:Mm,message:o,cause:r}),this[zm]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return X.hasMarker(t,jm)}},i(Cr,"InvalidToolInputError"),Cr);zm=$1;var Lm="AI_ToolCallNotFoundForApprovalError",qm=`vercel.ai.error.${Lm}`,T1=Symbol.for(qm),Um,Zm=(wr=class extends X{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 X.hasMarker(t,qm)}},i(wr,"ToolCallNotFoundForApprovalError"),wr);Um=T1;var Vm="AI_MissingToolResultsError",Gm=`vercel.ai.error.${Vm}`,S1=Symbol.for(Gm),Wm,Hm=(Fr=class extends X{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 X.hasMarker(t,Gm)}},i(Fr,"MissingToolResultsError"),Fr);Wm=S1;var Jm="AI_NoObjectGeneratedError",Km=`vercel.ai.error.${Jm}`,B1=Symbol.for(Km),Ym,rn=(Er=class extends X{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 X.hasMarker(t,Km)}},i(Er,"NoObjectGeneratedError"),Er);Ym=B1;var Xm="AI_NoOutputGeneratedError",Qm=`vercel.ai.error.${Xm}`,O1=Symbol.for(Qm),eh,R1=(xr=class extends X{constructor({message:t="No output generated.",cause:n}={}){super({name:Xm,message:t,cause:n}),this[eh]=!0}static isInstance(t){return X.hasMarker(t,Qm)}},i(xr,"NoOutputGeneratedError"),xr);eh=O1;var th="AI_NoSuchToolError",nh=`vercel.ai.error.${th}`,N1=Symbol.for(nh),rh,cu=(kr=class extends X{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 X.hasMarker(t,nh)}},i(kr,"NoSuchToolError"),kr);rh=N1;var oh="AI_ToolCallRepairError",ah=`vercel.ai.error.${oh}`,P1=Symbol.for(ah),sh,M1=(Ir=class extends X{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${po(t)}`}){super({name:oh,message:r,cause:t}),this[sh]=!0,this.originalError=n}static isInstance(t){return X.hasMarker(t,ah)}},i(Ir,"ToolCallRepairError"),Ir);sh=P1;var j1=(Ar=class extends X{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(Ar,"UnsupportedModelVersionError"),Ar),ih="AI_InvalidMessageRoleError",uh=`vercel.ai.error.${ih}`,z1=Symbol.for(uh),lh,L1=($r=class extends X{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 X.hasMarker(t,uh)}},i($r,"InvalidMessageRoleError"),$r);lh=z1;var ch="AI_RetryError",dh=`vercel.ai.error.${ch}`,q1=Symbol.for(dh),ph,fh=(Tr=class extends X{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 X.hasMarker(t,dh)}},i(Tr,"RetryError"),Tr);ph=q1;function U1({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(U1,"formatWarning");var Z1="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(Z1));for(const n of e.warnings)console.warn(U1({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function V1({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(V1,"logV2CompatibilityWarning");function G1(e){return e.specificationVersion==="v3"?e:(V1({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:W1(o.stream)}};default:return t[n]}}}))}i(G1,"asLanguageModelV3");function W1(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(W1,"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 j1({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return G1(e)}return H1().languageModel(e)}i(vh,"resolveLanguageModel");function H1(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:LE}i(H1,"getGlobalProvider");function yh(e){if(e!=null)return typeof e=="number"?e:e.totalMs}i(yh,"getTotalTimeoutMs");function J1(e){if(!(e==null||typeof e=="number"))return e.stepMs}i(J1,"getStepTimeoutMs");var K1=[{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]}],Y1=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 X1(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Y1(e):e}i(X1,"stripID3TagsIfPresent");function Q1({data:e,signatures:t}){const n=X1(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(Q1,"detectMediaType");var _h="6.0.97",e3=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}`,Mi()),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??Ni}),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"),t3=i((e=e3)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function n3(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(n3,"splitDataUrl");var bh=Q([p(),ka(Uint8Array),ka(ArrayBuffer),o2(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}=n3(e.toString());if(t==null||n==null)throw new X({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 r3(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Gn(new Uint8Array(e)):Gn(e)}i(r3,"convertDataContentToBase64String");function du(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(du,"asArray");async function o3({prompt:e,supportedUrls:t,download:n=t3()}){const r=await s3(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}]:du(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>a3({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(o3,"convertToLanguageModelPrompt");function a3({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=>i3(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 L1({role:r})}}}i(a3,"convertToLanguageModelMessage");async function s3(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&&G2({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(s3,"downloadAssets");function i3(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=Q1({data:l,signatures:K1}))!=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(i3,"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 Ka({toolCallId:e,input:t,output:n,tool:r,errorMode:o}){return o==="text"?{type:"error-text",value:po(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(Ka,"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 u3(e){return e!=null&&Object.keys(e).length>0}i(u3,"isNonEmptyObject");async function l3({tools:e,toolChoice:t,activeTools:n}){if(!u3(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(l3,"prepareToolsAndToolChoice");var Oo=xi(()=>Q([Xp(),p(),x(),Re(),Ce(p(),Oo.optional()),S(Oo)])),Pe=Ce(p(),Ce(p(),Oo.optional())),xh=g({type:F("text"),text:p(),providerOptions:Pe.optional()}),c3=g({type:F("image"),image:Q([bh,ka(URL)]),mediaType:p().optional(),providerOptions:Pe.optional()}),kh=g({type:F("file"),data:Q([bh,ka(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Pe.optional()}),d3=g({type:F("reasoning"),text:p(),providerOptions:Pe.optional()}),p3=g({type:F("tool-call"),toolCallId:p(),toolName:p(),input:lt(),providerOptions:Pe.optional(),providerExecuted:Re().optional()}),f3=ge("type",[g({type:F("text"),value:p(),providerOptions:Pe.optional()}),g({type:F("json"),value:Oo,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:Oo,providerOptions:Pe.optional()}),g({type:F("content"),value:S(Q([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:Q([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:Q([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:f3,providerOptions:Pe.optional()}),m3=g({type:F("tool-approval-request"),approvalId:p(),toolCallId:p()}),h3=g({type:F("tool-approval-response"),approvalId:p(),approved:Re(),reason:p().optional()}),D3=g({role:F("system"),content:p(),providerOptions:Pe.optional()}),g3=g({role:F("user"),content:Q([p(),S(Q([xh,c3,kh]))]),providerOptions:Pe.optional()}),v3=g({role:F("assistant"),content:Q([p(),S(Q([xh,kh,d3,p3,Ih,m3]))]),providerOptions:Pe.optional()}),y3=g({role:F("tool"),content:S(Q([Ih,h3])),providerOptions:Pe.optional()}),_3=Q([D3,g3,v3,y3]);async function b3(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"&&!du(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(_3)});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(b3,"standardizePrompt");function C3(e){if(!Xi.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 X({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
|
+
|
|
142
|
+
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
143
|
+
|
|
144
|
+
Alternatively, you can use a provider module instead of the AI Gateway.
|
|
145
|
+
|
|
146
|
+
Learn more: \x1B[34m${n}\x1B[0m
|
|
147
|
+
|
|
148
|
+
`),{name:"GatewayAuthenticationError"})}i(C3,"wrapGatewayError");function pu({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(pu,"assembleOperationName");function w3({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(w3,"getBaseTelemetryAttributes");var F3={startSpan(){return Ya},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Ya);if(typeof n=="function")return n(Ya);if(typeof r=="function")return r(Ya)}},Ya={spanContext(){return E3},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}},E3={traceId:"",spanId:"",traceFlags:0};function x3({isEnabled:e=!1,tracer:t}={}){return e?t||F1.getTracer("ai"):F3}i(x3,"getTracer");async function fu({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(fu,"recordSpan");function Ah(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ja.ERROR,message:t.message})):e.setStatus({code:Ja.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 k3(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?r3(n.data):n.data}:n)})))}i(k3,"stringifyForTelemetry");function I3(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(I3,"asLanguageModelUsage");function A3(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(A3,"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 $3({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($3,"getRetryDelayInMs");var T3=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 N2($3({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 S3({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:T3({maxRetries:n,abortSignal:t})}}i(S3,"prepareRetries");function B3({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 A1({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(B3,"collectToolApprovals");function mu(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}i(mu,"now");async function O3({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 fu({name:"ai.toolCall",attributes:Kn({telemetry:r,attributes:{...pu({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=mu();try{const T=WF({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=mu()-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=mu()-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(O3,"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 R3=(Sr=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(Sr,"DefaultGeneratedFile"),Sr);async function N3({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(N3,"isApprovalNeeded");var P3={};x1(P3,{array:i(()=>z3,"array"),choice:i(()=>L3,"choice"),json:i(()=>q3,"json"),object:i(()=>j3,"object"),text:i(()=>Oh,"text")});function M3(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(M3,"fixJson");async function Xa(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:M3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(Xa,"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"),j3=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 Xa(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},"object"),z3=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 Xa(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"),L3=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 Xa(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"),q3=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 Xa(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 U3({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 cu({toolName:e.toolName})}try{return await Nh({toolCall:e,tools:t})}catch(a){if(n==null||!(cu.isInstance(a)||lu.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 M1({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(U3,"parseToolCall");async function Rh(e){const t=e.input.trim()===""?{success:!0,value:{}}:await It({text:e.input});if(t.success===!1)throw new lu({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 cu({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 lu({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 Z3=(Br=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(Br,"DefaultStepResult"),Br);function V3(e){return({steps:t})=>t.length===e}i(V3,"stepCountIs");async function G3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(G3,"isStopConditionMet");async function W3({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 Ka({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 Ka({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 Ka({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(W3,"toResponseMessages");function H3(...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(H3,"mergeAbortSignals");var J3=ko({prefix:"aitxt",size:24});async function Yn({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:u,timeout:l,headers:c,stopWhen:d=V3(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:A=J3}={},experimental_onStart:I,experimental_onStepStart:ne,experimental_onToolCallStart:k,experimental_onToolCallFinish:ae,onStepFinish:B,onFinish:M,...z}){const L=vh(e),R=du(d),J=yh(l),he=J1(l),oe=he!=null?new AbortController:void 0,se=H3(u,J!=null?AbortSignal.timeout(J):void 0,oe?.signal),{maxRetries:re,retry:H}=S3({maxRetries:a,abortSignal:se}),je=Eh(z),xe=Cn(c??{},`ai/${_h}`),at=w3({model:L,telemetry:D,headers:xe,settings:{...je,maxRetries:re}}),Ae={provider:L.provider,modelId:L.modelId},j=await b3({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:re,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 ee=x3(D);try{return await fu({name:"ai.generateText",attributes:Kn({telemetry:D,attributes:{...pu({operationId:"ai.generateText",telemetry:D}),...at,"ai.model.provider":L.provider,"ai.model.id":L.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:o,messages:s}),"input")}}}),tracer:ee,fn:i(async Ge=>{var ve,Gr,Wr,Hr,Jr,Kr,Yr,Xr,Qr,_,U,ze,st;const Sn=j.messages,eo=[],{approvedToolApprovals:sl,deniedToolApprovals:cs}=B3({messages:Sn}),il=sl.filter(We=>!We.toolCall.providerExecuted);if(cs.length>0||il.length>0){const We=await Ph({toolCalls:il.map(pe=>pe.toolCall),tools:t,tracer:ee,telemetry:D,messages:Sn,abortSignal:se,experimental_context:T,stepNumber:0,model:Ae,onToolCallStart:k,onToolCallFinish:ae}),pt=[];for(const pe of We){const bt=await Ka({toolCallId:pe.toolCallId,input:pe.input,tool:t?.[pe.toolName],output:pe.type==="tool-result"?pe.output:pe.error,errorMode:pe.type==="tool-error"?"json":"none"});pt.push({type:"tool-result",toolCallId:pe.toolCallId,toolName:pe.toolName,output:bt})}for(const pe of cs)pt.push({type:"tool-result",toolCallId:pe.toolCall.toolCallId,toolName:pe.toolCall.toolName,output:{type:"execution-denied",reason:pe.approvalResponse.reason,...pe.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:pe.approvalResponse.approvalId}}}}});eo.push({role:"tool",content:pt})}const ul=[...sl,...cs].filter(We=>We.toolCall.providerExecuted);ul.length>0&&eo.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 TD=Eh(z);let Me,Uo=[],to=[];const dt=[],ds=new Map;do{const We=he!=null?setTimeout(()=>oe.abort(),he):void 0;try{const pt=[...Sn,...eo],pe=await C?.({model:L,steps:dt,stepNumber:dt.length,messages:pt,experimental_context:T}),bt=vh((ve=pe?.model)!=null?ve:L),no={provider:bt.provider,modelId:bt.modelId},dl=await o3({prompt:{system:(Gr=pe?.system)!=null?Gr:j.system,messages:(Wr=pe?.messages)!=null?Wr:pt},supportedUrls:await bt.supportedUrls,download:E});T=(Hr=pe?.experimental_context)!=null?Hr:T;const pl=(Jr=pe?.activeTools)!=null?Jr:y,{toolChoice:Zo,tools:ps}=await l3({tools:t,toolChoice:(Kr=pe?.toolChoice)!=null?Kr:n,activeTools:pl}),SD=(Yr=pe?.messages)!=null?Yr:pt,BD=(Xr=pe?.system)!=null?Xr:j.system,fl=$h(h,pe?.providerOptions);try{await ne?.({stepNumber:dt.length,model:no,system:BD,messages:SD,tools:t,toolChoice:Zo,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 de;return fu({name:"ai.generateText.doGenerate",attributes:Kn({telemetry:D,attributes:{...pu({operationId:"ai.generateText.doGenerate",telemetry:D}),...at,"ai.model.provider":bt.provider,"ai.model.id":bt.modelId,"ai.prompt.messages":{input:i(()=>k3(dl),"input")},"ai.prompt.tools":{input:i(()=>ps?.map(ft=>JSON.stringify(ft)),"input")},"ai.prompt.toolChoice":{input:i(()=>Zo!=null?JSON.stringify(Zo):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":(de=z.temperature)!=null?de:void 0,"gen_ai.request.top_k":z.topK,"gen_ai.request.top_p":z.topP}}),tracer:ee,fn:i(async ft=>{var ms,oo,Dl,gl,vl,yl,_l,bl;const Ye=await bt.doGenerate({...TD,tools:ps,toolChoice:Zo,responseFormat:await m?.responseFormat,prompt:dl,providerOptions:fl,abortSignal:se,headers:xe}),Bn={id:(oo=(ms=Ye.response)==null?void 0:ms.id)!=null?oo:A(),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 ro=await Promise.all(Me.content.filter(de=>de.type==="tool-call").map(de=>U3({toolCall:de,tools:t,repairToolCall:w,system:r,messages:pt}))),fs={};for(const de of ro){if(de.invalid)continue;const ft=t?.[de.toolName];ft!=null&&(ft?.onInputAvailable!=null&&await ft.onInputAvailable({input:de.input,toolCallId:de.toolCallId,messages:pt,abortSignal:se,experimental_context:T}),await N3({tool:ft,toolCall:de,messages:pt,experimental_context:T})&&(fs[de.toolCallId]={type:"tool-approval-request",approvalId:A(),toolCall:de}))}const OD=ro.filter(de=>de.invalid&&de.dynamic);to=[];for(const de of OD)to.push({type:"tool-error",toolCallId:de.toolCallId,toolName:de.toolName,input:de.input,error:bf(de.error),dynamic:!0});Uo=ro.filter(de=>!de.providerExecuted),t!=null&&to.push(...await Ph({toolCalls:Uo.filter(de=>!de.invalid&&fs[de.toolCallId]==null),tools:t,tracer:ee,telemetry:D,messages:pt,abortSignal:se,experimental_context:T,stepNumber:dt.length,model:no,onToolCallStart:k,onToolCallFinish:ae}));for(const de of ro){if(!de.providerExecuted)continue;const ft=t?.[de.toolName];ft?.type==="provider"&&ft.supportsDeferredResults&&(Me.content.some(oo=>oo.type==="tool-result"&&oo.toolCallId===de.toolCallId)||ds.set(de.toolCallId,{toolName:de.toolName}))}for(const de of Me.content)de.type==="tool-result"&&ds.delete(de.toolCallId);const ml=Y3({content:Me.content,toolCalls:ro,toolOutputs:to,toolApprovalRequests:Object.values(fs),tools:t});eo.push(...await W3({content:ml,tools:t}));const RD=(Qr=O?.requestBody)==null||Qr?(_=Me.request)!=null?_:{}:{...Me.request,body:void 0},ND={...Me.response,messages:structuredClone(eo),body:(U=O?.responseBody)==null||U?(ze=Me.response)==null?void 0:ze.body:void 0},PD=dt.length,hl=new Z3({stepNumber:PD,model:no,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T,content:ml,finishReason:Me.finishReason.unified,rawFinishReason:Me.finishReason.raw,usage:I3(Me.usage),warnings:Me.warnings,providerMetadata:Me.providerMetadata,request:RD,response:ND});hh({warnings:(st=Me.warnings)!=null?st:[],provider:no.provider,model:no.modelId}),dt.push(hl),await B?.(hl)}finally{We!=null&&clearTimeout(We)}}while((Uo.length>0&&to.length===Uo.length||ds.size>0)&&!await G3({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)=>A3(We,pt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await M?.({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 K3({steps:dt,totalUsage:ll,output:cl})},"fn")})}catch(Ge){throw C3(Ge)}}i(Yn,"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=>O3({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 K3=(Or=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 R1;return this._output}},i(Or,"DefaultGenerateTextResult"),Or);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 Y3({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 R3(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(Y3,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
150
|
+
|
|
151
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
152
|
+
|
|
153
|
+
`)}})}},ko({prefix:"aitxt",size:24}),ko({prefix:"aiobj",size:24}),ko({prefix:"aiobj",size:24});var hu=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:Q([p(),x()]).nullish()})}),Tt=gt({errorSchema:hu,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 X3({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(X3,"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 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 Q3=Y(()=>K(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()}))),ex=Y(()=>K(Q([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:ue(["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()}),hu]))),tx=Y(()=>K(g({logitBias:Ce(i2(),x()).optional(),logprobs:Q([Re(),x()]).optional(),parallelToolCalls:Re().optional(),user:p().optional(),reasoningEffort:ue(["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:ue(["auto","flex","priority","default"]).optional(),strictJsonSchema:Re().optional(),textVerbosity:ue(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:ue(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:ue(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));function nx({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(nx,"prepareChatTools");var rx=(Rr=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:tx}))!=null?h:{},T=jh(this.modelId),O=(v=E.forceReasoning)!=null?v:T.isReasoningModel;s!=null&&w.push({type:"unsupported",feature:"topK"});const{messages:A,warnings:I}=X3({prompt:t,systemMessageMode:(y=E.systemMessageMode)!=null?y:O?"developer":T.systemMessageMode});w.push(...I);const ne=(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:ne,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:A};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:ae,toolChoice:B,toolWarnings:M}=nx({tools:f,toolChoice:m});return{args:{...k,tools:ae,tool_choice:B},warnings:[...w,...M]}}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(Q3),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:{...Du(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(ex),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,A,I,ne,k,ae,B,M,z,L;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 oe=Du(R);Object.values(oe).some(Boolean)&&(d=!0,h.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&&(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 J=R.choices[0];if(J?.finish_reason!=null&&(l={unified:Lh(J.finish_reason),raw:J.finish_reason}),((w=J?.logprobs)==null?void 0:w.content)!=null&&(m.openai.logprobs=J.logprobs.content),J?.delta==null)return;const he=J.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 oe of he.tool_calls){const se=oe.index;if(u[se]==null){if(oe.type!=="function")throw new fo({data:oe,message:"Expected 'function' type."});if(oe.id==null)throw new fo({data:oe,message:"Expected 'id' to be a string."});if(((E=oe.function)==null?void 0:E.name)==null)throw new fo({data:oe,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:oe.id,toolName:oe.function.name}),u[se]={id:oe.id,type:"function",function:{name:oe.function.name,arguments:(T=oe.function.arguments)!=null?T:""},hasFinished:!1};const H=u[se];((O=H.function)==null?void 0:O.name)!=null&&((A=H.function)==null?void 0:A.arguments)!=null&&(H.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),Wa(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 re=u[se];re.hasFinished||(((ne=oe.function)==null?void 0:ne.arguments)!=null&&(re.function.arguments+=(ae=(k=oe.function)==null?void 0:k.arguments)!=null?ae:""),h.enqueue({type:"tool-input-delta",id:re.id,delta:(B=oe.function.arguments)!=null?B:""}),((M=re.function)==null?void 0:M.name)!=null&&((z=re.function)==null?void 0:z.arguments)!=null&&Wa(re.function.arguments)&&(h.enqueue({type:"tool-input-end",id:re.id}),h.enqueue({type:"tool-call",toolCallId:(L=re.id)!=null?L:Ve(),toolName:re.function.name,input:re.function.arguments}),re.hasFinished=!0))}if(he.annotations!=null)for(const oe of he.annotations)h.enqueue({type:"source",sourceType:"url",id:Ve(),url:oe.url_citation.url,title:oe.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(Rr,"OpenAIChatLanguageModel"),Rr);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 ox({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
154
|
+
|
|
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
|
+
${a}
|
|
157
|
+
|
|
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}:
|
|
159
|
+
${a}
|
|
160
|
+
|
|
161
|
+
`;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
|
|
162
|
+
`,{prompt:r,stopSequences:[`
|
|
163
|
+
${t}:`]}}i(ox,"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 ax=Y(()=>K(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()}))),sx=Y(()=>K(Q([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()}),hu]))),Vh=Y(()=>K(g({echo:Re().optional(),logitBias:Ce(p(),x()).optional(),suffix:p().optional(),user:p().optional(),logprobs:Q([Re(),x()]).optional()}))),ix=(Nr=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}=ox({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(ax),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(sx),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(Nr,"OpenAICompletionLanguageModel"),Nr),ux=Y(()=>K(g({dimensions:x().optional(),user:p().optional()}))),lx=Y(()=>K(g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish()}))),cx=(Pr=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:ux}))!=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(lx),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(Pr,"OpenAIEmbeddingModel"),Pr),Gh=Y(()=>K(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()}))),dx={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},px=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function fx(e){return px.some(t=>e.startsWith(t))}i(fx,"hasDefaultResponseFormat");var mx=(Mr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=dx[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 A=(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:ae}=await Vi({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}):Pi(B.url))),mask:r!=null?await hx(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:A,modelId:this.modelId,headers:ae},providerMetadata:{openai:{images:k.data.map((B,M)=>{var z,L,R,J,he,oe;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(z=k.created)!=null?z:void 0,size:(L=k.size)!=null?L:void 0,quality:(R=k.quality)!=null?R:void 0,background:(J=k.background)!=null?J:void 0,outputFormat:(he=k.output_format)!=null?he:void 0,...Wh((oe=k.usage)==null?void 0:oe.input_tokens_details,M,k.data.length)}})}}}}const{value:I,responseHeaders:ne}=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:{},...fx(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:A,modelId:this.modelId,headers:ne},providerMetadata:{openai:{images:I.data.map((k,ae)=>{var B,M,z,L,R,J;return{...k.revised_prompt?{revisedPrompt:k.revised_prompt}:{},created:(B=I.created)!=null?B:void 0,size:(M=I.size)!=null?M:void 0,quality:(z=I.quality)!=null?z:void 0,background:(L=I.background)!=null?L:void 0,outputFormat:(R=I.output_format)!=null?R:void 0,...Wh((J=I.usage)==null?void 0:J.input_tokens_details,ae,I.data.length)}})}}}}},i(Mr,"OpenAIImageModel"),Mr);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 hx(e){if(!e)return;if(e.type==="url")return Pi(e.url);const t=e.data instanceof Uint8Array?e.data:bn(e.data);return new Blob([t],{type:e.mediaType})}i(hx,"fileToBlob$1");var Hh=Y(()=>K(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=Y(()=>K(g({status:ue(["completed","failed"]),output:p().optional()}))),Dx=At({id:"openai.apply_patch",inputSchema:Hh,outputSchema:Jh}),gx=Dx,vx=Y(()=>K(g({code:p().nullish(),containerId:p()}))),yx=Y(()=>K(g({outputs:S(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullish()}))),_x=Y(()=>K(g({container:Q([p(),g({fileIds:S(p()).optional()})]).optional()}))),bx=At({id:"openai.code_interpreter",inputSchema:vx,outputSchema:yx}),Cx=i((e={})=>bx(e),"codeInterpreter"),Kh=g({key:p(),type:ue(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Q([p(),x(),Re(),S(p())])}),Yh=g({type:ue(["and","or"]),filters:S(Q([Kh,xi(()=>Yh)]))}),wx=Y(()=>K(g({vectorStoreIds:S(p()),maxNumResults:x().optional(),ranking:g({ranker:p().optional(),scoreThreshold:x().optional()}).optional(),filters:Q([Kh,Yh]).optional()}))),Fx=Y(()=>K(g({queries:S(p()),results:S(g({attributes:Ce(p(),lt()),fileId:p(),filename:p(),score:x(),text:p()})).nullable()}))),Ex=At({id:"openai.file_search",inputSchema:g({}),outputSchema:Fx}),xx=Y(()=>K(g({background:ue(["auto","opaque","transparent"]).optional(),inputFidelity:ue(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:ue(["auto"]).optional(),outputCompression:x().int().min(0).max(100).optional(),outputFormat:ue(["png","jpeg","webp"]).optional(),partialImages:x().int().min(0).max(3).optional(),quality:ue(["auto","low","medium","high"]).optional(),size:ue(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),kx=Y(()=>K(g({}))),Ix=Y(()=>K(g({result:p()}))),Ax=At({id:"openai.image_generation",inputSchema:kx,outputSchema:Ix}),$x=i((e={})=>Ax(e),"imageGeneration"),Xh=Y(()=>K(g({action:g({type:F("exec"),command:S(p()),timeoutMs:x().optional(),user:p().optional(),workingDirectory:p().optional(),env:Ce(p(),p()).optional()})}))),Qh=Y(()=>K(g({output:p()}))),Tx=At({id:"openai.local_shell",inputSchema:Xh,outputSchema:Qh}),eD=Y(()=>K(g({action:g({commands:S(p()),timeoutMs:x().optional(),maxOutputLength:x().optional()})}))),gu=Y(()=>K(g({output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exitCode:x()})])}))}))),Sx=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(),Bx=Y(()=>K(g({environment:Q([g({type:F("containerAuto"),fileIds:S(p()).optional(),memoryLimit:ue(["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:Sx}),g({type:F("containerReference"),containerId:p()}),g({type:F("local").optional(),skills:S(g({name:p(),description:p(),path:p()})).optional()})]).optional()}))),Ox=At({id:"openai.shell",inputSchema:eD,outputSchema:gu}),Rx=Y(()=>K(g({externalWebAccess:Re().optional(),filters:g({allowedDomains:S(p()).optional()}).optional(),searchContextSize:ue(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Nx=Y(()=>K(g({}))),Px=Y(()=>K(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()}))),Mx=At({id:"openai.web_search",inputSchema:Nx,outputSchema:Px}),jx=i((e={})=>Mx(e),"webSearch"),zx=Y(()=>K(g({searchContextSize:ue(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Lx=Y(()=>K(g({}))),qx=Y(()=>K(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()})])}))),Ux=At({id:"openai.web_search_preview",inputSchema:Lx,outputSchema:qx}),vu=xi(()=>Q([p(),x(),Re(),Xp(),S(vu),Ce(p(),vu)])),Zx=Y(()=>K(g({serverLabel:p(),allowedTools:Q([S(p()),g({readOnly:Re().optional(),toolNames:S(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:Ce(p(),p()).optional(),requireApproval:Q([ue(["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."))),Vx=Y(()=>K(g({}))),Gx=Y(()=>K(g({type:F("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:Q([p(),vu]).optional()}))),Wx=At({id:"openai.mcp",inputSchema:Vx,outputSchema:Gx}),Hx=i(e=>Wx(e),"mcp"),Jx={applyPatch:gx,codeInterpreter:Cx,fileSearch:Ex,imageGeneration:$x,localShell:Tx,shell:Ox,webSearchPreview:Ux,webSearch:jx,mcp:Hx};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 Kx({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 A=[],I=[],ne=new Set;for(const{role:k,content:ae}of e)switch(k){case"system":{switch(n){case"system":{A.push({role:"system",content:ae});break}case"developer":{A.push({role:"developer",content:ae});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":{A.push({role:"user",content:ae.map((B,M)=>{var z,L,R;switch(B.type){case"text":return{type:"input_text",text:B.text};case"file":if(B.mediaType.startsWith("image/")){const J=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:${J};base64,${Lt(B.data)}`},detail:(L=(z=B.providerOptions)==null?void 0:z[r])==null?void 0:L.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-${M}.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 M of ae)switch(M.type){case"text":{const z=(f=(d=M.providerOptions)==null?void 0:d[r])==null?void 0:f.itemId;if(a&&z!=null)break;if(s&&z!=null){A.push({type:"item_reference",id:z});break}A.push({role:"assistant",content:[{type:"output_text",text:M.text}],id:z});break}case"tool-call":{const z=(y=(D=(m=M.providerOptions)==null?void 0:m[r])==null?void 0:D.itemId)!=null?y:(v=(h=M.providerMetadata)==null?void 0:h[r])==null?void 0:v.itemId;if(a&&z!=null)break;if(M.providerExecuted){s&&z!=null&&A.push({type:"item_reference",id:z});break}if(s&&z!=null){A.push({type:"item_reference",id:z});break}const L=t.toProviderToolName(M.toolName);if(u&&L==="local_shell"){const R=await rt({value:M.input,schema:Xh});A.push({type:"local_shell_call",call_id:M.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&&L==="shell"){const R=await rt({value:M.input,schema:eD});A.push({type:"shell_call",call_id:M.toolCallId,id:z,status:"completed",action:{commands:R.action.commands,timeout_ms:R.action.timeoutMs,max_output_length:R.action.maxOutputLength}});break}if(c&&L==="apply_patch"){const R=await rt({value:M.input,schema:Hh});A.push({type:"apply_patch_call",call_id:R.callId,id:z,status:"completed",operation:R.operation});break}A.push({type:"function_call",call_id:M.toolCallId,name:L,arguments:JSON.stringify(M.input),id:z});break}case"tool-result":{if(M.output.type==="execution-denied"||M.output.type==="json"&&typeof M.output.value=="object"&&M.output.value!=null&&"type"in M.output.value&&M.output.value.type==="execution-denied"||a)break;const z=t.toProviderToolName(M.toolName);if(l&&z==="shell"){if(M.output.type==="json"){const L=await rt({value:M.output.value,schema:gu});A.push({type:"shell_call_output",call_id:M.toolCallId,output:L.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 L=(w=(C=(b=M.providerOptions)==null?void 0:b[r])==null?void 0:C.itemId)!=null?w:M.toolCallId;A.push({type:"item_reference",id:L})}else I.push({type:"other",message:`Results for OpenAI tool ${M.toolName} are not sent to the API when store is false`});break}case"reasoning":{const z=await tt({provider:r,providerOptions:M.providerOptions,schema:Yx}),L=z?.itemId;if(a&&L!=null)break;if(L!=null){const R=B[L];if(s)R===void 0&&(A.push({type:"item_reference",id:L}),B[L]={type:"reasoning",id:L,summary:[]});else{const J=[];M.text.length>0?J.push({type:"summary_text",text:M.text}):R!==void 0&&I.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(M)}.`}),R===void 0?(B[L]={type:"reasoning",id:L,encrypted_content:z?.reasoningEncryptedContent,summary:J},A.push(B[L])):(R.summary.push(...J),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(M)}.`});break}}break}case"tool":{for(const B of ae){if(B.type==="tool-approval-response"){const R=B;if(ne.has(R.approvalId))continue;ne.add(R.approvalId),s&&A.push({type:"item_reference",id:R.approvalId}),A.push({type:"mcp_approval_response",approval_request_id:R.approvalId,approve:R.approved});continue}const M=B.output;if(M.type==="execution-denied"&&((T=(E=M.providerOptions)==null?void 0:E.openai)==null?void 0:T.approvalId))continue;const z=t.toProviderToolName(B.toolName);if(u&&z==="local_shell"&&M.type==="json"){const R=await rt({value:M.value,schema:Qh});A.push({type:"local_shell_call_output",call_id:B.toolCallId,output:R.output});continue}if(l&&z==="shell"&&M.type==="json"){const R=await rt({value:M.value,schema:gu});A.push({type:"shell_call_output",call_id:B.toolCallId,output:R.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(c&&B.toolName==="apply_patch"&&M.type==="json"){const R=await rt({value:M.value,schema:Jh});A.push({type:"apply_patch_call_output",call_id:B.toolCallId,status:R.status,output:R.output});continue}let L;switch(M.type){case"text":case"error-text":L=M.value;break;case"execution-denied":L=(O=M.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":L=JSON.stringify(M.value);break;case"content":L=M.value.map(R=>{var J;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:(J=R.filename)!=null?J:"data",file_data:`data:${R.mediaType};base64,${R.data}`};default:{I.push({type:"other",message:`unsupported tool content part type: ${R.type}`});return}}}).filter(V2);break}A.push({type:"function_call_output",call_id:B.toolCallId,output:L})}break}default:{const B=k;throw new Error(`Unsupported role: ${B}`)}}return{input:A,warnings:I}}i(Kx,"convertToOpenAIResponsesInput");var Yx=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 Xx=Y(()=>K(Q([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:ue(["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:ue(["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:ue(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:ue(["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(),Q([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:Q([p(),g({type:p().optional(),code:Q([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:Q([p(),g({type:p().optional(),code:Q([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:ue(["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:ue(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:ue(["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}))]))),Qx=Y(()=>K(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(),Q([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:Q([p(),g({type:p().optional(),code:Q([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:Q([p(),g({type:p().optional(),code:Q([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:ue(["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:ue(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:ue(["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=Y(()=>K(g({conversation:p().nullish(),include:S(ue(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:Q([Re(),x().min(1).max(oD)]).optional(),maxToolCalls:x().nullish(),metadata:et().nullish(),parallelToolCalls:Re().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:ue(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:ue(["auto","flex","priority","default"]).nullish(),store:Re().nullish(),strictJsonSchema:Re().nullish(),textVerbosity:ue(["low","medium","high"]).nullish(),truncation:ue(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:ue(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));async function ek({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:wx});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:Bx});r.push({type:"shell",...a.environment&&{environment:tk(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:zx});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:Rx});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:_x});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:xx});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(ek,"prepareResponsesTools");function tk(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:nk(n.skills)}}return{type:"local",skills:e.skills}}i(tk,"mapShellEnvironment");function nk(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(nk,"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 rk=(jr=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 A=[],I=jh(this.modelId);s!=null&&A.push({type:"unsupported",feature:"topK"}),l!=null&&A.push({type:"unsupported",feature:"seed"}),a!=null&&A.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&A.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&A.push({type:"unsupported",feature:"stopSequences"});const ne=this.config.provider.includes("azure")?"azure":"openai";let k=await tt({provider:ne,providerOptions:d,schema:aD});k==null&&ne!=="openai"&&(k=await tt({provider:"openai",providerOptions:d,schema:aD}));const ae=(h=k?.forceReasoning)!=null?h:I.isReasoningModel;k?.conversation&&k?.previousResponseId&&A.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const B=R2({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:M,warnings:z}=await Kx({prompt:c,toolNameMapping:B,systemMessageMode:(v=k?.systemMessageMode)!=null?v:ae?"developer":I.systemMessageMode,providerOptionsName:ne,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")});A.push(...z);const L=(b=k?.strictJsonSchema)!=null?b:!0;let R=k?.include;function J(ee){R==null?R=[ee]:R.includes(ee)||(R=[...R,ee])}i(J,"addInclude");function he(ee){return f?.find(Ge=>Ge.type==="provider"&&Ge.id===ee)!=null}i(he,"hasOpenAITool");const oe=typeof k?.logprobs=="number"?k?.logprobs:k?.logprobs===!0?oD:void 0;oe&&J("message.output_text.logprobs");const se=(C=f?.find(ee=>ee.type==="provider"&&(ee.id==="openai.web_search"||ee.id==="openai.web_search_preview")))==null?void 0:C.name;se&&J("web_search_call.action.sources"),he("openai.code_interpreter")&&J("code_interpreter_call.outputs");const re=k?.store;re===!1&&ae&&J("reasoning.encrypted_content");const H={model:this.modelId,input:M,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:L,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:re,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:oe,truncation:k?.truncation,...ae&&(k?.reasoningEffort!=null||k?.reasoningSummary!=null)&&{reasoning:{...k?.reasoningEffort!=null&&{effort:k.reasoningEffort},...k?.reasoningSummary!=null&&{summary:k.reasoningSummary}}}};ae?k?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(H.temperature!=null&&(H.temperature=void 0,A.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),H.top_p!=null&&(H.top_p=void 0,A.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(k?.reasoningEffort!=null&&A.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),k?.reasoningSummary!=null&&A.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),k?.serviceTier==="flex"&&!I.supportsFlexProcessing&&(A.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&&(A.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 ek({tools:f,toolChoice:m}),Ae=(O=(T=(E=f?.find(ee=>ee.type==="provider"&&ee.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:se,args:{...H,tools:je,tool_choice:xe},warnings:[...A,...at],store:re,toolNameMapping:B,providerOptionsName:ne,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,A,I,ne,k;const{args:ae,warnings:B,webSearchToolName:M,toolNameMapping:z,providerOptionsName:L,isShellProviderExecuted:R}=await this.getArgs(t),J=this.config.url({path:"/responses",modelId:this.modelId}),he=sD(t.prompt),{responseHeaders:oe,value:se,rawValue:re}=await qe({url:J,headers:Ne(this.config.headers(),t.headers),body:ae,failedResponseHandler:Tt,successfulResponseHandler:Ke(Qx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(se.error)throw new Be({message:se.error.message,url:J,requestBodyValues:ae,statusCode:400,responseHeaders:oe,responseBody:re,isRetryable:!1});const H=[],je=[];let xe=!1;for(const j of se.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const ee of j.summary)H.push({type:"reasoning",text:ee.text,providerMetadata:{[L]:{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:{[L]:{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:{[L]:{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(ee=>({stdout:ee.stdout,stderr:ee.stderr,outcome:ee.outcome.type==="exit"?{type:"exit",exitCode:ee.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ee of j.content){(o=(r=t.providerOptions)==null?void 0:r[L])!=null&&o.logprobs&&ee.logprobs&&je.push(ee.logprobs);const Ge={itemId:j.id,...ee.annotations.length>0&&{annotations:ee.annotations}};H.push({type:"text",text:ee.text,providerMetadata:{[L]:Ge}});for(const ve of ee.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:{[L]:{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:{[L]:{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:{[L]:{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:{[L]:{itemId:j.id}}});break}case"web_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName(M??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName(M??"web_search"),result:uD(j.action)});break}case"mcp_call":{const ee=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:ee,toolName:Ge,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-result",toolCallId:ee,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:{[L]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ee=(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:ee,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:(A=(O=j.results)==null?void 0:O.map(ee=>({attributes:ee.attributes,fileId:ee.file_id,filename:ee.filename,score:ee.score,text:ee.text})))!=null?A: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:{[L]:{itemId:j.id}}});break}}const at={[L]:{responseId:se.id,...je.length>0?{logprobs:je}:{},...typeof se.service_tier=="string"?{serviceTier:se.service_tier}:{}}},Ae=se.usage;return{content:H,finishReason:{unified:rD({finishReason:(I=se.incomplete_details)==null?void 0:I.reason,hasFunctionCall:xe}),raw:(k=(ne=se.incomplete_details)==null?void 0:ne.reason)!=null?k:void 0},usage:tD(Ae),request:{body:ae},response:{id:se.id,timestamp:new Date(se.created_at*1e3),modelId:se.model,headers:oe,body:re},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(Xx),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(A){A.enqueue({type:"stream-start",warnings:r})},transform(A,I){var ne,k,ae,B,M,z,L,R,J,he,oe,se,re,H,je,xe,at,Ae,j,ee,Ge,ve,Gr,Wr,Hr,Jr,Kr,Yr,Xr,Qr;if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:A.rawValue}),!A.success){h={unified:"error",raw:void 0},I.enqueue({type:"error",error:A.error});return}const _=A.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:U,operation:ze}=_.item;if(C[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:U,applyPatch:{hasDiff:ze.type==="delete_file",endEmitted:ze.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:U,toolName:s.toCustomToolName("apply_patch")}),ze.type==="delete_file"){const st=JSON.stringify({callId:U,operation:ze});I.enqueue({type:"tool-input-delta",id:U,delta:st}),I.enqueue({type:"tool-input-end",id:U})}else I.enqueue({type:"tool-input-delta",id:U,delta:`{"callId":"${xn(U)}","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:(ne=_.item.encrypted_content)!=null?ne:null}}})))}else if(ak(_)){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:(ae=(k=_.item.results)==null?void 0:k.map(U=>({attributes:U.attributes,fileId:U.file_id,filename:U.filename,score:U.score,text:U.text})))!=null?ae: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 U=(B=_.item.approval_request_id)!=null?B:void 0,ze=U!=null&&(z=(M=D.get(U))!=null?M:m[U])!=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 U=C[_.output_index];U?.applyPatch&&!U.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(U.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:xn(_.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:U.toolCallId}),U.applyPatch.endEmitted=!0),U&&_.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:U.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 U=(J=(R=(L=f.config).generateId)==null?void 0:R.call(L))!=null?J:Ve(),ze=(he=_.item.approval_request_id)!=null?he:_.item.id;D.set(ze,U);const st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:U,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:ze,toolCallId:U})}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(U=>({stdout:U.stdout,stderr:U.stderr,outcome:U.outcome.type==="exit"?{type:"exit",exitCode:U.outcome.exit_code}:{type:"timeout"}}))}});else if(_.item.type==="reasoning"){const U=T[_.item.id],ze=Object.entries(U.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:(oe=_.item.encrypted_content)!=null?oe:null}}});delete T[_.item.id]}}else if(uk(_)){const U=C[_.output_index];U!=null&&I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:_.delta})}else if(pk(_)){const U=C[_.output_index];U?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:xn(_.delta)}),U.applyPatch.hasDiff=!0)}else if(fk(_)){const U=C[_.output_index];U?.applyPatch&&!U.applyPatch.endEmitted&&(U.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:xn(_.diff)}),U.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:U.toolCallId}),U.applyPatch.endEmitted=!0)}else if(lk(_))I.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(ck(_)){const U=C[_.output_index];U!=null&&I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:xn(_.delta)})}else if(dk(_)){const U=C[_.output_index];U!=null&&(I.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:U.toolCallId}),I.enqueue({type:"tool-call",toolCallId:U.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:U.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ik(_))b=_.response.id,I.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(ok(_))I.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(re=(se=t.providerOptions)==null?void 0:se[u])!=null&&re.logprobs&&_.logprobs&&y.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const U=T[_.item_id];U.summaryParts[_.summary_index]="active";for(const ze of Object.keys(U.summaryParts))U.summaryParts[ze]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${ze}`,providerMetadata:{[u]:{itemId:_.item_id}}}),U.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":sk(_)?(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)):mk(_)?(w.push(_.annotation),_.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(Ge=(ee=(j=f.config).generateId)==null?void 0:ee.call(j))!=null?Ge:Ve(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Wr=(Gr=(ve=f.config).generateId)==null?void 0:Gr.call(ve))!=null?Wr: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:(Kr=(Jr=(Hr=f.config).generateId)==null?void 0:Jr.call(Hr))!=null?Kr: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:(Qr=(Xr=(Yr=f.config).generateId)==null?void 0:Xr.call(Yr))!=null?Qr: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}}})):hk(_)&&I.enqueue({type:"error",error:_})},flush(A){const I={[u]:{responseId:b,...y.length>0?{logprobs:y}:{},...O!==void 0?{serviceTier:O}:{}}};A.enqueue({type:"finish",finishReason:h,usage:tD(v),providerMetadata:I})}})),request:{body:n},response:{headers:c}}}},i(jr,"OpenAIResponsesLanguageModel"),jr);function ok(e){return e.type==="response.output_text.delta"}i(ok,"isTextDeltaChunk");function ak(e){return e.type==="response.output_item.done"}i(ak,"isResponseOutputItemDoneChunk");function sk(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(sk,"isResponseFinishedChunk");function ik(e){return e.type==="response.created"}i(ik,"isResponseCreatedChunk");function uk(e){return e.type==="response.function_call_arguments.delta"}i(uk,"isResponseFunctionCallArgumentsDeltaChunk");function lk(e){return e.type==="response.image_generation_call.partial_image"}i(lk,"isResponseImageGenerationCallPartialImageChunk");function ck(e){return e.type==="response.code_interpreter_call_code.delta"}i(ck,"isResponseCodeInterpreterCallCodeDeltaChunk");function dk(e){return e.type==="response.code_interpreter_call_code.done"}i(dk,"isResponseCodeInterpreterCallCodeDoneChunk");function pk(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(pk,"isResponseApplyPatchCallOperationDiffDeltaChunk");function fk(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(fk,"isResponseApplyPatchCallOperationDiffDoneChunk");function iD(e){return e.type==="response.output_item.added"}i(iD,"isResponseOutputItemAddedChunk");function mk(e){return e.type==="response.output_text.annotation.added"}i(mk,"isResponseAnnotationAddedChunk");function hk(e){return e.type==="error"}i(hk,"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 Dk=Y(()=>K(g({instructions:p().nullish(),speed:x().min(.25).max(4).default(1).nullish()}))),gk=(zr=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:Dk}),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:VF(),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(zr,"OpenAISpeechModel"),zr),vk=Y(()=>K(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()}))),yk=Y(()=>K(g({include:S(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:x().min(0).max(1).default(0).optional(),timestampGranularities:S(ue(["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"},_k=(Lr=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:yk}),a=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([bn(t)]);a.append("model",this.modelId);const l=H2(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 Vi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),formData:f,failedResponseHandler:Tt,successfulResponseHandler:Ke(vk),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(Lr,"OpenAITranscriptionModel"),Lr),bk="3.0.30";function Ro(e={}){var t,n;const r=(t=Gi(Io({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 ${W2({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${bk}`),"getHeaders"),a=i(v=>new rx(v,{provider:`${o}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new ix(v,{provider:`${o}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new cx(v,{provider:`${o}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new mx(v,{provider:`${o}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new _k(v,{provider:`${o}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),f=i(v=>new gk(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 rk(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=Jx,h}i(Ro,"createOpenAI"),Ro();var Ck=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:Q([p(),x()]).nullish()})}),No={errorSchema:Ck,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 Po(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(Po,"getOpenAIMetadata");function wk(e){switch(e){case"audio/wav":return"wav";case"audio/mp3":case"audio/mpeg":return"mp3";default:return null}}i(wk,"getAudioFormat");function Fk(e){var t,n,r;const o=[];for(const{role:s,content:a,...u}of e){const l=Po({...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,...Po(a[0])});break}o.push({role:"user",content:a.map(c=>{var d;const f=Po(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=wk(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=Po(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=Po(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(Fk,"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 Ek({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(Ek,"prepareTools");var xk=(qr=class{constructor(t,n){this.specificationVersion="v3";var r,o;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:No;this.chunkSchema=Ak(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:A,toolChoice:I,toolWarnings:ne}=Ek({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:Fk(t),tools:A,tool_choice:I},warnings:[...w,...ne]}}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(kk),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 A of b.message.tool_calls){const I=(o=(r=A.extra_content)==null?void 0:r.google)==null?void 0:o.thought_signature;C.push({type:"tool-call",toolCallId:(s=A.id)!=null?s:Ve(),toolName:A.function.name,input:A.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,A,I,ne,k,ae,B,M,z,L,R,J,he,oe;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 se=y.value;m&&(m=!1,b.enqueue({type:"response-metadata",...dD(se)})),se.usage!=null&&(f=se.usage);const re=se.choices[0];if(re?.finish_reason!=null&&(d={unified:pD(re.finish_reason),raw:(C=re.finish_reason)!=null?C:void 0}),re?.delta==null)return;const H=re.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 fo({data:xe,message:"Expected 'id' to be a string."});if(((T=xe.function)==null?void 0:T.name)==null)throw new fo({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:(ne=(I=(A=xe.extra_content)==null?void 0:A.google)==null?void 0:I.thought_signature)!=null?ne:void 0};const j=c[at];((k=j.function)==null?void 0:k.name)!=null&&((ae=j.function)==null?void 0:ae.arguments)!=null&&(j.function.arguments.length>0&&b.enqueue({type:"tool-input-delta",id:j.id,delta:j.function.arguments}),Wa(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||(((M=xe.function)==null?void 0:M.arguments)!=null&&(Ae.function.arguments+=(L=(z=xe.function)==null?void 0:z.arguments)!=null?L:""),b.enqueue({type:"tool-input-delta",id:Ae.id,delta:(R=xe.function.arguments)!=null?R:""}),((J=Ae.function)==null?void 0:J.name)!=null&&((he=Ae.function)==null?void 0:he.arguments)!=null&&Wa(Ae.function.arguments)&&(b.enqueue({type:"tool-input-end",id:Ae.id}),b.enqueue({type:"tool-call",toolCallId:(oe=Ae.id)!=null?oe: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 A of c.filter(I=>!I.hasFinished))y.enqueue({type:"tool-input-end",id:A.id}),y.enqueue({type:"tool-call",toolCallId:(b=A.id)!=null?b:Ve(),toolName:A.function.name,input:A.function.arguments,...A.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:A.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(qr,"OpenAICompatibleChatLanguageModel"),qr),fD=Fi({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(),kk=Fi({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}),Ik=Fi({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:ue(["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}),Ak=i(e=>Q([Ik,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 $k({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
164
|
+
|
|
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
|
+
${a}
|
|
167
|
+
|
|
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}:
|
|
169
|
+
${a}
|
|
170
|
+
|
|
171
|
+
`;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
|
|
172
|
+
`,{prompt:r,stopSequences:[`
|
|
173
|
+
${t}:`]}}i($k,"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 Tk=g({echo:Re().optional(),logitBias:Ce(p(),x()).optional(),suffix:p().optional(),user:p().optional()}),Sk=(Ur=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const o=(r=n.errorStructure)!=null?r:No;this.chunkSchema=Ok(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:Tk}))!=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}=$k({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(Bk),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(Ur,"OpenAICompatibleCompletionLanguageModel"),Ur),gD=g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}),Bk=g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p()})),usage:gD.nullish()}),Ok=i(e=>Q([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"),yu=g({dimensions:x().optional(),user:p().optional()}),Rk=(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:yu});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:yu}))!=null?s:{},(a=await tt({provider:this.providerOptionsName,providerOptions:o,schema:yu}))!=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:No),successfulResponseHandler:Ke(Nk),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(Zr,"OpenAICompatibleEmbeddingModel"),Zr),Nk=g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish(),providerMetadata:Ce(p(),Ce(p(),et())).optional()}),Pk=(Vr=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[Mk(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 Vi({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(A=>yD(A))),mask:d!=null?await yD(d):void 0,n,size:r,...C}),failedResponseHandler:gt((h=this.config.errorStructure)!=null?h:No),successfulResponseHandler:Ke(vD),abortSignal:l,fetch:this.config.fetch});return{images:T.data.map(A=>A.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:No),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(Vr,"OpenAICompatibleImageModel"),Vr),vD=g({data:S(g({b64_json:p()}))});async function yD(e){if(e.type==="url")return Pi(e.url);const t=e.data instanceof Uint8Array?e.data:bn(e.data);return new Blob([t],{type:e.mediaType})}i(yD,"fileToBlob");function Mk(e){return e.replace(/[_-]([a-z])/g,t=>t[1].toUpperCase())}i(Mk,"toCamelCase");var jk="2.0.30";function es(e){const t=Gi(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},o=i(()=>Cn(r,`ai-sdk/openai-compatible/${jk}`),"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 xk(m,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs,transformRequestBody:e.transformRequestBody,metadataExtractor:e.metadataExtractor}),"createChatModel"),l=i(m=>new Sk(m,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(m=>new Rk(m,{...s("embedding")}),"createEmbeddingModel"),d=i(m=>new Pk(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(es,"createOpenAICompatible");const zk={plain:"<commit message>",conventional:`<type>[optional (<scope>)]: <commit message>
|
|
174
|
+
The commit message subject must start with a lowercase letter`,gitmoji:":emoji: <commit message>","subject+body":"<commit message subject>"},Lk=i(e=>`The output response must be in format:
|
|
175
|
+
${zk[e]}`,"specifyCommitFormat"),qk={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
|
+
${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)}`,"subject+body":"Output only the subject line; the body is generated separately."},Uk=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,qk[n],Lk(n)].filter(Boolean).join(`
|
|
178
|
+
`),"generatePrompt"),Zk=i((e,t,n)=>["You are generating the short body (description) of a git commit message. You are given the commit title and the code diff.","Output must be brief: use 3\u20136 bullet points (one short line each), or 2\u20134 short sentences. No long paragraphs. Focus on what changed and why, in present tense.",`Git convention: each line at most ${t} characters. When a bullet line wraps, indent the continuation with 2 spaces so it aligns under the bullet text.`,'Do not repeat the title. No meta-commentary (e.g. "This commit..."). Respond with ONLY the commit body.',`Message language: ${e}`,n].filter(Boolean).join(`
|
|
179
|
+
`),"generateDescriptionPrompt"),ts=i(()=>!process.stdin.isTTY||!process.stdout.isTTY,"isHeadless"),Mo=i(()=>!!(process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI),"isInteractive"),_D=i(()=>!!(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&!ts(),"shouldLogDebug"),bD=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),_u=i(e=>bD(e).trim().split(`
|
|
180
|
+
`)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),Vk=i(e=>bD(e).trim().replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeDescription"),CD=i(e=>Array.from(new Set(e)),"deduplicateMessages"),wD=i(async(e,t,n,r,o)=>{const s=new AbortController,a=setTimeout(()=>s.abort(),o);try{const u=await Yn({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),_u(u.text)}catch(u){throw clearTimeout(a),u}},"shortenCommitMessage"),ns=i(async({baseUrl:e,apiKey:t,model:n,locale:r,diff:o,completions:s,maxLength:a,type:u,timeout:l,customPrompt:c,headers:d})=>{_D()&&(console.log("Diff being sent to AI:"),console.log(o));try{const f=e==="https://api.openai.com/v1"?Ro({apiKey:t}):es({name:"custom",apiKey:t,baseURL:e,headers:d}),m=new AbortController,D=setTimeout(()=>m.abort(),l),h=Array.from({length:s},()=>Yn({model:f(n),system:Uk(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=CD(y.map(E=>_u(E)));const C=3;for(let E=0;E<C;E++){let T=!1;const O=await Promise.all(b.map(async A=>{if(A.length<=a)return A;T=!0;try{return await wD(f,n,A,a,l)}catch{return A}}));if(b=CD(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 le(`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 le(`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 le(h)}throw m}},"generateCommitMessage"),Gk=i((e,t)=>{const r=/^([-*]\s)/.exec(e)?" ":"",o=t-r.length;if(e.length<=t)return e;const s=[];let a=e,u=!0;for(;a.length>(u?t:o);){const l=u?t:o,d=a.slice(0,l).lastIndexOf(" "),f=d>0?d+1:l,m=a.slice(0,f).trim();s.push(u?m:r+m),a=a.slice(f).trim(),u=!1}return a.length>0&&s.push(u?a:r+a),s.join(`
|
|
181
|
+
`)},"wrapLine"),Wk=i(async({baseUrl:e,apiKey:t,model:n,locale:r,title:o,diff:s,timeout:a,maxLength:u,customPrompt:l,headers:c})=>{_D()&&(console.log("Title and diff for description:"),console.log({title:o,diffLength:s.length}));const d=e==="https://api.openai.com/v1"?Ro({apiKey:t}):es({name:"custom",apiKey:t,baseURL:e,headers:c}),f=new AbortController,m=setTimeout(()=>f.abort(),a);try{const D=await Yn({model:d(n),system:Zk(r,u,l),prompt:`Commit message title:
|
|
182
|
+
${o}
|
|
183
|
+
|
|
184
|
+
Code diff:
|
|
185
|
+
${s}`,temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:f.signal});clearTimeout(m);let h=Vk(D.text);return h=h.split(`
|
|
186
|
+
`).map(v=>Gk(v,u)).join(`
|
|
187
|
+
`),{description:h,usage:D.usage}}catch(D){clearTimeout(m);const h=D;throw h.name==="AbortError"||h.message?.includes("aborted")||h.message?.includes("This operation was aborted")?new le(`Request timed out after ${a/1e3} seconds. The API took too long to respond. Try again or use a different model.`):h.code==="ENOTFOUND"?new le(`Error connecting to ${h.hostname} (${h.syscall}). Are you connected to the internet?`):h}},"generateCommitDescription"),Hk=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"?Ro({apiKey:n}):es({name:"custom",apiKey:n,baseURL:t,headers:c}),f=new AbortController,m=setTimeout(()=>f.abort(),u),h=await Yn({model:d(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
|
|
188
|
+
|
|
189
|
+
Input: Several commit messages separated by newlines.
|
|
190
|
+
Output: A single commit message starting with type like 'feat:' or 'fix:'.
|
|
191
|
+
|
|
192
|
+
Do not add thanks, explanations, or any text outside the commit message.`,prompt:e.join(`
|
|
193
|
+
`),temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:f.signal});clearTimeout(m);let v=_u(h.text);if(v.length>s)try{v=await wD(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 le(`Request timed out after ${u/1e3} seconds. The API took too long to respond. Try again or use a different model.`):f}},"combineCommitMessages"),Jk=i(async(e,t)=>{const{select:n,confirm:r,isCancel:o}=await Promise.resolve().then(function(){return lo}),{dim:s}=await Promise.resolve().then(function(){return Ry});if(e.length===1){const[u]=e;if(t)return u;if(!Mo())throw new le("Interactive terminal required for commit message confirmation. Use --yes flag to skip confirmation.");console.log(`
|
|
194
|
+
\x1B[1m${u}\x1B[0m
|
|
195
|
+
`);const l=await r({message:"Use this commit message?"});return l&&!o(l)?u:null}if(t)return e[0];if(!Mo())throw new le("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 Kk=i(async(e,t,n,r,o,s,a,u,l)=>(async()=>{const c=ts();c||da(aa(na(" aicommits "))),await si(),n&&await He("git",["add","--update"]);const d=await md(t);if(!d)throw new le("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)}:
|
|
196
|
+
${d.files.map(ne=>` ${ne}`).join(`
|
|
197
|
+
`)}`)):(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 le("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 le(`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(),ne=D.getApiKey()||"",k=D.getHeaders(),ae=3e4;let B=d.diff;if(B.length>ae&&(B=B.substring(0,ae)+`
|
|
198
|
+
|
|
199
|
+
[Diff truncated due to size]`),m.type==="subject+body"){const M=await ns({baseUrl:I,apiKey:ne,model:m.model,locale:m.locale,diff:B,completions:1,maxLength:m["max-length"],type:"subject+body",timeout:h,customPrompt:u,headers:k}),z=M.messages[0],{description:L}=await Wk({baseUrl:I,apiKey:ne,model:m.model,locale:m.locale,title:z,diff:B,timeout:h,maxLength:m["max-length"],customPrompt:u,headers:k});T=[L.trim()?`${z}
|
|
200
|
+
|
|
201
|
+
${L.trim()}`:z],O=M.usage}else if(C){const M=[];for(let J=0;J<d.files.length;J+=b)M.push(d.files.slice(J,J+b));const z=[];let L={prompt_tokens:0,completion_tokens:0,total_tokens:0};for(const J of M){const he=await y0(J,t);if(he&&he.diff){let se=he.diff;se.length>3e4&&(se=se.substring(0,3e4)+`
|
|
202
|
+
|
|
203
|
+
[Diff truncated due to size]`);const re=await ns({baseUrl:I,apiKey:ne,model:m.model,locale:m.locale,diff:se,completions:m.generate,maxLength:m["max-length"],type:m.type,timeout:h,customPrompt:u,headers:k});z.push(...re.messages),re.usage&&(L.prompt_tokens+=re.usage.prompt_tokens||re.usage.promptTokens||0,L.completion_tokens+=re.usage.completion_tokens||re.usage.completionTokens||0,L.total_tokens+=re.usage.total_tokens||re.usage.totalTokens||0)}}const R=await Hk({messages:z,baseUrl:I,apiKey:ne,model:m.model,locale:m.locale,maxLength:m["max-length"],type:m.type,timeout:h,customPrompt:u,headers:k});T=R.messages,R.usage&&(L.prompt_tokens+=R.usage.prompt_tokens||R.usage.promptTokens||0,L.completion_tokens+=R.usage.completion_tokens||R.usage.completionTokens||0,L.total_tokens+=R.usage.total_tokens||R.usage.totalTokens||0),O=L}else{const M=await ns({baseUrl:I,apiKey:ne,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=M.messages,O=M.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 le("No commit messages were generated. Try again.");if(c){const I=T[0];console.log(I);return}const A=await Jk(T,o);if(!A){be("Commit cancelled");return}if(s){await Vc(A)&&be(`${it("\u2714")} Message copied to clipboard`);return}try{const I=A.includes(`
|
|
204
|
+
|
|
205
|
+
`)?["-m",A.split(/\n\n/)[0],"-m",A.slice(A.indexOf(`
|
|
206
|
+
|
|
207
|
+
`)+2)]:["-m",A];a&&I.push("--no-verify"),await He("git",["commit",...I,...l],{stdio:"inherit",cleanup:!0,timeout:1e4}),be(`${it("\u2714")} Successfully committed!`)}catch(I){if(I.timedOut){const ne=await Vc(A);be(ne?`${ra("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${ra("\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(` ${io("Use")} --no-verify ${io("to bypass pre-commit hooks")}`),process.exit(1)),I}})().catch(mn),"aicommits");const[rs,Yk]=process.argv.slice(2);var Xk=i(()=>(async()=>{if(!rs)throw new le('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(Yk)return;const e=await md();if(!e)return;const t=ts();t||da(aa(na(" aicommits ")));const n=await hn({}),r=jn(n);if(!r)throw new le("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const o=r.validateConfig();if(!o.valid)throw new le(`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 ns({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 Je.readFile(rs,"utf8")!=="",h=f.length>1;let v="";D&&(v=`# \u{1F916} AI generated commit${h?"s":""}
|
|
208
|
+
`),h?(D&&(v+=`# Select one of the following messages by uncommenting:
|
|
209
|
+
`),v+=`
|
|
210
|
+
${f.map(C=>`# ${C}`).join(`
|
|
211
|
+
`)}`):(D&&(v+=`# Edit the message below and commit:
|
|
212
|
+
`),v+=`
|
|
213
|
+
${f[0]}
|
|
214
|
+
`);const y=await Je.readFile(rs,"utf8"),b=v+`
|
|
215
|
+
`+y;await Je.writeFile(rs,b),t||be(`${it("\u2714")} Saved commit message!`)})().catch(mn),"prepareCommitMessageHook"),Qk=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(li(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 di(n.map(r=>r.split("=")));return}throw new le(`Invalid mode: ${t}`)})().catch(mn)}),e8=sn({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{if(!Mo())throw new le("Interactive terminal required for setup. Run `aicommits setup` in a terminal.");let t=await hn();const n=V0(),r=await oi({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||G0(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 q0}),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 oi({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"},{value:"subject+body",label:"Subject + body - Git-style subject line and body"}],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 di(m),be(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(mn)}),t8=sn({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{if(!Mo())throw new le("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 di([["OPENAI_MODEL",o]]),be(`\u2705 Model updated to: ${o}`)):be("Model selection cancelled")})().catch(mn)});const FD="prepare-commit-msg",ED=`.git/hooks/${FD}`,os=QD(new URL("cli.mjs",import.meta.url)),xD=process.argv[1].replace(/\\/g,"/").endsWith(`/${ED}`),kD=process.platform==="win32",ID=`
|
|
216
|
+
#!/usr/bin/env node
|
|
217
|
+
import(${JSON.stringify(eg(os))})
|
|
218
|
+
`.trim();var n8=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 si(),{installUninstall:n}=e._,r=Ct.join(t,ED),o=await ui(r);if(n==="install"){if(o){if(await Je.realpath(r).catch(()=>{})===os){console.warn("The hook is already installed");return}throw new le(`A different ${FD} hook seems to be installed. Please remove it before installing aicommits.`)}await Je.mkdir(Ct.dirname(r),{recursive:!0}),kD?await Je.writeFile(r,ID):(await Je.symlink(os,r,"file"),await Je.chmod(r,493)),console.log(`${it("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(kD){if(await Je.readFile(r,"utf8")!==ID){console.warn("Hook is not installed");return}}else if(await Je.realpath(r)!==os){console.warn("Hook is not installed");return}await Je.rm(r),console.log(`${it("\u2714")} Hook uninstalled`);return}throw new le(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${Wt("\u2716")} ${t.message}`),dd(t),process.exit(1)})});function r8(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 le(`Unsupported git provider. Supported: GitHub, GitLab, Bitbucket, Azure DevOps.
|
|
219
|
+
Remote URL: ${e}`)}i(r8,"parseRemoteUrl");function o8(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(o8,"getPrUrl");var a8=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(!Mo())throw new le("Interactive terminal required for PR creation.");da(aa(na(" aicommits pr "))),await si();const{stdout:e}=await He("git",["branch","--show-current"]);if(!e.trim())throw new le("Not on a branch");const{stdout:t}=await He("git",["remote","get-url","origin"]),n=r8(t),{provider:r,owner:o,repo:s}=n;let a="main";try{const{stdout:B}=await He("git",["symbolic-ref","refs/remotes/origin/HEAD"]);a=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===a)throw new le("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 He("git",["diff",`origin/${a}..HEAD`]);u=B}catch{throw new le(`Could not get diff from origin/${a}`)}if(!u)throw new le("No changes to create PR from");const l=u.split(`
|
|
220
|
+
`).filter(B=>B.startsWith("diff --git")).length,c=3e4;u.length>c&&(u=u.substring(0,c)+`
|
|
221
|
+
|
|
222
|
+
[Diff truncated due to size]`);const d=await hn(),f=await jn(d);if(!f)throw new le("No provider configured");let m=f.getBaseUrl();if(!m||m==="")throw new le("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 le("API key not configured. Please run `aicommits setup` to configure your provider.");const h=m==="https://api.openai.com/v1"?Ro({apiKey:D}):es({name:"custom",apiKey:D,baseURL:m}),v=Ot();v.start(`Generating PR title and description (${l} files changed)`);const y=Date.now(),C=(await Yn({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 Yn({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:A}=await Promise.resolve().then(function(){return lo}),I=await A({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 ne=Ot();ne.start(`Pushing branch to ${r}`);try{await He("git",["push","-u","origin",e.trim()]),ne.stop(`Branch pushed to ${r}`)}catch(B){throw ne.stop("Failed to push branch"),new le(`Failed to push branch: ${B instanceof Error?B.message:String(B)}`)}const k=o8(r,o,s,a,e.trim(),C,E),ae=Ot();ae.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await He(B,[k]),ae.stop("PR creation page opened in browser"),be(it("PR creation page opened! Please review and submit the PR."))}catch{ae.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 s8=Il(hs);function i8(e){return e==="0.0.0-semantic-release"||e.includes("semantic-release")?"latest":e.includes("-")?"develop":"latest"}i(i8,"getDistTag");function u8(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(u8,"detectPackageManager");async function l8(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(l8,"getLatestVersion");var c8=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=i8(Vt.version),t=u8(e);console.log(`${oa("\u2139")} Current version: ${Vt.version}`),console.log(`${oa("\u2139")} Package manager detected: ${t.name}`),e!=="latest"&&console.log(`${oa("\u2139")} Using '${e}' distribution tag`);const n=Ot();n.start("Checking for updates...");const r=await l8(e);if(!r)throw n.stop("Could not check for updates",1),new le("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 s8(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(`
|
|
223
|
+
${ra("You can manually update with:")}`),console.error(` ${t.updateCommand}`)),process.exit(1)}})().catch(mn)});const d8=Il(hs);function AD(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(AD,"parseVersion");function p8(e,t){const n=AD(e),r=AD(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(p8,"compareVersions");async function f8(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(f8,"fetchLatestVersion");async function m8(e){try{const{stdout:t}=await d8(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(m8,"checkIfGlobalInstallation");async function h8(e,t){return new Promise((n,r)=>{const o=hs(`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(h8,"runBackgroundUpdate");async function D8(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 f8(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}`),p8(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 m8(t.name)){console.log("Note: aicommits is installed locally. Auto-update skipped for local installations.");return}try{await h8(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(D8,"checkAndAutoUpdate"),globalThis.AI_SDK_LOG_WARNINGS=!1;const{description:g8,version:bu}=Vt;if(!xD&&!ts()&&bu!=="0.0.0-semantic-release"){const e=bu.includes("-")?"develop":"latest";D8({pkg:Vt,distTag:e,headless:!1})}const $D=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, gitmoji, and subject+body",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:[Qk,e8,t8,n8,a8,c8],help:{description:g8},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(bu),process.exit(0)),xD?Xk():Kk(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.yes,e.flags.clipboard,e.flags.noVerify,e.flags.prompt,$D)},$D);export{un as g,Pf as r};
|