@sugarmo/aicommits 1.12.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/LICENSE +21 -0
- package/README.md +387 -0
- package/dist/cli-2IldWz4f.mjs +217 -0
- package/dist/cli-B4CzHGlw.mjs +217 -0
- package/dist/cli-BLeSI0RG.mjs +217 -0
- package/dist/cli-BxYoCO_t.mjs +217 -0
- package/dist/cli-BxoTG54R.mjs +217 -0
- package/dist/cli-D5LKS_gV.mjs +214 -0
- package/dist/cli-DOlOxITZ.mjs +217 -0
- package/dist/cli-Dghc1HXo.mjs +217 -0
- package/dist/cli-DhEhfPVj.mjs +217 -0
- package/dist/cli-DoRxvV2c.mjs +214 -0
- package/dist/cli-VKXKWT-J.mjs +217 -0
- package/dist/cli-ZGc9mt4a.mjs +217 -0
- package/dist/cli.mjs +126 -0
- package/dist/token-BGl6xBJo.mjs +1 -0
- package/dist/token-BHAr8BGF.mjs +1 -0
- package/dist/token-BNKPepq2.mjs +1 -0
- package/dist/token-BU4WbpuT.mjs +1 -0
- package/dist/token-BgWUvNvl.mjs +1 -0
- package/dist/token-Bitulk9b.mjs +1 -0
- package/dist/token-C-_ybS1T.mjs +1 -0
- package/dist/token-D9tzl7Yz.mjs +1 -0
- package/dist/token-DSxWyl39.mjs +1 -0
- package/dist/token-Dqj85-rE.mjs +1 -0
- package/dist/token-pFVbzMqR.mjs +1 -0
- package/dist/token-util-12Sgwcw5.mjs +1 -0
- package/dist/token-util-BK5iblfw.mjs +1 -0
- package/dist/token-util-BNtjmkiu.mjs +1 -0
- package/dist/token-util-Bezp8Ra7.mjs +1 -0
- package/dist/token-util-BthbkaNP.mjs +1 -0
- package/dist/token-util-C-S1NtRU.mjs +1 -0
- package/dist/token-util-C08UmjgT.mjs +1 -0
- package/dist/token-util-C9k-Ose8.mjs +1 -0
- package/dist/token-util-CIaGUPau.mjs +1 -0
- package/dist/token-util-CghlsVgF.mjs +1 -0
- package/dist/token-util-Cm6RjjS1.mjs +1 -0
- package/dist/token-util-CnZZ1AJv.mjs +1 -0
- package/dist/token-util-CtBubgF8.mjs +1 -0
- package/dist/token-util-CzaKG7us.mjs +1 -0
- package/dist/token-util-D4W-wT_B.mjs +1 -0
- package/dist/token-util-DYebtoan.mjs +1 -0
- package/dist/token-util-Db6xqzh1.mjs +1 -0
- package/dist/token-util-Dg8-JbHb.mjs +1 -0
- package/dist/token-util-DtOpdBbh.mjs +1 -0
- package/dist/token-util-Hi0Y_OJ1.mjs +1 -0
- package/dist/token-util-Z9AnE2k6.mjs +1 -0
- package/dist/token-util-daVwaNP6.mjs +1 -0
- package/dist/token-util-r02UdbTi.mjs +1 -0
- package/dist/token-util-yhghfNwd.mjs +1 -0
- package/dist/token-xhtueDQA.mjs +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
var Xm=Object.defineProperty;var s=(e,t)=>Xm(e,"name",{value:t,configurable:!0});var gn,Kt,vn,yn,_n,Fn,Cn,bn,En,wn,Tt,An,In,Yt,Xt,xn,kn,$n,Tn,Bn,Sn,On,Rn,Nn,Pn,Mn,jn,zn,qn,Zn,Ln,Un,Vn,Gn,Wn,Hn,Jn,Kn,Yn,Xn,Qn,er,tr,nr,rr,or,ar,ir,sr;import Qm from"tty";import ef from"update-notifier";import{Buffer as tf}from"node:buffer";import nn from"node:path";import os,{ChildProcess as nf}from"node:child_process";import ke,{stdin as as,stdout as is}from"node:process";import rf from"child_process";import it from"path";import Po from"fs";import{fileURLToPath as ss}from"node:url";import of,{constants as us}from"node:os";import af from"assert";import sf from"events";import{createWriteStream as uf,createReadStream as lf}from"node:fs";import cf from"buffer";import Mo from"stream";import pf from"util";import{debuglog as df}from"node:util";import*as jr from"node:readline";import ls from"node:readline";import{Writable as mf}from"node:stream";import Ne from"fs/promises";import cs from"os";import ff from"crypto";import{fileURLToPath as hf,pathToFileURL as Df}from"url";var gf=Object.defineProperty,$e=s((e,t)=>gf(e,"name",{value:t,configurable:!0}),"a");const vf="known-flag",yf="unknown-flag",_f="argument",Ff=/\B([A-Z])/g,Cf=$e(e=>e.replaceAll(Ff,"-$1").toLowerCase(),"camelToKebab"),{hasOwnProperty:bf}=Object.prototype,dr=$e((e,t)=>bf.call(e,t),"hasOwn"),jo=$e(e=>typeof e=="function"?[e,!1]:Array.isArray(e)?[e[0],!0]:jo(e.type),"parseFlagType"),ps=$e((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),ds=$e((e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),"applyParser"),Ef=/[\s.:=]/,wf=$e(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(Ef);if(n)throw new Error(`${t} cannot contain "${n?.[0]}"`)},"validateFlagName"),zo=$e((e,t,n)=>{if(dr(e,t))throw new Error(`Duplicate flags named "${t}"`);e[t]=n},"setFlag"),Af=$e(e=>{const t={};for(const n in e){if(!dr(e,n))continue;wf(n);const r=e[n],a=[[],...jo(r),r];zo(t,n,a);const i=Cf(n);if(n!==i&&zo(t,i,a),"alias"in r&&typeof r.alias=="string"){const{alias:o}=r,u=`Flag alias "${o}" for flag "${n}"`;if(o.length===0)throw new Error(`${u} cannot be empty`);if(o.length>1)throw new Error(`${u} must be a single character`);zo(t,o,a)}}return t},"createRegistry"),If=$e((e,t)=>{const n={};for(const r in e){if(!dr(e,r))continue;const[a,,i,o]=t[r];if(a.length===0&&"default"in o){let{default:u}=o;typeof u=="function"&&(u=u()),n[r]=u}else n[r]=i?a:a.pop()}return n},"finalizeFlags"),zr="--",xf=3,kf=/^-{1,2}\w/,ms=$e(e=>{if(!kf.test(e))return;const t=!e.startsWith(zr);let n=e.slice(t?1:2),r,a=-1;for(const i of["=",":","."]){const o=n.indexOf(i);o!==-1&&(a===-1||o<a)&&(a=o)}return a!==-1&&(r=n.slice(a+1),n=n.slice(0,a)),[n,r,t]},"parseFlagArgv"),fs=$e((e,{onFlag:t,onArgument:n})=>{let r;const a=$e((i,o)=>{if(typeof r!="function")return!0;r(i,o),r=void 0},"triggerValueCallback");for(let i=0;i<e.length;i+=1){const o=e[i];if(o===zr){a();const l=e.slice(i+1);n?.(l,[i],!0);break}const u=ms(o);if(u){if(a(),!t)continue;const[l,c,d]=u;if(d)for(let m=0;m<l.length;m+=1){a();const h=m===l.length-1;r=t(l[m],h?c:void 0,[i,m+1,h])}else r=t(l,c,[i])}else a(o,[i])&&n?.([o],[i])}a()},"argvIterator"),hs=$e((e,t)=>{for(let n=t.length-1;n>=0;n-=1){const[r,a,i]=t[n];if(a){const o=e[r];let u=o.slice(0,a);if(i||(u+=o.slice(a+1)),u!=="-"){e[r]=u;continue}}e.splice(r,1)}},"spliceFromArgv"),$f=$e((e,t=process.argv.slice(2),{ignore:n}={})=>{const r=[],a=Af(e),i={},o=[];return o[zr]=[],fs(t,{onFlag(u,l,c){const d=(c.length===xf||u.length>1)&&dr(a,u);if(!n?.(d?vf:yf,u,l)){if(d){const[m,h]=a[u],D=ps(h,l),f=$e((g,y)=>{r.push(c),y&&r.push(y),m.push(ds(h,g||""))},"getFollowingValue");return D===void 0?f:f(D)}dr(i,u)||(i[u]=[]),i[u].push(l===void 0?!0:l),r.push(c)}},onArgument:$e((u,l,c)=>{n?.(_f,t[l[0]])||(o.push(...u),c?(o[zr]=u,t.splice(l[0])):r.push(l))},"onArgument")}),hs(t,r),{flags:If(e,a),unknownFlags:i,_:o}},"typeFlag");$e((e,t,n=process.argv.slice(2))=>{const r=new Set(e.split(",").map(l=>ms(l)?.[0])),[a,i]=jo(t),o=[],u=[];return fs(n,{onFlag:$e((l,c,d)=>{if(!r.has(l)||!i&&o.length>0)return;const m=ps(a,c),h=$e((D,f)=>{u.push(d),f&&u.push(f),o.push(ds(a,D||""))},"getFollowingValue");return m===void 0?h:h(m)},"onFlag")}),hs(n,u),i?o:o[0]},"getFlag");var Tf=Object.defineProperty,ne=s((e,t)=>Tf(e,"name",{value:t,configurable:!0}),"n");const Bf=ne(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 Ds({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")}s(Ds,"j$1"),ne(Ds,"ansiRegex");const Sf=Ds();function qo(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Sf,"")}s(qo,"w$2"),ne(qo,"stripAnsi");function gs(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}s(gs,"P$2"),ne(gs,"isAmbiguous");function vs(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}s(vs,"z$2"),ne(vs,"isFullWidth");function ys(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}s(ys,"G$3"),ne(ys,"isWide");function _s(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}s(_s,"Z$1"),ne(_s,"validate");function Fs(e,{ambiguousAsWide:t=!1}={}){return _s(e),vs(e)||ys(e)||t&&gs(e)?2:1}s(Fs,"V$3"),ne(Fs,"eastAsianWidth");var Of=ne(()=>/[#*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 Rf=new Intl.Segmenter,Nf=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Et(e,t={}){if(typeof e!="string"||e.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=qo(e)),e.length===0)return 0;let a=0;const i={ambiguousAsWide:!n};for(const{segment:o}of Rf.segment(e)){const u=o.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)&&!Nf.test(o)){if(Of().test(o)){a+=2;continue}a+=Fs(u,i)}}return a}s(Et,"d$2"),ne(Et,"stringWidth");const Cs=ne(e=>Math.max(...e.split(`
|
|
2
|
+
`).map(t=>Et(t))),"getLongestLineWidth"),Pf=ne(e=>{const t=[];for(const n of e){const{length:r}=n,a=r-t.length;for(let i=0;i<a;i+=1)t.push(0);for(let i=0;i<r;i+=1){const o=Cs(n[i]);o>t[i]&&(t[i]=o)}}return t},"getColumnContentWidths"),bs=/^\d+%$/,Es={width:"auto",align:"left",contentWidth:0,paddingLeft:0,paddingRight:0,paddingTop:0,paddingBottom:0,horizontalPadding:0,paddingLeftString:"",paddingRightString:""},Mf=ne((e,t)=>{const n=[];for(let r=0;r<e.length;r+=1){const a=t[r]??"auto";if(typeof a=="number"||a==="auto"||a==="content-width"||typeof a=="string"&&bs.test(a)){n.push({...Es,width:a,contentWidth:e[r]});continue}if(a&&typeof a=="object"){const i={...Es,...a,contentWidth:e[r]};i.horizontalPadding=i.paddingLeft+i.paddingRight,n.push(i);continue}throw new Error(`Invalid column width: ${JSON.stringify(a)}`)}return n},"initColumns"),jf=ne((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"&&bs.test(r)){const l=Number.parseFloat(r.slice(0,-1))/100;n.width=Math.floor(t*l)-(n.paddingLeft+n.paddingRight)}const{horizontalPadding:a}=n,i=1,o=i+a;if(o>=t){const l=o-t,c=Math.ceil(n.paddingLeft/a*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),i)}},"resolveColumnWidths"),ws=ne(()=>Object.assign([],{columns:0}),"makeRow"),zf=ne((e,t)=>{const n=[ws()];let[r]=n;for(const a of e){const i=a.width+a.horizontalPadding;r.columns+i>t&&(r=ws(),n.push(r)),r.push(a),r.columns+=i}for(const a of n){const i=a.reduce((h,D)=>h+D.width+D.horizontalPadding,0);let o=t-i;if(o===0)continue;const u=a.filter(h=>"autoOverflow"in h),l=u.filter(h=>h.autoOverflow>0),c=l.reduce((h,D)=>h+D.autoOverflow,0),d=Math.min(c,o);for(const h of l){const D=Math.floor(h.autoOverflow/c*d);h.width+=D,o-=D}const m=Math.floor(o/u.length);for(let h=0;h<u.length;h+=1){const D=u[h];h===u.length-1?D.width+=o:D.width+=m,o-=m}}return n},"balanceAuto"),qf=ne((e,t,n)=>{const r=Mf(n,t);return jf(r,e),zf(r,e)},"computeColumnWidths"),Zo=10,As=ne((e=0)=>t=>`\x1B[${t+e}m`,"wrapAnsi16"),Is=ne((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"wrapAnsi256"),xs=ne((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 Zf=Object.keys(_e.color),Lf=Object.keys(_e.bgColor);[...Zf,...Lf];function ks(){const e=new Map;for(const[t,n]of Object.entries(_e)){for(const[r,a]of Object.entries(n))_e[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=_e[r],e.set(a[0],a[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=As(),_e.color.ansi256=Is(),_e.color.ansi16m=xs(),_e.bgColor.ansi=As(Zo),_e.bgColor.ansi256=Is(Zo),_e.bgColor.ansi16m=xs(Zo),Object.defineProperties(_e,{rgbToAnsi256:{value:ne((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:ne(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(i=>i+i).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:ne(t=>_e.rgbToAnsi256(..._e.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:ne(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const i=Math.max(n,r,a)*2;if(i===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return i===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:ne((t,n,r)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:ne(t=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),"value"),enumerable:!1}}),_e}s(ks,"FD$1"),ne(ks,"assembleStyles");const Uf=ks(),qr=new Set(["\x1B","\x9B"]),Vf=39,Lo="\x07",$s="[",Gf="]",Ts="m",Zr=`${Gf}8;;`,Bs=ne(e=>`${qr.values().next().value}${$s}${e}${Ts}`,"wrapAnsiCode"),Ss=ne(e=>`${qr.values().next().value}${Zr}${e}${Lo}`,"wrapAnsiHyperlink"),Wf=ne(e=>e.split(" ").map(t=>Et(t)),"wordLengths"),Uo=ne((e,t,n)=>{const r=[...t];let a=!1,i=!1,o=Et(qo(e.at(-1)));for(const[u,l]of r.entries()){const c=Et(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),qr.has(l)&&(a=!0,i=r.slice(u+1,u+1+Zr.length).join("")===Zr),a){i?l===Lo&&(a=!1,i=!1):l===Ts&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"wrapWord"),Hf=ne(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(Et(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"stringVisibleTrimSpacesRight"),Jf=ne((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,i;const o=Wf(e);let u=[""];for(const[m,h]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u.at(-1).trimStart());let D=Et(u.at(-1));if(m!==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&&o[m]>t){const f=t-D,g=1+Math.floor((o[m]-f-1)/t);Math.floor((o[m]-1)/t)<g&&u.push(""),Uo(u,h,t);continue}if(D+o[m]>t&&D>0&&o[m]>0){if(n.wordWrap===!1&&D<t){Uo(u,h,t);continue}u.push("")}if(D+o[m]>t&&n.wordWrap===!1){Uo(u,h,t);continue}u[u.length-1]+=h}n.trim!==!1&&(u=u.map(m=>Hf(m)));const l=u.join(`
|
|
3
|
+
`),c=[...l];let d=0;for(const[m,h]of c.entries()){if(r+=h,qr.has(h)){const{groups:f}=new RegExp(`(?:\\${$s}(?<code>\\d+)m|\\${Zr}(?<uri>.*)${Lo})`).exec(l.slice(d))||{groups:{}};if(f.code!==void 0){const g=Number.parseFloat(f.code);a=g===Vf?void 0:g}else f.uri!==void 0&&(i=f.uri.length===0?void 0:f.uri)}const D=Uf.codes.get(Number(a));c[m+1]===`
|
|
4
|
+
`?(i&&(r+=Ss("")),a&&D&&(r+=Bs(D))):h===`
|
|
5
|
+
`&&(a&&D&&(r+=Bs(a)),i&&(r+=Ss(i))),d+=h.length}return r},"exec");function Os(e,t,n){return String(e).normalize().replaceAll(`\r
|
|
6
|
+
`,`
|
|
7
|
+
`).split(`
|
|
8
|
+
`).map(r=>Jf(r,t,n)).join(`
|
|
9
|
+
`)}s(Os,"BD$1"),ne(Os,"wrapAnsi");const Rs=ne(e=>Array.from({length:e}).fill(""),"emptyLines"),Kf=ne((e,t)=>{const n=[];let r=0;for(const a of e){let i=0;const o=a.map(l=>{let c=t[r]??"";r+=1,l.preprocess&&(c=l.preprocess(c)),Cs(c)>l.width&&(c=Os(c,l.width,{hard:!0}));let d=c.split(`
|
|
10
|
+
`);if(l.postprocess){const{postprocess:m}=l;d=d.map((h,D)=>m.call(l,h,D))}return l.paddingTop&&d.unshift(...Rs(l.paddingTop)),l.paddingBottom&&d.push(...Rs(l.paddingBottom)),d.length>i&&(i=d.length),{...l,lines:d}}),u=[];for(let l=0;l<i;l+=1){const c=o.map(d=>{const m=d.lines[l]??"",h=Number.isFinite(d.width)?" ".repeat(d.width-Et(m)):"";let D=d.paddingLeftString;return d.align==="right"&&(D+=h),D+=m,d.align==="left"&&(D+=h),D+d.paddingRightString}).join("");u.push(c)}n.push(u.join(`
|
|
11
|
+
`))}return n.join(`
|
|
12
|
+
`)},"renderRow"),Yf=ne((e,t)=>{if(!e||e.length===0)return"";const n=Pf(e),r=n.length;if(r===0)return"";const{stdoutColumns:a,columns:i}=Bf(t);if(i.length>r)throw new Error(`${i.length} columns defined, but only ${r} columns found`);const o=qf(a,i,n);return e.map(u=>Kf(o,u)).join(`
|
|
13
|
+
`)},"terminalColumns"),Xf=["<",">","=",">=","<="],Qf=ne(e=>{if(!Xf.includes(e))throw new TypeError(`Invalid breakpoint operator: ${e}`)},"assertOperator"),eh=ne(e=>{const t=Object.keys(e).map(n=>{const[r,a]=n.split(" ");Qf(r);const i=Number.parseInt(a,10);if(Number.isNaN(i))throw new TypeError(`Invalid breakpoint value: ${a}`);const o=e[n];return{operator:r,breakpoint:i,value:o}}).sort((n,r)=>r.breakpoint-n.breakpoint);return n=>t.find(({operator:r,breakpoint:a})=>r==="="&&n===a||r===">"&&n>a||r==="<"&&n<a||r===">="&&n>=a||r==="<="&&n<=a)?.value},"breakpoints");var th=Object.defineProperty,ge=s((e,t)=>th(e,"name",{value:t,configurable:!0}),"s");const nh=ge(e=>e.replaceAll(/[\W_]([a-z\d])?/gi,(t,n)=>n?n.toUpperCase():""),"camelCase"),rh=ge(e=>e.replaceAll(/\B([A-Z])/g,"-$1").toLowerCase(),"kebabCase"),oh={"> 80":[{width:"content-width",paddingLeft:2,paddingRight:8},{width:"auto"}],"> 40":[{width:"auto",paddingLeft:2,paddingRight:8,preprocess:ge(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 Ns(e){let t=!1;return{type:"table",data:{tableData:Object.keys(e).sort((n,r)=>n.localeCompare(r)).map(n=>{const r=e[n],a="alias"in r;return a&&(t=!0),{name:n,flag:r,flagFormatted:`--${rh(n)}`,aliasesEnabled:t,aliasFormatted:a?`-${r.alias}`:void 0}}).map(n=>(n.aliasesEnabled=t,[{type:"flagName",data:n},{type:"flagDescription",data:n}])),tableBreakpoints:oh}}}s(Ns,"T"),ge(Ns,"renderFlags");const Ps=ge(e=>!e||(e.version??(e.help?e.help.version:void 0)),"getVersion"),Ms=ge(e=>{const t="parent"in e&&e.parent?.name;return(t?`${t} `:"")+e.name},"getName");function js(e){const t=[];e.name&&t.push(Ms(e));const n=Ps(e)??("parent"in e&&Ps(e.parent));if(n&&t.push(`v${n}`),t.length!==0)return{id:"name",type:"text",data:`${t.join(" ")}
|
|
14
|
+
`}}s(js,"k$2"),ge(js,"getNameAndVersion");function zs(e){const{help:t}=e;if(!(!t||!t.description))return{id:"description",type:"text",data:`${t.description}
|
|
15
|
+
`}}s(zs,"_$1"),ge(zs,"getDescription");function qs(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=[Ms(e)];if(e.flags&&Object.keys(e.flags).length>0&&r.push("[flags...]"),e.parameters&&e.parameters.length>0){const{parameters:a}=e,i=a.indexOf("--"),o=i!==-1&&a.slice(i+1).some(u=>u.startsWith("<"));r.push(a.map(u=>u!=="--"?u:o?"--":"[--]").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
|
+
`)}}}}s(qs,"F"),ge(qs,"getUsage");function Zs(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}}}s(Zs,"H"),ge(Zs,"getCommands");function Ls(e){if(!(!e.flags||Object.keys(e.flags).length===0))return{id:"flags",type:"section",data:{title:"Flags:",body:Ns(e.flags),indentBody:0}}}s(Ls,"U$1"),ge(Ls,"getFlags");function Us(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}}}s(Us,"V$2"),ge(Us,"getExamples");function Vs(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}}}s(Vs,"J$1"),ge(Vs,"getAliases");const ah=ge(e=>[js,zs,qs,Zs,Ls,Us,Vs].map(t=>t(e)).filter(Boolean),"generateHelp"),ih=Qm.WriteStream.prototype.hasColors(),Gs=(gn=class{text(t){return t}bold(t){return ih?`\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 Yf(t.map(a=>a.map(i=>this.render(i))),r?eh(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:a,aliasFormatted:i}=t;let o="";if(i?o+=`${i}, `:a&&(o+=" "),o+=r,"placeholder"in n&&typeof n.placeholder=="string")o+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(o+=`${this.flagOperator(t)}${u}`)}return o}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)}`)}},s(gn,"_z"),gn);ge(Gs,"Renderers");let sh=Gs;const Vo=ge(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:ft}=JSON,uh=/[|\\{}()[\]^$+*?.]/;function Lr(e){const t=[];let n,r;for(const a of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${ft(r)} must be last`);const i=a[0],o=a.at(-1);let u;if(i==="<"&&o===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${ft(a)} cannot come after optional parameter ${ft(n)}`);if(i==="["&&o==="]"&&(u=!1,n=a),u===void 0)throw new Error(`Invalid parameter: ${ft(a)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=a.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=a,l=l.slice(0,-3));const d=l.match(uh);if(d)throw new Error(`Invalid parameter: ${ft(a)}. Invalid character found ${ft(d[0])}`);t.push({name:l,required:u,spread:c})}return t}s(Lr,"b$1"),ge(Lr,"parseParameters");function Ur(e,t,n,r){for(let a=0;a<t.length;a+=1){const{name:i,required:o,spread:u}=t[a],l=nh(i);if(l in e)throw new Error(`Invalid parameter: ${ft(i)} is used more than once.`);const c=u?n.slice(a):n[a];if(u&&(a=t.length),o&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${ft(i)}
|
|
22
|
+
`),r(),process.exit(1);e[l]=c}}s(Ur,"v"),ge(Ur,"mapParametersToArguments");function Ws(e){return e===void 0||e!==!1}s(Ws,"G$2"),ge(Ws,"helpEnabled");function Go(e,t,n,r){const a={...t.flags},i=t.version&&!("version"in a);i&&(a.version={type:Boolean,description:"Show version"});const{help:o}=t,u=Ws(o);u&&!("help"in a)&&(a.help={type:Boolean,alias:"h",description:"Show help"});const l=$f(a,r,{ignore:t.ignoreArgv}),c=ge(()=>{console.log(t.version)},"showVersion");if(i&&l.flags.version===!0)return c(),process.exit(0);const d=new sh,m=u&&o?.render?o.render:g=>d.render(g),h=ge(g=>{const y=ah({...t,...g?{help:g}:{},flags:a});console.log(m(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:g}=t,y=l._;const F=g.indexOf("--"),w=g.slice(F+1),b=Object.create(null);if(F>-1&&w.length>0){g=g.slice(0,F);const E=l._["--"];y=y.slice(0,-E.length||void 0),Ur(b,Lr(g),y,h),Ur(b,Lr(w),E,h)}else Ur(b,Lr(g),y,h);Object.assign(l._,b)}const D={...l,showVersion:c,showHelp:h},f={command:e,...D};if(typeof n=="function"){const g=n(D);if(g&&"then"in g)return Object.assign(Promise.resolve(g),f)}return f}s(Go,"j"),ge(Go,"cliBase");function Hs(e,t){const n=new Map;for(const r of t){const a=[r.options.name],{alias:i}=r.options;i&&(Array.isArray(i)?a.push(...i):a.push(i));for(const o of a){if(n.has(o))throw new Error(`Duplicate command name found: ${ft(o)}`);n.set(o,r)}}return n.get(e)}s(Hs,"K$1"),ge(Hs,"getCommand");function Js(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!Vo(e.name)))throw new Error(`Invalid script name: ${ft(e.name)}`);const r=n[0];if(e.commands&&r&&Vo(r)){const a=Hs(r,e.commands);if(a)return Go(a.options.name,{...a.options,parent:e},a.callback,n.slice(1))}return Go(void 0,e,t,n)}s(Js,"Q"),ge(Js,"cli");function rn(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(!Vo(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}s(rn,"X"),ge(rn,"command");var lh="aicommits",ch="0.0.0-semantic-release",ph="Writes your git commit messages for you with AI",dh=["ai","git","commit","code changes"],mh="MIT",fh={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},hh="Hassan El Mghari (@nutlope)",Dh="module",gh=["dist"],vh={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},yh={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},_h={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","@types/update-notifier":"^6.0.8","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",clipboardy:"^5.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.13","@ai-sdk/openai":"^3.0.5","@ai-sdk/openai-compatible":"^2.0.4",pkgroll:"^2.20.1",tsx:"^4.20.6",typescript:"^5.9.3"},Fh={branches:["main",{name:"develop",prerelease:!0}]},Ch={"update-notifier":"^7.3.1"},bh="pnpm@10.29.2+sha512.bef43fa759d91fd2da4b319a5a0d13ef7a45bb985a3d7342058470f9d2051a3ba8674e629672654686ef9443ad13a82da2beb9eeb3e0221c87b8154fff9d74b8",Wo={name:lh,version:ch,description:ph,keywords:dh,license:mh,repository:fh,author:hh,type:Dh,files:gh,bin:vh,scripts:yh,devDependencies:_h,release:Fh,dependencies:Ch,packageManager:bh},wt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function St(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}s(St,"getDefaultExportFromCjs");var Ot={exports:{}},Ho,Ks;function Eh(){if(Ks)return Ho;Ks=1,Ho=r,r.sync=a;var e=Po;function t(i,o){var u=o.pathExt!==void 0?o.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&&i.substr(-c.length).toLowerCase()===c)return!0}return!1}s(t,"checkPathExt");function n(i,o,u){return!i.isSymbolicLink()&&!i.isFile()?!1:t(o,u)}s(n,"checkStat");function r(i,o,u){e.stat(i,function(l,c){u(l,l?!1:n(c,i,o))})}s(r,"isexe");function a(i,o){return n(e.statSync(i),i,o)}return s(a,"sync"),Ho}s(Eh,"requireWindows");var Jo,Ys;function wh(){if(Ys)return Jo;Ys=1,Jo=t,t.sync=n;var e=Po;function t(i,o,u){e.stat(i,function(l,c){u(l,l?!1:r(c,o))})}s(t,"isexe");function n(i,o){return r(e.statSync(i),o)}s(n,"sync");function r(i,o){return i.isFile()&&a(i,o)}s(r,"checkStat");function a(i,o){var u=i.mode,l=i.uid,c=i.gid,d=o.uid!==void 0?o.uid:process.getuid&&process.getuid(),m=o.gid!==void 0?o.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),f=parseInt("001",8),g=h|D,y=u&f||u&D&&c===m||u&h&&l===d||u&g&&d===0;return y}return s(a,"checkMode"),Jo}s(wh,"requireMode");var Ko,Xs;function Ah(){if(Xs)return Ko;Xs=1;var e;process.platform==="win32"||wt.TESTING_WINDOWS?e=Eh():e=wh(),Ko=t,t.sync=n;function t(r,a,i){if(typeof a=="function"&&(i=a,a={}),!i){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,u){t(r,a||{},function(l,c){l?u(l):o(c)})})}e(r,a||{},function(o,u){o&&(o.code==="EACCES"||a&&a.ignoreErrors)&&(o=null,u=!1),i(o,u)})}s(t,"isexe");function n(r,a){try{return e.sync(r,a||{})}catch(i){if(a&&a.ignoreErrors||i.code==="EACCES")return!1;throw i}}return s(n,"sync"),Ko}s(Ah,"requireIsexe");var Yo,Qs;function Ih(){if(Qs)return Yo;Qs=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=it,n=e?";":":",r=Ah(),a=s(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),i=s((l,c)=>{const d=c.colon||n,m=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:m,pathExt:D,pathExtExe:h}},"getPathInfo"),o=s((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:m,pathExt:h,pathExtExe:D}=i(l,c),f=[],g=s(F=>new Promise((w,b)=>{if(F===m.length)return c.all&&f.length?w(f):b(a(l));const E=m[F],O=/^".*"$/.test(E)?E.slice(1,-1):E,k=t.join(O,l),C=!O&&/^\.[\\\/]/.test(l)?l.slice(0,2)+k:k;w(y(C,F,0))}),"step"),y=s((F,w,b)=>new Promise((E,O)=>{if(b===h.length)return E(g(w+1));const k=h[b];r(F+k,{pathExt:D},(C,L)=>{if(!C&&L)if(c.all)f.push(F+k);else return E(F+k);return E(y(F,w,b+1))})}),"subStep");return d?g(0).then(F=>d(null,F),d):g(0)},"which"),u=s((l,c)=>{c=c||{};const{pathEnv:d,pathExt:m,pathExtExe:h}=i(l,c),D=[];for(let f=0;f<d.length;f++){const g=d[f],y=/^".*"$/.test(g)?g.slice(1,-1):g,F=t.join(y,l),w=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+F:F;for(let b=0;b<m.length;b++){const E=w+m[b];try{if(r.sync(E,{pathExt:h}))if(c.all)D.push(E);else return E}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw a(l)},"whichSync");return Yo=o,o.sync=u,Yo}s(Ih,"requireWhich");var Vr={exports:{}},eu;function xh(){if(eu)return Vr.exports;eu=1;const e=s((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"},"pathKey");return Vr.exports=e,Vr.exports.default=e,Vr.exports}s(xh,"requirePathKey");var Xo,tu;function kh(){if(tu)return Xo;tu=1;const e=it,t=Ih(),n=xh();function r(i,o){const u=i.options.env||process.env,l=process.cwd(),c=i.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(i.options.cwd)}catch{}let m;try{m=t.sync(i.command,{path:u[n({env:u})],pathExt:o?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return m&&(m=e.resolve(c?i.options.cwd:"",m)),m}s(r,"resolveCommandAttempt");function a(i){return r(i)||r(i,!0)}return s(a,"resolveCommand"),Xo=a,Xo}s(kh,"requireResolveCommand");var Gr={},nu;function $h(){if(nu)return Gr;nu=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}s(t,"escapeCommand");function n(r,a){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),a&&(r=r.replace(e,"^$1")),r}return s(n,"escapeArgument"),Gr.command=t,Gr.argument=n,Gr}s($h,"require_escape");var Qo,ru;function Th(){return ru||(ru=1,Qo=/^#!(.*)/),Qo}s(Th,"requireShebangRegex");var ea,ou;function Bh(){if(ou)return ea;ou=1;const e=Th();return ea=s((t="")=>{const n=t.match(e);if(!n)return null;const[r,a]=n[0].replace(/#! ?/,"").split(" "),i=r.split("/").pop();return i==="env"?a:a?`${i} ${a}`:i},"shebangCommand"),ea}s(Bh,"requireShebangCommand");var ta,au;function Sh(){if(au)return ta;au=1;const e=Po,t=Bh();function n(r){const i=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,i,0,150,0),e.closeSync(o)}catch{}return t(i.toString())}return s(n,"readShebang"),ta=n,ta}s(Sh,"requireReadShebang");var na,iu;function Oh(){if(iu)return na;iu=1;const e=it,t=kh(),n=$h(),r=Sh(),a=process.platform==="win32",i=/\.(?:com|exe)$/i,o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const m=d.file&&r(d.file);return m?(d.args.unshift(d.file),d.command=m,t(d)):d.file}s(u,"detectShebang");function l(d){if(!a)return d;const m=u(d),h=!i.test(m);if(d.options.forceShell||h){const D=o.test(m);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(g=>n.argument(g,D));const f=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${f}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}s(l,"parseNonShell");function c(d,m,h){m&&!Array.isArray(m)&&(h=m,m=null),m=m?m.slice(0):[],h=Object.assign({},h);const D={command:d,args:m,options:h,file:void 0,original:{command:d,args:m}};return h.shell?D:l(D)}return s(c,"parse"),na=c,na}s(Oh,"requireParse");var ra,su;function Rh(){if(su)return ra;su=1;const e=process.platform==="win32";function t(i,o){return Object.assign(new Error(`${o} ${i.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${i.command}`,path:i.command,spawnargs:i.args})}s(t,"notFoundError");function n(i,o){if(!e)return;const u=i.emit;i.emit=function(l,c){if(l==="exit"){const d=r(c,o);if(d)return u.call(i,"error",d)}return u.apply(i,arguments)}}s(n,"hookChildProcess");function r(i,o){return e&&i===1&&!o.file?t(o.original,"spawn"):null}s(r,"verifyENOENT");function a(i,o){return e&&i===1&&!o.file?t(o.original,"spawnSync"):null}return s(a,"verifyENOENTSync"),ra={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:a,notFoundError:t},ra}s(Rh,"requireEnoent");var uu;function Nh(){if(uu)return Ot.exports;uu=1;const e=rf,t=Oh(),n=Rh();function r(i,o,u){const l=t(i,o,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}s(r,"spawn");function a(i,o,u){const l=t(i,o,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return s(a,"spawnSync"),Ot.exports=r,Ot.exports.spawn=r,Ot.exports.sync=a,Ot.exports._parse=t,Ot.exports._enoent=n,Ot.exports}s(Nh,"requireCrossSpawn");var Ph=Nh(),Mh=St(Ph);function jh(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}s(jh,"stripFinalNewline");function lu(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"}s(lu,"pathKey");const zh=s(({cwd:e=ke.cwd(),path:t=ke.env[lu()],preferLocal:n=!0,execPath:r=ke.execPath,addExecPath:a=!0}={})=>{const i=e instanceof URL?ss(e):e,o=nn.resolve(i),u=[];return n&&qh(u,o),a&&Zh(u,r,o),[...u,t].join(nn.delimiter)},"npmRunPath"),qh=s((e,t)=>{let n;for(;n!==t;)e.push(nn.join(t,"node_modules/.bin")),n=t,t=nn.resolve(t,"..")},"applyPreferLocal"),Zh=s((e,t,n)=>{const r=t instanceof URL?ss(t):t;e.push(nn.resolve(n,r,".."))},"applyExecPath"),Lh=s(({env:e=ke.env,...t}={})=>{e={...e};const n=lu({env:e});return t.path=e[n],e[n]=zh(t),e},"npmRunPathEnv"),Uh=s((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const a=Object.getOwnPropertyDescriptor(e,n),i=Object.getOwnPropertyDescriptor(t,n);!Vh(a,i)&&r||Object.defineProperty(e,n,i)},"copyProperty"),Vh=s(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"),Gh=s((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),Wh=s((e,t)=>`/* Wrapped ${e}*/
|
|
24
|
+
${t}`,"wrappedToString"),Hh=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Jh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Kh=s((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,a=Wh.bind(null,r,t.toString());Object.defineProperty(a,"name",Jh),Object.defineProperty(e,"toString",{...Hh,value:a})},"changeToString");function Yh(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const a of Reflect.ownKeys(t))Uh(e,t,a,n);return Gh(e,t),Kh(e,t,r),e}s(Yh,"mimicFunction");const Wr=new WeakMap,cu=s((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const a=e.displayName||e.name||"<anonymous>",i=s(function(...o){if(Wr.set(i,++r),r===1)n=e.apply(this,o),e=null;else if(t.throw===!0)throw new Error(`Function \`${a}\` can only be called once`);return n},"onetime2");return Yh(i,e),Wr.set(i,r),i},"onetime");cu.callCount=e=>{if(!Wr.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Wr.get(e)};const Xh=s(()=>{const e=du-pu+1;return Array.from({length:e},Qh)},"getRealtimeSignals"),Qh=s((e,t)=>({name:`SIGRT${t+1}`,number:pu+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),pu=34,du=64,eD=[{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"}],mu=s(()=>{const e=Xh();return[...eD,...e].map(tD)},"getSignals"),tD=s(({name:e,number:t,description:n,action:r,forced:a=!1,standard:i})=>{const{signals:{[e]:o}}=us,u=o!==void 0;return{name:e,number:u?o:t,description:n,supported:u,action:r,forced:a,standard:i}},"normalizeSignal"),nD=s(()=>{const e=mu();return Object.fromEntries(e.map(rD))},"getSignalsByName"),rD=s(({name:e,number:t,description:n,supported:r,action:a,forced:i,standard:o})=>[e,{name:e,number:t,description:n,supported:r,action:a,forced:i,standard:o}],"getSignalByName"),oD=nD(),aD=s(()=>{const e=mu(),t=du+1,n=Array.from({length:t},(r,a)=>iD(a,e));return Object.assign({},...n)},"getSignalsByNumber"),iD=s((e,t)=>{const n=sD(e,t);if(n===void 0)return{};const{name:r,description:a,supported:i,action:o,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:a,supported:i,action:o,forced:u,standard:l}}},"getSignalByNumber"),sD=s((e,t)=>{const n=t.find(({name:r})=>us.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");aD();const uD=s(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:a,exitCode:i,isCanceled:o})=>e?`timed out after ${t} milliseconds`:o?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${a})`:i!==void 0?`failed with exit code ${i}`:"failed","getErrorPrefix"),fu=s(({stdout:e,stderr:t,all:n,error:r,signal:a,exitCode:i,command:o,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:m,cwd:h=ke.cwd()}}})=>{i=i===null?void 0:i,a=a===null?void 0:a;const D=a===void 0?void 0:oD[a].description,f=r&&r.code,y=`Command ${uD({timedOut:l,timeout:m,errorCode:f,signal:a,signalDescription:D,exitCode:i,isCanceled:c})}: ${o}`,F=Object.prototype.toString.call(r)==="[object Error]",w=F?`${y}
|
|
25
|
+
${r.message}`:y,b=[w,t,e].filter(Boolean).join(`
|
|
26
|
+
`);return F?(r.originalMessage=r.message,r.message=b):r=new Error(b),r.shortMessage=w,r.command=o,r.escapedCommand=u,r.exitCode=i,r.signal=a,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Hr=["stdin","stdout","stderr"],lD=s(e=>Hr.some(t=>e[t]!==void 0),"hasAlias"),cD=s(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Hr.map(r=>e[r]);if(lD(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Hr.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,Hr.length);return Array.from({length:n},(r,a)=>t[a])},"normalizeStdio");var Rt={exports:{}},oa={exports:{}},hu;function pD(){return hu||(hu=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")})(oa)),oa.exports}s(pD,"requireSignals");var Du;function dD(){if(Du)return Rt.exports;Du=1;var e=wt.process;const t=s(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))Rt.exports=function(){return function(){}};else{var n=af,r=pD(),a=/^win/i.test(e.platform),i=sf;typeof i!="function"&&(i=i.EventEmitter);var o;e.__signal_exit_emitter__?o=e.__signal_exit_emitter__:(o=e.__signal_exit_emitter__=new i,o.count=0,o.emitted={}),o.infinite||(o.setMaxListeners(1/0),o.infinite=!0),Rt.exports=function(y,F){if(!t(wt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&m();var w="exit";F&&F.alwaysLast&&(w="afterexit");var b=s(function(){o.removeListener(w,y),o.listeners("exit").length===0&&o.listeners("afterexit").length===0&&u()},"remove");return o.on(w,y),b};var u=s(function(){!d||!t(wt.process)||(d=!1,r.forEach(function(F){try{e.removeListener(F,c[F])}catch{}}),e.emit=f,e.reallyExit=h,o.count-=1)},"unload2");Rt.exports.unload=u;var l=s(function(F,w,b){o.emitted[F]||(o.emitted[F]=!0,o.emit(F,w,b))},"emit2"),c={};r.forEach(function(y){c[y]=s(function(){if(t(wt.process)){var w=e.listeners(y);w.length===o.count&&(u(),l("exit",null,y),l("afterexit",null,y),a&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),Rt.exports.signals=function(){return r};var d=!1,m=s(function(){d||!t(wt.process)||(d=!0,o.count+=1,r=r.filter(function(F){try{return e.on(F,c[F]),!0}catch{return!1}}),e.emit=g,e.reallyExit=D)},"load2");Rt.exports.load=m;var h=e.reallyExit,D=s(function(F){t(wt.process)&&(e.exitCode=F||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),f=e.emit,g=s(function(F,w){if(F==="exit"&&t(wt.process)){w!==void 0&&(e.exitCode=w);var b=f.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),b}else return f.apply(this,arguments)},"processEmit2")}return Rt.exports}s(dD,"requireSignalExit");var mD=dD(),fD=St(mD);const hD=1e3*5,DD=s((e,t="SIGTERM",n={})=>{const r=e(t);return gD(e,t,n,r),r},"spawnedKill"),gD=s((e,t,n,r)=>{if(!vD(t,n,r))return;const a=_D(n),i=setTimeout(()=>{e("SIGKILL")},a);i.unref&&i.unref()},"setKillTimeout"),vD=s((e,{forceKillAfterTimeout:t},n)=>yD(e)&&t!==!1&&n,"shouldForceKill"),yD=s(e=>e===of.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),_D=s(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return hD;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"),FD=s((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),CD=s((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),bD=s((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let a;const i=new Promise((u,l)=>{a=setTimeout(()=>{CD(e,n,l)},t)}),o=r.finally(()=>{clearTimeout(a)});return Promise.race([i,o])},"setupTimeout"),ED=s(({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"),wD=s(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const a=fD(()=>{e.kill()});return r.finally(()=>{a()})},"setExitHandler");function gu(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}s(gu,"isStream");function vu(e){return gu(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}s(vu,"isWritableStream");const AD=s(e=>e instanceof nf&&typeof e.then=="function","isExecaChildProcess"),aa=s((e,t,n)=>{if(typeof n=="string")return e[t].pipe(uf(n)),e;if(vu(n))return e[t].pipe(n),e;if(!AD(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!vu(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),ID=s(e=>{e.stdout!==null&&(e.pipeStdout=aa.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=aa.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=aa.bind(void 0,e,"all"))},"addPipeMethods");var on={exports:{}},ia,yu;function xD(){if(yu)return ia;yu=1;const{PassThrough:e}=Mo;return ia=s(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const a=r==="buffer";let i=!1;n?i=!(r||a):r=r||"utf8",a&&(r=null);const o=new e({objectMode:i});r&&o.setEncoding(r);let u=0;const l=[];return o.on("data",c=>{l.push(c),i?u=l.length:u+=c.length}),o.getBufferedValue=()=>n?l:a?Buffer.concat(l,u):l.join(""),o.getBufferedLength=()=>u,o},"bufferStream"),ia}s(xD,"requireBufferStream");var _u;function kD(){if(_u)return on.exports;_u=1;const{constants:e}=cf,t=Mo,{promisify:n}=pf,r=xD(),a=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};s(u,"MaxBufferError");let i=u;async function o(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,m=r(c);return await new Promise((h,D)=>{const f=s(g=>{g&&m.getBufferedLength()<=e.MAX_LENGTH&&(g.bufferedData=m.getBufferedValue()),D(g)},"rejectPromise");(async()=>{try{await a(l,m),h()}catch(g){f(g)}})(),m.on("data",()=>{m.getBufferedLength()>d&&f(new i)})}),m.getBufferedValue()}return s(o,"getStream"),on.exports=o,on.exports.buffer=(l,c)=>o(l,{...c,encoding:"buffer"}),on.exports.array=(l,c)=>o(l,{...c,array:!0}),on.exports.MaxBufferError=i,on.exports}s(kD,"requireGetStream");var $D=kD(),Fu=St($D),sa,Cu;function TD(){if(Cu)return sa;Cu=1;const{PassThrough:e}=Mo;return sa=s(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=a,n.on("unpipe",i),Array.prototype.slice.call(arguments).forEach(r),n;function r(o){return Array.isArray(o)?(o.forEach(r),this):(t.push(o),o.once("end",i.bind(null,o)),o.once("error",n.emit.bind(n,"error")),o.pipe(n,{end:!1}),this)}s(r,"add");function a(){return t.length==0}s(a,"isEmpty");function i(o){t=t.filter(function(u){return u!==o}),!t.length&&n.readable&&n.end()}s(i,"remove")},"mergeStream$1"),sa}s(TD,"requireMergeStream");var BD=TD(),SD=St(BD);const OD=s(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),RD=s(({input:e,inputFile:t})=>typeof t!="string"?e:(OD(e),lf(t)),"getInput"),ND=s((e,t)=>{const n=RD(t);n!==void 0&&(gu(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),PD=s((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=SD();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),ua=s(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),la=s((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Fu(e,{encoding:t,maxBuffer:r}):Fu.buffer(e,{maxBuffer:r})},"getStreamPromise"),MD=s(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:a,maxBuffer:i},o)=>{const u=la(e,{encoding:r,buffer:a,maxBuffer:i}),l=la(t,{encoding:r,buffer:a,maxBuffer:i}),c=la(n,{encoding:r,buffer:a,maxBuffer:i*2});try{return await Promise.all([o,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},ua(e,u),ua(t,l),ua(n,c)])}},"getSpawnedResult"),jD=(async()=>{})().constructor.prototype,zD=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(jD,e)]),bu=s((e,t)=>{for(const[n,r]of zD){const a=typeof t=="function"?(...i)=>Reflect.apply(r.value,t(),i):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:a})}},"mergePromise"),qD=s(e=>new Promise((t,n)=>{e.on("exit",(r,a)=>{t({exitCode:r,signal:a})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),Eu=s((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),ZD=/^[\w.-]+$/,LD=/"/g,UD=s(e=>typeof e!="string"||ZD.test(e)?e:`"${e.replace(LD,'\\"')}"`,"escapeArg"),VD=s((e,t)=>Eu(e,t).join(" "),"joinCommand"),GD=s((e,t)=>Eu(e,t).map(n=>UD(n)).join(" "),"getEscapedCommand"),WD=df("execa").enabled,Jr=s((e,t)=>String(e).padStart(t,"0"),"padField"),HD=s(()=>{const e=new Date;return`${Jr(e.getHours(),2)}:${Jr(e.getMinutes(),2)}:${Jr(e.getSeconds(),2)}.${Jr(e.getMilliseconds(),3)}`},"getTimestamp"),JD=s((e,{verbose:t})=>{t&&ke.stderr.write(`[${HD()}] ${e}
|
|
27
|
+
`)},"logCommand"),KD=1e3*1e3*100,YD=s(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:a})=>{const i=t?{...ke.env,...e}:e;return n?Lh({env:i,cwd:r,execPath:a}):i},"getEnv"),XD=s((e,t,n={})=>{const r=Mh._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:KD,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||ke.cwd(),execPath:ke.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:WD,...n},n.env=YD(n),n.stdio=cD(n),ke.platform==="win32"&&nn.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),ca=s((e,t,n)=>typeof t!="string"&&!tf.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?jh(t):t,"handleOutput");function We(e,t,n){const r=XD(e,t,n),a=VD(e,t),i=GD(e,t);JD(i,r.options),ED(r.options);let o;try{o=os.spawn(r.file,r.args,r.options)}catch(D){const f=new os.ChildProcess,g=Promise.reject(fu({error:D,stdout:"",stderr:"",all:"",command:a,escapedCommand:i,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return bu(f,g),f}const u=qD(o),l=bD(o,r.options,u),c=wD(o,r.options,l),d={isCanceled:!1};o.kill=DD.bind(null,o.kill.bind(o)),o.cancel=FD.bind(null,o,d);const h=cu(s(async()=>{const[{error:D,exitCode:f,signal:g,timedOut:y},F,w,b]=await MD(o,r.options,c),E=ca(r.options,F),O=ca(r.options,w),k=ca(r.options,b);if(D||f!==0||g!==null){const C=fu({error:D,exitCode:f,signal:g,stdout:E,stderr:O,all:k,command:a,escapedCommand:i,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:o.killed});if(!r.options.reject)return C;throw C}return{command:a,escapedCommand:i,exitCode:0,stdout:E,stderr:O,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return ND(o,r.options),o.all=PD(o,r.options),ID(o),bu(o,h),o}s(We,"execa");let Nt=!0;const an=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let mr=0;if(an.process&&an.process.env&&an.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:a}=an.process.env;t||n||e==="0"?Nt=!1:e==="1"||e==="2"||e==="3"?Nt=!0:r==="dumb"?Nt=!1:"CI"in an.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in an.process.env)?Nt=!0:Nt=process.stdout.isTTY,Nt&&(process.platform==="win32"||a&&(a==="truecolor"||a==="24bit")?mr=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?mr=2:mr=1)}let pa={enabled:Nt,supportLevel:mr};function sn(e,t,n=1){const r=`\x1B[${e}m`,a=`\x1B[${t}m`,i=new RegExp(`\\x1b\\[${t}m`,"g");return o=>pa.enabled&&pa.supportLevel>=n?r+(""+o).replace(i,r)+a:""+o}s(sn,"kolorist");const da=sn(2,22),Kr=sn(30,39),ma=sn(31,39),ht=sn(32,39),fa=sn(33,39),Yr=sn(46,49);var QD=Object.freeze({__proto__:null,bgCyan:Yr,black:Kr,dim:da,green:ht,options:pa,red:ma,yellow:fa});const fr={};fr.write=async e=>{await navigator.clipboard.writeText(e)},fr.read=async()=>navigator.clipboard.readText(),fr.readSync=()=>{throw new Error("`.readSync()` is not supported in browsers!")},fr.writeSync=()=>{throw new Error("`.writeSync()` is not supported in browsers!")};async function wu(e){try{return process.platform==="darwin"?await We("pbcopy",{input:e}):await fr.write(e),!0}catch{return!1}}s(wu,"copyToClipboard");var ha,Au;function eg(){if(Au)return ha;Au=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(o,u){return u?`${t}${u+1};${o+1}H`:`${t}${o+1}G`},move(o,u){let l="";return o<0?l+=`${t}${-o}D`:o>0&&(l+=`${t}${o}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:s((o=1)=>`${t}${o}A`,"up"),down:s((o=1)=>`${t}${o}B`,"down"),forward:s((o=1)=>`${t}${o}C`,"forward"),backward:s((o=1)=>`${t}${o}D`,"backward"),nextLine:s((o=1)=>`${t}E`.repeat(o),"nextLine"),prevLine:s((o=1)=>`${t}F`.repeat(o),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},a={up:s((o=1)=>`${t}S`.repeat(o),"up"),down:s((o=1)=>`${t}T`.repeat(o),"down")},i={screen:`${t}2J`,up:s((o=1)=>`${t}1J`.repeat(o),"up"),down:s((o=1)=>`${t}J`.repeat(o),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(o){let u="";for(let l=0;l<o;l++)u+=this.line+(l<o-1?r.up():"");return o&&(u+=r.left),u}};return ha={cursor:r,scroll:a,erase:i,beep:n},ha}s(eg,"requireSrc");var Me=eg(),Xr={exports:{}},Iu;function tg(){if(Iu)return Xr.exports;Iu=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),a=s((u,l,c=u)=>d=>{let m=""+d,h=m.indexOf(l,u.length);return~h?u+i(m,l,c,h)+l:u+m+l},"formatter"),i=s((u,l,c,d)=>{let m="",h=0;do m+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return m+u.substring(h)},"replaceClose"),o=s((u=r)=>{let l=u?a:()=>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 Xr.exports=o(),Xr.exports.createColors=o,Xr.exports}s(tg,"requirePicocolors");var ng=tg(),N=St(ng);function rg({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")}s(rg,"DD");const og=rg();function xu(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(og,"")}s(xu,"P$1");function ku(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}s(ku,"L$1");var $u={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var a=r.charCodeAt(0),i=r.length==2?r.charCodeAt(1):0,o=a;return 55296<=a&&a<=56319&&56320<=i&&i<=57343&&(a&=1023,i&=1023,o=a<<10|i,o+=65536),o==12288||65281<=o&&o<=65376||65504<=o&&o<=65510?"F":o==8361||65377<=o&&o<=65470||65474<=o&&o<=65479||65482<=o&&o<=65487||65490<=o&&o<=65495||65498<=o&&o<=65500||65512<=o&&o<=65518?"H":4352<=o&&o<=4447||4515<=o&&o<=4519||4602<=o&&o<=4607||9001<=o&&o<=9002||11904<=o&&o<=11929||11931<=o&&o<=12019||12032<=o&&o<=12245||12272<=o&&o<=12283||12289<=o&&o<=12350||12353<=o&&o<=12438||12441<=o&&o<=12543||12549<=o&&o<=12589||12593<=o&&o<=12686||12688<=o&&o<=12730||12736<=o&&o<=12771||12784<=o&&o<=12830||12832<=o&&o<=12871||12880<=o&&o<=13054||13056<=o&&o<=19903||19968<=o&&o<=42124||42128<=o&&o<=42182||43360<=o&&o<=43388||44032<=o&&o<=55203||55216<=o&&o<=55238||55243<=o&&o<=55291||63744<=o&&o<=64255||65040<=o&&o<=65049||65072<=o&&o<=65106||65108<=o&&o<=65126||65128<=o&&o<=65131||110592<=o&&o<=110593||127488<=o&&o<=127490||127504<=o&&o<=127546||127552<=o&&o<=127560||127568<=o&&o<=127569||131072<=o&&o<=194367||177984<=o&&o<=196605||196608<=o&&o<=262141?"W":32<=o&&o<=126||162<=o&&o<=163||165<=o&&o<=166||o==172||o==175||10214<=o&&o<=10221||10629<=o&&o<=10630?"Na":o==161||o==164||167<=o&&o<=168||o==170||173<=o&&o<=174||176<=o&&o<=180||182<=o&&o<=186||188<=o&&o<=191||o==198||o==208||215<=o&&o<=216||222<=o&&o<=225||o==230||232<=o&&o<=234||236<=o&&o<=237||o==240||242<=o&&o<=243||247<=o&&o<=250||o==252||o==254||o==257||o==273||o==275||o==283||294<=o&&o<=295||o==299||305<=o&&o<=307||o==312||319<=o&&o<=322||o==324||328<=o&&o<=331||o==333||338<=o&&o<=339||358<=o&&o<=359||o==363||o==462||o==464||o==466||o==468||o==470||o==472||o==474||o==476||o==593||o==609||o==708||o==711||713<=o&&o<=715||o==717||o==720||728<=o&&o<=731||o==733||o==735||768<=o&&o<=879||913<=o&&o<=929||931<=o&&o<=937||945<=o&&o<=961||963<=o&&o<=969||o==1025||1040<=o&&o<=1103||o==1105||o==8208||8211<=o&&o<=8214||8216<=o&&o<=8217||8220<=o&&o<=8221||8224<=o&&o<=8226||8228<=o&&o<=8231||o==8240||8242<=o&&o<=8243||o==8245||o==8251||o==8254||o==8308||o==8319||8321<=o&&o<=8324||o==8364||o==8451||o==8453||o==8457||o==8467||o==8470||8481<=o&&o<=8482||o==8486||o==8491||8531<=o&&o<=8532||8539<=o&&o<=8542||8544<=o&&o<=8555||8560<=o&&o<=8569||o==8585||8592<=o&&o<=8601||8632<=o&&o<=8633||o==8658||o==8660||o==8679||o==8704||8706<=o&&o<=8707||8711<=o&&o<=8712||o==8715||o==8719||o==8721||o==8725||o==8730||8733<=o&&o<=8736||o==8739||o==8741||8743<=o&&o<=8748||o==8750||8756<=o&&o<=8759||8764<=o&&o<=8765||o==8776||o==8780||o==8786||8800<=o&&o<=8801||8804<=o&&o<=8807||8810<=o&&o<=8811||8814<=o&&o<=8815||8834<=o&&o<=8835||8838<=o&&o<=8839||o==8853||o==8857||o==8869||o==8895||o==8978||9312<=o&&o<=9449||9451<=o&&o<=9547||9552<=o&&o<=9587||9600<=o&&o<=9615||9618<=o&&o<=9621||9632<=o&&o<=9633||9635<=o&&o<=9641||9650<=o&&o<=9651||9654<=o&&o<=9655||9660<=o&&o<=9661||9664<=o&&o<=9665||9670<=o&&o<=9672||o==9675||9678<=o&&o<=9681||9698<=o&&o<=9701||o==9711||9733<=o&&o<=9734||o==9737||9742<=o&&o<=9743||9748<=o&&o<=9749||o==9756||o==9758||o==9792||o==9794||9824<=o&&o<=9825||9827<=o&&o<=9829||9831<=o&&o<=9834||9836<=o&&o<=9837||o==9839||9886<=o&&o<=9887||9918<=o&&o<=9919||9924<=o&&o<=9933||9935<=o&&o<=9953||o==9955||9960<=o&&o<=9983||o==10045||o==10071||10102<=o&&o<=10111||11093<=o&&o<=11097||12872<=o&&o<=12879||57344<=o&&o<=63743||65024<=o&&o<=65039||o==65533||127232<=o&&o<=127242||127248<=o&&o<=127277||127280<=o&&o<=127337||127344<=o&&o<=127386||917760<=o&&o<=917999||983040<=o&&o<=1048573||1048576<=o&&o<=1114109?"A":"N"},t.characterLength=function(r){var a=this.eastAsianWidth(r);return a=="F"||a=="W"||a=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}s(n,"t"),t.length=function(r){for(var a=n(r),i=0,o=0;o<a.length;o++)i=i+this.characterLength(a[o]);return i},t.slice=function(r,a,i){textLen=t.length(r),a=a||0,i=i||1,a<0&&(a=textLen+a),i<0&&(i=textLen+i);for(var o="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],m=t.length(d);if(u>=a-(m==2?1:0))if(u+m<=i)o+=d;else break;u+=m}return o}})($u);var ag=$u.exports;const ig=ku(ag);var sg=s(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 ug=ku(sg);function hr(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=xu(e),e.length===0))return 0;e=e.replace(ug()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const a of e){const i=a.codePointAt(0);if(!(i<=31||i>=127&&i<=159||i>=768&&i<=879))switch(ig.eastAsianWidth(a)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}s(hr,"p");const Da=10,Tu=s((e=0)=>t=>`\x1B[${t+e}m`,"N"),Bu=s((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Su=s((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Fe={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(Fe.modifier);const lg=Object.keys(Fe.color),cg=Object.keys(Fe.bgColor);[...lg,...cg];function pg(){const e=new Map;for(const[t,n]of Object.entries(Fe)){for(const[r,a]of Object.entries(n))Fe[r]={open:`\x1B[${a[0]}m`,close:`\x1B[${a[1]}m`},n[r]=Fe[r],e.set(a[0],a[1]);Object.defineProperty(Fe,t,{value:n,enumerable:!1})}return Object.defineProperty(Fe,"codes",{value:e,enumerable:!1}),Fe.color.close="\x1B[39m",Fe.bgColor.close="\x1B[49m",Fe.color.ansi=Tu(),Fe.color.ansi256=Bu(),Fe.color.ansi16m=Su(),Fe.bgColor.ansi=Tu(Da),Fe.bgColor.ansi256=Bu(Da),Fe.bgColor.ansi16m=Su(Da),Object.defineProperties(Fe,{rgbToAnsi256:{value:s((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:s(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(i=>i+i).join(""));const a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,a&255]},"value"),enumerable:!1},hexToAnsi256:{value:s(t=>Fe.rgbToAnsi256(...Fe.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:s(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,a;if(t>=232)n=((t-232)*10+8)/255,r=n,a=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,a=u%6/5}const i=Math.max(n,r,a)*2;if(i===0)return 30;let o=30+(Math.round(a)<<2|Math.round(r)<<1|Math.round(n));return i===2&&(o+=60),o},"value"),enumerable:!1},rgbToAnsi:{value:s((t,n,r)=>Fe.ansi256ToAnsi(Fe.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:s(t=>Fe.ansi256ToAnsi(Fe.hexToAnsi256(t)),"value"),enumerable:!1}}),Fe}s(pg,"rD");const dg=pg(),Qr=new Set(["\x1B","\x9B"]),mg=39,ga="\x07",Ou="[",fg="]",Ru="m",va=`${fg}8;;`,Nu=s(e=>`${Qr.values().next().value}${Ou}${e}${Ru}`,"z"),Pu=s(e=>`${Qr.values().next().value}${va}${e}${ga}`,"K"),hg=s(e=>e.split(" ").map(t=>hr(t)),"aD"),ya=s((e,t,n)=>{const r=[...t];let a=!1,i=!1,o=hr(xu(e[e.length-1]));for(const[u,l]of r.entries()){const c=hr(l);if(o+c<=n?e[e.length-1]+=l:(e.push(l),o=0),Qr.has(l)&&(a=!0,i=r.slice(u+1).join("").startsWith(va)),a){i?l===ga&&(a=!1,i=!1):l===Ru&&(a=!1);continue}o+=c,o===n&&u<r.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),Dg=s(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(hr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),gg=s((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",a,i;const o=hg(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let m=hr(u[u.length-1]);if(c!==0&&(m>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),m=0),(m>0||n.trim===!1)&&(u[u.length-1]+=" ",m++)),n.hard&&o[c]>t){const h=t-m,D=1+Math.floor((o[c]-h-1)/t);Math.floor((o[c]-1)/t)<D&&u.push(""),ya(u,d,t);continue}if(m+o[c]>t&&m>0&&o[c]>0){if(n.wordWrap===!1&&m<t){ya(u,d,t);continue}u.push("")}if(m+o[c]>t&&n.wordWrap===!1){ya(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Dg(c)));const l=[...u.join(`
|
|
28
|
+
`)];for(const[c,d]of l.entries()){if(r+=d,Qr.has(d)){const{groups:h}=new RegExp(`(?:\\${Ou}(?<code>\\d+)m|\\${va}(?<uri>.*)${ga})`).exec(l.slice(c).join(""))||{groups:{}};if(h.code!==void 0){const D=Number.parseFloat(h.code);a=D===mg?void 0:D}else h.uri!==void 0&&(i=h.uri.length===0?void 0:h.uri)}const m=dg.codes.get(Number(a));l[c+1]===`
|
|
29
|
+
`?(i&&(r+=Pu("")),a&&m&&(r+=Nu(m))):d===`
|
|
30
|
+
`&&(a&&m&&(r+=Nu(a)),i&&(r+=Pu(i)))}return r},"lD");function Mu(e,t,n){return String(e).normalize().replace(/\r\n/g,`
|
|
31
|
+
`).split(`
|
|
32
|
+
`).map(r=>gg(r,t,n)).join(`
|
|
33
|
+
`)}s(Mu,"Y$1");const vg=["up","down","left","right","space","enter","cancel"],eo={actions:new Set(vg),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]])};function _a(e,t){if(typeof e=="string")return eo.aliases.get(e)===t;for(const n of e)if(n!==void 0&&_a(n,t))return!0;return!1}s(_a,"$");function yg(e,t){if(e===t)return;const n=e.split(`
|
|
34
|
+
`),r=t.split(`
|
|
35
|
+
`),a=[];for(let i=0;i<Math.max(n.length,r.length);i++)n[i]!==r[i]&&a.push(i);return a}s(yg,"BD");const _g=globalThis.process.platform.startsWith("win"),Fa=Symbol("clack:cancel");function Dr(e){return e===Fa}s(Dr,"pD");function to(e,t){const n=e;n.isTTY&&n.setRawMode(t)}s(to,"m");function Fg({input:e=as,output:t=is,overwrite:n=!0,hideCursor:r=!0}={}){const a=jr.createInterface({input:e,output:t,prompt:"",tabSize:1});jr.emitKeypressEvents(e,a),e.isTTY&&e.setRawMode(!0);const i=s((o,{name:u,sequence:l})=>{const c=String(o);if(_a([c,u,l],"cancel")){r&&t.write(Me.cursor.show),process.exit(0);return}if(!n)return;const d=u==="return"?0:-1,m=u==="return"?-1:0;jr.moveCursor(t,d,m,()=>{jr.clearLine(t,1,()=>{e.once("keypress",i)})})},"i");return r&&t.write(Me.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write(Me.cursor.show),e.isTTY&&!_g&&e.setRawMode(!1),a.terminal=!1,a.close()}}s(Fg,"fD");var Cg=Object.defineProperty,bg=s((e,t,n)=>t in e?Cg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"vD"),He=s((e,t,n)=>(bg(e,typeof t!="symbol"?t+"":t,n),n),"h");const Ni=class Ni{constructor(t,n=!0){He(this,"input"),He(this,"output"),He(this,"_abortSignal"),He(this,"rl"),He(this,"opts"),He(this,"_render"),He(this,"_track",!1),He(this,"_prevFrame",""),He(this,"_subscribers",new Map),He(this,"_cursor",0),He(this,"state","initial"),He(this,"error",""),He(this,"value");const{input:r=as,output:a=is,render:i,signal:o,...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=i.bind(this),this._track=n,this._abortSignal=o,this.input=r,this.output=a}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)??[],a=[];for(const i of r)i.cb(...n),i.once&&a.push(()=>r.splice(r.indexOf(i),1));for(const i of a)i()}prompt(){return new Promise((t,n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Fa);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}const r=new mf;r._write=(a,i,o)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),o()},this.input.pipe(r),this.rl=ls.createInterface({input:this.input,output:r,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),ls.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),to(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),to(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Me.cursor.show),this.output.off("resize",this.render),to(this.input,!1),t(Fa)})})}onKeypress(t,n){if(this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&eo.aliases.has(n.name)&&this.emit("cursor",eo.aliases.get(n.name)),eo.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")}_a([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
|
+
`),to(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){const t=Mu(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
37
|
+
`).length-1;this.output.write(Me.cursor.move(-999,t*-1))}render(){const t=Mu(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Me.cursor.hide);else{const n=yg(this._prevFrame,t);if(this.restoreCursor(),n&&n?.length===1){const r=n[0];this.output.write(Me.cursor.move(0,r)),this.output.write(Me.erase.lines(1));const a=t.split(`
|
|
38
|
+
`);this.output.write(a[r]),this._prevFrame=t,this.output.write(Me.cursor.move(0,a.length-r-1));return}if(n&&n?.length>1){const r=n[0];this.output.write(Me.cursor.move(0,r)),this.output.write(Me.erase.down());const a=t.split(`
|
|
39
|
+
`).slice(r);this.output.write(a.join(`
|
|
40
|
+
`)),this._prevFrame=t;return}this.output.write(Me.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};s(Ni,"x");let un=Ni;const Pi=class Pi extends un{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(Me.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};s(Pi,"dD");let Ca=Pi;var Eg=Object.defineProperty,wg=s((e,t,n)=>t in e?Eg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"jD"),ju=s((e,t,n)=>(wg(e,typeof t!="symbol"?t+"":t,n),n),"U");const Mi=class Mi extends un{constructor({mask:t,...n}){super(n),ju(this,"valueWithCursor",""),ju(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}${N.inverse(N.hidden("_"))}`;else{const r=this.masked.slice(0,this.cursor),a=this.masked.slice(this.cursor);this.valueWithCursor=`${r}${N.inverse(a[0])}${a.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}};s(Mi,"MD");let ba=Mi;var Ag=Object.defineProperty,Ig=s((e,t,n)=>t in e?Ag(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"PD"),zu=s((e,t,n)=>(Ig(e,typeof t!="symbol"?t+"":t,n),n),"J");const ji=class ji extends un{constructor(t){super(t,!1),zu(this,"options"),zu(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}};s(ji,"LD");let Ea=ji;const zi=class zi extends un{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}${N.inverse(n)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}};s(zi,"RD");let wa=zi;function xg(){return ke.platform!=="win32"?ke.env.TERM!=="linux":!!ke.env.CI||!!ke.env.WT_SESSION||!!ke.env.TERMINUS_SUBLIME||ke.env.ConEmuTask==="{cmd::Cmder}"||ke.env.TERM_PROGRAM==="Terminus-Sublime"||ke.env.TERM_PROGRAM==="vscode"||ke.env.TERM==="xterm-256color"||ke.env.TERM==="alacritty"||ke.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}s(xg,"ce");const Aa=xg(),Dt=s((e,t)=>Aa?e:t,"u"),kg=Dt("\u25C6","*"),qu=Dt("\u25A0","x"),Zu=Dt("\u25B2","x"),Lu=Dt("\u25C7","o"),$g=Dt("\u250C","T"),fe=Dt("\u2502","|"),Pt=Dt("\u2514","\u2014"),Ia=Dt("\u25CF",">"),xa=Dt("\u25CB"," "),Tg=Dt("\u25AA","\u2022"),no=s(e=>{switch(e){case"initial":case"active":return N.cyan(kg);case"cancel":return N.red(qu);case"error":return N.yellow(Zu);case"submit":return N.green(Lu)}},"b"),Bg=s(e=>{const{cursor:t,options:n,style:r}=e,a=e.maxItems??Number.POSITIVE_INFINITY,i=Math.max(process.stdout.rows-4,0),o=Math.min(i,Math.max(a,5));let u=0;t>=u+o-3?u=Math.max(Math.min(t-o+3,n.length-o),0):t<u+2&&(u=Math.max(t-2,0));const l=o<n.length&&u>0,c=o<n.length&&u+o<n.length;return n.slice(u,u+o).map((d,m,h)=>{const D=m===0&&l,f=m===h.length-1&&c;return D||f?N.dim("..."):r(d,m+u===t)})},"G"),Uu=s(e=>new wa({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){const t=`${N.gray(fe)}
|
|
41
|
+
${no(this.state)} ${e.message}
|
|
42
|
+
`,n=e.placeholder?N.inverse(e.placeholder[0])+N.dim(e.placeholder.slice(1)):N.inverse(N.hidden("_")),r=this.value?this.valueWithCursor:n;switch(this.state){case"error":return`${t.trim()}
|
|
43
|
+
${N.yellow(fe)} ${r}
|
|
44
|
+
${N.yellow(Pt)} ${N.yellow(this.error)}
|
|
45
|
+
`;case"submit":return`${t}${N.gray(fe)} ${N.dim(this.value||e.placeholder)}`;case"cancel":return`${t}${N.gray(fe)} ${N.strikethrough(N.dim(this.value??""))}${this.value?.trim()?`
|
|
46
|
+
${N.gray(fe)}`:""}`;default:return`${t}${N.cyan(fe)} ${r}
|
|
47
|
+
${N.cyan(Pt)}
|
|
48
|
+
`}}}).prompt(),"he"),Sg=s(e=>new ba({validate:e.validate,mask:e.mask??Tg,render(){const t=`${N.gray(fe)}
|
|
49
|
+
${no(this.state)} ${e.message}
|
|
50
|
+
`,n=this.valueWithCursor,r=this.masked;switch(this.state){case"error":return`${t.trim()}
|
|
51
|
+
${N.yellow(fe)} ${r}
|
|
52
|
+
${N.yellow(Pt)} ${N.yellow(this.error)}
|
|
53
|
+
`;case"submit":return`${t}${N.gray(fe)} ${N.dim(r)}`;case"cancel":return`${t}${N.gray(fe)} ${N.strikethrough(N.dim(r??""))}${r?`
|
|
54
|
+
${N.gray(fe)}`:""}`;default:return`${t}${N.cyan(fe)} ${n}
|
|
55
|
+
${N.cyan(Pt)}
|
|
56
|
+
`}}}).prompt(),"ge"),Og=s(e=>{const t=e.active??"Yes",n=e.inactive??"No";return new Ca({active:t,inactive:n,initialValue:e.initialValue??!0,render(){const r=`${N.gray(fe)}
|
|
57
|
+
${no(this.state)} ${e.message}
|
|
58
|
+
`,a=this.value?t:n;switch(this.state){case"submit":return`${r}${N.gray(fe)} ${N.dim(a)}`;case"cancel":return`${r}${N.gray(fe)} ${N.strikethrough(N.dim(a))}
|
|
59
|
+
${N.gray(fe)}`;default:return`${r}${N.cyan(fe)} ${this.value?`${N.green(Ia)} ${t}`:`${N.dim(xa)} ${N.dim(t)}`} ${N.dim("/")} ${this.value?`${N.dim(xa)} ${N.dim(n)}`:`${N.green(Ia)} ${n}`}
|
|
60
|
+
${N.cyan(Pt)}
|
|
61
|
+
`}}}).prompt()},"ye"),Vu=s(e=>{const t=s((n,r)=>{const a=n.label??String(n.value);switch(r){case"selected":return`${N.dim(a)}`;case"active":return`${N.green(Ia)} ${a} ${n.hint?N.dim(`(${n.hint})`):""}`;case"cancelled":return`${N.strikethrough(N.dim(a))}`;default:return`${N.dim(xa)} ${N.dim(a)}`}},"n");return new Ea({options:e.options,initialValue:e.initialValue,render(){const n=`${N.gray(fe)}
|
|
62
|
+
${no(this.state)} ${e.message}
|
|
63
|
+
`;switch(this.state){case"submit":return`${n}${N.gray(fe)} ${t(this.options[this.cursor],"selected")}`;case"cancel":return`${n}${N.gray(fe)} ${t(this.options[this.cursor],"cancelled")}
|
|
64
|
+
${N.gray(fe)}`;default:return`${n}${N.cyan(fe)} ${Bg({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:s((r,a)=>t(r,a?"active":"inactive"),"style")}).join(`
|
|
65
|
+
${N.cyan(fe)} `)}
|
|
66
|
+
${N.cyan(Pt)}
|
|
67
|
+
`}}}).prompt()},"ve"),ro=s((e="")=>{process.stdout.write(`${N.gray($g)} ${e}
|
|
68
|
+
`)},"Ie"),ve=s((e="")=>{process.stdout.write(`${N.gray(fe)}
|
|
69
|
+
${N.gray(Pt)} ${e}
|
|
70
|
+
|
|
71
|
+
`)},"Se");`${N.gray(fe)}`;const Mt=s(({indicator:e="dots"}={})=>{const t=Aa?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Aa?80:120,r=process.env.CI==="true";let a,i,o=!1,u="",l,c=performance.now();const d=s(E=>{const O=E>1?"Something went wrong":"Canceled";o&&b(O,E)},"p"),m=s(()=>d(2),"v"),h=s(()=>d(1),"f"),D=s(()=>{process.on("uncaughtExceptionMonitor",m),process.on("unhandledRejection",m),process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",d)},"j"),f=s(()=>{process.removeListener("uncaughtExceptionMonitor",m),process.removeListener("unhandledRejection",m),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),process.removeListener("exit",d)},"E"),g=s(()=>{if(l===void 0)return;r&&process.stdout.write(`
|
|
72
|
+
`);const E=l.split(`
|
|
73
|
+
`);process.stdout.write(Me.cursor.move(-999,E.length-1)),process.stdout.write(Me.erase.down(E.length))},"B"),y=s(E=>E.replace(/\.+$/,""),"R"),F=s(E=>{const O=(performance.now()-E)/1e3,k=Math.floor(O/60),C=Math.floor(O%60);return k>0?`[${k}m ${C}s]`:`[${C}s]`},"O"),w=s((E="")=>{o=!0,a=Fg(),u=y(E),c=performance.now(),process.stdout.write(`${N.gray(fe)}
|
|
74
|
+
`);let O=0,k=0;D(),i=setInterval(()=>{if(r&&u===l)return;g(),l=u;const C=N.magenta(t[O]);if(r)process.stdout.write(`${C} ${u}...`);else if(e==="timer")process.stdout.write(`${C} ${u} ${F(c)}`);else{const L=".".repeat(Math.floor(k)).slice(0,3);process.stdout.write(`${C} ${u}${L}`)}O=O+1<t.length?O+1:0,k=k<t.length?k+.125:0},n)},"H"),b=s((E="",O=0)=>{o=!1,clearInterval(i),g();const k=O===0?N.green(Lu):O===1?N.red(qu):N.red(Zu);u=y(E??u),e==="timer"?process.stdout.write(`${k} ${u} ${F(c)}
|
|
75
|
+
`):process.stdout.write(`${k} ${u}
|
|
76
|
+
`),f(),a()},"N");return{start:w,stop:b,message:s((E="")=>{u=y(E??u)},"message")}},"Y");var gr=Object.freeze({__proto__:null,confirm:Og,intro:ro,isCancel:Dr,outro:ve,password:Sg,select:Vu,spinner:Mt,text:Uu});const{version:Rg}=Wo,qi=class qi extends Error{};s(qi,"KnownError");let se=qi;const ka=" ",Gu=s(e=>{e instanceof Error&&!(e instanceof se)&&(e.stack&&console.error(da(e.stack.split(`
|
|
77
|
+
`).slice(1).join(`
|
|
78
|
+
`))),console.error(`
|
|
79
|
+
${ka}${da(`aicommits v${Rg}`)}`),console.error(`
|
|
80
|
+
${ka}Please open a Bug report with the information above:`),console.error(`${ka}https://github.com/Nutlope/aicommits/issues/new/choose`))},"handleCliError"),oo=s(e=>{process.stderr.write(`${ma("\u2716")} ${e.message}
|
|
81
|
+
`),Gu(e),process.exit(1)},"handleCommandError"),$a=s(async()=>{const{stdout:e,failed:t}=await We("git",["rev-parse","--show-toplevel"],{reject:!1});if(t)throw new se("The current directory must be a Git repository!");return e},"assertGitRepo"),ao=s(e=>`:(exclude)${e}`,"excludeFromDiff"),Wu=["package-lock.json","pnpm-lock.yaml","*.lock"],Ng=s(e=>Wu.some(t=>t.includes("*")?e.endsWith(".lock"):e===t),"isLockFile"),Hu=Wu.map(ao),Ju=s(async e=>{const t=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await We("git",[...t,"--name-only",...e?e.map(ao):[]]);if(!n)return;const a=n.split(`
|
|
82
|
+
`).filter(Boolean).some(l=>!Ng(l));let i=[];a&&(i=[...Hu]),i=[...i,...e?e.map(ao):[]];const{stdout:o}=await We("git",[...t,"--name-only",...i]);if(!o)return;const{stdout:u}=await We("git",[...t,...i]);return{files:o.split(`
|
|
83
|
+
`),diff:u}},"getStagedDiff"),Pg=s(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...Hu,...t?t.map(ao):[]],{stdout:a}=await We("git",[...n,...r,"--",...e]);return{files:e,diff:a}},"getStagedDiffForFiles"),Ku=s(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var Ta,Yu;function Mg(){if(Yu)return Ta;Yu=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
|
|
84
|
+
`:`
|
|
85
|
+
`,n=s((l,c)=>{const d=[];let m="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const f=l[D];if(f&&Array.isArray(f))for(const g of f)m+=o(D+"[]")+h+o(g)+t;else f&&typeof f=="object"?d.push(D):m+=o(D)+h+o(f)+t}c.section&&m.length&&(m="["+o(c.section)+"]"+t+m);for(const D of d){const f=r(D).join("\\."),g=(c.section?c.section+".":"")+f,{whitespace:y}=c,F=n(l[D],{section:g,whitespace:y});m.length&&F.length&&(m+=t),m+=F}return m},"encode"),r=s(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),a=s(l=>{const c=Object.create(null);let d=c,m=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const g of D){if(!g||g.match(/^\s*[;#]/))continue;const y=g.match(h);if(!y)continue;if(y[1]!==void 0){if(m=u(y[1]),m==="__proto__"){d=Object.create(null);continue}d=c[m]=c[m]||Object.create(null);continue}const F=u(y[2]),w=F.length>2&&F.slice(-2)==="[]",b=w?F.slice(0,-2):F;if(b==="__proto__")continue;const E=y[3]?u(y[4]):!0,O=E==="true"||E==="false"||E==="null"?JSON.parse(E):E;w&&(e.call(d,b)?Array.isArray(d[b])||(d[b]=[d[b]]):d[b]=[]),Array.isArray(d[b])?d[b].push(O):d[b]=O}const f=[];for(const g of Object.keys(c)){if(!e.call(c,g)||typeof c[g]!="object"||Array.isArray(c[g]))continue;const y=r(g);d=c;const F=y.pop(),w=F.replace(/\\\./g,".");for(const b of y)b!=="__proto__"&&((!e.call(d,b)||typeof d[b]!="object")&&(d[b]=Object.create(null)),d=d[b]);d===c&&w===F||(d[w]=c[g],f.push(g))}for(const g of f)delete c[g];return c},"decode"),i=s(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),o=s(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&i(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=s((l,c)=>{if(l=(l||"").trim(),i(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,m="";for(let h=0,D=l.length;h<D;h++){const f=l.charAt(h);if(d)"\\;#".indexOf(f)!==-1?m+=f:m+="\\"+f,d=!1;else{if(";#".indexOf(f)!==-1)break;f==="\\"?d=!0:m+=f}}return d&&(m+="\\"),m.trim()}return l},"unsafe");return Ta={parse:a,decode:a,stringify:n,encode:n,safe:o,unsafe:u},Ta}s(Mg,"requireIni");var jg=Mg(),Xu=St(jg);const Ba=s(e=>Ne.lstat(e).then(()=>!0,()=>!1),"fileExists"),zg=["","conventional","gitmoji"],{hasOwnProperty:qg}=Object.prototype,Sa=s((e,t)=>qg.call(e,t),"hasOwn"),Zg=s((e,t,n)=>{if(!t)return n;const r=t.trim().toLowerCase();if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1;throw new se(`Invalid config property ${e}: Must be a boolean (true/false)`)},"parseBoolean"),Lg=s(e=>{let t;try{t=JSON.parse(e)}catch{throw new se("Invalid config property conventional-types: Must be valid JSON")}Le("conventional-types",!!t&&typeof t=="object"&&!Array.isArray(t),'Must be a JSON object with "type":"description" pairs');const n=Object.entries(t);Le("conventional-types",n.length>0,"Must contain at least one type");const r=n.map(([a,i])=>(Le("conventional-types",typeof a=="string"&&a.trim().length>0,"Type names must be non-empty strings"),Le("conventional-types",typeof i=="string"&&i.trim().length>0,"Type descriptions must be non-empty strings"),[a.trim(),String(i).trim()]));return JSON.stringify(Object.fromEntries(r))},"parseConventionalTypes$1"),Le=s((e,t,n)=>{if(!t)throw new se(`Invalid config property ${e}: ${n}`)},"parseAssert"),io={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Le("locale",!!e,"Cannot be empty"),Le("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Le("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Le("generate",t>0,"Must be greater than 0"),Le("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Le("type",zg.includes(e),"Invalid commit type"),e):""},proxy(e){if(!(!e||e.length===0))throw new se('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Le("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Le("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Le("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Le("max-length",t>=20,"Must be greater than 20 characters"),t},details(e){return Zg("details",e,!1)},instructions(e){return e?.trim()||""},"conventional-format"(e){return e?.trim()||""},"conventional-types"(e){return e?Lg(e):""}},Ug={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:s(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["essentialai/rnj-1-instruct","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","meta-llama/Llama-3.2-3B-Instruct-Turbo","Qwen/Qwen3-Next-80B-A3B-Instruct"],requiresApiKey:!0},Vg={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:s(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},Gg={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:s(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},Wg={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:s(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},Hg={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:s(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},Jg={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:s(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},vr=[Ug,Vg,Gg,Jg,Hg,Wg],Kg=s(()=>vr.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),Yg=s((e,t)=>{if(e){const n=vr.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"),Oa=s(()=>it.join(cs.homedir(),".aicommits"),"getConfigPath"),Qu=s(async()=>{if(!await Ba(Oa()))return Object.create(null);const t=await Ne.readFile(Oa(),"utf8");return Xu.parse(t)},"readConfigFile"),jt=s(async(e,t,n)=>{const r=await Qu();Sa(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const a={},i=t??{};for(const c of Object.keys(io)){const d=io[c],m=e?.[c]??i?.[c]??r[c];if(n)try{a[c]=d(m)}catch{}else a[c]=d(m)}let o,u=a.OPENAI_BASE_URL;const l=a.OPENAI_API_KEY;return!u&&l&&(u=Kg(),a.OPENAI_BASE_URL=u),o=Yg(u,l),{...a,model:a.OPENAI_MODEL,provider:o}},"getConfig"),Ra=s(async e=>{const t=await Qu();for(const[n,r]of e){if(!Sa(io,n))throw new se(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const a=io[n](r);t[n]=a}}await Ne.writeFile(Oa(),Xu.stringify(t),"utf8")},"setConfigs"),el=s(e=>`[${e} - \u2705]`,"CURRENT_LABEL_FORMAT"),Xg=3600*1e3,tl=s(()=>{const e=process.platform,t=cs.homedir();if(e==="darwin")return it.join(t,"Library","Caches","aicommits","models");if(e==="win32")return it.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||it.join(t,".cache");return it.join(r,"aicommits","models")}},"getCacheDir"),Qg=s(e=>{const t=ff.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),nl=s(e=>it.join(tl(),`${e}.json`),"getCachePath"),ev=s(async e=>{const t=nl(e);try{if(!await Ba(t))return null;const n=await Ne.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),tv=s(async(e,t)=>{try{const n=tl();await Ne.mkdir(n,{recursive:!0});const r=nl(e);await Ne.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),Na=s(async(e,t)=>{const n=Qg(e),r=Date.now(),a=await ev(n);if(a&&r-a.timestamp<Xg)return a.data;try{const i=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const o=await i.json(),u=(o.data?o.data:o)||[],l={models:u};return u.length>0&&await tv(n,{data:l,timestamp:r}),l}catch(i){const o=i instanceof Error?i.message:"Request failed";return{models:[],error:o}}},"fetchModels"),nv=s(async(e,t,n)=>{const r=await Na(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let a=[];return n?.modelsFilter?a=n.modelsFilter(r.models):a=r.models.map(i=>i.id||i.name).filter(Boolean),a},"fetchAndFilterModels"),rv=s((e,t,n)=>{let r=e.map(a=>({label:a,value:a}));if(n?.defaultModels&&n.defaultModels.length>0){const a=n.defaultModels.filter(i=>r.some(o=>o.value===i));a.forEach(i=>{const o=r.findIndex(u=>u.value===i);o>=0&&r.splice(o,1)}),a.forEach((i,o)=>{const l=o===0?`\u{1F451} ${i} (default)`:`\u{1F525} ${i}`;r.unshift({label:l,value:i})})}if(t&&t!=="undefined"){const a=n?.defaultModels?.includes(t),i=r.findIndex(o=>o.value===t);if(i>=0&&!a){if(r[i].label=el(r[i].value),i>0){const[o]=r.splice(i,1),u=n?.defaultModels?.length||0;r.splice(u,0,o)}}else if(i<0&&!a){const o=n?.defaultModels?.length||0;r.splice(o,0,{label:el(t),value:t})}}return r},"prepareModelOptions"),ov=s(async(e,t,n,r)=>{const a=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(a))return null;let i=e;a&&(i=e.filter(l=>l.toLowerCase().includes(a.toLowerCase())));let o=i.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${a}"):`,options:[...o,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),av=s(async e=>{const t=await e({message:"Enter your custom model name:",validate:s(n=>{if(!n)return"Model name is required"},"validate")});return Dr(t)?null:t},"handleCustom"),rl=s(async(e,t,n,r)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const a=Mt();a.start("Fetching available models...");const i=await nv(e,t,r);a.stop();let o=null;if(i.length>0){const{select:u,text:l,isCancel:c}=await Promise.resolve().then(function(){return gr});let d=rv(i,n,r);const m=10;d.length>m&&(d=d.slice(0,m));let h=await u({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...d,{label:"Custom model name...",value:"custom"}],initialValue:d.length>0?d[0].value:void 0});if(c(h))return null;if(h==="search"){const D=await ov(i,u,l,c);if(D===null)return null;h=D}if(h==="custom"){if(o=await av(l),o===null)return null}else o=h}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:u,isCancel:l}=await Promise.resolve().then(function(){return gr});try{const c=await u({message:"Enter your model name:",validate:s(d=>{if(!d)return"Model name is required"},"validate")});if(l(c))return null;o=c}catch{return null}}return o},"selectModel");var iv=Object.freeze({__proto__:null,fetchModels:Na,selectModel:rl}),sv=Object.defineProperty,uv=s((e,t,n)=>t in e?sv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),ol=s((e,t,n)=>uv(e,typeof t!="symbol"?t+"":t,n),"__publicField");const Zi=class Zi{constructor(t,n){ol(this,"config"),ol(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 gr}),a=[];if(this.def.requiresApiKey){const i=this.getApiKey(),o=await n({message:i?`Enter your API key (leave empty to keep current: ${i.substring(0,4)}****):`:"Enter your API key:",validate:s(u=>{if(!u&&!i)return"API key is required"},"validate")});if(r(o))throw new Error("Setup cancelled");o&&a.push(["OPENAI_API_KEY",o])}if(this.name==="ollama"){const i=this.getBaseUrl(),o=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:i});if(r(o))throw new Error("Setup cancelled");o&&o!=="http://localhost:11434/v1"&&a.push(["OPENAI_BASE_URL",o])}return a}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await Na(t,n);if(r.error)return{models:[],error:r.error};let a;return this.def.modelsFilter?a=this.def.modelsFilter(r.models):a=r.models.map(i=>i.id||i.name).filter(Boolean),{models:a}}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}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}}};s(Zi,"Provider");let Pa=Zi;function ln(e){const t=e.provider,n=vr.find(r=>r.name===t);return n?new Pa(n,e):null}s(ln,"getProvider");function lv(){return vr.map(e=>({value:e.name,label:e.displayName}))}s(lv,"getAvailableProviders");function cv(e){return vr.find(n=>n.name===e)?.baseUrl||""}s(cv,"getProviderBaseUrl");var al="vercel.ai.error",pv=Symbol.for(al),il,sl,W=(Kt=class extends(sl=Error,il=pv,sl){constructor({name:t,message:n,cause:r}){super(n),this[il]=!0,this.name=t,this.cause=r}static isInstance(t){return Kt.hasMarker(t,al)}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}},s(Kt,"_AISDKError"),Kt),ul="AI_APICallError",ll=`vercel.ai.error.${ul}`,dv=Symbol.for(ll),cl,pl,Re=(vn=class extends(pl=W,cl=dv,pl){constructor({message:t,url:n,requestBodyValues:r,statusCode:a,responseHeaders:i,responseBody:o,cause:u,isRetryable:l=a!=null&&(a===408||a===409||a===429||a>=500),data:c}){super({name:ul,message:t,cause:u}),this[cl]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=i,this.responseBody=o,this.isRetryable=l,this.data=c}static isInstance(t){return W.hasMarker(t,ll)}},s(vn,"APICallError"),vn),dl="AI_EmptyResponseBodyError",ml=`vercel.ai.error.${dl}`,mv=Symbol.for(ml),fl,hl,fv=(yn=class extends(hl=W,fl=mv,hl){constructor({message:t="Empty response body"}={}){super({name:dl,message:t}),this[fl]=!0}static isInstance(t){return W.hasMarker(t,ml)}},s(yn,"EmptyResponseBodyError"),yn);function yr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}s(yr,"getErrorMessage$1");var Dl="AI_InvalidArgumentError",gl=`vercel.ai.error.${Dl}`,hv=Symbol.for(gl),vl,yl,_l=(_n=class extends(yl=W,vl=hv,yl){constructor({message:t,cause:n,argument:r}){super({name:Dl,message:t,cause:n}),this[vl]=!0,this.argument=r}static isInstance(t){return W.hasMarker(t,gl)}},s(_n,"InvalidArgumentError"),_n),Fl="AI_InvalidPromptError",Cl=`vercel.ai.error.${Fl}`,Dv=Symbol.for(Cl),bl,El,At=(Fn=class extends(El=W,bl=Dv,El){constructor({prompt:t,message:n,cause:r}){super({name:Fl,message:`Invalid prompt: ${n}`,cause:r}),this[bl]=!0,this.prompt=t}static isInstance(t){return W.hasMarker(t,Cl)}},s(Fn,"InvalidPromptError"),Fn),wl="AI_InvalidResponseDataError",Al=`vercel.ai.error.${wl}`,gv=Symbol.for(Al),Il,xl,_r=(Cn=class extends(xl=W,Il=gv,xl){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:wl,message:n}),this[Il]=!0,this.data=t}static isInstance(t){return W.hasMarker(t,Al)}},s(Cn,"InvalidResponseDataError"),Cn),kl="AI_JSONParseError",$l=`vercel.ai.error.${kl}`,vv=Symbol.for($l),Tl,Bl,so=(bn=class extends(Bl=W,Tl=vv,Bl){constructor({text:t,cause:n}){super({name:kl,message:`JSON parsing failed: Text: ${t}.
|
|
86
|
+
Error message: ${yr(n)}`,cause:n}),this[Tl]=!0,this.text=t}static isInstance(t){return W.hasMarker(t,$l)}},s(bn,"JSONParseError"),bn),Sl="AI_LoadAPIKeyError",Ol=`vercel.ai.error.${Sl}`,yv=Symbol.for(Ol),Rl,Nl,uo=(En=class extends(Nl=W,Rl=yv,Nl){constructor({message:t}){super({name:Sl,message:t}),this[Rl]=!0}static isInstance(t){return W.hasMarker(t,Ol)}},s(En,"LoadAPIKeyError"),En),Pl="AI_TooManyEmbeddingValuesForCallError",Ml=`vercel.ai.error.${Pl}`,_v=Symbol.for(Ml),jl,zl,ql=(wn=class extends(zl=W,jl=_v,zl){constructor(t){super({name:Pl,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[jl]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return W.hasMarker(t,Ml)}},s(wn,"TooManyEmbeddingValuesForCallError"),wn),Zl="AI_TypeValidationError",Ll=`vercel.ai.error.${Zl}`,Fv=Symbol.for(Ll),Ul,Vl,zt=(Tt=class extends(Vl=W,Ul=Fv,Vl){constructor({value:t,cause:n}){super({name:Zl,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
87
|
+
Error message: ${yr(n)}`,cause:n}),this[Ul]=!0,this.value=t}static isInstance(t){return W.hasMarker(t,Ll)}static wrap({value:t,cause:n}){return Tt.isInstance(n)&&n.value===t?n:new Tt({value:t,cause:n})}},s(Tt,"_TypeValidationError"),Tt),Gl="AI_UnsupportedFunctionalityError",Wl=`vercel.ai.error.${Gl}`,Cv=Symbol.for(Wl),Hl,Jl,Je=(An=class extends(Jl=W,Hl=Cv,Jl){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:Gl,message:n}),this[Hl]=!0,this.functionality=t}static isInstance(t){return W.hasMarker(t,Wl)}},s(An,"UnsupportedFunctionalityError"),An);function x(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 m in o.prototype)m in l||Object.defineProperty(l,m,{value:o.prototype[m].bind(l)});l._zod.constr=o,l._zod.def=c}s(r,"init");const a=n?.Parent??Object,u=class u extends a{};s(u,"Definition");let i=u;Object.defineProperty(i,"name",{value:e});function o(l){var c;const d=n?.Parent?new i:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const m of d._zod.deferred)m();return d}return s(o,"_"),Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:s(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(o,"name",{value:e}),o}s(x,"$constructor");const Li=class Li extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};s(Li,"$ZodAsyncError");let qt=Li;const Kl={};function It(e){return Kl}s(It,"config");function Yl(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}s(Yl,"getEnumValues");function bv(e,t){return typeof t=="bigint"?t.toString():t}s(bv,"jsonStringifyReplacer");function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}s(Ma,"cached");function ja(e){return e==null}s(ja,"nullish");function za(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}s(za,"cleanRegex");function Ev(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,a=n>r?n:r,i=Number.parseInt(e.toFixed(a).replace(".","")),o=Number.parseInt(t.toFixed(a).replace(".",""));return i%o/10**a}s(Ev,"floatSafeRemainder");function ue(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})}s(ue,"defineLazy");function qa(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}s(qa,"assignProp");function Fr(e){return JSON.stringify(e)}s(Fr,"esc");const Xl=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(lo,"isObject");const wv=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function co(e){if(lo(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(lo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}s(co,"isPlainObject");const Av=new Set(["string","number","symbol"]);function Cr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(Cr,"escapeRegex");function Zt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}s(Zt,"clone");function z(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:s(()=>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:s(()=>t.error,"error")}:t}s(z,"normalizeParams");function Iv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}s(Iv,"optionalKeys");const xv={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 kv(e,t){const n={},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(n[a]=r.shape[a])}return Zt(e,{...e._zod.def,shape:n,checks:[]})}s(kv,"pick");function $v(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete n[a]}return Zt(e,{...e._zod.def,shape:n,checks:[]})}s($v,"omit");function Tv(e,t){if(!co(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 qa(this,"shape",r),r},checks:[]};return Zt(e,n)}s(Tv,"extend");function Bv(e,t){return Zt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return qa(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}s(Bv,"merge");function Sv(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(a[i]=e?new e({type:"optional",innerType:r[i]}):r[i])}else for(const i in r)a[i]=e?new e({type:"optional",innerType:r[i]}):r[i];return Zt(t,{...t._zod.def,shape:a,checks:[]})}s(Sv,"partial");function Ov(e,t,n){const r=t._zod.def.shape,a={...r};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(a[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)a[i]=new e({type:"nonoptional",innerType:r[i]});return Zt(t,{...t._zod.def,shape:a,checks:[]})}s(Ov,"required");function br(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}s(br,"aborted");function Lt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}s(Lt,"prefixIssues");function po(e){return typeof e=="string"?e:e?.message}s(po,"unwrapMessage");function xt(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=po(e.inst?._zod.def?.error?.(e))??po(t?.error?.(e))??po(n.customError?.(e))??po(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}s(xt,"finalizeIssue");function Za(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}s(Za,"getLengthableOrigin");function Er(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}s(Er,"issue");const Ql=s((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,bv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:s(()=>e.message,"value"),enumerable:!1})},"initializer$1"),ec=x("$ZodError",Ql),tc=x("$ZodError",Ql,{Parent:Error});function Rv(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}s(Rv,"flattenError");function Nv(e,t){const n=t||function(i){return i.message},r={_errors:[]},a=s(i=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(u=>a({issues:u}));else if(o.code==="invalid_key")a({issues:o.issues});else if(o.code==="invalid_element")a({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let u=r,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(o))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return a(e),r}s(Nv,"formatError");const Pv=s(e=>(t,n,r,a)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new qt;if(o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,i,It())));throw Xl(u,a?.callee),u}return o.value},"_parse$1"),Mv=s(e=>async(t,n,r,a)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const u=new(a?.Err??e)(o.issues.map(l=>xt(l,i,It())));throw Xl(u,a?.callee),u}return o.value},"_parseAsync"),nc=s(e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new qt;return i.issues.length?{success:!1,error:new(e??ec)(i.issues.map(o=>xt(o,a,It())))}:{success:!0,data:i.value}},"_safeParse"),jv=nc(tc),rc=s(e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(o=>xt(o,a,It())))}:{success:!0,data:i.value}},"_safeParseAsync"),zv=rc(tc),qv=/^[cC][^\s-]{8,}$/,Zv=/^[0-9a-z]+$/,Lv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Uv=/^[0-9a-vA-V]{20}$/,Vv=/^[A-Za-z0-9]{27}$/,Gv=/^[a-zA-Z0-9_-]{21}$/,Wv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Hv=/^([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})$/,oc=s(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"),Jv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Kv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Yv(){return new RegExp(Kv,"u")}s(Yv,"emoji");const Xv=/^(?:(?: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])$/,Qv=/^(([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})$/,ey=/^((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])$/,ty=/^(([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])$/,ny=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ac=/^[A-Za-z0-9_-]*$/,ry=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,oy=/^\+(?:[0-9]){6,14}[0-9]$/,ic="(?:(?:\\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])))",ay=new RegExp(`^${ic}$`);function sc(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+)?)?`}s(sc,"timeSource");function iy(e){return new RegExp(`^${sc(e)}$`)}s(iy,"time$1");function sy(e){const t=sc({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(`^${ic}T(?:${r})$`)}s(sy,"datetime$1");const uy=s(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),ly=/^\d+$/,cy=/^-?\d+(?:\.\d+)?/i,py=/true|false/i,dy=/null/i,my=/^[^A-Z]*$/,fy=/^[^a-z]*$/,Ue=x("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),uc={number:"number",bigint:"bigint",object:"date"},lc=x("$ZodCheckLessThan",(e,t)=>{Ue.init(e,t);const n=uc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?a.maximum=t.value:a.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})}}),cc=x("$ZodCheckGreaterThan",(e,t)=>{Ue.init(e,t);const n=uc[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?a.minimum=t.value:a.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})}}),hy=x("$ZodCheckMultipleOf",(e,t)=>{Ue.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):Ev(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})}}),Dy=x("$ZodCheckNumberFormat",(e,t)=>{Ue.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[a,i]=xv[t.format];e._zod.onattach.push(o=>{const u=o._zod.bag;u.format=t.format,u.minimum=a,u.maximum=i,n&&(u.pattern=ly)}),e._zod.check=o=>{const u=o.value;if(n){if(!Number.isInteger(u)){o.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?o.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}):o.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<a&&o.issues.push({origin:"number",input:u,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),u>i&&o.issues.push({origin:"number",input:u,code:"too_big",maximum:i,inst:e})}}),gy=x("$ZodCheckMaxLength",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!ja(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const o=Za(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),vy=x("$ZodCheckMinLength",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!ja(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const o=Za(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),yy=x("$ZodCheckLengthEquals",(e,t)=>{var n;Ue.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!ja(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,i=a.length;if(i===t.length)return;const o=Za(a),u=i>t.length;r.issues.push({origin:o,...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})}}),mo=x("$ZodCheckStringFormat",(e,t)=>{var n,r;Ue.init(e,t),e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),_y=x("$ZodCheckRegex",(e,t)=>{mo.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})}}),Fy=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=my),mo.init(e,t)}),Cy=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=fy),mo.init(e,t)}),by=x("$ZodCheckIncludes",(e,t)=>{Ue.init(e,t);const n=Cr(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),Ey=x("$ZodCheckStartsWith",(e,t)=>{Ue.init(e,t);const n=new RegExp(`^${Cr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),wy=x("$ZodCheckEndsWith",(e,t)=>{Ue.init(e,t);const n=new RegExp(`.*${Cr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Ay=x("$ZodCheckOverwrite",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Ui=class Ui{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(o=>o),a=Math.min(...r.map(o=>o.length-o.trimStart().length)),i=r.map(o=>o.slice(a)).map(o=>" ".repeat(this.indent*2)+o);for(const o of i)this.content.push(o)}compile(){const t=Function,n=this?.args,a=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,a.join(`
|
|
89
|
+
`))}};s(Ui,"Doc");let La=Ui;const Iy={major:4,minor:0,patch:0},de=x("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Iy;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const i of a._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const a=s((i,o,u)=>{let l=br(i),c;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(l)continue;const m=i.issues.length,h=d._zod.check(i);if(h instanceof Promise&&u?.async===!1)throw new qt;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,i.issues.length!==m&&(l||(l=br(i,m)))});else{if(i.issues.length===m)continue;l||(l=br(i,m))}}return c?c.then(()=>i):i},"runChecks");e._zod.run=(i,o)=>{const u=e._zod.parse(i,o);if(u instanceof Promise){if(o.async===!1)throw new qt;return u.then(l=>a(l,r,o))}return a(u,r,o)}}e["~standard"]={validate:s(a=>{try{const i=jv(e,a);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return zv(e,a).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}}),Ua=x("$ZodString",(e,t)=>{de.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??uy(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}}),Ce=x("$ZodStringFormat",(e,t)=>{mo.init(e,t),Ua.init(e,t)}),xy=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Hv),Ce.init(e,t)}),ky=x("$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=oc(r))}else t.pattern??(t.pattern=oc());Ce.init(e,t)}),$y=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Jv),Ce.init(e,t)}),Ty=x("$ZodURL",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{try{const r=n.value,a=new URL(r),i=a.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ry.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.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("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),By=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Yv()),Ce.init(e,t)}),Sy=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Gv),Ce.init(e,t)}),Oy=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=qv),Ce.init(e,t)}),Ry=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Zv),Ce.init(e,t)}),Ny=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Lv),Ce.init(e,t)}),Py=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Uv),Ce.init(e,t)}),My=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Vv),Ce.init(e,t)}),jy=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=sy(t)),Ce.init(e,t)}),zy=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ay),Ce.init(e,t)}),qy=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=iy(t)),Ce.init(e,t)}),Zy=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Wv),Ce.init(e,t)}),Ly=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Xv),Ce.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Uy=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Qv),Ce.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})}}}),Vy=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ey),Ce.init(e,t)}),Gy=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ty),Ce.init(e,t),e._zod.check=n=>{const[r,a]=n.value.split("/");try{if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>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 pc(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}s(pc,"isValidBase64");const Wy=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ny),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{pc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Hy(e){if(!ac.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return pc(n)}s(Hy,"isValidBase64URL");const Jy=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ac),Ce.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Hy(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ky=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=oy),Ce.init(e,t)});function Yy(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}s(Yy,"isValidJWT");const Xy=x("$ZodJWT",(e,t)=>{Ce.init(e,t),e._zod.check=n=>{Yy(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),dc=x("$ZodNumber",(e,t)=>{de.init(e,t),e._zod.pattern=e._zod.bag.pattern??cy,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...i?{received:i}:{}}),n}}),Qy=x("$ZodNumber",(e,t)=>{Dy.init(e,t),dc.init(e,t)}),e0=x("$ZodBoolean",(e,t)=>{de.init(e,t),e._zod.pattern=py,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),t0=x("$ZodNull",(e,t)=>{de.init(e,t),e._zod.pattern=dy,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),n0=x("$ZodAny",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),r0=x("$ZodUnknown",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),o0=x("$ZodNever",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function mc(e,t,n){e.issues.length&&t.issues.push(...Lt(n,e.issues)),t.value[n]=e.value}s(mc,"handleArrayResult");const a0=x("$ZodArray",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const i=[];for(let o=0;o<a.length;o++){const u=a[o],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?i.push(l.then(c=>mc(c,n,o))):mc(l,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function fo(e,t,n){e.issues.length&&t.issues.push(...Lt(n,e.issues)),t.value[n]=e.value}s(fo,"handleObjectResult");function fc(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(...Lt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}s(fc,"handleOptionalObjectResult");const i0=x("$ZodObject",(e,t)=>{de.init(e,t);const n=Ma(()=>{const m=Object.keys(t.shape);for(const D of m)if(!(t.shape[D]instanceof de))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=Iv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(h)}});ue(e._zod,"propValues",()=>{const m=t.shape,h={};for(const D in m){const f=m[D]._zod;if(f.values){h[D]??(h[D]=new Set);for(const g of f.values)h[D].add(g)}}return h});const r=s(m=>{const h=new La(["shape","payload","ctx"]),D=n.value,f=s(w=>{const b=Fr(w);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const g=Object.create(null);let y=0;for(const w of D.keys)g[w]=`key_${y++}`;h.write("const newResult = {}");for(const w of D.keys)if(D.optionalKeys.has(w)){const b=g[w];h.write(`const ${b} = ${f(w)};`);const E=Fr(w);h.write(`
|
|
90
|
+
if (${b}.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
|
+
${b}.issues.map((iss) => ({
|
|
98
|
+
...iss,
|
|
99
|
+
path: iss.path ? [${E}, ...iss.path] : [${E}],
|
|
100
|
+
}))
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
} else if (${b}.value === undefined) {
|
|
104
|
+
if (${E} in input) newResult[${E}] = undefined;
|
|
105
|
+
} else {
|
|
106
|
+
newResult[${E}] = ${b}.value;
|
|
107
|
+
}
|
|
108
|
+
`)}else{const b=g[w];h.write(`const ${b} = ${f(w)};`),h.write(`
|
|
109
|
+
if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
110
|
+
...iss,
|
|
111
|
+
path: iss.path ? [${Fr(w)}, ...iss.path] : [${Fr(w)}]
|
|
112
|
+
})));`),h.write(`newResult[${Fr(w)}] = ${b}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const F=h.compile();return(w,b)=>F(m,w,b)},"generateFastpass");let a;const i=lo,o=!Kl.jitless,l=o&&wv.value,c=t.catchall;let d;e._zod.parse=(m,h)=>{d??(d=n.value);const D=m.value;if(!i(D))return m.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),m;const f=[];if(o&&l&&h?.async===!1&&h.jitless!==!0)a||(a=r(t.shape)),m=a(m,h);else{m.value={};const b=d.shape;for(const E of d.keys){const O=b[E],k=O._zod.run({value:D[E],issues:[]},h),C=O._zod.optin==="optional"&&O._zod.optout==="optional";k instanceof Promise?f.push(k.then(L=>C?fc(L,m,E,D):fo(L,m,E))):C?fc(k,m,E,D):fo(k,m,E)}}if(!c)return f.length?Promise.all(f).then(()=>m):m;const g=[],y=d.keySet,F=c._zod,w=F.def.type;for(const b of Object.keys(D)){if(y.has(b))continue;if(w==="never"){g.push(b);continue}const E=F.run({value:D[b],issues:[]},h);E instanceof Promise?f.push(E.then(O=>fo(O,m,b))):fo(E,m,b)}return g.length&&m.issues.push({code:"unrecognized_keys",keys:g,input:D,inst:e}),f.length?Promise.all(f).then(()=>m):m}});function hc(e,t,n,r){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(a=>a.issues.map(i=>xt(i,r,It())))}),t}s(hc,"handleUnionResults");const Dc=x("$ZodUnion",(e,t)=>{de.init(e,t),ue(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ue(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ue(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ue(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=>za(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let a=!1;const i=[];for(const o of t.options){const u=o._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)i.push(u),a=!0;else{if(u.issues.length===0)return u;i.push(u)}}return a?Promise.all(i).then(o=>hc(o,n,e,r)):hc(i,n,e,r)}}),s0=x("$ZodDiscriminatedUnion",(e,t)=>{Dc.init(e,t);const n=e._zod.parse;ue(e._zod,"propValues",()=>{const a={};for(const i of t.options){const o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[u,l]of Object.entries(o)){a[u]||(a[u]=new Set);for(const c of l)a[u].add(c)}}return a});const r=Ma(()=>{const a=t.options,i=new Map;for(const o of a){const u=o._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const l of u){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,o)}}return i});e._zod.parse=(a,i)=>{const o=a.value;if(!lo(o))return a.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),a;const u=r.value.get(o?.[t.discriminator]);return u?u._zod.run(a,i):t.unionFallback?n(a,i):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[t.discriminator],inst:e}),a)}}),u0=x("$ZodIntersection",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value,i=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([l,c])=>gc(n,l,c)):gc(n,i,o)}});function Va(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(co(e)&&co(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),a={...e,...t};for(const i of r){const o=Va(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};a[i]=o.data}return{valid:!0,data:a}}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 a=e[r],i=t[r],o=Va(a,i);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}s(Va,"mergeValues");function gc(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),br(e))return e;const r=Va(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}s(gc,"handleIntersectionResults");const l0=x("$ZodRecord",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!co(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),n;const i=[];if(t.keyType._zod.values){const o=t.keyType._zod.values;n.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:a[l],issues:[]},r);c instanceof Promise?i.push(c.then(d=>{d.issues.length&&n.issues.push(...Lt(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...Lt(l,c.issues)),n.value[l]=c.value)}let u;for(const l in a)o.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:u})}else{n.value={};for(const o of Reflect.ownKeys(a)){if(o==="__proto__")continue;const u=t.keyType._zod.run({value:o,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=>xt(c,r,It())),input:o,path:[o],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:a[o],issues:[]},r);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&n.issues.push(...Lt(o,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...Lt(o,l.issues)),n.value[u.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),c0=x("$ZodEnum",(e,t)=>{de.init(e,t);const n=Yl(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>Av.has(typeof r)).map(r=>typeof r=="string"?Cr(r):r.toString()).join("|")})$`),e._zod.parse=(r,a)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),p0=x("$ZodLiteral",(e,t)=>{de.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Cr(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const a=n.value;return e._zod.values.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}}),d0=x("$ZodTransform",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(o=>(n.value=o,n));if(a instanceof Promise)throw new qt;return n.value=a,n}}),m0=x("$ZodOptional",(e,t)=>{de.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ue(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ue(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${za(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)}),f0=x("$ZodNullable",(e,t)=>{de.init(e,t),ue(e._zod,"optin",()=>t.innerType._zod.optin),ue(e._zod,"optout",()=>t.innerType._zod.optout),ue(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${za(n.source)}|null)$`):void 0}),ue(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)}),h0=x("$ZodDefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",ue(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>vc(i,t)):vc(a,t)}});function vc(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}s(vc,"handleDefaultResult");const D0=x("$ZodPrefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",ue(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))}),g0=x("$ZodNonOptional",(e,t)=>{de.init(e,t),ue(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 a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>yc(i,e)):yc(a,e)}});function yc(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}s(yc,"handleNonOptionalResult");const v0=x("$ZodCatch",(e,t)=>{de.init(e,t),e._zod.optin="optional",ue(e._zod,"optout",()=>t.innerType._zod.optout),ue(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>xt(o,r,It()))},input:n.value}),n.issues=[]),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>xt(i,r,It()))},input:n.value}),n.issues=[]),n)}}),y0=x("$ZodPipe",(e,t)=>{de.init(e,t),ue(e._zod,"values",()=>t.in._zod.values),ue(e._zod,"optin",()=>t.in._zod.optin),ue(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>_c(i,t,r)):_c(a,t,r)}});function _c(e,t,n){return br(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}s(_c,"handlePipeResult");const _0=x("$ZodReadonly",(e,t)=>{de.init(e,t),ue(e._zod,"propValues",()=>t.innerType._zod.propValues),ue(e._zod,"values",()=>t.innerType._zod.values),ue(e._zod,"optin",()=>t.innerType._zod.optin),ue(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(Fc):Fc(a)}});function Fc(e){return e.value=Object.freeze(e.value),e}s(Fc,"handleReadonlyResult");const F0=x("$ZodLazy",(e,t)=>{de.init(e,t),ue(e._zod,"innerType",()=>t.getter()),ue(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),ue(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),ue(e._zod,"optin",()=>e._zod.innerType._zod.optin),ue(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),C0=x("$ZodCustom",(e,t)=>{Ue.init(e,t),de.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(i=>Cc(i,n,r,e));Cc(a,n,r,e)}});function Cc(e,t,n,r){if(!e){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(Er(a))}}s(Cc,"handleRefineResult");const Vi=class Vi{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)}};s(Vi,"$ZodRegistry");let ho=Vi;function b0(){return new ho}s(b0,"registry");const wr=b0();function E0(e,t){return new e({type:"string",...z(t)})}s(E0,"_string");function w0(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...z(t)})}s(w0,"_email");function bc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...z(t)})}s(bc,"_guid");function A0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...z(t)})}s(A0,"_uuid");function I0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(t)})}s(I0,"_uuidv4");function x0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(t)})}s(x0,"_uuidv6");function k0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(t)})}s(k0,"_uuidv7");function $0(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...z(t)})}s($0,"_url");function T0(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...z(t)})}s(T0,"_emoji");function B0(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(t)})}s(B0,"_nanoid");function S0(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...z(t)})}s(S0,"_cuid");function O0(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(t)})}s(O0,"_cuid2");function R0(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...z(t)})}s(R0,"_ulid");function N0(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...z(t)})}s(N0,"_xid");function P0(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(t)})}s(P0,"_ksuid");function M0(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(t)})}s(M0,"_ipv4");function j0(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(t)})}s(j0,"_ipv6");function z0(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(t)})}s(z0,"_cidrv4");function q0(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(t)})}s(q0,"_cidrv6");function Z0(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...z(t)})}s(Z0,"_base64");function L0(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...z(t)})}s(L0,"_base64url");function U0(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...z(t)})}s(U0,"_e164");function V0(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...z(t)})}s(V0,"_jwt");function G0(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(t)})}s(G0,"_isoDateTime");function W0(e,t){return new e({type:"string",format:"date",check:"string_format",...z(t)})}s(W0,"_isoDate");function H0(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...z(t)})}s(H0,"_isoTime");function J0(e,t){return new e({type:"string",format:"duration",check:"string_format",...z(t)})}s(J0,"_isoDuration");function K0(e,t){return new e({type:"number",checks:[],...z(t)})}s(K0,"_number");function Y0(e,t){return new e({type:"number",coerce:!0,checks:[],...z(t)})}s(Y0,"_coercedNumber");function X0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...z(t)})}s(X0,"_int");function Q0(e,t){return new e({type:"boolean",...z(t)})}s(Q0,"_boolean");function e_(e,t){return new e({type:"null",...z(t)})}s(e_,"_null$1");function t_(e){return new e({type:"any"})}s(t_,"_any");function n_(e){return new e({type:"unknown"})}s(n_,"_unknown");function r_(e,t){return new e({type:"never",...z(t)})}s(r_,"_never");function Ec(e,t){return new lc({check:"less_than",...z(t),value:e,inclusive:!1})}s(Ec,"_lt");function Ga(e,t){return new lc({check:"less_than",...z(t),value:e,inclusive:!0})}s(Ga,"_lte");function wc(e,t){return new cc({check:"greater_than",...z(t),value:e,inclusive:!1})}s(wc,"_gt");function Wa(e,t){return new cc({check:"greater_than",...z(t),value:e,inclusive:!0})}s(Wa,"_gte");function Ac(e,t){return new hy({check:"multiple_of",...z(t),value:e})}s(Ac,"_multipleOf");function Ic(e,t){return new gy({check:"max_length",...z(t),maximum:e})}s(Ic,"_maxLength");function Do(e,t){return new vy({check:"min_length",...z(t),minimum:e})}s(Do,"_minLength");function xc(e,t){return new yy({check:"length_equals",...z(t),length:e})}s(xc,"_length");function o_(e,t){return new _y({check:"string_format",format:"regex",...z(t),pattern:e})}s(o_,"_regex");function a_(e){return new Fy({check:"string_format",format:"lowercase",...z(e)})}s(a_,"_lowercase");function i_(e){return new Cy({check:"string_format",format:"uppercase",...z(e)})}s(i_,"_uppercase");function s_(e,t){return new by({check:"string_format",format:"includes",...z(t),includes:e})}s(s_,"_includes");function u_(e,t){return new Ey({check:"string_format",format:"starts_with",...z(t),prefix:e})}s(u_,"_startsWith");function l_(e,t){return new wy({check:"string_format",format:"ends_with",...z(t),suffix:e})}s(l_,"_endsWith");function Ar(e){return new Ay({check:"overwrite",tx:e})}s(Ar,"_overwrite");function c_(e){return Ar(t=>t.normalize(e))}s(c_,"_normalize");function p_(){return Ar(e=>e.trim())}s(p_,"_trim");function d_(){return Ar(e=>e.toLowerCase())}s(d_,"_toLowerCase");function m_(){return Ar(e=>e.toUpperCase())}s(m_,"_toUpperCase");function f_(e,t,n){return new e({type:"array",element:t,...z(n)})}s(f_,"_array");function h_(e,t,n){const r=z(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}s(h_,"_custom");function D_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...z(n)})}s(D_,"_refine");const Gi=class Gi{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??wr,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 a=t._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,n.schemaPath.includes(t)&&(o.cycle=n.path),o.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 m={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,m),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(a.type){case"string":{const f=D;f.type="string";const{minimum:g,maximum:y,format:F,patterns:w,contentEncoding:b}=t._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof y=="number"&&(f.maxLength=y),F&&(f.format=i[F]??F,f.format===""&&delete f.format),b&&(f.contentEncoding=b),w&&w.size>0){const E=[...w];E.length===1?f.pattern=E[0].source:E.length>1&&(u.schema.allOf=[...E.map(O=>({...this.target==="draft-7"?{type:"string"}:{},pattern:O.source}))])}break}case"number":{const f=D,{minimum:g,maximum:y,format:F,multipleOf:w,exclusiveMaximum:b,exclusiveMinimum:E}=t._zod.bag;typeof F=="string"&&F.includes("int")?f.type="integer":f.type="number",typeof E=="number"&&(f.exclusiveMinimum=E),typeof g=="number"&&(f.minimum=g,typeof E=="number"&&(E>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof b=="number"&&(f.exclusiveMaximum=b),typeof y=="number"&&(f.maximum=y,typeof b=="number"&&(b<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof w=="number"&&(f.multipleOf=w);break}case"boolean":{const f=D;f.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 f=D,{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(f.minItems=g),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(a.element,{...m,path:[...m.path,"items"]});break}case"object":{const f=D;f.type="object",f.properties={};const g=a.shape;for(const w in g)f.properties[w]=this.process(g[w],{...m,path:[...m.path,"properties",w]});const y=new Set(Object.keys(g)),F=new Set([...y].filter(w=>{const b=a.shape[w]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));F.size>0&&(f.required=Array.from(F)),a.catchall?._zod.def.type==="never"?f.additionalProperties=!1:a.catchall?a.catchall&&(f.additionalProperties=this.process(a.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=D;f.anyOf=a.options.map((g,y)=>this.process(g,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const f=D,g=this.process(a.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(a.right,{...m,path:[...m.path,"allOf",1]}),F=s(b=>"allOf"in b&&Object.keys(b).length===1,"isSimpleIntersection"),w=[...F(g)?g.allOf:[g],...F(y)?y.allOf:[y]];f.allOf=w;break}case"tuple":{const f=D;f.type="array";const g=a.items.map((w,b)=>this.process(w,{...m,path:[...m.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,a.rest){const w=this.process(a.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?f.items=w:f.additionalItems=w}a.rest&&(f.items=this.process(a.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:F}=t._zod.bag;typeof y=="number"&&(f.minItems=y),typeof F=="number"&&(f.maxItems=F);break}case"record":{const f=D;f.type="object",f.propertyNames=this.process(a.keyType,{...m,path:[...m.path,"propertyNames"]}),f.additionalProperties=this.process(a.valueType,{...m,path:[...m.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 f=D,g=Yl(a.entries);g.every(y=>typeof y=="number")&&(f.type="number"),g.every(y=>typeof y=="string")&&(f.type="string"),f.enum=g;break}case"literal":{const f=D,g=[];for(const y of a.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");g.push(Number(y))}else g.push(y);if(g.length!==0)if(g.length===1){const y=g[0];f.type=y===null?"null":typeof y,f.const=y}else g.every(y=>typeof y=="number")&&(f.type="number"),g.every(y=>typeof y=="string")&&(f.type="string"),g.every(y=>typeof y=="boolean")&&(f.type="string"),g.every(y=>y===null)&&(f.type="null"),f.enum=g;break}case"file":{const f=D,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:F,mime:w}=t._zod.bag;y!==void 0&&(g.minLength=y),F!==void 0&&(g.maxLength=F),w?w.length===1?(g.contentMediaType=w[0],Object.assign(f,g)):f.anyOf=w.map(b=>({...g,contentMediaType:b})):Object.assign(f,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(a.innerType,m);D.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"success":{const f=D;f.type="boolean";break}case"default":{this.process(a.innerType,m),u.ref=a.innerType,D.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,m),u.ref=a.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,m),u.ref=a.innerType;let f;try{f=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=D,g=t._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.source;break}case"pipe":{const f=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(f,m),u.ref=f;break}case"readonly":{this.process(a.innerType,m),u.ref=a.innerType,D.readOnly=!0;break}case"promise":{this.process(a.innerType,m),u.ref=a.innerType;break}case"optional":{this.process(a.innerType,m),u.ref=a.innerType;break}case"lazy":{const f=t._zod.innerType;this.process(f,m),u.ref=f;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"&&Te(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},a=this.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=s(d=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const g=r.external.registry.get(d[0])?.id,y=r.external.uri??(w=>w);if(g)return{ref:y(g)};const F=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=F,{defId:F,ref:`${y("__shared")}#/${m}/${F}`}}if(d[1]===a)return{ref:"#"};const D=`#/${m}/`,f=d[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:D+f}},"makeURI"),o=s(d=>{if(d[1].schema.$ref)return;const m=d[1],{ref:h,defId:D}=i(d);m.def={...m.schema},D&&(m.defId=D);const f=m.schema;for(const g in f)delete f[g];f.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const m=d[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.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 m=d[1];if(t===d[0]){o(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){o(d);continue}}if(this.metadataRegistry.get(d[0])?.id){o(d);continue}if(m.cycle){o(d);continue}if(m.count>1&&r.reused==="ref"){o(d);continue}}const u=s((d,m)=>{const h=this.seen.get(d),D=h.def??h.schema,f={...D};if(h.ref===null)return;const g=h.ref;if(h.ref=null,g){u(g,m);const y=this.seen.get(g).schema;y.$ref&&m.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,f))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,a.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const m=d[1];m.def&&m.defId&&(c[m.defId]=m.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.")}}};s(Gi,"JSONSchemaGenerator");let go=Gi;function g_(e,t){if(e instanceof ho){const r=new go(t),a={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const i={},o={registry:e,uri:t?.uri,defs:a};for(const u of e._idmap.entries()){const[l,c]=u;i[l]=r.emit(c,{...t,external:o})}if(Object.keys(a).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:a}}return{schemas:i}}const n=new go(t);return n.process(e),n.emit(e,t)}s(g_,"toJSONSchema");function Te(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;switch(a.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 Te(a.element,n);case"object":{for(const i in a.shape)if(Te(a.shape[i],n))return!0;return!1}case"union":{for(const i of a.options)if(Te(i,n))return!0;return!1}case"intersection":return Te(a.left,n)||Te(a.right,n);case"tuple":{for(const i of a.items)if(Te(i,n))return!0;return!!(a.rest&&Te(a.rest,n))}case"record":return Te(a.keyType,n)||Te(a.valueType,n);case"map":return Te(a.keyType,n)||Te(a.valueType,n);case"set":return Te(a.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Te(a.innerType,n);case"lazy":return Te(a.getter(),n);case"default":return Te(a.innerType,n);case"prefault":return Te(a.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Te(a.in,n)||Te(a.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${a.type}`)}s(Te,"isTransforming");const v_=x("ZodISODateTime",(e,t)=>{jy.init(e,t),Ee.init(e,t)});function y_(e){return G0(v_,e)}s(y_,"datetime");const __=x("ZodISODate",(e,t)=>{zy.init(e,t),Ee.init(e,t)});function F_(e){return W0(__,e)}s(F_,"date");const C_=x("ZodISOTime",(e,t)=>{qy.init(e,t),Ee.init(e,t)});function b_(e){return H0(C_,e)}s(b_,"time");const E_=x("ZodISODuration",(e,t)=>{Zy.init(e,t),Ee.init(e,t)});function w_(e){return J0(E_,e)}s(w_,"duration");const A_=s((e,t)=>{ec.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:s(n=>Nv(e,n),"value")},flatten:{value:s(n=>Rv(e,n),"value")},addIssue:{value:s(n=>e.issues.push(n),"value")},addIssues:{value:s(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),vo=x("ZodError",A_,{Parent:Error}),I_=Pv(vo),x_=Mv(vo),k_=nc(vo),kc=rc(vo),ye=x("ZodType",(e,t)=>(de.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)=>Zt(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>I_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>k_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>kc(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(EF(n,r)),e.superRefine=n=>e.check(wF(n)),e.overwrite=n=>e.check(Ar(n)),e.optional=()=>Nc(e),e.nullable=()=>Pc(e),e.nullish=()=>Nc(Pc(e)),e.nonoptional=n=>hF(e,n),e.array=()=>B(e),e.or=n=>J([e,n]),e.and=n=>aF(e,n),e.transform=n=>jc(e,lF(n)),e.default=n=>dF(e,n),e.prefault=n=>fF(e,n),e.catch=n=>gF(e,n),e.pipe=n=>jc(e,n),e.readonly=()=>_F(e),e.describe=n=>{const r=e.clone();return wr.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return wr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return wr.get(e);const r=e.clone();return wr.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),$c=x("_ZodString",(e,t)=>{Ua.init(e,t),ye.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(o_(...r)),e.includes=(...r)=>e.check(s_(...r)),e.startsWith=(...r)=>e.check(u_(...r)),e.endsWith=(...r)=>e.check(l_(...r)),e.min=(...r)=>e.check(Do(...r)),e.max=(...r)=>e.check(Ic(...r)),e.length=(...r)=>e.check(xc(...r)),e.nonempty=(...r)=>e.check(Do(1,...r)),e.lowercase=r=>e.check(a_(r)),e.uppercase=r=>e.check(i_(r)),e.trim=()=>e.check(p_()),e.normalize=(...r)=>e.check(c_(...r)),e.toLowerCase=()=>e.check(d_()),e.toUpperCase=()=>e.check(m_())}),$_=x("ZodString",(e,t)=>{Ua.init(e,t),$c.init(e,t),e.email=n=>e.check(w0(T_,n)),e.url=n=>e.check($0(B_,n)),e.jwt=n=>e.check(V0(W_,n)),e.emoji=n=>e.check(T0(S_,n)),e.guid=n=>e.check(bc(Tc,n)),e.uuid=n=>e.check(A0(yo,n)),e.uuidv4=n=>e.check(I0(yo,n)),e.uuidv6=n=>e.check(x0(yo,n)),e.uuidv7=n=>e.check(k0(yo,n)),e.nanoid=n=>e.check(B0(O_,n)),e.guid=n=>e.check(bc(Tc,n)),e.cuid=n=>e.check(S0(R_,n)),e.cuid2=n=>e.check(O0(N_,n)),e.ulid=n=>e.check(R0(P_,n)),e.base64=n=>e.check(Z0(U_,n)),e.base64url=n=>e.check(L0(V_,n)),e.xid=n=>e.check(N0(M_,n)),e.ksuid=n=>e.check(P0(j_,n)),e.ipv4=n=>e.check(M0(z_,n)),e.ipv6=n=>e.check(j0(q_,n)),e.cidrv4=n=>e.check(z0(Z_,n)),e.cidrv6=n=>e.check(q0(L_,n)),e.e164=n=>e.check(U0(G_,n)),e.datetime=n=>e.check(y_(n)),e.date=n=>e.check(F_(n)),e.time=n=>e.check(b_(n)),e.duration=n=>e.check(w_(n))});function p(e){return E0($_,e)}s(p,"string");const Ee=x("ZodStringFormat",(e,t)=>{Ce.init(e,t),$c.init(e,t)}),T_=x("ZodEmail",(e,t)=>{$y.init(e,t),Ee.init(e,t)}),Tc=x("ZodGUID",(e,t)=>{xy.init(e,t),Ee.init(e,t)}),yo=x("ZodUUID",(e,t)=>{ky.init(e,t),Ee.init(e,t)}),B_=x("ZodURL",(e,t)=>{Ty.init(e,t),Ee.init(e,t)}),S_=x("ZodEmoji",(e,t)=>{By.init(e,t),Ee.init(e,t)}),O_=x("ZodNanoID",(e,t)=>{Sy.init(e,t),Ee.init(e,t)}),R_=x("ZodCUID",(e,t)=>{Oy.init(e,t),Ee.init(e,t)}),N_=x("ZodCUID2",(e,t)=>{Ry.init(e,t),Ee.init(e,t)}),P_=x("ZodULID",(e,t)=>{Ny.init(e,t),Ee.init(e,t)}),M_=x("ZodXID",(e,t)=>{Py.init(e,t),Ee.init(e,t)}),j_=x("ZodKSUID",(e,t)=>{My.init(e,t),Ee.init(e,t)}),z_=x("ZodIPv4",(e,t)=>{Ly.init(e,t),Ee.init(e,t)}),q_=x("ZodIPv6",(e,t)=>{Uy.init(e,t),Ee.init(e,t)}),Z_=x("ZodCIDRv4",(e,t)=>{Vy.init(e,t),Ee.init(e,t)}),L_=x("ZodCIDRv6",(e,t)=>{Gy.init(e,t),Ee.init(e,t)}),U_=x("ZodBase64",(e,t)=>{Wy.init(e,t),Ee.init(e,t)}),V_=x("ZodBase64URL",(e,t)=>{Jy.init(e,t),Ee.init(e,t)}),G_=x("ZodE164",(e,t)=>{Ky.init(e,t),Ee.init(e,t)}),W_=x("ZodJWT",(e,t)=>{Xy.init(e,t),Ee.init(e,t)}),Ha=x("ZodNumber",(e,t)=>{dc.init(e,t),ye.init(e,t),e.gt=(r,a)=>e.check(wc(r,a)),e.gte=(r,a)=>e.check(Wa(r,a)),e.min=(r,a)=>e.check(Wa(r,a)),e.lt=(r,a)=>e.check(Ec(r,a)),e.lte=(r,a)=>e.check(Ga(r,a)),e.max=(r,a)=>e.check(Ga(r,a)),e.int=r=>e.check(Bc(r)),e.safe=r=>e.check(Bc(r)),e.positive=r=>e.check(wc(0,r)),e.nonnegative=r=>e.check(Wa(0,r)),e.negative=r=>e.check(Ec(0,r)),e.nonpositive=r=>e.check(Ga(0,r)),e.multipleOf=(r,a)=>e.check(Ac(r,a)),e.step=(r,a)=>e.check(Ac(r,a)),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 A(e){return K0(Ha,e)}s(A,"number$1");const H_=x("ZodNumberFormat",(e,t)=>{Qy.init(e,t),Ha.init(e,t)});function Bc(e){return X0(H_,e)}s(Bc,"int");const J_=x("ZodBoolean",(e,t)=>{e0.init(e,t),ye.init(e,t)});function Ae(e){return Q0(J_,e)}s(Ae,"boolean");const K_=x("ZodNull",(e,t)=>{t0.init(e,t),ye.init(e,t)});function Sc(e){return e_(K_,e)}s(Sc,"_null");const Y_=x("ZodAny",(e,t)=>{n0.init(e,t),ye.init(e,t)});function qe(){return t_(Y_)}s(qe,"any");const X_=x("ZodUnknown",(e,t)=>{r0.init(e,t),ye.init(e,t)});function gt(){return n_(X_)}s(gt,"unknown");const Q_=x("ZodNever",(e,t)=>{o0.init(e,t),ye.init(e,t)});function eF(e){return r_(Q_,e)}s(eF,"never");const tF=x("ZodArray",(e,t)=>{a0.init(e,t),ye.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Do(n,r)),e.nonempty=n=>e.check(Do(1,n)),e.max=(n,r)=>e.check(Ic(n,r)),e.length=(n,r)=>e.check(xc(n,r)),e.unwrap=()=>e.element});function B(e,t){return f_(tF,e,t)}s(B,"array$1");const nF=x("ZodObject",(e,t)=>{i0.init(e,t),ye.init(e,t),ue(e,"shape",()=>t.shape),e.keyof=()=>oe(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:gt()}),e.loose=()=>e.clone({...e._zod.def,catchall:gt()}),e.strict=()=>e.clone({...e._zod.def,catchall:eF()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Tv(e,n),e.merge=n=>Bv(e,n),e.pick=n=>kv(e,n),e.omit=n=>$v(e,n),e.partial=(...n)=>Sv(Rc,e,n[0]),e.required=(...n)=>Ov(Mc,e,n[0])});function v(e,t){const n={type:"object",get shape(){return qa(this,"shape",{...e}),this.shape},...z(t)};return new nF(n)}s(v,"object$1");const Oc=x("ZodUnion",(e,t)=>{Dc.init(e,t),ye.init(e,t),e.options=t.options});function J(e,t){return new Oc({type:"union",options:e,...z(t)})}s(J,"union");const rF=x("ZodDiscriminatedUnion",(e,t)=>{Oc.init(e,t),s0.init(e,t)});function Ie(e,t,n){return new rF({type:"union",options:t,discriminator:e,...z(n)})}s(Ie,"discriminatedUnion");const oF=x("ZodIntersection",(e,t)=>{u0.init(e,t),ye.init(e,t)});function aF(e,t){return new oF({type:"intersection",left:e,right:t})}s(aF,"intersection");const iF=x("ZodRecord",(e,t)=>{l0.init(e,t),ye.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function me(e,t,n){return new iF({type:"record",keyType:e,valueType:t,...z(n)})}s(me,"record");const Ja=x("ZodEnum",(e,t)=>{c0.init(e,t),ye.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,a)=>{const i={};for(const o of r)if(n.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ja({...t,checks:[],...z(a),entries:i})},e.exclude=(r,a)=>{const i={...t.entries};for(const o of r)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ja({...t,checks:[],...z(a),entries:i})}});function oe(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ja({type:"enum",entries:n,...z(t)})}s(oe,"_enum");const sF=x("ZodLiteral",(e,t)=>{p0.init(e,t),ye.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 I(e,t){return new sF({type:"literal",values:Array.isArray(e)?e:[e],...z(t)})}s(I,"literal");const uF=x("ZodTransform",(e,t)=>{d0.init(e,t),ye.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(Er(i,n.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Er(o))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n)):(n.value=a,n)}});function lF(e){return new uF({type:"transform",transform:e})}s(lF,"transform");const Rc=x("ZodOptional",(e,t)=>{m0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Nc(e){return new Rc({type:"optional",innerType:e})}s(Nc,"optional");const cF=x("ZodNullable",(e,t)=>{f0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new cF({type:"nullable",innerType:e})}s(Pc,"nullable");const pF=x("ZodDefault",(e,t)=>{h0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function dF(e,t){return new pF({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}s(dF,"_default");const mF=x("ZodPrefault",(e,t)=>{D0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fF(e,t){return new mF({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}s(fF,"prefault");const Mc=x("ZodNonOptional",(e,t)=>{g0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hF(e,t){return new Mc({type:"nonoptional",innerType:e,...z(t)})}s(hF,"nonoptional");const DF=x("ZodCatch",(e,t)=>{v0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gF(e,t){return new DF({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}s(gF,"_catch");const vF=x("ZodPipe",(e,t)=>{y0.init(e,t),ye.init(e,t),e.in=t.in,e.out=t.out});function jc(e,t){return new vF({type:"pipe",in:e,out:t})}s(jc,"pipe");const yF=x("ZodReadonly",(e,t)=>{_0.init(e,t),ye.init(e,t)});function _F(e){return new yF({type:"readonly",innerType:e})}s(_F,"readonly");const FF=x("ZodLazy",(e,t)=>{F0.init(e,t),ye.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ka(e){return new FF({type:"lazy",getter:e})}s(Ka,"lazy");const Ya=x("ZodCustom",(e,t)=>{C0.init(e,t),ye.init(e,t)});function CF(e){const t=new Ue({check:"custom"});return t._zod.check=e,t}s(CF,"check");function bF(e,t){return h_(Ya,e??(()=>!0),t)}s(bF,"custom");function EF(e,t={}){return D_(Ya,e,t)}s(EF,"refine");function wF(e){const t=CF(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Er(r,n.value,t._zod.def));else{const a=r;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),a.continue??(a.continue=!t._zod.def.abort),n.issues.push(Er(a))}},e(n.value,n)));return t}s(wF,"superRefine");function _o(e,t={error:`Input not instance of ${e.name}`}){const n=new Ya({type:"custom",check:"custom",fn:s(r=>r instanceof e,"fn"),abort:!0,...z(t)});return n._zod.bag.Class=e,n}s(_o,"_instanceof");function AF(e){return Y0(Ha,e)}s(AF,"number");var Y;(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"})(Y||(Y={}));const Wi=class Wi 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}};s(Wi,"ParseError");let Fo=Wi;function Xa(e){}s(Xa,"noop");function IF(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=Xa,onError:n=Xa,onRetry:r=Xa,onComment:a}=e;let i="",o=!0,u,l="",c="";function d(g){const y=o?g.replace(/^\xEF\xBB\xBF/,""):g,[F,w]=xF(`${i}${y}`);for(const b of F)m(b);i=w,o=!1}s(d,"feed");function m(g){if(g===""){D();return}if(g.startsWith(":")){a&&a(g.slice(g.startsWith(": ")?2:1));return}const y=g.indexOf(":");if(y!==-1){const F=g.slice(0,y),w=g[y+1]===" "?2:1,b=g.slice(y+w);h(F,b,g);return}h(g,"",g)}s(m,"parseLine");function h(g,y,F){switch(g){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 Fo(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:F}));break;default:n(new Fo(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:y,line:F}));break}}s(h,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
|
|
116
|
+
`)?l.slice(0,-1):l}),u=void 0,l="",c=""}s(D,"dispatchEvent");function f(g={}){i&&g.consume&&m(i),o=!0,u=void 0,l="",c="",i=""}return s(f,"reset"),{feed:d,reset:f}}s(IF,"createParser");function xF(e){const t=[];let n="",r=0;for(;r<e.length;){const a=e.indexOf("\r",r),i=e.indexOf(`
|
|
117
|
+
`,r);let o=-1;if(a!==-1&&i!==-1?o=Math.min(a,i):a!==-1?a===e.length-1?o=-1:o=a:i!==-1&&(o=i),o===-1){n=e.slice(r);break}else{const u=e.slice(r,o);t.push(u),r=o+1,e[r-1]==="\r"&&e[r]===`
|
|
118
|
+
`&&r++}}return[t,n]}s(xF,"splitLines");const Hi=class Hi extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(i){a=IF({onEvent:s(o=>{i.enqueue(o)},"onEvent"),onError(o){t==="terminate"?i.error(o):typeof t=="function"&&t(o)},onRetry:n,onComment:r})},transform(i){a.feed(i)}})}};s(Hi,"EventSourceParserStream");let Qa=Hi;function xe(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}s(xe,"combineHeaders");function kF({tools:e=[],providerToolNames:t}){const n={},r={};for(const a of e)if(a.type==="provider"&&a.id in t){const i=t[a.id];n[a.name]=i,r[i]=a.name}return{toProviderToolName:s(a=>{var i;return(i=n[a])!=null?i:a},"toProviderToolName"),toCustomToolName:s(a=>{var i;return(i=r[a])!=null?i:a},"toCustomToolName")}}s(kF,"createToolNameMapping");async function $F(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,a)=>{if(n?.aborted){a(zc());return}const i=setTimeout(()=>{o(),r()},e),o=s(()=>{clearTimeout(i),n?.removeEventListener("abort",u)},"cleanup"),u=s(()=>{o(),a(zc())},"onAbort");n?.addEventListener("abort",u)})}s($F,"delay");function zc(){return new DOMException("Delay was aborted","AbortError")}s(zc,"createAbortError");function cn(e){return Object.fromEntries([...e.headers])}s(cn,"extractResponseHeaders");var{btoa:TF,atob:BF}=globalThis;function Ut(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=BF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}s(Ut,"convertBase64ToUint8Array");function Ir(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return TF(t)}s(Ir,"convertUint8ArrayToBase64");function Vt(e){return e instanceof Uint8Array?Ir(e):e}s(Vt,"convertToBase64");function qc(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[a,i]of Object.entries(e))if(i!=null){if(Array.isArray(i)){if(i.length===1){r.append(a,i[0]);continue}const o=n?`${a}[]`:a;for(const u of i)r.append(o,u);continue}r.append(a,i)}return r}s(qc,"convertToFormData");var Zc="AI_DownloadError",Lc=`vercel.ai.error.${Zc}`,SF=Symbol.for(Lc),Uc,Vc,pn=(In=class extends(Vc=W,Uc=SF,Vc){constructor({url:t,statusCode:n,statusText:r,cause:a,message:i=a==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${a}`}){super({name:Zc,message:i,cause:a}),this[Uc]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return W.hasMarker(t,Lc)}},s(In,"DownloadError"),In);async function ei(e){try{const t=await fetch(e);if(!t.ok)throw new pn({url:e,statusCode:t.status,statusText:t.statusText});return await t.blob()}catch(t){throw pn.isInstance(t)?t:new pn({url:e,cause:t})}}s(ei,"downloadBlob");var xr=s(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const a=s(()=>{const i=n.length,o=new Array(t);for(let u=0;u<t;u++)o[u]=n[Math.random()*i|0];return o.join("")},"generator");if(e==null)return a;if(n.includes(r))throw new _l({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${a()}`},"createIdGenerator"),Be=xr();function Gc(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}s(Gc,"getErrorMessage");function dn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}s(dn,"isAbortError");var OF=["fetch failed","failed to fetch"];function Wc({error:e,url:t,requestBodyValues:n}){if(dn(e))return e;if(e instanceof TypeError&&OF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Re({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}s(Wc,"handleFetchError");function ti(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"}s(ti,"getRuntimeEnvironmentUserAgent");function RF(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}s(RF,"normalizeHeaders");function Gt(e,...t){const n=new Headers(RF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}s(Gt,"withUserAgentSuffix");var Hc="4.0.4",NF=s(()=>globalThis.fetch,"getOriginalFetch"),Jc=s(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:a,fetch:i=NF()})=>{try{const o=await i(e,{method:"GET",headers:Gt(t,`ai-sdk/provider-utils/${Hc}`,ti()),signal:a}),u=cn(o);if(!o.ok){let l;try{l=await r({response:o,url:e,requestBodyValues:{}})}catch(c){throw dn(c)||Re.isInstance(c)?c:new Re({message:"Failed to process error response",cause:c,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(dn(l)||Re.isInstance(l))?l:new Re({message:"Failed to process successful response",cause:l,statusCode:o.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(o){throw Wc({error:o,url:e,requestBodyValues:{}})}},"getFromApi");function PF(e){return e!=null}s(PF,"isNonNullable");function MF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,a])=>{const i=r.toLowerCase();return i==="*"||i==="*/*"?{mediaTypePrefix:"",regexes:a}:{mediaTypePrefix:i.replace(/\*/,""),regexes:a}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}s(MF,"isUrlSupported");function jF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new uo({message:`${r} API key must be a string.`});if(typeof process>"u")throw new uo({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 uo({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new uo({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}s(jF,"loadApiKey");function kr({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}s(kr,"loadOptionalSetting");function zF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}s(zF,"mediaTypeToExtension");var qF=/"__proto__"\s*:/,ZF=/"constructor"\s*:/;function Kc(e){const t=JSON.parse(e);return t===null||typeof t!="object"||qF.test(e)===!1&&ZF.test(e)===!1?t:LF(t)}s(Kc,"_parse");function LF(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 a in r){const i=r[a];i&&typeof i=="object"&&t.push(i)}}}return e}s(LF,"filter");function ni(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Kc(e)}try{return Kc(e)}finally{Error.stackTraceLimit=t}}s(ni,"secureJsonParse");function Yc(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]=Wt(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Wt):Wt(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Wt)),e.allOf!=null&&(e.allOf=e.allOf.map(Wt)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Wt));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=Wt(t[n]);return e}s(Yc,"addAdditionalPropertiesToJsonSchema");function Wt(e){return typeof e=="boolean"?e:Yc(e)}s(Wt,"visit");var UF=Symbol("Let zodToJsonSchema decide on which parser to use"),Xc={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"},VF=s(e=>typeof e=="string"?{...Xc,name:e}:{...Xc,...e},"getDefaultOptions");function Ke(){return{}}s(Ke,"parseAnyDef");function GF(e,t){var n,r,a;const i={type:"array"};return(n=e.type)!=null&&n._def&&((a=(r=e.type)==null?void 0:r._def)==null?void 0:a.typeName)!==Y.ZodAny&&(i.items=ce(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}s(GF,"parseArrayDef");function WF(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}s(WF,"parseBigintDef");function HF(){return{type:"boolean"}}s(HF,"parseBooleanDef");function Qc(e,t){return ce(e.type._def,t)}s(Qc,"parseBrandedDef");var JF=s((e,t)=>ce(e.innerType._def,t),"parseCatchDef");function ep(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,i)=>ep(e,t,a))};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 KF(e)}}s(ep,"parseDateDef");var KF=s(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 YF(e,t){return{...ce(e.innerType._def,t),default:e.defaultValue()}}s(YF,"parseDefaultDef");function XF(e,t){return t.effectStrategy==="input"?ce(e.schema._def,t):Ke()}s(XF,"parseEffectsDef");function QF(e){return{type:"string",enum:Array.from(e.values)}}s(QF,"parseEnumDef");var e2=s(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function t2(e,t){const n=[ce(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ce(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),r=[];return n.forEach(a=>{if(e2(a))r.push(...a.allOf);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}r.push(i)}}),r.length?{allOf:r}:void 0}s(t2,"parseIntersectionDef");function n2(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}}s(n2,"parseLiteralDef");var ri=void 0,st={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:s(()=>(ri===void 0&&(ri=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ri),"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 tp(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":ut(n,"email",r.message,t);break;case"format:idn-email":ut(n,"idn-email",r.message,t);break;case"pattern:zod":Ze(n,st.email,r.message,t);break}break;case"url":ut(n,"uri",r.message,t);break;case"uuid":ut(n,"uuid",r.message,t);break;case"regex":Ze(n,r.regex,r.message,t);break;case"cuid":Ze(n,st.cuid,r.message,t);break;case"cuid2":Ze(n,st.cuid2,r.message,t);break;case"startsWith":Ze(n,RegExp(`^${oi(r.value,t)}`),r.message,t);break;case"endsWith":Ze(n,RegExp(`${oi(r.value,t)}$`),r.message,t);break;case"datetime":ut(n,"date-time",r.message,t);break;case"date":ut(n,"date",r.message,t);break;case"time":ut(n,"time",r.message,t);break;case"duration":ut(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":{Ze(n,RegExp(oi(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&ut(n,"ipv4",r.message,t),r.version!=="v4"&&ut(n,"ipv6",r.message,t);break}case"base64url":Ze(n,st.base64url,r.message,t);break;case"jwt":Ze(n,st.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Ze(n,st.ipv4Cidr,r.message,t),r.version!=="v4"&&Ze(n,st.ipv6Cidr,r.message,t);break}case"emoji":Ze(n,st.emoji(),r.message,t);break;case"ulid":{Ze(n,st.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ut(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Ze(n,st.base64,r.message,t);break}}break}case"nanoid":Ze(n,st.nanoid,r.message,t)}return n}s(tp,"parseStringDef");function oi(e,t){return t.patternStrategy==="escape"?o2(e):e}s(oi,"escapeLiteralCheckValue");var r2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function o2(e){let t="";for(let n=0;n<e.length;n++)r2.has(e[n])||(t+="\\"),t+=e[n];return t}s(o2,"escapeNonAlphaNumeric");function ut(e,t,n,r){var a;e.format||(a=e.anyOf)!=null&&a.some(i=>i.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}s(ut,"addFormat");function Ze(e,t,n,r){var a;e.pattern||(a=e.allOf)!=null&&a.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:np(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=np(t,r)}s(Ze,"addPattern");function np(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")},a=r.i?e.source.toLowerCase():e.source;let i="",o=!1,u=!1,l=!1;for(let c=0;c<a.length;c++){if(o){i+=a[c],o=!1;continue}if(r.i){if(u){if(a[c].match(/[a-z]/)){l?(i+=a[c],i+=`${a[c-2]}-${a[c]}`.toUpperCase(),l=!1):a[c+1]==="-"&&((n=a[c+2])!=null&&n.match(/[a-z]/))?(i+=a[c],l=!0):i+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){i+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){i+=`(^|(?<=[\r
|
|
119
|
+
]))`;continue}else if(a[c]==="$"){i+=`($|(?=[\r
|
|
120
|
+
]))`;continue}}if(r.s&&a[c]==="."){i+=u?`${a[c]}\r
|
|
121
|
+
`:`[${a[c]}\r
|
|
122
|
+
]`;continue}i+=a[c],a[c]==="\\"?o=!0:u&&a[c]==="]"?u=!1:!u&&a[c]==="["&&(u=!0)}try{new RegExp(i)}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 i}s(np,"stringifyRegExpWithFlags");function rp(e,t){var n,r,a,i,o,u;const l={type:"object",additionalProperties:(n=ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===Y.ZodString&&((a=e.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=tp(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===Y.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((o=e.keyType)==null?void 0:o._def.typeName)===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Qc(e.keyType._def,t);return{...l,propertyNames:d}}}return l}s(rp,"parseRecordDef");function a2(e,t){if(t.mapStrategy==="record")return rp(e,t);const n=ce(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(),r=ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}s(a2,"parseMapDef");function i2(e){const t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),a=Array.from(new Set(r.map(i=>typeof i)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}s(i2,"parseNativeEnumDef");function s2(){return{not:Ke()}}s(s2,"parseNeverDef");function u2(){return{type:"null"}}s(u2,"parseNullDef");var ai={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function l2(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in ai&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((a,i)=>{const o=ai[i._def.typeName];return o&&!a.includes(o)?[...a,o]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((a,i)=>{const o=typeof i._def.value;switch(o){case"string":case"number":case"boolean":return[...a,o];case"bigint":return[...a,"integer"];case"object":if(i._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){const a=r.filter((i,o,u)=>u.indexOf(i)===o);return{type:a.length>1?a:a[0],enum:n.reduce((i,o)=>i.includes(o._def.value)?i:[...i,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(i=>!r.includes(i))],[])};return c2(e,t)}s(l2,"parseUnionDef");var c2=s((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,a)=>ce(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function p2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ai[e.innerType._def.typeName],"null"]};const n=ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}s(p2,"parseNullableDef");function d2(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}s(d2,"parseNumberDef");function m2(e,t){const n={type:"object",properties:{}},r=[],a=e.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;const l=h2(u),c=ce(u._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});c!==void 0&&(n.properties[o]=c,l||r.push(o))}r.length&&(n.required=r);const i=f2(e,t);return i!==void 0&&(n.additionalProperties=i),n}s(m2,"parseObjectDef");function f2(e,t){if(e.catchall._def.typeName!=="ZodNever")return ce(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}}s(f2,"decideAdditionalProperties");function h2(e){try{return e.isOptional()}catch{return!0}}s(h2,"safeIsOptional");var D2=s((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return ce(e.innerType._def,t);const r=ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke()},r]}:Ke()},"parseOptionalDef"),g2=s((e,t)=>{if(t.pipeStrategy==="input")return ce(e.in._def,t);if(t.pipeStrategy==="output")return ce(e.out._def,t);const n=ce(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=ce(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}},"parsePipelineDef");function v2(e,t){return ce(e.type._def,t)}s(v2,"parsePromiseDef");function y2(e,t){const r={type:"array",uniqueItems:!0,items:ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}s(y2,"parseSetDef");function _2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>ce(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ce(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>ce(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}s(_2,"parseTupleDef");function F2(){return{not:Ke()}}s(F2,"parseUndefinedDef");function C2(){return Ke()}s(C2,"parseUnknownDef");var b2=s((e,t)=>ce(e.innerType._def,t),"parseReadonlyDef"),E2=s((e,t,n)=>{switch(t){case Y.ZodString:return tp(e,n);case Y.ZodNumber:return d2(e);case Y.ZodObject:return m2(e,n);case Y.ZodBigInt:return WF(e);case Y.ZodBoolean:return HF();case Y.ZodDate:return ep(e,n);case Y.ZodUndefined:return F2();case Y.ZodNull:return u2();case Y.ZodArray:return GF(e,n);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return l2(e,n);case Y.ZodIntersection:return t2(e,n);case Y.ZodTuple:return _2(e,n);case Y.ZodRecord:return rp(e,n);case Y.ZodLiteral:return n2(e);case Y.ZodEnum:return QF(e);case Y.ZodNativeEnum:return i2(e);case Y.ZodNullable:return p2(e,n);case Y.ZodOptional:return D2(e,n);case Y.ZodMap:return a2(e,n);case Y.ZodSet:return y2(e,n);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return v2(e,n);case Y.ZodNaN:case Y.ZodNever:return s2();case Y.ZodEffects:return XF(e,n);case Y.ZodAny:return Ke();case Y.ZodUnknown:return C2();case Y.ZodDefault:return YF(e,n);case Y.ZodBranded:return Qc(e,n);case Y.ZodReadonly:return b2(e,n);case Y.ZodCatch:return JF(e,n);case Y.ZodPipeline:return g2(e,n);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),w2=s((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 ce(e,t,n=!1){var r;const a=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,a,n);if(l!==UF)return l}if(a&&!n){const l=A2(a,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const o=E2(e,e.typeName,t),u=typeof o=="function"?ce(o(),t):o;if(u&&I2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return i.jsonSchema=u,l}return i.jsonSchema=u,u}s(ce,"parseDef");var A2=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:w2(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`),Ke()):t.$refStrategy==="seen"?Ke():void 0}},"get$ref"),I2=s((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),x2=s(e=>{const t=VF(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,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),k2=s((e,t)=>{var n;const r=x2(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,m])=>{var h;return{...c,[d]:(h=ce(m._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:Ke()}},{}):void 0;const i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=(n=ce(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1))!=null?n:Ke(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(o.title=u);const l=i===void 0?a?{...o,[r.definitionPath]:a}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...a,[i]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),ii=Symbol.for("vercel.ai.schema");function K(e){let t;return()=>(t==null&&(t=e()),t)}s(K,"lazySchema");function Co(e,{validate:t}={}){return{[ii]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s(Co,"jsonSchema");function $2(e){return typeof e=="object"&&e!==null&&ii in e&&e[ii]===!0&&"jsonSchema"in e&&"validate"in e}s($2,"isSchema");function mn(e){return e==null?Co({properties:{},additionalProperties:!1}):$2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?H(e):T2(e):e()}s(mn,"asSchema");function T2(e){return Co(()=>e["~standard"].jsonSchema.input({target:"draft-07"}),{validate:s(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new zt({value:t,cause:n.issues})}},"validate")})}s(T2,"standardSchema");function B2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Co(()=>k2(e,{$refStrategy:r?"root":"none"}),{validate:s(async a=>{const i=await e.safeParseAsync(a);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(B2,"zod3Schema");function S2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Co(()=>Yc(g_(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:s(async a=>{const i=await kc(e,a);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(S2,"zod4Schema");function O2(e){return"_zod"in e}s(O2,"isZod4Schema");function H(e,t){return O2(e)?S2(e):B2(e)}s(H,"zodSchema");async function tt({value:e,schema:t}){const n=await lt({value:e,schema:t});if(!n.success)throw zt.wrap({value:e,cause:n.error});return n.value}s(tt,"validateTypes");async function lt({value:e,schema:t}){const n=mn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:zt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:zt.wrap({value:e,cause:r}),rawValue:e}}}s(lt,"safeValidateTypes");async function R2({text:e,schema:t}){try{const n=ni(e);return t==null?n:tt({value:n,schema:t})}catch(n){throw so.isInstance(n)||zt.isInstance(n)?n:new so({text:e,cause:n})}}s(R2,"parseJSON");async function ct({text:e,schema:t}){try{const n=ni(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(n){return{success:!1,error:so.isInstance(n)?n:new so({text:e,cause:n}),rawValue:void 0}}}s(ct,"safeParseJSON");function bo(e){try{return ni(e),!0}catch{return!1}}s(bo,"isParsableJson");function N2({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Qa).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await ct({text:n,schema:t}))}}))}s(N2,"parseJsonEventStream");async function Ve({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await lt({value:t[e],schema:n});if(!r.success)throw new _l({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}s(Ve,"parseProviderOptions");var P2=s(()=>globalThis.fetch,"getOriginalFetch2"),Se=s(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:i,fetch:o})=>op({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:i,fetch:o}),"postJsonToApi"),si=s(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:a,abortSignal:i,fetch:o})=>op({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:a,abortSignal:i,fetch:o}),"postFormDataToApi"),op=s(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:a,abortSignal:i,fetch:o=P2()})=>{try{const u=await o(e,{method:"POST",headers:Gt(t,`ai-sdk/provider-utils/${Hc}`,ti()),body:n.content,signal:i}),l=cn(u);if(!u.ok){let c;try{c=await a({response:u,url:e,requestBodyValues:n.values})}catch(d){throw dn(d)||Re.isInstance(d)?d:new Re({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&&(dn(c)||Re.isInstance(c))?c:new Re({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw Wc({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function X1(e){return e}s(X1,"tool");function yt({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:a,needsApproval:i,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:a,needsApproval:i,toModelOutput:o,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}s(yt,"createProviderToolFactoryWithOutputSchema");async function nt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}s(nt,"resolve");var rt=s(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:a,requestBodyValues:i})=>{const o=await r.text(),u=cn(r);if(o.trim()==="")return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:i,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})};try{const l=await R2({text:o,schema:e});return{responseHeaders:u,value:new Re({message:t(l),url:a,requestBodyValues:i,statusCode:r.status,responseHeaders:u,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Re({message:r.statusText,url:a,requestBodyValues:i,statusCode:r.status,responseHeaders:u,responseBody:o,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),fn=s(e=>async({response:t})=>{const n=cn(t);if(t.body==null)throw new fv({});return{responseHeaders:n,value:N2({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Pe=s(e=>async({response:t,url:n,requestBodyValues:r})=>{const a=await t.text(),i=await ct({text:a,schema:e}),o=cn(t);if(!i.success)throw new Re({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:o,responseBody:a,url:n,requestBodyValues:r});return{responseHeaders:o,value:i.value,rawValue:i.rawValue}},"createJsonResponseHandler"),M2=s(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=cn(e);if(!e.body)throw new Re({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const a=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(a)}}catch(a){throw new Re({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:a})}},"createBinaryResponseHandler");function ui(e){return e?.replace(/\/$/,"")}s(ui,"withoutTrailingSlash");function j2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}s(j2,"isAsyncIterable");async function*z2({execute:e,input:t,options:n}){const r=e(t,n);if(j2(r)){let a;for await(const i of r)a=i,yield{type:"preliminary",output:i};yield{type:"final",output:a}}else yield{type:"final",output:await r}}s(z2,"executeTool");var li,ap;function ip(){if(ap)return li;ap=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=s((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),i=s((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:s(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=s(d=>i(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{SYMBOL_FOR_REQ_CONTEXT:s(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:s(()=>c,"getContext")}),li=o(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return s(c,"getContext"),li}s(ip,"requireGetContext");var ci,sp;function up(){if(sp)return ci;sp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=s((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),i=s((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:s(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=s(d=>i(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{VercelOidcTokenError:s(()=>l,"VercelOidcTokenError")}),ci=o(u);const c=class c extends Error{constructor(m,h){super(m),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};s(c,"VercelOidcTokenError");let l=c;return ci}s(up,"requireTokenError");var pi,lp;function q2(){if(lp)return pi;lp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=s((h,D)=>{for(var f in D)e(h,f,{get:D[f],enumerable:!0})},"__export"),i=s((h,D,f,g)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==f&&e(h,y,{get:s(()=>D[y],"get"),enumerable:!(g=t(D,y))||g.enumerable});return h},"__copyProps"),o=s(h=>i(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};a(u,{getVercelOidcToken:s(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:s(()=>m,"getVercelOidcTokenSync")}),pi=o(u);var l=ip(),c=up();async function d(){let h="",D;try{h=m()}catch(f){D=f}try{const[{getTokenPayload:f,isExpired:g},{refreshToken:y}]=await Promise.all([await import("./token-util-daVwaNP6.mjs").then(function(F){return F.t}),await import("./token-BU4WbpuT.mjs").then(function(F){return F.t})]);(!h||g(f(h)))&&(await y(),h=m())}catch(f){let g=D instanceof Error?D.message:"";throw f instanceof Error&&(g=`${g}
|
|
123
|
+
${f.message}`),g?new c.VercelOidcTokenError(g):f}return h}s(d,"getVercelOidcToken");function m(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return s(m,"getVercelOidcTokenSync"),pi}s(q2,"requireGetVercelOidcToken");var di,cp;function Z2(){if(cp)return di;cp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,a=s((d,m)=>{for(var h in m)e(d,h,{get:m[h],enumerable:!0})},"__export"),i=s((d,m,h,D)=>{if(m&&typeof m=="object"||typeof m=="function")for(let f of n(m))!r.call(d,f)&&f!==h&&e(d,f,{get:s(()=>m[f],"get"),enumerable:!(D=t(m,f))||D.enumerable});return d},"__copyProps"),o=s(d=>i(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};a(u,{getContext:s(()=>c.getContext,"getContext"),getVercelOidcToken:s(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:s(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),di=o(u);var l=q2(),c=ip();return di}s(Z2,"requireDist");var pp=Z2(),L2="vercel.ai.gateway.error",mi=Symbol.for(L2),dp,mp,Ye=(Yt=class extends(mp=Error,dp=mi,mp){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[dp]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return Yt.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&mi in t&&t[mi]===!0}},s(Yt,"_GatewayError"),Yt),fp="GatewayAuthenticationError",U2=`vercel.ai.gateway.error.${fp}`,hp=Symbol.for(U2),Dp,gp,fi=(Xt=class extends(gp=Ye,Dp=hp,gp){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Dp]=!0,this.name=fp,this.type="authentication_error"}static isInstance(t){return Ye.hasMarker(t)&&hp in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:a=401,cause:i}){let o;return t?o=`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?o=`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`:o=`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 Xt({message:o,statusCode:a,cause:i})}},s(Xt,"_GatewayAuthenticationError"),Xt),vp="GatewayInvalidRequestError",V2=`vercel.ai.gateway.error.${vp}`,yp=Symbol.for(V2),_p,Fp,G2=(xn=class extends(Fp=Ye,_p=yp,Fp){constructor({message:t="Invalid request",statusCode:n=400,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[_p]=!0,this.name=vp,this.type="invalid_request_error"}static isInstance(t){return Ye.hasMarker(t)&&yp in t}},s(xn,"GatewayInvalidRequestError"),xn),Cp="GatewayRateLimitError",W2=`vercel.ai.gateway.error.${Cp}`,bp=Symbol.for(W2),Ep,wp,H2=(kn=class extends(wp=Ye,Ep=bp,wp){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Ep]=!0,this.name=Cp,this.type="rate_limit_exceeded"}static isInstance(t){return Ye.hasMarker(t)&&bp in t}},s(kn,"GatewayRateLimitError"),kn),Ap="GatewayModelNotFoundError",J2=`vercel.ai.gateway.error.${Ap}`,Ip=Symbol.for(J2),K2=K(()=>H(v({modelId:p()}))),xp,kp,Y2=($n=class extends(kp=Ye,xp=Ip,kp){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:a}={}){super({message:t,statusCode:n,cause:a}),this[xp]=!0,this.name=Ap,this.type="model_not_found",this.modelId=r}static isInstance(t){return Ye.hasMarker(t)&&Ip in t}},s($n,"GatewayModelNotFoundError"),$n),$p="GatewayInternalServerError",X2=`vercel.ai.gateway.error.${$p}`,Tp=Symbol.for(X2),Bp,Sp,Op=(Tn=class extends(Sp=Ye,Bp=Tp,Sp){constructor({message:t="Internal server error",statusCode:n=500,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Bp]=!0,this.name=$p,this.type="internal_server_error"}static isInstance(t){return Ye.hasMarker(t)&&Tp in t}},s(Tn,"GatewayInternalServerError"),Tn),Rp="GatewayResponseError",Q2=`vercel.ai.gateway.error.${Rp}`,Np=Symbol.for(Q2),Pp,Mp,eC=(Bn=class extends(Mp=Ye,Pp=Np,Mp){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:a,cause:i}={}){super({message:t,statusCode:n,cause:i}),this[Pp]=!0,this.name=Rp,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return Ye.hasMarker(t)&&Np in t}},s(Bn,"GatewayResponseError"),Bn);async function jp({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:a}){const i=await lt({value:e,schema:tC});if(!i.success)return new eC({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:i.error,cause:r});const o=i.value,u=o.error.type,l=o.error.message;switch(u){case"authentication_error":return fi.createContextualError({apiKeyProvided:a==="api-key",oidcTokenProvided:a==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new G2({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new H2({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await lt({value:o.error.param,schema:K2});return new Y2({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new Op({message:l,statusCode:t,cause:r});default:return new Op({message:l,statusCode:t,cause:r})}}s(jp,"createGatewayErrorFromResponse");var tC=K(()=>H(v({error:v({message:p(),type:p().nullish(),param:gt().nullish(),code:J([p(),A()]).nullish()})})));function kt(e,t){var n;return Ye.isInstance(e)?e:Re.isInstance(e)?jp({response:nC(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):jp({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}s(kt,"asGatewayError");function nC(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}s(nC,"extractApiCallResponse");var zp="ai-gateway-auth-method";async function hn(e){const t=await lt({value:e[zp],schema:rC});return t.success?t.value:void 0}s(hn,"parseAuthMethod");var rC=K(()=>H(J([I("api-key"),I("oidc")]))),qp=(Sn=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Jc({url:`${this.config.baseURL}/config`,headers:await nt(this.config.headers()),successfulResponseHandler:Pe(oC),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await kt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await Jc({url:`${t.origin}/v1/credits`,headers:await nt(this.config.headers()),successfulResponseHandler:Pe(aC),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await kt(t)}}},s(Sn,"GatewayFetchMetadata"),Sn),oC=K(()=>H(v({models:B(v({id:p(),name:p(),description:p().nullish(),pricing:v({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:v({specificationVersion:I("v3"),provider:p(),modelId:p()}),modelType:oe(["language","embedding","image"]).nullish()}))}))),aC=K(()=>H(v({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),iC=(On=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:a}=t,i=await nt(this.config.headers());try{const{responseHeaders:o,value:u,rawValue:l}=await Se({url:this.getUrl(),headers:xe(i,t.headers,this.getModelConfigHeaders(this.modelId,!1),await nt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Pe(qe()),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(c=>c,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:o,body:l},warnings:r}}catch(o){throw await kt(o,await hn(i))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,i=await nt(this.config.headers());try{const{value:o,responseHeaders:u}=await Se({url:this.getUrl(),headers:xe(i,t.headers,this.getModelConfigHeaders(this.modelId,!0),await nt(this.config.o11yHeaders)),body:n,successfulResponseHandler:fn(qe()),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(l=>l,"errorToMessage")}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:o.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(o){throw await kt(o,await hn(i))}}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 a=r;if(a.data instanceof Uint8Array){const i=Uint8Array.from(a.data),o=Buffer.from(i).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${o}`)}}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)}}},s(On,"GatewayLanguageModel"),On),sC=(Rn=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:a}){var i;const o=await nt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.getUrl(),headers:xe(o,n??{},this.getModelConfigHeaders(),await nt(this.config.o11yHeaders)),body:{values:t,...a?{providerOptions:a}:{}},successfulResponseHandler:Pe(uC),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(i=l.usage)!=null?i:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await kt(u,await hn(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},s(Rn,"GatewayEmbeddingModel"),Rn),uC=K(()=>H(v({embeddings:B(B(A())),usage:v({tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),gt())).optional()}))),lC=(Nn=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:a,seed:i,files:o,mask:u,providerOptions:l,headers:c,abortSignal:d}){var m;const h=await nt(this.config.headers());try{const{responseHeaders:D,value:f,rawValue:g}=await Se({url:this.getUrl(),headers:xe(h,c??{},this.getModelConfigHeaders(),await nt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...a&&{aspectRatio:a},...i&&{seed:i},...l&&{providerOptions:l},...o&&{files:o.map(y=>Zp(y))},...u&&{mask:Zp(u)}},successfulResponseHandler:Pe(pC),failedResponseHandler:rt({errorSchema:qe(),errorToMessage:s(y=>y,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:f.images,warnings:(m=f.warnings)!=null?m:[],providerMetadata:f.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:D}}}catch(D){throw kt(D,await hn(h))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},s(Nn,"GatewayImageModel"),Nn);function Zp(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Ir(e.data)}:e}s(Zp,"maybeEncodeImageFile");var cC=v({images:B(gt()).optional()}).catchall(gt()),pC=v({images:B(p()),warnings:B(v({type:I("other"),message:p()})).optional(),providerMetadata:me(p(),cC).optional()});async function dC(){var e;return(e=pp.getContext().headers)==null?void 0:e["x-vercel-id"]}s(dC,"getVercelRequestId");var mC="3.0.9",fC="0.0.1";function hC(e={}){var t,n;let r=null,a=null;const i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let o=0;const u=(n=ui(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=s(async()=>{try{const g=await gC(e);return Gt({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":fC,[zp]:g.authMethod,...e.headers},`ai-sdk/gateway/${mC}`)}catch(g){throw fi.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:g})}},"getHeaders"),c=s(()=>{const g=kr({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=kr({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),F=kr({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await dC();return{...g&&{"ai-o11y-deployment-id":g},...y&&{"ai-o11y-environment":y},...F&&{"ai-o11y-region":F},...w&&{"ai-o11y-request-id":w}}}},"createO11yHeaders"),d=s(g=>new iC(g,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),m=s(async()=>{var g,y,F;const w=(F=(y=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:y.call(g).getTime())!=null?F:Date.now();return(!r||w-o>i)&&(o=w,r=new qp({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(a=b,b)).catch(async b=>{throw await kt(b,await hn(await l()))})),a?Promise.resolve(a):r},"getAvailableModels"),h=s(async()=>new qp({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async g=>{throw await kt(g,await hn(await l()))}),"getCredits"),D=s(function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(g)},"provider");D.specificationVersion="v3",D.getAvailableModels=m,D.getCredits=h,D.imageModel=g=>new lC(g,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const f=s(g=>new sC(g,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=f,D.textEmbeddingModel=f,D}s(hC,"createGatewayProvider");var DC=hC();async function gC(e){const t=kr({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await pp.getVercelOidcToken(),authMethod:"oidc"}}s(gC,"getGatewayAuthToken");var vC=typeof globalThis=="object"?globalThis:global,Ht="1.9.0",Lp=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function yC(e){var t=new Set([e]),n=new Set,r=e.match(Lp);if(!r)return function(){return!1};var a={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(a.prerelease!=null)return s(function(l){return l===e},"isExactmatch");function i(u){return n.add(u),!1}s(i,"_reject");function o(u){return t.add(u),!0}return s(o,"_accept"),s(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(Lp);if(!c)return i(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||a.major!==d.major?i(l):a.major===0?a.minor===d.minor&&a.patch<=d.patch?o(l):i(l):a.minor<=d.minor?o(l):i(l)},"isCompatible2")}s(yC,"_makeCompatibilityCheck");var _C=yC(Ht),FC=Ht.split(".")[0],$r=Symbol.for("opentelemetry.js.api."+FC),Tr=vC;function hi(e,t,n,r){var a;r===void 0&&(r=!1);var i=Tr[$r]=(a=Tr[$r])!==null&&a!==void 0?a:{version:Ht};if(!r&&i[e]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(o.stack||o.message),!1}if(i.version!==Ht){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+Ht);return n.error(o.stack||o.message),!1}return i[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ht+"."),!0}s(hi,"registerGlobal");function Br(e){var t,n,r=(t=Tr[$r])===null||t===void 0?void 0:t.version;if(!(!r||!_C(r)))return(n=Tr[$r])===null||n===void 0?void 0:n[e]}s(Br,"getGlobal");function Di(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ht+".");var n=Tr[$r];n&&delete n[e]}s(Di,"unregisterGlobal");var CC=s(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},"__read$3"),bC=s(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},"__spreadArray$3"),EC=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return s(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Sr("verbose",this._namespace,t)},e})();function Sr(e,t,n){var r=Br("diag");if(r)return n.unshift(t),r[e].apply(r,bC([],CC(n),!1))}s(Sr,"logProxy");var Xe;(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"})(Xe||(Xe={}));function wC(e,t){e<Xe.NONE?e=Xe.NONE:e>Xe.ALL&&(e=Xe.ALL),t=t||{};function n(r,a){var i=t[r];return typeof i=="function"&&e>=a?i.bind(t):function(){}}return s(n,"_filterFunc"),{error:n("error",Xe.ERROR),warn:n("warn",Xe.WARN),info:n("info",Xe.INFO),debug:n("debug",Xe.DEBUG),verbose:n("verbose",Xe.VERBOSE)}}s(wC,"createLogLevelDiagLogger");var AC=s(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},"__read$2"),IC=s(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},"__spreadArray$2"),xC="diag",Eo=(function(){function e(){function t(a){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var u=Br("diag");if(u)return u[a].apply(u,IC([],AC(i),!1))}}s(t,"_logProxy");var n=this,r=s(function(a,i){var o,u,l;if(i===void 0&&(i={logLevel:Xe.INFO}),a===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((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof i=="number"&&(i={logLevel:i});var d=Br("diag"),m=wC((u=i.logLevel)!==null&&u!==void 0?u:Xe.INFO,a);if(d&&!i.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),m.warn("Current logger will overwrite one already registered from "+h)}return hi("diag",m,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){Di(xC,n)},n.createComponentLogger=function(a){return new EC(a)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return s(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function kC(e){return Symbol.for(e)}s(kC,"createContextKey");var $C=(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,a){var i=new e(n._currentContext);return i._currentContext.set(r,a),i},n.deleteValue=function(r){var a=new e(n._currentContext);return a._currentContext.delete(r),a}}return s(e,"BaseContext2"),e})(),TC=new $C,BC=s(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},"__read$1"),SC=s(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},"__spreadArray$1"),OC=(function(){function e(){}return s(e,"NoopContextManager2"),e.prototype.active=function(){return TC},e.prototype.with=function(t,n,r){for(var a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return n.call.apply(n,SC([r],BC(a),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),RC=s(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(u){o={error:u}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},"__read"),NC=s(function(e,t,n){if(arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},"__spreadArray"),gi="context",PC=new OC,Up=(function(){function e(){}return s(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return hi(gi,t,Eo.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var a,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,NC([t,n,r],RC(i),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Br(gi)||PC},e.prototype.disable=function(){this._getContextManager().disable(),Di(gi,Eo.instance())},e})(),vi;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(vi||(vi={}));var Vp="0000000000000000",Gp="00000000000000000000000000000000",MC={traceId:Gp,spanId:Vp,traceFlags:vi.NONE},Or=(function(){function e(t){t===void 0&&(t=MC),this._spanContext=t}return s(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})(),yi=kC("OpenTelemetry Context Key SPAN");function _i(e){return e.getValue(yi)||void 0}s(_i,"getSpan");function jC(){return _i(Up.getInstance().active())}s(jC,"getActiveSpan");function Fi(e,t){return e.setValue(yi,t)}s(Fi,"setSpan");function zC(e){return e.deleteValue(yi)}s(zC,"deleteSpan");function qC(e,t){return Fi(e,new Or(t))}s(qC,"setSpanContext");function Wp(e){var t;return(t=_i(e))===null||t===void 0?void 0:t.spanContext()}s(Wp,"getSpanContext");var ZC=/^([0-9a-f]{32})$/i,LC=/^[0-9a-f]{16}$/i;function UC(e){return ZC.test(e)&&e!==Gp}s(UC,"isValidTraceId");function VC(e){return LC.test(e)&&e!==Vp}s(VC,"isValidSpanId");function Hp(e){return UC(e.traceId)&&VC(e.spanId)}s(Hp,"isSpanContextValid");function GC(e){return new Or(e)}s(GC,"wrapSpanContext");var Ci=Up.getInstance(),Jp=(function(){function e(){}return s(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=Ci.active());var a=!!n?.root;if(a)return new Or;var i=r&&Wp(r);return WC(i)&&Hp(i)?new Or(i):new Or},e.prototype.startActiveSpan=function(t,n,r,a){var i,o,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(i=n,u=r):(i=n,o=r,u=a);var l=o??Ci.active(),c=this.startSpan(t,i,l),d=Fi(l,c);return Ci.with(d,u,void 0,c)}},e})();function WC(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}s(WC,"isSpanContext");var HC=new Jp,JC=(function(){function e(t,n,r,a){this._provider=t,this.name=n,this.version=r,this.options=a}return s(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,a){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,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):HC},e})(),KC=(function(){function e(){}return s(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Jp},e})(),YC=new KC,Kp=(function(){function e(){}return s(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var a;return(a=this.getDelegateTracer(t,n,r))!==null&&a!==void 0?a:new JC(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:YC},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(t,n,r)},e})(),wo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(wo||(wo={}));var bi="trace",XC=(function(){function e(){this._proxyTracerProvider=new Kp,this.wrapSpanContext=GC,this.isSpanContextValid=Hp,this.deleteSpan=zC,this.getSpan=_i,this.getActiveSpan=jC,this.getSpanContext=Wp,this.setSpan=Fi,this.setSpanContext=qC}return s(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=hi(bi,this._proxyTracerProvider,Eo.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Br(bi)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Di(bi,Eo.instance()),this._proxyTracerProvider=new Kp},e})(),QC=XC.getInstance(),eb=Object.defineProperty,tb=s((e,t)=>{for(var n in t)eb(e,n,{get:t[n],enumerable:!0})},"__export"),Yp="AI_InvalidArgumentError",Xp=`vercel.ai.error.${Yp}`,nb=Symbol.for(Xp),Qp,_t=(Pn=class extends W{constructor({parameter:t,value:n,message:r}){super({name:Yp,message:`Invalid argument for parameter ${t}: ${r}`}),this[Qp]=!0,this.parameter=t,this.value=n}static isInstance(t){return W.hasMarker(t,Xp)}},s(Pn,"InvalidArgumentError"),Pn);Qp=nb;var ed="AI_InvalidToolApprovalError",td=`vercel.ai.error.${ed}`,rb=Symbol.for(td),nd,ob=(Mn=class extends W{constructor({approvalId:t}){super({name:ed,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[nd]=!0,this.approvalId=t}static isInstance(t){return W.hasMarker(t,td)}},s(Mn,"InvalidToolApprovalError"),Mn);nd=rb;var rd="AI_InvalidToolInputError",od=`vercel.ai.error.${rd}`,ab=Symbol.for(od),ad,Ei=(jn=class extends W{constructor({toolInput:t,toolName:n,cause:r,message:a=`Invalid input for tool ${n}: ${yr(r)}`}){super({name:rd,message:a,cause:r}),this[ad]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return W.hasMarker(t,od)}},s(jn,"InvalidToolInputError"),jn);ad=ab;var id="AI_ToolCallNotFoundForApprovalError",sd=`vercel.ai.error.${id}`,ib=Symbol.for(sd),ud,ld=(zn=class extends W{constructor({toolCallId:t,approvalId:n}){super({name:id,message:`Tool call "${t}" not found for approval request "${n}".`}),this[ud]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return W.hasMarker(t,sd)}},s(zn,"ToolCallNotFoundForApprovalError"),zn);ud=ib;var cd="AI_NoObjectGeneratedError",pd=`vercel.ai.error.${cd}`,sb=Symbol.for(pd),dd,$t=(qn=class extends W{constructor({message:t="No object generated.",cause:n,text:r,response:a,usage:i,finishReason:o}){super({name:cd,message:t,cause:n}),this[dd]=!0,this.text=r,this.response=a,this.usage=i,this.finishReason=o}static isInstance(t){return W.hasMarker(t,pd)}},s(qn,"NoObjectGeneratedError"),qn);dd=sb;var md="AI_NoOutputGeneratedError",fd=`vercel.ai.error.${md}`,ub=Symbol.for(fd),hd,lb=(Zn=class extends W{constructor({message:t="No output generated.",cause:n}={}){super({name:md,message:t,cause:n}),this[hd]=!0}static isInstance(t){return W.hasMarker(t,fd)}},s(Zn,"NoOutputGeneratedError"),Zn);hd=ub;var Dd="AI_NoSuchToolError",gd=`vercel.ai.error.${Dd}`,cb=Symbol.for(gd),vd,wi=(Ln=class extends W{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:Dd,message:r}),this[vd]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return W.hasMarker(t,gd)}},s(Ln,"NoSuchToolError"),Ln);vd=cb;var yd="AI_ToolCallRepairError",_d=`vercel.ai.error.${yd}`,pb=Symbol.for(_d),Fd,db=(Un=class extends W{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${yr(t)}`}){super({name:yd,message:r,cause:t}),this[Fd]=!0,this.originalError=n}static isInstance(t){return W.hasMarker(t,_d)}},s(Un,"ToolCallRepairError"),Un);Fd=pb;var mb=(Vn=class extends W{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}},s(Vn,"UnsupportedModelVersionError"),Vn),Cd="AI_InvalidMessageRoleError",bd=`vercel.ai.error.${Cd}`,fb=Symbol.for(bd),Ed,hb=(Gn=class extends W{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Cd,message:n}),this[Ed]=!0,this.role=t}static isInstance(t){return W.hasMarker(t,bd)}},s(Gn,"InvalidMessageRoleError"),Gn);Ed=fb;var wd="AI_RetryError",Ad=`vercel.ai.error.${wd}`,Db=Symbol.for(Ad),Id,xd=(Wn=class extends W{constructor({message:t,reason:n,errors:r}){super({name:wd,message:t}),this[Id]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return W.hasMarker(t,Ad)}},s(Wn,"RetryError"),Wn);Id=Db;function gb({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let a=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(a+=` ${e.details}`),a}case"compatibility":{let a=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(a+=` ${e.details}`),a}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}s(gb,"formatWarning");var vb="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",kd=!1,$d=s(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}kd||(kd=!0,console.info(vb));for(const n of e.warnings)console.warn(gb({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function yb({provider:e,modelId:t}){$d({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}s(yb,"logV2CompatibilityWarning");function _b(e){return e.specificationVersion==="v3"?e:(yb({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const a=await t.doGenerate(...r);return{...a,finishReason:Td(a.finishReason),usage:Bd(a.usage)}};case"doStream":return async(...r)=>{const a=await t.doStream(...r);return{...a,stream:Fb(a.stream)}};default:return t[n]}}}))}s(_b,"asLanguageModelV3");function Fb(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:Td(t.finishReason),usage:Bd(t.usage)});break;default:n.enqueue(t);break}}}))}s(Fb,"convertV2StreamToV3");function Td(e){return{unified:e==="unknown"?"other":e,raw:void 0}}s(Td,"convertV2FinishReasonToV3");function Bd(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}}}s(Bd,"convertV2UsageToV3");function Sd(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new mb({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return _b(e)}return Cb().languageModel(e)}s(Sd,"resolveLanguageModel");function Cb(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:DC}s(Cb,"getGlobalProvider");var bb=[{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]}],Eb=s(e=>{const t=typeof e=="string"?Ut(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 wb(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Eb(e):e}s(wb,"stripID3TagsIfPresent");function Ab({data:e,signatures:t}){const n=wb(e),r=typeof n=="string"?Ut(n.substring(0,Math.min(n.length,24))):n;for(const a of t)if(r.length>=a.bytesPrefix.length&&a.bytesPrefix.every((i,o)=>i===null||r[o]===i))return a.mediaType}s(Ab,"detectMediaType");var Od="6.0.13",Ib=s(async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Gt({},`ai-sdk/${Od}`,ti())});if(!r.ok)throw new pn({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw pn.isInstance(r)?r:new pn({url:n,cause:r})}},"download"),xb=s((e=Ib)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function kb(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}s(kb,"splitDataUrl");var Rd=J([p(),_o(Uint8Array),_o(ArrayBuffer),bF(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Nd(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}=kb(e.toString());if(t==null||n==null)throw new W({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}s(Nd,"convertToLanguageModelV3DataContent");function $b(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Ir(new Uint8Array(e)):Ir(e)}s($b,"convertDataContentToBase64String");function Ai(e){return e===void 0?[]:Array.isArray(e)?e:[e]}s(Ai,"asArray");async function Tb({prompt:e,supportedUrls:t,download:n=xb()}){const r=await Sb(e.messages,n,t),a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Ai(e.system).map(o=>({role:"system",content:o.content,providerOptions:o.providerOptions})):[],...e.messages.map(o=>Bb({message:o,downloadedAssets:r}))],i=[];for(const o of a){if(o.role!=="tool"){i.push(o);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...o.content):i.push(o)}return i}s(Tb,"convertToLanguageModelPrompt");function Bb({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=>Ob(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 a=r.providerOptions;switch(r.type){case"file":{const{data:i,mediaType:o}=Nd(r.data);return{type:"file",data:i,filename:r.filename,mediaType:o??r.mediaType,providerOptions:a}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:a};case"text":return{type:"text",text:r.text,providerOptions:a};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:a};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:Pd(r.output),providerOptions:a}}}),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:Pd(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 hb({role:r})}}}s(Bb,"convertToLanguageModelMessage");async function Sb(e,t,n){const r=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var o;const u=(o=i.mediaType)!=null?o:i.type==="image"?"image/*":void 0;let l=i.type==="image"?i.image:i.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&MF({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:n})})),a=await t(r);return Object.fromEntries(a.map((i,o)=>i==null?null:[r[o].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}s(Sb,"downloadAssets");function Ob(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const a=e.type;switch(a){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${a}`)}const{data:i,mediaType:o}=Nd(r);let u=o??e.mediaType,l=i;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(a){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=Ab({data:l,signatures:bb}))!=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}}}}s(Ob,"convertPartToLanguageModelPart");function Pd(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})}}s(Pd,"mapToolResultOutput");async function Ao({toolCallId:e,input:t,output:n,tool:r,errorMode:a}){return a==="text"?{type:"error-text",value:yr(n)}:a==="json"?{type:"error-json",value:Md(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:Md(n)}}s(Ao,"createToolModelOutput");function Md(e){return e===void 0?null:e}s(Md,"toJSONValue");function jd({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:i,seed:o,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new _t({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new _t({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new _t({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new _t({parameter:"topK",value:r,message:"topK must be a number"});if(a!=null&&typeof a!="number")throw new _t({parameter:"presencePenalty",value:a,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new _t({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new _t({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:a,frequencyPenalty:i,stopSequences:u,seed:o}}s(jd,"prepareCallSettings");function Rb(e){return e!=null&&Object.keys(e).length>0}s(Rb,"isNonEmptyObject");async function Nb({tools:e,toolChoice:t,activeTools:n}){if(!Rb(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([i])=>n.includes(i)):Object.entries(e),a=[];for(const[i,o]of r){const u=o.type;switch(u){case void 0:case"dynamic":case"function":a.push({type:"function",name:i,description:o.description,inputSchema:await mn(o.inputSchema).jsonSchema,...o.inputExamples!=null?{inputExamples:o.inputExamples}:{},providerOptions:o.providerOptions,...o.strict!=null?{strict:o.strict}:{}});break;case"provider":a.push({type:"provider",name:i,id:o.id,args:o.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:a,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}s(Nb,"prepareToolsAndToolChoice");var Rr=Ka(()=>J([Sc(),p(),A(),Ae(),me(p(),Rr.optional()),B(Rr)])),we=me(p(),me(p(),Rr.optional())),zd=v({type:I("text"),text:p(),providerOptions:we.optional()}),Pb=v({type:I("image"),image:J([Rd,_o(URL)]),mediaType:p().optional(),providerOptions:we.optional()}),qd=v({type:I("file"),data:J([Rd,_o(URL)]),filename:p().optional(),mediaType:p(),providerOptions:we.optional()}),Mb=v({type:I("reasoning"),text:p(),providerOptions:we.optional()}),jb=v({type:I("tool-call"),toolCallId:p(),toolName:p(),input:gt(),providerOptions:we.optional(),providerExecuted:Ae().optional()}),zb=Ie("type",[v({type:I("text"),value:p(),providerOptions:we.optional()}),v({type:I("json"),value:Rr,providerOptions:we.optional()}),v({type:I("execution-denied"),reason:p().optional(),providerOptions:we.optional()}),v({type:I("error-text"),value:p(),providerOptions:we.optional()}),v({type:I("error-json"),value:Rr,providerOptions:we.optional()}),v({type:I("content"),value:B(J([v({type:I("text"),text:p(),providerOptions:we.optional()}),v({type:I("media"),data:p(),mediaType:p()}),v({type:I("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:we.optional()}),v({type:I("file-url"),url:p(),providerOptions:we.optional()}),v({type:I("file-id"),fileId:J([p(),me(p(),p())]),providerOptions:we.optional()}),v({type:I("image-data"),data:p(),mediaType:p(),providerOptions:we.optional()}),v({type:I("image-url"),url:p(),providerOptions:we.optional()}),v({type:I("image-file-id"),fileId:J([p(),me(p(),p())]),providerOptions:we.optional()}),v({type:I("custom"),providerOptions:we.optional()})]))})]),Zd=v({type:I("tool-result"),toolCallId:p(),toolName:p(),output:zb,providerOptions:we.optional()}),qb=v({type:I("tool-approval-request"),approvalId:p(),toolCallId:p()}),Zb=v({type:I("tool-approval-response"),approvalId:p(),approved:Ae(),reason:p().optional()}),Lb=v({role:I("system"),content:p(),providerOptions:we.optional()}),Ub=v({role:I("user"),content:J([p(),B(J([zd,Pb,qd]))]),providerOptions:we.optional()}),Vb=v({role:I("assistant"),content:J([p(),B(J([zd,qd,Mb,jb,Zd,qb]))]),providerOptions:we.optional()}),Gb=v({role:I("tool"),content:B(J([Zd,Zb])),providerOptions:we.optional()}),Wb=J([Lb,Ub,Vb,Gb]);async function Hb(e){if(e.prompt==null&&e.messages==null)throw new At({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new At({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Ai(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new At({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 At({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new At({prompt:e,message:"messages must not be empty"});const n=await lt({value:t,schema:B(Wb)});if(!n.success)throw new At({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}s(Hb,"standardizePrompt");function Jb(e){if(!fi.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 W({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
|
|
139
|
+
|
|
140
|
+
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
141
|
+
|
|
142
|
+
Alternatively, you can use a provider module instead of the AI Gateway.
|
|
143
|
+
|
|
144
|
+
Learn more: \x1B[34m${n}\x1B[0m
|
|
145
|
+
|
|
146
|
+
`),{name:"GatewayAuthenticationError"})}s(Jb,"wrapGatewayError");function Ii({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}}s(Ii,"assembleOperationName");function Kb({model:e,settings:t,telemetry:n,headers:r}){var a;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[o,u])=>(i[`ai.settings.${o}`]=u,i),{}),...Object.entries((a=n?.metadata)!=null?a:{}).reduce((i,[o,u])=>(i[`ai.telemetry.metadata.${o}`]=u,i),{}),...Object.entries(r??{}).reduce((i,[o,u])=>(u!==void 0&&(i[`ai.request.headers.${o}`]=u),i),{})}}s(Kb,"getBaseTelemetryAttributes");var Yb={startSpan(){return Io},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Io);if(typeof n=="function")return n(Io);if(typeof r=="function")return r(Io)}},Io={spanContext(){return Xb},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}},Xb={traceId:"",spanId:"",traceFlags:0};function Qb({isEnabled:e=!1,tracer:t}={}){return e?t||QC.getTracer("ai"):Yb}s(Qb,"getTracer");async function xi({name:e,tracer:t,attributes:n,fn:r,endWhenDone:a=!0}){return t.startActiveSpan(e,{attributes:await n},async i=>{try{const o=await r(i);return a&&i.end(),o}catch(o){try{Ld(i,o)}finally{i.end()}throw o}})}s(xi,"recordSpan");function Ld(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:wo.ERROR,message:t.message})):e.setStatus({code:wo.ERROR})}s(Ld,"recordErrorOnSpan");async function Dn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,a]of Object.entries(t))if(a!=null){if(typeof a=="object"&&"input"in a&&typeof a.input=="function"){if(e?.recordInputs===!1)continue;const i=await a.input();i!=null&&(n[r]=i);continue}if(typeof a=="object"&&"output"in a&&typeof a.output=="function"){if(e?.recordOutputs===!1)continue;const i=await a.output();i!=null&&(n[r]=i);continue}n[r]=a}return n}s(Dn,"selectTelemetryAttributes");function eE(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?$b(n.data):n.data}:n)})))}s(eE,"stringifyForTelemetry");function tE(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:pt(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}s(tE,"asLanguageModelUsage");function nE(e,t){var n,r,a,i,o,u,l,c,d,m;return{inputTokens:pt(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:pt((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:pt((a=e.inputTokenDetails)==null?void 0:a.cacheReadTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheReadTokens),cacheWriteTokens:pt((o=e.inputTokenDetails)==null?void 0:o.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:pt(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:pt((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:pt((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:pt(e.totalTokens,t.totalTokens),reasoningTokens:pt(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:pt(e.cachedInputTokens,t.cachedInputTokens)}}s(nE,"addLanguageModelUsage");function pt(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}s(pt,"addTokenCounts");function Ud(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 a=t[r];if(a===void 0)continue;const i=r in e?e[r]:void 0,o=a!==null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp),u=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);o&&u?n[r]=Ud(i,a):n[r]=a}return n}s(Ud,"mergeObjects");function rE({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const a=n["retry-after-ms"];if(a){const o=parseFloat(a);Number.isNaN(o)||(r=o)}const i=n["retry-after"];if(i&&r===void 0){const o=parseFloat(i);Number.isNaN(o)?r=Date.parse(i)-Date.now():r=o*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}s(rE,"getRetryDelayInMs");var oE=s(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async a=>Vd(a,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function Vd(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:a},i=[]){try{return await e()}catch(o){if(dn(o)||t===0)throw o;const u=Gc(o),l=[...i,o],c=l.length;if(c>t)throw new xd({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Re.isInstance(o)&&o.isRetryable===!0&&c<=t)return await $F(rE({error:o,exponentialBackoffDelay:n}),{abortSignal:a}),Vd(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:a},l);throw c===1?o:new xd({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}s(Vd,"_retryWithExponentialBackoff");function aE({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new _t({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:oE({maxRetries:n,abortSignal:t})}}s(aE,"prepareRetries");function iE({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 a={};for(const l of t.content)l.type==="tool-result"&&(a[l.toolCallId]=l);const i=[],o=[],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 ob({approvalId:l.approvalId});if(a[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new ld({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?i.push(m):o.push(m)}return{approvedToolApprovals:i,deniedToolApprovals:o}}s(iE,"collectToolApprovals");async function sE({toolCall:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:i,experimental_context:o,onPreliminaryToolResult:u}){const{toolName:l,toolCallId:c,input:d}=e,m=t?.[l];if(m?.execute!=null)return xi({name:"ai.toolCall",attributes:Dn({telemetry:r,attributes:{...Ii({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:s(()=>JSON.stringify(d),"output")}}}),tracer:n,fn:s(async h=>{let D;try{const f=z2({execute:m.execute.bind(m),input:d,options:{toolCallId:c,messages:a,abortSignal:i,experimental_context:o}});for await(const g of f)g.type==="preliminary"?u?.({...e,type:"tool-result",output:g.output,preliminary:!0}):D=g.output}catch(f){return Ld(h,f),{type:"tool-error",toolCallId:c,toolName:l,input:d,error:f,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}try{h.setAttributes(await Dn({telemetry:r,attributes:{"ai.toolCall.result":{output:s(()=>JSON.stringify(D),"output")}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:d,output:D,dynamic:m.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}s(sE,"executeToolCall");function Gd(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}s(Gd,"extractTextContent");var uE=(Hn=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=Ir(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Ut(this.base64Data)),this.uint8ArrayData}},s(Hn,"DefaultGeneratedFile"),Hn);async function lE({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})}s(lE,"isApprovalNeeded");var cE={};tb(cE,{array:s(()=>mE,"array"),choice:s(()=>fE,"choice"),json:s(()=>hE,"json"),object:s(()=>dE,"object"),text:s(()=>Wd,"text")});function pE(e){const t=["ROOT"];let n=-1,r=null;function a(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}}}s(a,"processValueStart");function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}s(i,"processAfterObjectValue");function o(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}s(o,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":a(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":{a(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(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,a(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":{a(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"&&o(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(r,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(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}s(pE,"fixJson");async function xo(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await ct({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await ct({text:pE(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}s(xo,"parsePartialJson");var Wd=s(()=>({responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}}}),"text"),dE=s(({schema:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:nt(r.jsonSchema).then(a=>({type:"json",schema:a,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:a},i){const o=await ct({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:i.response,usage:i.usage,finishReason:i.finishReason});const u=await lt({value:o.value,schema:r});if(!u.success)throw new $t({message:"No object generated: response did not match schema.",cause:u.error,text:a,response:i.response,usage:i.usage,finishReason:i.finishReason});return u.value},async parsePartialOutput({text:a}){const i=await xo(a);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value}}}}},"object"),mE=s(({element:e,name:t,description:n})=>{const r=mn(e);return{responseFormat:nt(r.jsonSchema).then(a=>{const{$schema:i,...o}=a;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:o}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:a},i){const o=await ct({text:a});if(!o.success)throw new $t({message:"No object generated: could not parse the response.",cause:o.error,text:a,response:i.response,usage:i.usage,finishReason:i.finishReason});const u=o.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:u,cause:"response must be an object with an elements array"}),text:a,response:i.response,usage:i.usage,finishReason:i.finishReason});for(const l of u.elements){const c=await lt({value:l,schema:r});if(!c.success)throw new $t({message:"No object generated: response did not match schema.",cause:c.error,text:a,response:i.response,usage:i.usage,finishReason:i.finishReason})}return u.elements},async parsePartialOutput({text:a}){const i=await xo(a);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const o=i.value;if(o==null||typeof o!="object"||!("elements"in o)||!Array.isArray(o.elements))return;const u=i.state==="repaired-parse"&&o.elements.length>0?o.elements.slice(0,-1):o.elements,l=[];for(const c of u){const d=await lt({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}}}},"array"),fE=s(({options:e,name:t,description:n})=>({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},a){const i=await ct({text:r});if(!i.success)throw new $t({message:"No object generated: could not parse the response.",cause:i.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const o=i.value;if(o==null||typeof o!="object"||!("result"in o)||typeof o.result!="string"||!e.includes(o.result))throw new $t({message:"No object generated: response did not match schema.",cause:new zt({value:o,cause:"response must be an object that contains a choice value."}),text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return o.result},async parsePartialOutput({text:r}){const a=await xo(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=a.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string")return;const o=e.filter(u=>u.startsWith(i.result));return a.state==="successful-parse"?o.includes(i.result)?{partial:i.result}:void 0:o.length===1?{partial:o[0]}:void 0}}}}),"choice"),hE=s(({name:e,description:t}={})=>({responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const a=await ct({text:n});if(!a.success)throw new $t({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return a.value},async parsePartialOutput({text:n}){const r=await xo(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}}}}),"json");async function DE({toolCall:e,tools:t,repairToolCall:n,system:r,messages:a}){var i;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await Hd(e);throw new wi({toolName:e.toolName})}try{return await Jd({toolCall:e,tools:t})}catch(o){if(n==null||!(wi.isInstance(o)||Ei.isInstance(o)))throw o;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:s(async({toolName:l})=>{const{inputSchema:c}=t[l];return await mn(c).jsonSchema},"inputSchema"),system:r,messages:a,error:o})}catch(l){throw new db({cause:l,originalError:o})}if(u==null)throw o;return await Jd({toolCall:u,tools:t})}}catch(o){const u=await ct({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:o,title:(i=t?.[e.toolName])==null?void 0:i.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}s(DE,"parseToolCall");async function Hd(e){const t=e.input.trim()===""?{success:!0,value:{}}:await ct({text:e.input});if(t.success===!1)throw new Ei({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}}s(Hd,"parseProviderExecutedDynamicToolCall");async function Jd({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await Hd(e);throw new wi({toolName:e.toolName,availableTools:Object.keys(t)})}const a=mn(r.inputSchema),i=e.input.trim()===""?await lt({value:{},schema:a}):await ct({text:e.input,schema:a});if(i.success===!1)throw new Ei({toolName:n,toolInput:e.input,cause:i.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}s(Jd,"doParseToolCall");var gE=(Jn=class{constructor({content:t,finishReason:n,rawFinishReason:r,usage:a,warnings:i,request:o,response:u,providerMetadata:l}){this.content=t,this.finishReason=n,this.rawFinishReason=r,this.usage=a,this.warnings=i,this.request=o,this.response=u,this.providerMetadata=l}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)}},s(Jn,"DefaultStepResult"),Jn);function vE(e){return({steps:t})=>t.length===e}s(vE,"stepCountIs");async function yE({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}s(yE,"isStopConditionMet");async function _E({content:e,tools:t}){const n=[],r=[];for(const i of e)if(i.type!=="source"&&!((i.type==="tool-result"||i.type==="tool-error")&&!i.providerExecuted)&&!(i.type==="text"&&i.text.length===0))switch(i.type){case"text":r.push({type:"text",text:i.text,providerOptions:i.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:i.text,providerOptions:i.providerMetadata});break;case"file":r.push({type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata});break;case"tool-result":{const o=await Ao({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:o,providerOptions:i.providerMetadata});break}case"tool-error":{const o=await Ao({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:o,providerOptions:i.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:i.approvalId,toolCallId:i.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const a=[];for(const i of e){if(!(i.type==="tool-result"||i.type==="tool-error")||i.providerExecuted)continue;const o=await Ao({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"});a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:o,...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}})}return a.length>0&&n.push({role:"tool",content:a}),n}s(_E,"toResponseMessages");var FE=xr({prefix:"aitxt",size:24});async function Nr({model:e,tools:t,toolChoice:n,system:r,prompt:a,messages:i,maxRetries:o,abortSignal:u,headers:l,stopWhen:c=vE(1),experimental_output:d,output:m=d,experimental_telemetry:h,providerOptions:D,experimental_activeTools:f,activeTools:g=f,experimental_prepareStep:y,prepareStep:F=y,experimental_repairToolCall:w,experimental_download:b,experimental_context:E,_internal:{generateId:O=FE,currentDate:k=s(()=>new Date,"currentDate")}={},onStepFinish:C,onFinish:L,...Q}){const S=Sd(e),P=Ai(c),{maxRetries:$,retry:M}=aE({maxRetries:o,abortSignal:u}),Z=jd(Q),R=Gt(l??{},`ai/${Od}`),q=Kb({model:S,telemetry:h,headers:R,settings:{...Z,maxRetries:$}}),ee=await Hb({system:r,prompt:a,messages:i}),ae=Qb(h);try{return await xi({name:"ai.generateText",attributes:Dn({telemetry:h,attributes:{...Ii({operationId:"ai.generateText",telemetry:h}),...q,"ai.model.provider":S.provider,"ai.model.id":S.modelId,"ai.prompt":{input:s(()=>JSON.stringify({system:r,prompt:a,messages:i}),"input")}}}),tracer:ae,fn:s(async V=>{var X,G,te,le,ot,Oe,Ft,ie;const mt=ee.messages,at=[],{approvedToolApprovals:vt,deniedToolApprovals:Ct}=iE({messages:mt}),j=vt.filter(De=>!De.toolCall.providerExecuted);if(Ct.length>0||j.length>0){const De=await Kd({toolCalls:j.map(T=>T.toolCall),tools:t,tracer:ae,telemetry:h,messages:mt,abortSignal:u,experimental_context:E}),_=[];for(const T of De){const be=await Ao({toolCallId:T.toolCallId,input:T.input,tool:t?.[T.toolName],output:T.type==="tool-result"?T.output:T.error,errorMode:T.type==="tool-error"?"json":"none"});_.push({type:"tool-result",toolCallId:T.toolCallId,toolName:T.toolName,output:be})}for(const T of Ct)_.push({type:"tool-result",toolCallId:T.toolCall.toolCallId,toolName:T.toolCall.toolName,output:{type:"execution-denied",reason:T.approvalResponse.reason,...T.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:T.approvalResponse.approvalId}}}}});at.push({role:"tool",content:_})}const he=[...vt,...Ct].filter(De=>De.toolCall.providerExecuted);he.length>0&&at.push({role:"tool",content:he.map(De=>({type:"tool-approval-response",approvalId:De.approvalResponse.approvalId,approved:De.approvalResponse.approved,reason:De.approvalResponse.reason,providerExecuted:!0}))});const Qe=jd(Q);let U,Bt=[],bt=[];const et=[],Qt=new Map;do{const De=[...mt,...at],_=await F?.({model:S,steps:et,stepNumber:et.length,messages:De,experimental_context:E}),T=Sd((X=_?.model)!=null?X:S),be=await Tb({prompt:{system:(G=_?.system)!=null?G:ee.system,messages:(te=_?.messages)!=null?te:De},supportedUrls:await T.supportedUrls,download:b});E=(le=_?.experimental_context)!=null?le:E;const{toolChoice:je,tools:en}=await Nb({tools:t,toolChoice:(ot=_?.toolChoice)!=null?ot:n,activeTools:(Oe=_?.activeTools)!=null?Oe:g});U=await M(()=>{var re;return xi({name:"ai.generateText.doGenerate",attributes:Dn({telemetry:h,attributes:{...Ii({operationId:"ai.generateText.doGenerate",telemetry:h}),...q,"ai.model.provider":T.provider,"ai.model.id":T.modelId,"ai.prompt.messages":{input:s(()=>eE(be),"input")},"ai.prompt.tools":{input:s(()=>en?.map(Ge=>JSON.stringify(Ge)),"input")},"ai.prompt.toolChoice":{input:s(()=>je!=null?JSON.stringify(je):void 0,"input")},"gen_ai.system":T.provider,"gen_ai.request.model":T.modelId,"gen_ai.request.frequency_penalty":Q.frequencyPenalty,"gen_ai.request.max_tokens":Q.maxOutputTokens,"gen_ai.request.presence_penalty":Q.presencePenalty,"gen_ai.request.stop_sequences":Q.stopSequences,"gen_ai.request.temperature":(re=Q.temperature)!=null?re:void 0,"gen_ai.request.top_k":Q.topK,"gen_ai.request.top_p":Q.topP}}),tracer:ae,fn:s(async Ge=>{var No,pr,Yi,Xi,Qi,es,ts,ns;const Ym=Ud(D,_?.providerOptions),ze=await T.doGenerate({...Qe,tools:en,toolChoice:je,responseFormat:await m?.responseFormat,prompt:be,providerOptions:Ym,abortSignal:u,headers:R}),tn={id:(pr=(No=ze.response)==null?void 0:No.id)!=null?pr:O(),timestamp:(Xi=(Yi=ze.response)==null?void 0:Yi.timestamp)!=null?Xi:k(),modelId:(es=(Qi=ze.response)==null?void 0:Qi.modelId)!=null?es:T.modelId,headers:(ts=ze.response)==null?void 0:ts.headers,body:(ns=ze.response)==null?void 0:ns.body};return Ge.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":ze.finishReason.unified,"ai.response.text":{output:s(()=>Gd(ze.content),"output")},"ai.response.toolCalls":{output:s(()=>{const rs=Yd(ze.content);return rs==null?void 0:JSON.stringify(rs)},"output")},"ai.response.id":tn.id,"ai.response.model":tn.modelId,"ai.response.timestamp":tn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ze.providerMetadata),"ai.usage.promptTokens":ze.usage.inputTokens.total,"ai.usage.completionTokens":ze.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ze.finishReason.unified],"gen_ai.response.id":tn.id,"gen_ai.response.model":tn.modelId,"gen_ai.usage.input_tokens":ze.usage.inputTokens.total,"gen_ai.usage.output_tokens":ze.usage.outputTokens.total}})),{...ze,response:tn}},"fn")})});const cr=await Promise.all(U.content.filter(re=>re.type==="tool-call").map(re=>DE({toolCall:re,tools:t,repairToolCall:w,system:r,messages:De}))),Ro={};for(const re of cr){if(re.invalid)continue;const Ge=t?.[re.toolName];Ge!=null&&(Ge?.onInputAvailable!=null&&await Ge.onInputAvailable({input:re.input,toolCallId:re.toolCallId,messages:De,abortSignal:u,experimental_context:E}),await lE({tool:Ge,toolCall:re,messages:De,experimental_context:E})&&(Ro[re.toolCallId]={type:"tool-approval-request",approvalId:O(),toolCall:re}))}const Km=cr.filter(re=>re.invalid&&re.dynamic);bt=[];for(const re of Km)bt.push({type:"tool-error",toolCallId:re.toolCallId,toolName:re.toolName,input:re.input,error:Gc(re.error),dynamic:!0});Bt=cr.filter(re=>!re.providerExecuted),t!=null&&bt.push(...await Kd({toolCalls:Bt.filter(re=>!re.invalid&&Ro[re.toolCallId]==null),tools:t,tracer:ae,telemetry:h,messages:De,abortSignal:u,experimental_context:E}));for(const re of cr){if(!re.providerExecuted)continue;const Ge=t?.[re.toolName];Ge?.type==="provider"&&Ge.supportsDeferredResults&&(U.content.some(pr=>pr.type==="tool-result"&&pr.toolCallId===re.toolCallId)||Qt.set(re.toolCallId,{toolName:re.toolName}))}for(const re of U.content)re.type==="tool-result"&&Qt.delete(re.toolCallId);const Ji=bE({content:U.content,toolCalls:cr,toolOutputs:bt,toolApprovalRequests:Object.values(Ro),tools:t});at.push(...await _E({content:Ji,tools:t}));const Ki=new gE({content:Ji,finishReason:U.finishReason.unified,rawFinishReason:U.finishReason.raw,usage:tE(U.usage),warnings:U.warnings,providerMetadata:U.providerMetadata,request:(Ft=U.request)!=null?Ft:{},response:{...U.response,messages:structuredClone(at)}});$d({warnings:(ie=U.warnings)!=null?ie:[],provider:T.provider,model:T.modelId}),et.push(Ki),await C?.(Ki)}while((Bt.length>0&&bt.length===Bt.length||Qt.size>0)&&!await yE({stopConditions:P,steps:et}));V.setAttributes(await Dn({telemetry:h,attributes:{"ai.response.finishReason":U.finishReason.unified,"ai.response.text":{output:s(()=>Gd(U.content),"output")},"ai.response.toolCalls":{output:s(()=>{const De=Yd(U.content);return De==null?void 0:JSON.stringify(De)},"output")},"ai.response.providerMetadata":JSON.stringify(U.providerMetadata),"ai.usage.promptTokens":U.usage.inputTokens.total,"ai.usage.completionTokens":U.usage.outputTokens.total}}));const pe=et[et.length-1],ur=et.reduce((De,_)=>nE(De,_.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await L?.({finishReason:pe.finishReason,rawFinishReason:pe.rawFinishReason,usage:pe.usage,content:pe.content,text:pe.text,reasoningText:pe.reasoningText,reasoning:pe.reasoning,files:pe.files,sources:pe.sources,toolCalls:pe.toolCalls,staticToolCalls:pe.staticToolCalls,dynamicToolCalls:pe.dynamicToolCalls,toolResults:pe.toolResults,staticToolResults:pe.staticToolResults,dynamicToolResults:pe.dynamicToolResults,request:pe.request,response:pe.response,warnings:pe.warnings,providerMetadata:pe.providerMetadata,steps:et,totalUsage:ur,experimental_context:E});let lr;return pe.finishReason==="stop"&&(lr=await(m??Wd()).parseCompleteOutput({text:pe.text},{response:pe.response,usage:pe.usage,finishReason:pe.finishReason})),new CE({steps:et,totalUsage:ur,output:lr})},"fn")})}catch(V){throw Jb(V)}}s(Nr,"generateText");async function Kd({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:i,experimental_context:o}){return(await Promise.all(e.map(async l=>sE({toolCall:l,tools:t,tracer:n,telemetry:r,messages:a,abortSignal:i,experimental_context:o})))).filter(l=>l!=null)}s(Kd,"executeTools");var CE=(Kn=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 lb;return this._output}},s(Kn,"DefaultGenerateTextResult"),Kn);function Yd(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}))}s(Yd,"asToolCalls");function bE({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:a}){const i=[];for(const o of e)switch(o.type){case"text":case"reasoning":case"source":i.push(o);break;case"file":{i.push({type:"file",file:new uE(o),...o.providerMetadata!=null?{providerMetadata:o.providerMetadata}:{}});break}case"tool-call":{i.push(t.find(u=>u.toolCallId===o.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null){const l=a?.[o.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${o.toolCallId} not found.`);o.isError?i.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,error:o.result,providerExecuted:!0,dynamic:o.dynamic}):i.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:void 0,output:o.result,providerExecuted:!0,dynamic:o.dynamic});break}o.isError?i.push({type:"tool-error",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,error:o.result,providerExecuted:!0,dynamic:u.dynamic}):i.push({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,input:u.input,output:o.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===o.toolCallId);if(u==null)throw new ld({toolCallId:o.toolCallId,approvalId:o.approvalId});i.push({type:"tool-approval-request",approvalId:o.approvalId,toolCall:u});break}}return[...i,...n,...r]}s(bE,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
147
|
+
|
|
148
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
149
|
+
|
|
150
|
+
`)}})}},xr({prefix:"aitxt",size:24}),xr({prefix:"aiobj",size:24}),xr({prefix:"aiobj",size:24});var ki=v({error:v({message:p(),type:p().nullish(),param:qe().nullish(),code:J([p(),A()]).nullish()})}),dt=rt({errorSchema:ki,errorToMessage:s(e=>e.error.message,"errorToMessage")});function Xd(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"),a=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:a}}s(Xd,"getOpenAILanguageModelCapabilities");function Qd(e){var t,n,r,a,i,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 u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(i=e.completion_tokens_details)==null?void 0:i.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}s(Qd,"convertOpenAIChatUsage");function EE({prompt:e,systemMessageMode:t="system"}){var n;const r=[],a=[];for(const{role:i,content:o}of e)switch(i){case"system":{switch(t){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{a.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(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((u,l)=>{var c,d,m;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${Vt(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 Je({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vt(u.data),format:"mp3"}};default:throw new Je({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new Je({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(m=u.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Vt(u.data)}`}}}else throw new Je({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of o)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 o){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=i;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:a}}s(EE,"convertToOpenAIChatMessages");function $i({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}s($i,"getResponseMetadata$1");function em(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"}}s(em,"mapOpenAIFinishReason");var wE=K(()=>H(v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({message:v({role:I("assistant").nullish(),content:p().nullish(),tool_calls:B(v({id:p().nullish(),type:I("function"),function:v({name:p(),arguments:p()})})).nullish(),annotations:B(v({type:I("url_citation"),url_citation:v({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}),index:A(),logprobs:v({content:B(v({token:p(),logprob:A(),top_logprobs:B(v({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:v({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:v({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:v({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}))),AE=K(()=>H(J([v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({delta:v({role:oe(["assistant"]).nullish(),content:p().nullish(),tool_calls:B(v({index:A(),id:p().nullish(),type:I("function").nullish(),function:v({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:B(v({type:I("url_citation"),url_citation:v({start_index:A(),end_index:A(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:v({content:B(v({token:p(),logprob:A(),top_logprobs:B(v({token:p(),logprob:A()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:A()})),usage:v({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:v({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:v({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}),ki]))),IE=K(()=>H(v({logitBias:me(AF(),A()).optional(),logprobs:J([Ae(),A()]).optional(),parallelToolCalls:Ae().optional(),user:p().optional(),reasoningEffort:oe(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:A().optional(),store:Ae().optional(),metadata:me(p().max(64),p().max(512)).optional(),prediction:me(p(),qe()).optional(),serviceTier:oe(["auto","flex","priority","default"]).optional(),strictJsonSchema:Ae().optional(),textVerbosity:oe(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:oe(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:oe(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));function xE({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 i of e)switch(i.type){case"function":r.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,...i.strict!=null?{strict:i.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${i.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const i=a;throw new Je({functionality:`tool choice type: ${i}`})}}}s(xE,"prepareChatTools");var kE=(Yn=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:a,topK:i,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:m,toolChoice:h,providerOptions:D}){var f,g,y,F,w;const b=[],E=(f=await Ve({provider:"openai",providerOptions:D,schema:IE}))!=null?f:{},O=Xd(this.modelId),k=(g=E.forceReasoning)!=null?g:O.isReasoningModel;i!=null&&b.push({type:"unsupported",feature:"topK"});const{messages:C,warnings:L}=EE({prompt:t,systemMessageMode:(y=E.systemMessageMode)!=null?y:k?"developer":O.systemMessageMode});b.push(...L);const Q=(F=E.strictJsonSchema)!=null?F:!0,S={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:a,frequency_penalty:o,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:Q,name:(w=c.name)!=null?w:"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:C};k?((E.reasoningEffort!=="none"||!O.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,b.push({type:"other",message:"logprobs is not supported for reasoning models"}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,b.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,b.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,b.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,b.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),S.max_tokens!=null&&(S.max_completion_tokens==null&&(S.max_completion_tokens=S.max_tokens),S.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&S.temperature!=null&&(S.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),E.serviceTier==="flex"&&!O.supportsFlexProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),E.serviceTier==="priority"&&!O.supportsPriorityProcessing&&(b.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"}),S.service_tier=void 0);const{tools:P,toolChoice:$,toolWarnings:M}=xE({tools:m,toolChoice:h});return{args:{...S,tools:P,tool_choice:$},warnings:[...b,...M]}}async doGenerate(t){var n,r,a,i,o,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:c,failedResponseHandler:dt,successfulResponseHandler:Pe(wE),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],g=[],y=f.message.content;y!=null&&y.length>0&&g.push({type:"text",text:y});for(const b of(n=f.message.tool_calls)!=null?n:[])g.push({type:"tool-call",toolCallId:(r=b.id)!=null?r:Be(),toolName:b.function.name,input:b.function.arguments});for(const b of(a=f.message.annotations)!=null?a:[])g.push({type:"source",sourceType:"url",id:Be(),url:b.url_citation.url,title:b.url_citation.title});const F=(i=h.usage)==null?void 0:i.completion_tokens_details;(o=h.usage)==null||o.prompt_tokens_details;const w={openai:{}};return F?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=F?.rejected_prediction_tokens),((u=f.logprobs)==null?void 0:u.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:em(f.finish_reason),raw:(l=f.finish_reason)!=null?l:void 0},usage:Qd(h.usage),request:{body:c},response:{...$i(h),headers:m,body:D},warnings:d,providerMetadata:w}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:dt,successfulResponseHandler:fn(AE),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,m=!1;const h={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,f){var g,y,F,w,b,E,O,k,C,L,Q,S,P,$,M,Z,R;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}const q=D.value;if("error"in q){l={unified:"error",raw:void 0},f.enqueue({type:"error",error:q.error});return}if(!d){const V=$i(q);Object.values(V).some(Boolean)&&(d=!0,f.enqueue({type:"response-metadata",...$i(q)}))}q.usage!=null&&(c=q.usage,((g=q.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=q.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((F=q.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=q.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const ee=q.choices[0];if(ee?.finish_reason!=null&&(l={unified:em(ee.finish_reason),raw:ee.finish_reason}),((b=ee?.logprobs)==null?void 0:b.content)!=null&&(h.openai.logprobs=ee.logprobs.content),ee?.delta==null)return;const ae=ee.delta;if(ae.content!=null&&(m||(f.enqueue({type:"text-start",id:"0"}),m=!0),f.enqueue({type:"text-delta",id:"0",delta:ae.content})),ae.tool_calls!=null)for(const V of ae.tool_calls){const X=V.index;if(u[X]==null){if(V.type!=="function")throw new _r({data:V,message:"Expected 'function' type."});if(V.id==null)throw new _r({data:V,message:"Expected 'id' to be a string."});if(((E=V.function)==null?void 0:E.name)==null)throw new _r({data:V,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),u[X]={id:V.id,type:"function",function:{name:V.function.name,arguments:(O=V.function.arguments)!=null?O:""},hasFinished:!1};const te=u[X];((k=te.function)==null?void 0:k.name)!=null&&((C=te.function)==null?void 0:C.arguments)!=null&&(te.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:te.id,delta:te.function.arguments}),bo(te.function.arguments)&&(f.enqueue({type:"tool-input-end",id:te.id}),f.enqueue({type:"tool-call",toolCallId:(L=te.id)!=null?L:Be(),toolName:te.function.name,input:te.function.arguments}),te.hasFinished=!0));continue}const G=u[X];G.hasFinished||(((Q=V.function)==null?void 0:Q.arguments)!=null&&(G.function.arguments+=(P=(S=V.function)==null?void 0:S.arguments)!=null?P:""),f.enqueue({type:"tool-input-delta",id:G.id,delta:($=V.function.arguments)!=null?$:""}),((M=G.function)==null?void 0:M.name)!=null&&((Z=G.function)==null?void 0:Z.arguments)!=null&&bo(G.function.arguments)&&(f.enqueue({type:"tool-input-end",id:G.id}),f.enqueue({type:"tool-call",toolCallId:(R=G.id)!=null?R:Be(),toolName:G.function.name,input:G.function.arguments}),G.hasFinished=!0))}if(ae.annotations!=null)for(const V of ae.annotations)f.enqueue({type:"source",sourceType:"url",id:Be(),url:V.url_citation.url,title:V.url_citation.title})},flush(D){m&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Qd(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:i}}}},s(Yn,"OpenAIChatLanguageModel"),Yn);function tm(e){var t,n,r,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 i=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:i,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(a=e.completion_tokens)!=null?a:void 0,text:o,reasoning:void 0},raw:e}}s(tm,"convertOpenAICompletionUsage");function $E({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
151
|
+
|
|
152
|
+
`,e=e.slice(1));for(const{role:a,content:i}of e)switch(a){case"system":throw new At({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const o=i.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
|
|
153
|
+
${o}
|
|
154
|
+
|
|
155
|
+
`;break}case"assistant":{const o=i.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new Je({functionality:"tool-call messages"})}}).join("");r+=`${n}:
|
|
156
|
+
${o}
|
|
157
|
+
|
|
158
|
+
`;break}case"tool":throw new Je({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return r+=`${n}:
|
|
159
|
+
`,{prompt:r,stopSequences:[`
|
|
160
|
+
${t}:`]}}s($E,"convertToOpenAICompletionPrompt");function nm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}s(nm,"getResponseMetadata2$1");function rm(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"}}s(rm,"mapOpenAIFinishReason2");var TE=K(()=>H(v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({text:p(),finish_reason:p(),logprobs:v({tokens:B(p()),token_logprobs:B(A()),top_logprobs:B(me(p(),A())).nullish()}).nullish()})),usage:v({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}))),BE=K(()=>H(J([v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({text:p(),finish_reason:p().nullish(),index:A(),logprobs:v({tokens:B(p()),token_logprobs:B(A()),top_logprobs:B(me(p(),A())).nullish()}).nullish()})),usage:v({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}),ki]))),om=K(()=>H(v({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional(),logprobs:J([Ae(),A()]).optional()}))),SE=(Xn=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:a,topK:i,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:m,seed:h,providerOptions:D}){const f=[],g={...await Ve({provider:"openai",providerOptions:D,schema:om}),...await Ve({provider:this.providerOptionsName,providerOptions:D,schema:om})};i!=null&&f.push({type:"unsupported",feature:"topK"}),d?.length&&f.push({type:"unsupported",feature:"tools"}),m!=null&&f.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:F}=$E({prompt:t}),w=[...F??[],...l??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:g?.logprobs===!0?0:g?.logprobs===!1?void 0:g?.logprobs,suffix:g.suffix,user:g.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,seed:h,prompt:y,stop:w.length>0?w:void 0},warnings:f}}async doGenerate(t){var n;const{args:r,warnings:a}=await this.getArgs(t),{responseHeaders:i,value:o,rawValue:u}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:r,failedResponseHandler:dt,successfulResponseHandler:Pe(TE),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=o.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:tm(o.usage),finishReason:{unified:rm(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...nm(o),headers:i,body:u},providerMetadata:c,warnings:a}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:dt,successfulResponseHandler:fn(BE),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:o.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:r})},transform(m,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:m.error});return}const D=m.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...nm(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:rm(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(l.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(m){d||m.enqueue({type:"text-end",id:"0"}),m.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:tm(c)})}})),request:{body:a},response:{headers:i}}}},s(Xn,"OpenAICompletionLanguageModel"),Xn),OE=K(()=>H(v({dimensions:A().optional(),user:p().optional()}))),RE=K(()=>H(v({data:B(v({embedding:B(A())})),usage:v({prompt_tokens:A()}).nullish()}))),NE=(Qn=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:a}){var i;if(t.length>this.maxEmbeddingsPerCall)throw new ql({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(i=await Ve({provider:"openai",providerOptions:a,schema:OE}))!=null?i:{},{responseHeaders:u,value:l,rawValue:c}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:dt,successfulResponseHandler:Pe(RE),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}}}},s(Qn,"OpenAIEmbeddingModel"),Qn),am=K(()=>H(v({created:A().nullish(),data:B(v({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:v({input_tokens:A().nullish(),output_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_details:v({image_tokens:A().nullish(),text_tokens:A().nullish()}).nullish()}).nullish()}))),PE={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},ME=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),jE=(er=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=PE[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:a,size:i,aspectRatio:o,seed:u,providerOptions:l,headers:c,abortSignal:d}){var m,h,D,f,g,y,F,w,b,E,O;const k=[];o!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&k.push({type:"unsupported",feature:"seed"});const C=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(n!=null){const{value:S,responseHeaders:P}=await si({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),c),formData:qc({model:this.modelId,prompt:t,image:await Promise.all(n.map($=>$.type==="file"?new Blob([$.data instanceof Uint8Array?new Blob([$.data],{type:$.mediaType}):new Blob([Ut($.data)],{type:$.mediaType})],{type:$.mediaType}):ei($.url))),mask:r!=null?await zE(r):void 0,n:a,size:i,...(f=l.openai)!=null?f:{}}),failedResponseHandler:dt,successfulResponseHandler:Pe(am),abortSignal:d,fetch:this.config.fetch});return{images:S.data.map($=>$.b64_json),warnings:k,usage:S.usage!=null?{inputTokens:(g=S.usage.input_tokens)!=null?g:void 0,outputTokens:(y=S.usage.output_tokens)!=null?y:void 0,totalTokens:(F=S.usage.total_tokens)!=null?F:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:P},providerMetadata:{openai:{images:S.data.map($=>{var M,Z,R,q,ee;return{...$.revised_prompt?{revisedPrompt:$.revised_prompt}:{},created:(M=S.created)!=null?M:void 0,size:(Z=S.size)!=null?Z:void 0,quality:(R=S.quality)!=null?R:void 0,background:(q=S.background)!=null?q:void 0,outputFormat:(ee=S.output_format)!=null?ee:void 0}})}}}}const{value:L,responseHeaders:Q}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:a,size:i,...(w=l.openai)!=null?w:{},...ME.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:dt,successfulResponseHandler:Pe(am),abortSignal:d,fetch:this.config.fetch});return{images:L.data.map(S=>S.b64_json),warnings:k,usage:L.usage!=null?{inputTokens:(b=L.usage.input_tokens)!=null?b:void 0,outputTokens:(E=L.usage.output_tokens)!=null?E:void 0,totalTokens:(O=L.usage.total_tokens)!=null?O:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:Q},providerMetadata:{openai:{images:L.data.map(S=>{var P,$,M,Z,R;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(P=L.created)!=null?P:void 0,size:($=L.size)!=null?$:void 0,quality:(M=L.quality)!=null?M:void 0,background:(Z=L.background)!=null?Z:void 0,outputFormat:(R=L.output_format)!=null?R:void 0}})}}}}},s(er,"OpenAIImageModel"),er);async function zE(e){if(!e)return;if(e.type==="url")return ei(e.url);const t=e.data instanceof Uint8Array?e.data:Ut(e.data);return new Blob([t],{type:e.mediaType})}s(zE,"fileToBlob$1");var qE=K(()=>H(v({callId:p(),operation:Ie("type",[v({type:I("create_file"),path:p(),diff:p()}),v({type:I("delete_file"),path:p()}),v({type:I("update_file"),path:p(),diff:p()})])}))),im=K(()=>H(v({status:oe(["completed","failed"]),output:p().optional()}))),ZE=yt({id:"openai.apply_patch",inputSchema:qE,outputSchema:im}),LE=ZE,UE=K(()=>H(v({code:p().nullish(),containerId:p()}))),VE=K(()=>H(v({outputs:B(Ie("type",[v({type:I("logs"),logs:p()}),v({type:I("image"),url:p()})])).nullish()}))),GE=K(()=>H(v({container:J([p(),v({fileIds:B(p()).optional()})]).optional()}))),WE=yt({id:"openai.code_interpreter",inputSchema:UE,outputSchema:VE}),HE=s((e={})=>WE(e),"codeInterpreter"),sm=v({key:p(),type:oe(["eq","ne","gt","gte","lt","lte","in","nin"]),value:J([p(),A(),Ae(),B(p())])}),um=v({type:oe(["and","or"]),filters:B(J([sm,Ka(()=>um)]))}),JE=K(()=>H(v({vectorStoreIds:B(p()),maxNumResults:A().optional(),ranking:v({ranker:p().optional(),scoreThreshold:A().optional()}).optional(),filters:J([sm,um]).optional()}))),KE=K(()=>H(v({queries:B(p()),results:B(v({attributes:me(p(),gt()),fileId:p(),filename:p(),score:A(),text:p()})).nullable()}))),YE=yt({id:"openai.file_search",inputSchema:v({}),outputSchema:KE}),XE=K(()=>H(v({background:oe(["auto","opaque","transparent"]).optional(),inputFidelity:oe(["low","high"]).optional(),inputImageMask:v({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:oe(["auto"]).optional(),outputCompression:A().int().min(0).max(100).optional(),outputFormat:oe(["png","jpeg","webp"]).optional(),partialImages:A().int().min(0).max(3).optional(),quality:oe(["auto","low","medium","high"]).optional(),size:oe(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),QE=K(()=>H(v({}))),ew=K(()=>H(v({result:p()}))),tw=yt({id:"openai.image_generation",inputSchema:QE,outputSchema:ew}),nw=s((e={})=>tw(e),"imageGeneration"),lm=K(()=>H(v({action:v({type:I("exec"),command:B(p()),timeoutMs:A().optional(),user:p().optional(),workingDirectory:p().optional(),env:me(p(),p()).optional()})}))),cm=K(()=>H(v({output:p()}))),rw=yt({id:"openai.local_shell",inputSchema:lm,outputSchema:cm}),pm=K(()=>H(v({action:v({commands:B(p()),timeoutMs:A().optional(),maxOutputLength:A().optional()})}))),dm=K(()=>H(v({output:B(v({stdout:p(),stderr:p(),outcome:Ie("type",[v({type:I("timeout")}),v({type:I("exit"),exitCode:A()})])}))}))),ow=yt({id:"openai.shell",inputSchema:pm,outputSchema:dm}),aw=K(()=>H(v({externalWebAccess:Ae().optional(),filters:v({allowedDomains:B(p()).optional()}).optional(),searchContextSize:oe(["low","medium","high"]).optional(),userLocation:v({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),iw=K(()=>H(v({}))),sw=K(()=>H(v({action:Ie("type",[v({type:I("search"),query:p().optional()}),v({type:I("openPage"),url:p().nullish()}),v({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:B(Ie("type",[v({type:I("url"),url:p()}),v({type:I("api"),name:p()})])).optional()}))),uw=yt({id:"openai.web_search",inputSchema:iw,outputSchema:sw}),lw=s((e={})=>uw(e),"webSearch"),cw=K(()=>H(v({searchContextSize:oe(["low","medium","high"]).optional(),userLocation:v({type:I("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),pw=K(()=>H(v({}))),dw=K(()=>H(v({action:Ie("type",[v({type:I("search"),query:p().optional()}),v({type:I("openPage"),url:p().nullish()}),v({type:I("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),mw=yt({id:"openai.web_search_preview",inputSchema:pw,outputSchema:dw}),Ti=Ka(()=>J([p(),A(),Ae(),Sc(),B(Ti),me(p(),Ti)])),fw=K(()=>H(v({serverLabel:p(),allowedTools:J([B(p()),v({readOnly:Ae().optional(),toolNames:B(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:me(p(),p()).optional(),requireApproval:J([oe(["always","never"]),v({never:v({toolNames:B(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."))),hw=K(()=>H(v({}))),Dw=K(()=>H(v({type:I("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:J([p(),Ti]).optional()}))),gw=yt({id:"openai.mcp",inputSchema:hw,outputSchema:Dw}),vw=s(e=>gw(e),"mcp"),yw={applyPatch:LE,codeInterpreter:HE,fileSearch:YE,imageGeneration:nw,localShell:rw,shell:ow,webSearchPreview:mw,webSearch:lw,mcp:vw};function mm(e){var t,n,r,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 i=e.input_tokens,o=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(a=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:o,text:o-l,reasoning:l},raw:e}}s(mm,"convertOpenAIResponsesUsage");function fm(e,t){return t?t.some(n=>e.startsWith(n)):!1}s(fm,"isFileId");async function _w({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:a,store:i,hasLocalShellTool:o=!1,hasShellTool:u=!1,hasApplyPatchTool:l=!1}){var c,d,m,h,D,f,g,y,F,w,b,E,O;const k=[],C=[],L=new Set;for(const{role:Q,content:S}of e)switch(Q){case"system":{switch(n){case"system":{k.push({role:"system",content:S});break}case"developer":{k.push({role:"developer",content:S});break}case"remove":{C.push({type:"other",message:"system messages are removed for this model"});break}default:{const P=n;throw new Error(`Unsupported system message mode: ${P}`)}}break}case"user":{k.push({role:"user",content:S.map((P,$)=>{var M,Z,R;switch(P.type){case"text":return{type:"input_text",text:P.text};case"file":if(P.mediaType.startsWith("image/")){const q=P.mediaType==="image/*"?"image/jpeg":P.mediaType;return{type:"input_image",...P.data instanceof URL?{image_url:P.data.toString()}:typeof P.data=="string"&&fm(P.data,a)?{file_id:P.data}:{image_url:`data:${q};base64,${Vt(P.data)}`},detail:(Z=(M=P.providerOptions)==null?void 0:M[r])==null?void 0:Z.imageDetail}}else{if(P.mediaType==="application/pdf")return P.data instanceof URL?{type:"input_file",file_url:P.data.toString()}:{type:"input_file",...typeof P.data=="string"&&fm(P.data,a)?{file_id:P.data}:{filename:(R=P.filename)!=null?R:`part-${$}.pdf`,file_data:`data:application/pdf;base64,${Vt(P.data)}`}};throw new Je({functionality:`file part media type ${P.mediaType}`})}}})});break}case"assistant":{const P={};for(const $ of S)switch($.type){case"text":{const M=(d=(c=$.providerOptions)==null?void 0:c[r])==null?void 0:d.itemId;if(i&&M!=null){k.push({type:"item_reference",id:M});break}k.push({role:"assistant",content:[{type:"output_text",text:$.text}],id:M});break}case"tool-call":{const M=(g=(h=(m=$.providerOptions)==null?void 0:m[r])==null?void 0:h.itemId)!=null?g:(f=(D=$.providerMetadata)==null?void 0:D[r])==null?void 0:f.itemId;if($.providerExecuted){i&&M!=null&&k.push({type:"item_reference",id:M});break}if(i&&M!=null){k.push({type:"item_reference",id:M});break}const Z=t.toProviderToolName($.toolName);if(o&&Z==="local_shell"){const R=await tt({value:$.input,schema:lm});k.push({type:"local_shell_call",call_id:$.toolCallId,id:M,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(u&&Z==="shell"){const R=await tt({value:$.input,schema:pm});k.push({type:"shell_call",call_id:$.toolCallId,id:M,status:"completed",action:{commands:R.action.commands,timeout_ms:R.action.timeoutMs,max_output_length:R.action.maxOutputLength}});break}k.push({type:"function_call",call_id:$.toolCallId,name:Z,arguments:JSON.stringify($.input),id:M});break}case"tool-result":{if($.output.type==="execution-denied"||$.output.type==="json"&&typeof $.output.value=="object"&&$.output.value!=null&&"type"in $.output.value&&$.output.value.type==="execution-denied")break;if(i){const M=(w=(F=(y=$.providerMetadata)==null?void 0:y[r])==null?void 0:F.itemId)!=null?w:$.toolCallId;k.push({type:"item_reference",id:M})}else C.push({type:"other",message:`Results for OpenAI tool ${$.toolName} are not sent to the API when store is false`});break}case"reasoning":{const M=await Ve({provider:r,providerOptions:$.providerOptions,schema:Fw}),Z=M?.itemId;if(Z!=null){const R=P[Z];if(i)R===void 0&&(k.push({type:"item_reference",id:Z}),P[Z]={type:"reasoning",id:Z,summary:[]});else{const q=[];$.text.length>0?q.push({type:"summary_text",text:$.text}):R!==void 0&&C.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify($)}.`}),R===void 0?(P[Z]={type:"reasoning",id:Z,encrypted_content:M?.reasoningEncryptedContent,summary:q},k.push(P[Z])):(R.summary.push(...q),M?.reasoningEncryptedContent!=null&&(R.encrypted_content=M.reasoningEncryptedContent))}}else C.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify($)}.`});break}}break}case"tool":{for(const P of S){if(P.type==="tool-approval-response"){const R=P;if(L.has(R.approvalId))continue;L.add(R.approvalId),i&&k.push({type:"item_reference",id:R.approvalId}),k.push({type:"mcp_approval_response",approval_request_id:R.approvalId,approve:R.approved});continue}const $=P.output;if($.type==="execution-denied"&&((E=(b=$.providerOptions)==null?void 0:b.openai)==null?void 0:E.approvalId))continue;const M=t.toProviderToolName(P.toolName);if(o&&M==="local_shell"&&$.type==="json"){const R=await tt({value:$.value,schema:cm});k.push({type:"local_shell_call_output",call_id:P.toolCallId,output:R.output});continue}if(u&&M==="shell"&&$.type==="json"){const R=await tt({value:$.value,schema:dm});k.push({type:"shell_call_output",call_id:P.toolCallId,output:R.output.map(q=>({stdout:q.stdout,stderr:q.stderr,outcome:q.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:q.outcome.exitCode}}))});continue}if(l&&P.toolName==="apply_patch"&&$.type==="json"){const R=await tt({value:$.value,schema:im});k.push({type:"apply_patch_call_output",call_id:P.toolCallId,status:R.status,output:R.output});continue}let Z;switch($.type){case"text":case"error-text":Z=$.value;break;case"execution-denied":Z=(O=$.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":Z=JSON.stringify($.value);break;case"content":Z=$.value.map(R=>{var q;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"file-data":return{type:"input_file",filename:(q=R.filename)!=null?q:"data",file_data:`data:${R.mediaType};base64,${R.data}`};default:{C.push({type:"other",message:`unsupported tool content part type: ${R.type}`});return}}}).filter(PF);break}k.push({type:"function_call_output",call_id:P.toolCallId,output:Z})}break}default:{const P=Q;throw new Error(`Unsupported role: ${P}`)}}return{input:k,warnings:C}}s(_w,"convertToOpenAIResponsesInput");var Fw=v({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function hm({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"}}s(hm,"mapOpenAIResponseFinishReason");var Cw=K(()=>H(J([v({type:I("response.output_text.delta"),item_id:p(),delta:p(),logprobs:B(v({token:p(),logprob:A(),top_logprobs:B(v({token:p(),logprob:A()}))})).nullish()}),v({type:oe(["response.completed","response.incomplete"]),response:v({incomplete_details:v({reason:p()}).nullish(),usage:v({input_tokens:A(),input_tokens_details:v({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:v({reasoning_tokens:A().nullish()}).nullish()}),service_tier:p().nullish()})}),v({type:I("response.created"),response:v({id:p(),created_at:A(),model:p(),service_tier:p().nullish()})}),v({type:I("response.output_item.added"),output_index:A(),item:Ie("type",[v({type:I("message"),id:p()}),v({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),v({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),v({type:I("web_search_call"),id:p(),status:p()}),v({type:I("computer_call"),id:p(),status:p()}),v({type:I("file_search_call"),id:p()}),v({type:I("image_generation_call"),id:p()}),v({type:I("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:B(Ie("type",[v({type:I("logs"),logs:p()}),v({type:I("image"),url:p()})])).nullable(),status:p()}),v({type:I("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),v({type:I("mcp_list_tools"),id:p()}),v({type:I("mcp_approval_request"),id:p()}),v({type:I("apply_patch_call"),id:p(),call_id:p(),status:oe(["in_progress","completed"]),operation:Ie("type",[v({type:I("create_file"),path:p(),diff:p()}),v({type:I("delete_file"),path:p()}),v({type:I("update_file"),path:p(),diff:p()})])}),v({type:I("shell_call"),id:p(),call_id:p(),status:oe(["in_progress","completed","incomplete"]),action:v({commands:B(p())})})])}),v({type:I("response.output_item.done"),output_index:A(),item:Ie("type",[v({type:I("message"),id:p()}),v({type:I("reasoning"),id:p(),encrypted_content:p().nullish()}),v({type:I("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:I("completed")}),v({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:B(Ie("type",[v({type:I("logs"),logs:p()}),v({type:I("image"),url:p()})])).nullable()}),v({type:I("image_generation_call"),id:p(),result:p()}),v({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[v({type:I("search"),query:p().nullish(),sources:B(Ie("type",[v({type:I("url"),url:p()}),v({type:I("api"),name:p()})])).nullish()}),v({type:I("open_page"),url:p().nullish()}),v({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),v({type:I("file_search_call"),id:p(),queries:B(p()),results:B(v({attributes:me(p(),J([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),v({type:I("local_shell_call"),id:p(),call_id:p(),action:v({type:I("exec"),command:B(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),v({type:I("computer_call"),id:p(),status:I("completed")}),v({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:J([p(),v({type:p().optional(),code:J([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),v({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:B(v({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:J([p(),v({type:p().optional(),code:J([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),v({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),v({type:I("apply_patch_call"),id:p(),call_id:p(),status:oe(["in_progress","completed"]),operation:Ie("type",[v({type:I("create_file"),path:p(),diff:p()}),v({type:I("delete_file"),path:p()}),v({type:I("update_file"),path:p(),diff:p()})])}),v({type:I("shell_call"),id:p(),call_id:p(),status:oe(["in_progress","completed","incomplete"]),action:v({commands:B(p())})})])}),v({type:I("response.function_call_arguments.delta"),item_id:p(),output_index:A(),delta:p()}),v({type:I("response.image_generation_call.partial_image"),item_id:p(),output_index:A(),partial_image_b64:p()}),v({type:I("response.code_interpreter_call_code.delta"),item_id:p(),output_index:A(),delta:p()}),v({type:I("response.code_interpreter_call_code.done"),item_id:p(),output_index:A(),code:p()}),v({type:I("response.output_text.annotation.added"),annotation:Ie("type",[v({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),v({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),v({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),v({type:I("file_path"),file_id:p(),index:A().nullish()})])}),v({type:I("response.reasoning_summary_part.added"),item_id:p(),summary_index:A()}),v({type:I("response.reasoning_summary_text.delta"),item_id:p(),summary_index:A(),delta:p()}),v({type:I("response.reasoning_summary_part.done"),item_id:p(),summary_index:A()}),v({type:I("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:A(),delta:p(),obfuscation:p().nullish()}),v({type:I("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:A(),diff:p()}),v({type:I("error"),sequence_number:A(),error:v({type:p(),code:p(),message:p(),param:p().nullish()})}),v({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),bw=K(()=>H(v({id:p().optional(),created_at:A().optional(),error:v({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:B(Ie("type",[v({type:I("message"),role:I("assistant"),id:p(),content:B(v({type:I("output_text"),text:p(),logprobs:B(v({token:p(),logprob:A(),top_logprobs:B(v({token:p(),logprob:A()}))})).nullish(),annotations:B(Ie("type",[v({type:I("url_citation"),start_index:A(),end_index:A(),url:p(),title:p()}),v({type:I("file_citation"),file_id:p(),filename:p().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:p().nullish()}),v({type:I("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),v({type:I("file_path"),file_id:p(),index:A().nullish()})]))}))}),v({type:I("web_search_call"),id:p(),status:p(),action:Ie("type",[v({type:I("search"),query:p().nullish(),sources:B(Ie("type",[v({type:I("url"),url:p()}),v({type:I("api"),name:p()})])).nullish()}),v({type:I("open_page"),url:p().nullish()}),v({type:I("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),v({type:I("file_search_call"),id:p(),queries:B(p()),results:B(v({attributes:me(p(),J([p(),A(),Ae()])),file_id:p(),filename:p(),score:A(),text:p()})).nullish()}),v({type:I("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:B(Ie("type",[v({type:I("logs"),logs:p()}),v({type:I("image"),url:p()})])).nullable()}),v({type:I("image_generation_call"),id:p(),result:p()}),v({type:I("local_shell_call"),id:p(),call_id:p(),action:v({type:I("exec"),command:B(p()),timeout_ms:A().optional(),user:p().optional(),working_directory:p().optional(),env:me(p(),p()).optional()})}),v({type:I("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),v({type:I("computer_call"),id:p(),status:p().optional()}),v({type:I("reasoning"),id:p(),encrypted_content:p().nullish(),summary:B(v({type:I("summary_text"),text:p()}))}),v({type:I("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:J([p(),v({type:p().optional(),code:J([A(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),v({type:I("mcp_list_tools"),id:p(),server_label:p(),tools:B(v({name:p(),description:p().optional(),input_schema:qe(),annotations:me(p(),gt()).optional()})),error:J([p(),v({type:p().optional(),code:J([A(),p()]).optional(),message:p().optional()}).loose()]).optional()}),v({type:I("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),v({type:I("apply_patch_call"),id:p(),call_id:p(),status:oe(["in_progress","completed"]),operation:Ie("type",[v({type:I("create_file"),path:p(),diff:p()}),v({type:I("delete_file"),path:p()}),v({type:I("update_file"),path:p(),diff:p()})])}),v({type:I("shell_call"),id:p(),call_id:p(),status:oe(["in_progress","completed","incomplete"]),action:v({commands:B(p())})})])).optional(),service_tier:p().nullish(),incomplete_details:v({reason:p()}).nullish(),usage:v({input_tokens:A(),input_tokens_details:v({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:v({reasoning_tokens:A().nullish()}).nullish()}).optional()}))),Dm=20,gm=K(()=>H(v({conversation:p().nullish(),include:B(oe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:J([Ae(),A().min(1).max(Dm)]).optional(),maxToolCalls:A().nullish(),metadata:qe().nullish(),parallelToolCalls:Ae().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:oe(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:oe(["auto","flex","priority","default"]).nullish(),store:Ae().nullish(),strictJsonSchema:Ae().nullish(),textVerbosity:oe(["low","medium","high"]).nullish(),truncation:oe(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:oe(["system","developer","remove"]).optional(),forceReasoning:Ae().optional()})));async function Ew({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 i of e)switch(i.type){case"function":r.push({type:"function",name:i.name,description:i.description,parameters:i.inputSchema,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":{switch(i.id){case"openai.file_search":{const o=await tt({value:i.args,schema:JE});r.push({type:"file_search",vector_store_ids:o.vectorStoreIds,max_num_results:o.maxNumResults,ranking_options:o.ranking?{ranker:o.ranking.ranker,score_threshold:o.ranking.scoreThreshold}:void 0,filters:o.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{r.push({type:"shell"});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const o=await tt({value:i.args,schema:cw});r.push({type:"web_search_preview",search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.web_search":{const o=await tt({value:i.args,schema:aw});r.push({type:"web_search",filters:o.filters!=null?{allowed_domains:o.filters.allowedDomains}:void 0,external_web_access:o.externalWebAccess,search_context_size:o.searchContextSize,user_location:o.userLocation});break}case"openai.code_interpreter":{const o=await tt({value:i.args,schema:GE});r.push({type:"code_interpreter",container:o.container==null?{type:"auto",file_ids:void 0}:typeof o.container=="string"?o.container:{type:"auto",file_ids:o.container.fileIds}});break}case"openai.image_generation":{const o=await tt({value:i.args,schema:XE});r.push({type:"image_generation",background:o.background,input_fidelity:o.inputFidelity,input_image_mask:o.inputImageMask?{file_id:o.inputImageMask.fileId,image_url:o.inputImageMask.imageUrl}:void 0,model:o.model,moderation:o.moderation,partial_images:o.partialImages,quality:o.quality,output_compression:o.outputCompression,output_format:o.outputFormat,size:o.size});break}case"openai.mcp":{const o=await tt({value:i.args,schema:fw}),u=s(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=o.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:o.serverLabel,allowed_tools:Array.isArray(o.allowedTools)?o.allowedTools:o.allowedTools?{read_only:o.allowedTools.readOnly,tool_names:o.allowedTools.toolNames}:void 0,authorization:o.authorization,connector_id:o.connectorId,headers:o.headers,require_approval:c??"never",server_description:o.serverDescription,server_url:o.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${i}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,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 i=a;throw new Je({functionality:`tool choice type: ${i}`})}}}s(Ew,"prepareResponsesTools");function vm(e){var t,n;const r={};for(const a of e)if(a.role==="assistant")for(const i of a.content){if(i.type!=="tool-call")continue;const o=(n=(t=i.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;o!=null&&(r[o]=i.toolCallId)}return r}s(vm,"extractApprovalRequestIdToToolCallIdMapping");var ww=(tr=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:a,topK:i,presencePenalty:o,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:m,toolChoice:h,responseFormat:D}){var f,g,y,F,w,b;const E=[],O=Xd(this.modelId);i!=null&&E.push({type:"unsupported",feature:"topK"}),l!=null&&E.push({type:"unsupported",feature:"seed"}),o!=null&&E.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&E.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&E.push({type:"unsupported",feature:"stopSequences"});const k=this.config.provider.includes("azure")?"azure":"openai";let C=await Ve({provider:k,providerOptions:d,schema:gm});C==null&&k!=="openai"&&(C=await Ve({provider:"openai",providerOptions:d,schema:gm}));const L=(f=C?.forceReasoning)!=null?f:O.isReasoningModel;C?.conversation&&C?.previousResponseId&&E.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const Q=kF({tools:m,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:S,warnings:P}=await _w({prompt:c,toolNameMapping:Q,systemMessageMode:(g=C?.systemMessageMode)!=null?g:L?"developer":O.systemMessageMode,providerOptionsName:k,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=C?.store)!=null?y:!0,hasLocalShellTool:R("openai.local_shell"),hasShellTool:R("openai.shell"),hasApplyPatchTool:R("openai.apply_patch")});E.push(...P);const $=(F=C?.strictJsonSchema)!=null?F:!0;let M=C?.include;function Z(le){M==null?M=[le]:M.includes(le)||(M=[...M,le])}s(Z,"addInclude");function R(le){return m?.find(ot=>ot.type==="provider"&&ot.id===le)!=null}s(R,"hasOpenAITool");const q=typeof C?.logprobs=="number"?C?.logprobs:C?.logprobs===!0?Dm:void 0;q&&Z("message.output_text.logprobs");const ee=(w=m?.find(le=>le.type==="provider"&&(le.id==="openai.web_search"||le.id==="openai.web_search_preview")))==null?void 0:w.name;ee&&Z("web_search_call.action.sources"),R("openai.code_interpreter")&&Z("code_interpreter_call.outputs");const ae=C?.store;ae===!1&&L&&Z("reasoning.encrypted_content");const V={model:this.modelId,input:S,temperature:n,top_p:a,max_output_tokens:t,...(D?.type==="json"||C?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:$,name:(b=D.name)!=null?b:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...C?.textVerbosity&&{verbosity:C.textVerbosity}}},conversation:C?.conversation,max_tool_calls:C?.maxToolCalls,metadata:C?.metadata,parallel_tool_calls:C?.parallelToolCalls,previous_response_id:C?.previousResponseId,store:ae,user:C?.user,instructions:C?.instructions,service_tier:C?.serviceTier,include:M,prompt_cache_key:C?.promptCacheKey,prompt_cache_retention:C?.promptCacheRetention,safety_identifier:C?.safetyIdentifier,top_logprobs:q,truncation:C?.truncation,...L&&(C?.reasoningEffort!=null||C?.reasoningSummary!=null)&&{reasoning:{...C?.reasoningEffort!=null&&{effort:C.reasoningEffort},...C?.reasoningSummary!=null&&{summary:C.reasoningSummary}}}};L?C?.reasoningEffort==="none"&&O.supportsNonReasoningParameters||(V.temperature!=null&&(V.temperature=void 0,E.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),V.top_p!=null&&(V.top_p=void 0,E.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(C?.reasoningEffort!=null&&E.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),C?.reasoningSummary!=null&&E.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),C?.serviceTier==="flex"&&!O.supportsFlexProcessing&&(E.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete V.service_tier),C?.serviceTier==="priority"&&!O.supportsPriorityProcessing&&(E.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 V.service_tier);const{tools:X,toolChoice:G,toolWarnings:te}=await Ew({tools:m,toolChoice:h});return{webSearchToolName:ee,args:{...V,tools:X,tool_choice:G},warnings:[...E,...te],store:ae,toolNameMapping:Q,providerOptionsName:k}}async doGenerate(t){var n,r,a,i,o,u,l,c,d,m,h,D,f,g,y,F,w,b,E,O,k,C,L,Q,S,P,$,M,Z,R,q;const{args:ee,warnings:ae,webSearchToolName:V,toolNameMapping:X,providerOptionsName:G}=await this.getArgs(t),te=this.config.url({path:"/responses",modelId:this.modelId}),le=vm(t.prompt),{responseHeaders:ot,value:Oe,rawValue:Ft}=await Se({url:te,headers:xe(this.config.headers(),t.headers),body:ee,failedResponseHandler:dt,successfulResponseHandler:Pe(bw),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Oe.error)throw new Re({message:Oe.error.message,url:te,requestBodyValues:ee,statusCode:400,responseHeaders:ot,responseBody:Ft,isRetryable:!1});const ie=[],mt=[];let at=!1;for(const j of Oe.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const he of j.summary)ie.push({type:"reasoning",text:he.text,providerMetadata:{[G]:{itemId:j.id,reasoningEncryptedContent:(n=j.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{ie.push({type:"tool-call",toolCallId:j.id,toolName:X.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ie.push({type:"tool-result",toolCallId:j.id,toolName:X.toCustomToolName("image_generation"),result:{result:j.result}});break}case"local_shell_call":{ie.push({type:"tool-call",toolCallId:j.call_id,toolName:X.toCustomToolName("local_shell"),input:JSON.stringify({action:j.action}),providerMetadata:{[G]:{itemId:j.id}}});break}case"shell_call":{ie.push({type:"tool-call",toolCallId:j.call_id,toolName:X.toCustomToolName("shell"),input:JSON.stringify({action:{commands:j.action.commands}}),providerMetadata:{[G]:{itemId:j.id}}});break}case"message":{for(const he of j.content){(a=(r=t.providerOptions)==null?void 0:r[G])!=null&&a.logprobs&&he.logprobs&&mt.push(he.logprobs);const Qe={itemId:j.id,...he.annotations.length>0&&{annotations:he.annotations}};ie.push({type:"text",text:he.text,providerMetadata:{[G]:Qe}});for(const U of he.annotations)U.type==="url_citation"?ie.push({type:"source",sourceType:"url",id:(u=(o=(i=this.config).generateId)==null?void 0:o.call(i))!=null?u:Be(),url:U.url,title:U.title}):U.type==="file_citation"?ie.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Be(),mediaType:"text/plain",title:(h=(m=U.quote)!=null?m:U.filename)!=null?h:"Document",filename:(D=U.filename)!=null?D:U.file_id,...U.file_id?{providerMetadata:{[G]:{fileId:U.file_id}}}:{}}):U.type==="container_file_citation"?ie.push({type:"source",sourceType:"document",id:(y=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?y:Be(),mediaType:"text/plain",title:(w=(F=U.filename)!=null?F:U.file_id)!=null?w:"Document",filename:(b=U.filename)!=null?b:U.file_id,providerMetadata:{[G]:{fileId:U.file_id,containerId:U.container_id,...U.index!=null?{index:U.index}:{}}}}):U.type==="file_path"&&ie.push({type:"source",sourceType:"document",id:(k=(O=(E=this.config).generateId)==null?void 0:O.call(E))!=null?k:Be(),mediaType:"application/octet-stream",title:U.file_id,filename:U.file_id,providerMetadata:{[G]:{fileId:U.file_id,...U.index!=null?{index:U.index}:{}}}})}break}case"function_call":{at=!0,ie.push({type:"tool-call",toolCallId:j.call_id,toolName:j.name,input:j.arguments,providerMetadata:{[G]:{itemId:j.id}}});break}case"web_search_call":{ie.push({type:"tool-call",toolCallId:j.id,toolName:X.toCustomToolName(V??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ie.push({type:"tool-result",toolCallId:j.id,toolName:X.toCustomToolName(V??"web_search"),result:_m(j.action)});break}case"mcp_call":{const he=j.approval_request_id!=null&&(C=le[j.approval_request_id])!=null?C:j.id,Qe=`mcp.${j.name}`;ie.push({type:"tool-call",toolCallId:he,toolName:Qe,input:j.arguments,providerExecuted:!0,dynamic:!0}),ie.push({type:"tool-result",toolCallId:he,toolName:Qe,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:{[G]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const he=(L=j.approval_request_id)!=null?L:j.id,Qe=(P=(S=(Q=this.config).generateId)==null?void 0:S.call(Q))!=null?P:Be(),U=`mcp.${j.name}`;ie.push({type:"tool-call",toolCallId:Qe,toolName:U,input:j.arguments,providerExecuted:!0,dynamic:!0}),ie.push({type:"tool-approval-request",approvalId:he,toolCallId:Qe});break}case"computer_call":{ie.push({type:"tool-call",toolCallId:j.id,toolName:X.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ie.push({type:"tool-result",toolCallId:j.id,toolName:X.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:j.status||"completed"}});break}case"file_search_call":{ie.push({type:"tool-call",toolCallId:j.id,toolName:X.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ie.push({type:"tool-result",toolCallId:j.id,toolName:X.toCustomToolName("file_search"),result:{queries:j.queries,results:(M=($=j.results)==null?void 0:$.map(he=>({attributes:he.attributes,fileId:he.file_id,filename:he.filename,score:he.score,text:he.text})))!=null?M:null}});break}case"code_interpreter_call":{ie.push({type:"tool-call",toolCallId:j.id,toolName:X.toCustomToolName("code_interpreter"),input:JSON.stringify({code:j.code,containerId:j.container_id}),providerExecuted:!0}),ie.push({type:"tool-result",toolCallId:j.id,toolName:X.toCustomToolName("code_interpreter"),result:{outputs:j.outputs}});break}case"apply_patch_call":{ie.push({type:"tool-call",toolCallId:j.call_id,toolName:X.toCustomToolName("apply_patch"),input:JSON.stringify({callId:j.call_id,operation:j.operation}),providerMetadata:{[G]:{itemId:j.id}}});break}}const vt={[G]:{responseId:Oe.id}};mt.length>0&&(vt[G].logprobs=mt),typeof Oe.service_tier=="string"&&(vt[G].serviceTier=Oe.service_tier);const Ct=Oe.usage;return{content:ie,finishReason:{unified:hm({finishReason:(Z=Oe.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:at}),raw:(q=(R=Oe.incomplete_details)==null?void 0:R.reason)!=null?q:void 0},usage:mm(Ct),request:{body:ee},response:{id:Oe.id,timestamp:new Date(Oe.created_at*1e3),modelId:Oe.model,headers:ot,body:Ft},providerMetadata:vt,warnings:ae}}async doStream(t){const{args:n,warnings:r,webSearchToolName:a,toolNameMapping:i,store:o,providerOptionsName:u}=await this.getArgs(t),{responseHeaders:l,value:c}=await Se({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:dt,successfulResponseHandler:fn(Cw),abortSignal:t.abortSignal,fetch:this.config.fetch}),d=this,m=vm(t.prompt),h=new Map;let D={unified:"other",raw:void 0},f;const g=[];let y=null;const F={},w=[];let b=!1;const E={};let O;return{stream:c.pipeThrough(new TransformStream({start(k){k.enqueue({type:"stream-start",warnings:r})},transform(k,C){var L,Q,S,P,$,M,Z,R,q,ee,ae,V,X,G,te,le,ot,Oe,Ft,ie,mt,at,vt,Ct,j,he,Qe,U,Bt,bt,et,Qt,pe,ur,lr,De;if(t.includeRawChunks&&C.enqueue({type:"raw",rawValue:k.rawValue}),!k.success){D={unified:"error",raw:void 0},C.enqueue({type:"error",error:k.error});return}const _=k.value;if(ym(_)){if(_.item.type==="function_call")F[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},C.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")F[_.output_index]={toolName:i.toCustomToolName(a??"web_search"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:i.toCustomToolName(a??"web_search"),providerExecuted:!0}),C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:i.toCustomToolName(a??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")F[_.output_index]={toolName:i.toCustomToolName("computer_use"),toolCallId:_.item.id},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:i.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")F[_.output_index]={toolName:i.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},C.enqueue({type:"tool-input-start",id:_.item.id,toolName:i.toCustomToolName("code_interpreter"),providerExecuted:!0}),C.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:i.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:i.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:T,operation:be}=_.item;if(F[_.output_index]={toolName:i.toCustomToolName("apply_patch"),toolCallId:T,applyPatch:{hasDiff:be.type==="delete_file",endEmitted:be.type==="delete_file"}},C.enqueue({type:"tool-input-start",id:T,toolName:i.toCustomToolName("apply_patch")}),be.type==="delete_file"){const je=JSON.stringify({callId:T,operation:be});C.enqueue({type:"tool-input-delta",id:T,delta:je}),C.enqueue({type:"tool-input-end",id:T})}else C.enqueue({type:"tool-input-delta",id:T,delta:`{"callId":"${Jt(T)}","operation":{"type":"${Jt(be.type)}","path":"${Jt(be.path)}","diff":"`})}else _.item.type==="shell_call"?F[_.output_index]={toolName:i.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="message"?(w.splice(0,w.length),C.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):ym(_)&&_.item.type==="reasoning"&&(E[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},C.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(L=_.item.encrypted_content)!=null?L:null}}}))}else if(Iw(_)){if(_.item.type==="message")C.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...w.length>0&&{annotations:w}}}});else if(_.item.type==="function_call")F[_.output_index]=void 0,b=!0,C.enqueue({type:"tool-input-end",id:_.item.call_id}),C.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")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:i.toCustomToolName(a??"web_search"),result:_m(_.item.action)});else if(_.item.type==="computer_call")F[_.output_index]=void 0,C.enqueue({type:"tool-input-end",id:_.item.id}),C.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:i.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:i.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:i.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(S=(Q=_.item.results)==null?void 0:Q.map(T=>({attributes:T.attributes,fileId:T.file_id,filename:T.filename,score:T.score,text:T.text})))!=null?S:null}});else if(_.item.type==="code_interpreter_call")F[_.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:i.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")C.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:i.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){F[_.output_index]=void 0;const T=(P=_.item.approval_request_id)!=null?P:void 0,be=T!=null&&(M=($=h.get(T))!=null?$:m[T])!=null?M:_.item.id,je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:be,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-result",toolCallId:be,toolName:je,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")F[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const T=F[_.output_index];T?.applyPatch&&!T.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(T.applyPatch.hasDiff||C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:Jt(_.item.operation.diff)}),C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:T.toolCallId}),T.applyPatch.endEmitted=!0),T&&_.item.status==="completed"&&C.enqueue({type:"tool-call",toolCallId:T.toolCallId,toolName:i.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),F[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){F[_.output_index]=void 0;const T=(q=(R=(Z=d.config).generateId)==null?void 0:R.call(Z))!=null?q:Be(),be=(ee=_.item.approval_request_id)!=null?ee:_.item.id;h.set(be,T);const je=`mcp.${_.item.name}`;C.enqueue({type:"tool-call",toolCallId:T,toolName:je,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-approval-request",approvalId:be,toolCallId:T})}else if(_.item.type==="local_shell_call")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:i.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")F[_.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:i.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="reasoning"){const T=E[_.item.id],be=Object.entries(T.summaryParts).filter(([je,en])=>en==="active"||en==="can-conclude").map(([je])=>je);for(const je of be)C.enqueue({type:"reasoning-end",id:`${_.item.id}:${je}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(ae=_.item.encrypted_content)!=null?ae:null}}});delete E[_.item.id]}}else if($w(_)){const T=F[_.output_index];T!=null&&C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:_.delta})}else if(Ow(_)){const T=F[_.output_index];T?.applyPatch&&(C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:Jt(_.delta)}),T.applyPatch.hasDiff=!0)}else if(Rw(_)){const T=F[_.output_index];T?.applyPatch&&!T.applyPatch.endEmitted&&(T.applyPatch.hasDiff||(C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:Jt(_.diff)}),T.applyPatch.hasDiff=!0),C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:T.toolCallId}),T.applyPatch.endEmitted=!0)}else if(Tw(_))C.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:i.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(Bw(_)){const T=F[_.output_index];T!=null&&C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:Jt(_.delta)})}else if(Sw(_)){const T=F[_.output_index];T!=null&&(C.enqueue({type:"tool-input-delta",id:T.toolCallId,delta:'"}'}),C.enqueue({type:"tool-input-end",id:T.toolCallId}),C.enqueue({type:"tool-call",toolCallId:T.toolCallId,toolName:i.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:T.codeInterpreter.containerId}),providerExecuted:!0}))}else if(kw(_))y=_.response.id,C.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(Aw(_))C.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(X=(V=t.providerOptions)==null?void 0:V[u])!=null&&X.logprobs&&_.logprobs&&g.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const T=E[_.item_id];T.summaryParts[_.summary_index]="active";for(const be of Object.keys(T.summaryParts))T.summaryParts[be]==="can-conclude"&&(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${be}`,providerMetadata:{[u]:{itemId:_.item_id}}}),T.summaryParts[be]="concluded");C.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(te=(G=E[_.item_id])==null?void 0:G.encryptedContent)!=null?te:null}}})}}else _.type==="response.reasoning_summary_text.delta"?C.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?o?(C.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),E[_.item_id].summaryParts[_.summary_index]="concluded"):E[_.item_id].summaryParts[_.summary_index]="can-conclude":xw(_)?(D={unified:hm({finishReason:(le=_.response.incomplete_details)==null?void 0:le.reason,hasFunctionCall:b}),raw:(Oe=(ot=_.response.incomplete_details)==null?void 0:ot.reason)!=null?Oe:void 0},f=_.response.usage,typeof _.response.service_tier=="string"&&(O=_.response.service_tier)):Nw(_)?(w.push(_.annotation),_.annotation.type==="url_citation"?C.enqueue({type:"source",sourceType:"url",id:(mt=(ie=(Ft=d.config).generateId)==null?void 0:ie.call(Ft))!=null?mt:Be(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?C.enqueue({type:"source",sourceType:"document",id:(Ct=(vt=(at=d.config).generateId)==null?void 0:vt.call(at))!=null?Ct:Be(),mediaType:"text/plain",title:(he=(j=_.annotation.quote)!=null?j:_.annotation.filename)!=null?he:"Document",filename:(Qe=_.annotation.filename)!=null?Qe:_.annotation.file_id,..._.annotation.file_id?{providerMetadata:{[u]:{fileId:_.annotation.file_id}}}:{}}):_.annotation.type==="container_file_citation"?C.enqueue({type:"source",sourceType:"document",id:(bt=(Bt=(U=d.config).generateId)==null?void 0:Bt.call(U))!=null?bt:Be(),mediaType:"text/plain",title:(Qt=(et=_.annotation.filename)!=null?et:_.annotation.file_id)!=null?Qt:"Document",filename:(pe=_.annotation.filename)!=null?pe:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,containerId:_.annotation.container_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}}):_.annotation.type==="file_path"&&C.enqueue({type:"source",sourceType:"document",id:(De=(lr=(ur=d.config).generateId)==null?void 0:lr.call(ur))!=null?De:Be(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{fileId:_.annotation.file_id,..._.annotation.index!=null?{index:_.annotation.index}:{}}}})):Pw(_)&&C.enqueue({type:"error",error:_})},flush(k){const C={[u]:{responseId:y}};g.length>0&&(C[u].logprobs=g),O!==void 0&&(C[u].serviceTier=O),k.enqueue({type:"finish",finishReason:D,usage:mm(f),providerMetadata:C})}})),request:{body:n},response:{headers:l}}}},s(tr,"OpenAIResponsesLanguageModel"),tr);function Aw(e){return e.type==="response.output_text.delta"}s(Aw,"isTextDeltaChunk");function Iw(e){return e.type==="response.output_item.done"}s(Iw,"isResponseOutputItemDoneChunk");function xw(e){return e.type==="response.completed"||e.type==="response.incomplete"}s(xw,"isResponseFinishedChunk");function kw(e){return e.type==="response.created"}s(kw,"isResponseCreatedChunk");function $w(e){return e.type==="response.function_call_arguments.delta"}s($w,"isResponseFunctionCallArgumentsDeltaChunk");function Tw(e){return e.type==="response.image_generation_call.partial_image"}s(Tw,"isResponseImageGenerationCallPartialImageChunk");function Bw(e){return e.type==="response.code_interpreter_call_code.delta"}s(Bw,"isResponseCodeInterpreterCallCodeDeltaChunk");function Sw(e){return e.type==="response.code_interpreter_call_code.done"}s(Sw,"isResponseCodeInterpreterCallCodeDoneChunk");function Ow(e){return e.type==="response.apply_patch_call_operation_diff.delta"}s(Ow,"isResponseApplyPatchCallOperationDiffDeltaChunk");function Rw(e){return e.type==="response.apply_patch_call_operation_diff.done"}s(Rw,"isResponseApplyPatchCallOperationDiffDoneChunk");function ym(e){return e.type==="response.output_item.added"}s(ym,"isResponseOutputItemAddedChunk");function Nw(e){return e.type==="response.output_text.annotation.added"}s(Nw,"isResponseAnnotationAddedChunk");function Pw(e){return e.type==="error"}s(Pw,"isErrorChunk");function _m(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}}}}s(_m,"mapWebSearchOutput");function Jt(e){return JSON.stringify(e).slice(1,-1)}s(Jt,"escapeJSONDelta");var Mw=K(()=>H(v({instructions:p().nullish(),speed:A().min(.25).max(4).default(1).nullish()}))),jw=(nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:a,instructions:i,language:o,providerOptions:u}){const l=[],c=await Ve({provider:"openai",providerOptions:u,schema:Mw}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:a,instructions:i};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 m={};for(const h in m){const D=m[h];D!==void 0&&(d[h]=D)}}return o&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,a;const i=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{requestBody:o,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await Se({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:o,failedResponseHandler:dt,successfulResponseHandler:M2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(o)},response:{timestamp:i,modelId:this.modelId,headers:c,body:d}}}},s(nr,"OpenAISpeechModel"),nr),zw=K(()=>H(v({text:p(),language:p().nullish(),duration:A().nullish(),words:B(v({word:p(),start:A(),end:A()})).nullish(),segments:B(v({id:A(),seek:A(),start:A(),end:A(),text:p(),tokens:B(A()),temperature:A(),avg_logprob:A(),compression_ratio:A(),no_speech_prob:A()})).nullish()}))),qw=K(()=>H(v({include:B(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:A().min(0).max(1).default(0).optional(),timestampGranularities:B(oe(["word","segment"])).default(["segment"]).optional()}))),Fm={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"},Zw=(rr=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 a=[],i=await Ve({provider:"openai",providerOptions:r,schema:qw}),o=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([Ut(t)]);o.append("model",this.modelId);const l=zF(n);if(o.append("file",new File([u],"audio",{type:n}),`audio.${l}`),i){const c={include:i.include,language:i.language,prompt:i.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(const[d,m]of Object.entries(c))if(m!=null)if(Array.isArray(m))for(const h of m)o.append(`${d}[]`,String(h));else o.append(d,String(m))}return{formData:o,warnings:a}}async doGenerate(t){var n,r,a,i,o,u,l,c;const d=(a=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?a:new Date,{formData:m,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:f,rawValue:g}=await si({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),formData:m,failedResponseHandler:dt,successfulResponseHandler:Pe(zw),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in Fm?Fm[D.language]:void 0;return{text:D.text,segments:(l=(u=(i=D.segments)==null?void 0:i.map(F=>({text:F.text,startSecond:F.start,endSecond:F.end})))!=null?u:(o=D.words)==null?void 0:o.map(F=>({text:F.word,startSecond:F.start,endSecond:F.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:f,body:g}}}},s(rr,"OpenAITranscriptionModel"),rr),Lw="3.0.5";function ko(e={}){var t,n;const r=(t=ui(kr({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",a=(n=e.name)!=null?n:"openai",i=s(()=>Gt({Authorization:`Bearer ${jF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Lw}`),"getHeaders"),o=s(g=>new kE(g,{provider:`${a}.chat`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createChatModel"),u=s(g=>new SE(g,{provider:`${a}.completion`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createCompletionModel"),l=s(g=>new NE(g,{provider:`${a}.embedding`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createEmbeddingModel"),c=s(g=>new jE(g,{provider:`${a}.image`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createImageModel"),d=s(g=>new Zw(g,{provider:`${a}.transcription`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createTranscriptionModel"),m=s(g=>new jw(g,{provider:`${a}.speech`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch}),"createSpeechModel"),h=s(g=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(g)},"createLanguageModel"),D=s(g=>new ww(g,{provider:`${a}.responses`,url:s(({path:y})=>`${r}${y}`,"url"),headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),f=s(function(g){return h(g)},"provider");return f.specificationVersion="v3",f.languageModel=h,f.chat=o,f.completion=u,f.responses=D,f.embedding=l,f.embeddingModel=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=d,f.transcriptionModel=d,f.speech=m,f.speechModel=m,f.tools=yw,f}s(ko,"createOpenAI"),ko();var Uw=v({error:v({message:p(),type:p().nullish(),param:qe().nullish(),code:J([p(),A()]).nullish()})}),Pr={errorSchema:Uw,errorToMessage:s(e=>e.error.message,"errorToMessage")};function Cm(e){var t,n,r,a,i,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 u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(a=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?a:0,d=(o=(i=e.completion_tokens_details)==null?void 0:i.reasoning_tokens)!=null?o:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}s(Cm,"convertOpenAICompatibleChatUsage");function Mr(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}s(Mr,"getOpenAIMetadata");function Vw(e){var t;const n=[];for(const{role:r,content:a,...i}of e){const o=Mr({...i});switch(r){case"system":{n.push({role:"system",content:a,...o});break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text,...Mr(a[0])});break}n.push({role:"user",content:a.map(u=>{const l=Mr(u);switch(u.type){case"text":return{type:"text",text:u.text,...l};case"file":if(u.mediaType.startsWith("image/")){const c=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${c};base64,${Vt(u.data)}`},...l}}else throw new Je({functionality:`file part media type ${u.mediaType}`})}}),...o});break}case"assistant":{let u="";const l=[];for(const c of a){const d=Mr(c);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)},...d});break}}}n.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0,...o});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=(t=l.reason)!=null?t:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}const d=Mr(u);n.push({role:"tool",tool_call_id:u.toolCallId,content:c,...d})}break}default:{const u=r;throw new Error(`Unsupported role: ${u}`)}}}return n}s(Vw,"convertToOpenAICompatibleChatMessages");function bm({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}s(bm,"getResponseMetadata");function Em(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"}}s(Em,"mapOpenAICompatibleFinishReason");var Bi=v({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional()});function Gw({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 i of e)i.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${i.id}`}):r.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,...i.strict!=null?{strict:i.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:r,toolChoice:a,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const i=a;throw new Je({functionality:`tool choice type: ${i}`})}}}s(Gw,"prepareTools");var Ww=(or=class{constructor(t,n){this.specificationVersion="v3";var r,a;this.modelId=t,this.config=n;const i=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=Kw(i.errorSchema),this.failedResponseHandler=rt(i),this.supportsStructuredOutputs=(a=n.supportsStructuredOutputs)!=null?a:!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:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:a,topK:i,frequencyPenalty:o,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:m,toolChoice:h,tools:D}){var f,g,y,F;const w=[],b=Object.assign((f=await Ve({provider:"openai-compatible",providerOptions:l,schema:Bi}))!=null?f:{},(g=await Ve({provider:this.providerOptionsName,providerOptions:l,schema:Bi}))!=null?g:{});i!=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:E,toolChoice:O,toolWarnings:k}=Gw({tools:D,toolChoice:h});return{args:{model:this.modelId,user:b.user,max_tokens:n,temperature:r,top_p:a,frequency_penalty:o,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,name:(y=d.name)!=null?y:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:m,...Object.fromEntries(Object.entries((F=l?.[this.providerOptionsName])!=null?F:{}).filter(([C])=>!Object.keys(Bi.shape).includes(C))),reasoning_effort:b.reasoningEffort,verbosity:b.textVerbosity,messages:Vw(t),tools:E,tool_choice:O},warnings:[...w,...k]}}async doGenerate(t){var n,r,a,i,o,u;const{args:l,warnings:c}=await this.getArgs({...t}),d=JSON.stringify(l),{responseHeaders:m,value:h,rawValue:D}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:l,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(Hw),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=h.choices[0],g=[],y=f.message.content;y!=null&&y.length>0&&g.push({type:"text",text:y});const F=(n=f.message.reasoning_content)!=null?n:f.message.reasoning;if(F!=null&&F.length>0&&g.push({type:"reasoning",text:F}),f.message.tool_calls!=null)for(const E of f.message.tool_calls)g.push({type:"tool-call",toolCallId:(r=E.id)!=null?r:Be(),toolName:E.function.name,input:E.function.arguments});const w={[this.providerOptionsName]:{},...await((i=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:i.call(a,{parsedBody:D}))},b=(o=h.usage)==null?void 0:o.completion_tokens_details;return b?.accepted_prediction_tokens!=null&&(w[this.providerOptionsName].acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(w[this.providerOptionsName].rejectedPredictionTokens=b?.rejected_prediction_tokens),{content:g,finishReason:{unified:Em(f.finish_reason),raw:(u=f.finish_reason)!=null?u:void 0},usage:Cm(h.usage),providerMetadata:w,request:{body:d},response:{...bm(h),headers:m,body:D},warnings:c}}async doStream(t){var n;const{args:r,warnings:a}=await this.getArgs({...t}),i={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await Se({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:i,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},m,h=!0;const D=this.providerOptionsName;let f=!1,g=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:a})},transform(y,F){var w,b,E,O,k,C,L,Q,S,P,$,M,Z,R;if(t.includeRawChunks&&F.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.error});return}if(o?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},F.enqueue({type:"error",error:y.value.error.message});return}const q=y.value;h&&(h=!1,F.enqueue({type:"response-metadata",...bm(q)})),q.usage!=null&&(m=q.usage);const ee=q.choices[0];if(ee?.finish_reason!=null&&(d={unified:Em(ee.finish_reason),raw:(w=ee.finish_reason)!=null?w:void 0}),ee?.delta==null)return;const ae=ee.delta,V=(b=ae.reasoning_content)!=null?b:ae.reasoning;if(V&&(f||(F.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),F.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:V})),ae.content&&(g||(F.enqueue({type:"text-start",id:"txt-0"}),g=!0),F.enqueue({type:"text-delta",id:"txt-0",delta:ae.content})),ae.tool_calls!=null)for(const X of ae.tool_calls){const G=X.index;if(c[G]==null){if(X.id==null)throw new _r({data:X,message:"Expected 'id' to be a string."});if(((E=X.function)==null?void 0:E.name)==null)throw new _r({data:X,message:"Expected 'function.name' to be a string."});F.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),c[G]={id:X.id,type:"function",function:{name:X.function.name,arguments:(O=X.function.arguments)!=null?O:""},hasFinished:!1};const le=c[G];((k=le.function)==null?void 0:k.name)!=null&&((C=le.function)==null?void 0:C.arguments)!=null&&(le.function.arguments.length>0&&F.enqueue({type:"tool-input-delta",id:le.id,delta:le.function.arguments}),bo(le.function.arguments)&&(F.enqueue({type:"tool-input-end",id:le.id}),F.enqueue({type:"tool-call",toolCallId:(L=le.id)!=null?L:Be(),toolName:le.function.name,input:le.function.arguments}),le.hasFinished=!0));continue}const te=c[G];te.hasFinished||(((Q=X.function)==null?void 0:Q.arguments)!=null&&(te.function.arguments+=(P=(S=X.function)==null?void 0:S.arguments)!=null?P:""),F.enqueue({type:"tool-input-delta",id:te.id,delta:($=X.function.arguments)!=null?$:""}),((M=te.function)==null?void 0:M.name)!=null&&((Z=te.function)==null?void 0:Z.arguments)!=null&&bo(te.function.arguments)&&(F.enqueue({type:"tool-input-end",id:te.id}),F.enqueue({type:"tool-call",toolCallId:(R=te.id)!=null?R:Be(),toolName:te.function.name,input:te.function.arguments}),te.hasFinished=!0))}},flush(y){var F,w,b,E,O;f&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&y.enqueue({type:"text-end",id:"txt-0"});for(const C of c.filter(L=>!L.hasFinished))y.enqueue({type:"tool-input-end",id:C.id}),y.enqueue({type:"tool-call",toolCallId:(F=C.id)!=null?F:Be(),toolName:C.function.name,input:C.function.arguments});const k={[D]:{},...o?.buildMetadata()};((w=m?.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens)!=null&&(k[D].acceptedPredictionTokens=(b=m?.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((E=m?.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens)!=null&&(k[D].rejectedPredictionTokens=(O=m?.completion_tokens_details)==null?void 0:O.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:Cm(m),providerMetadata:k})}})),request:{body:i},response:{headers:u}}}},s(or,"OpenAICompatibleChatLanguageModel"),or),wm=v({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:v({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:v({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish(),Hw=v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({message:v({role:I("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:B(v({id:p().nullish(),function:v({name:p(),arguments:p()})})).nullish()}),finish_reason:p().nullish()})),usage:wm}),Jw=v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({delta:v({role:oe(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:B(v({index:A(),id:p().nullish(),function:v({name:p().nullish(),arguments:p().nullish()})})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:wm}),Kw=s(e=>J([Jw,e]),"createOpenAICompatibleChatChunkSchema");function Am(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,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:a,text:a,reasoning:void 0},raw:e}}s(Am,"convertOpenAICompatibleCompletionUsage");function Yw({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
161
|
+
|
|
162
|
+
`,e=e.slice(1));for(const{role:a,content:i}of e)switch(a){case"system":throw new At({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const o=i.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
|
|
163
|
+
${o}
|
|
164
|
+
|
|
165
|
+
`;break}case"assistant":{const o=i.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new Je({functionality:"tool-call messages"})}}).join("");r+=`${n}:
|
|
166
|
+
${o}
|
|
167
|
+
|
|
168
|
+
`;break}case"tool":throw new Je({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return r+=`${n}:
|
|
169
|
+
`,{prompt:r,stopSequences:[`
|
|
170
|
+
${t}:`]}}s(Yw,"convertToOpenAICompatibleCompletionPrompt");function Im({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}s(Im,"getResponseMetadata2");function xm(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"}}s(xm,"mapOpenAICompatibleFinishReason2");var Xw=v({echo:Ae().optional(),logitBias:me(p(),A()).optional(),suffix:p().optional(),user:p().optional()}),Qw=(ar=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const a=(r=n.errorStructure)!=null?r:Pr;this.chunkSchema=t1(a.errorSchema),this.failedResponseHandler=rt(a)}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:a,topK:i,frequencyPenalty:o,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:m,tools:h,toolChoice:D}){var f;const g=[],y=(f=await Ve({provider:this.providerOptionsName,providerOptions:m,schema:Xw}))!=null?f:{};i!=null&&g.push({type:"unsupported",feature:"topK"}),h?.length&&g.push({type:"unsupported",feature:"tools"}),D!=null&&g.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&g.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:F,stopSequences:w}=Yw({prompt:t}),b=[...w??[],...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:a,frequency_penalty:o,presence_penalty:u,seed:d,...m?.[this.providerOptionsName],prompt:F,stop:b.length>0?b:void 0},warnings:g}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Pe(e1),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=i.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:Am(i.usage),finishReason:{unified:xm(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...Im(i),headers:a,body:o},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),a={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:i,value:o}=await Se({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xe(this.config.headers(),t.headers),body:a,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:fn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,m){var h;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...Im(D)}),m.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const f=D.choices[0];f?.finish_reason!=null&&(u={unified:xm(f.finish_reason),raw:(h=f.finish_reason)!=null?h:void 0}),f?.text!=null&&m.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:Am(l)})}})),request:{body:a},response:{headers:i}}}},s(ar,"OpenAICompatibleCompletionLanguageModel"),ar),km=v({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}),e1=v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({text:p(),finish_reason:p()})),usage:km.nullish()}),t1=s(e=>J([v({id:p().nullish(),created:A().nullish(),model:p().nullish(),choices:B(v({text:p(),finish_reason:p().nullish(),index:A()})),usage:km.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),$m=v({dimensions:A().optional(),user:p().optional()}),n1=(ir=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:a}){var i,o,u;const l=Object.assign((i=await Ve({provider:"openai-compatible",providerOptions:a,schema:$m}))!=null?i:{},(o=await Ve({provider:this.providerOptionsName,providerOptions:a,schema:$m}))!=null?o:{});if(t.length>this.maxEmbeddingsPerCall)throw new ql({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:c,value:d,rawValue:m}=await Se({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xe(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:l.dimensions,user:l.user},failedResponseHandler:rt((u=this.config.errorStructure)!=null?u:Pr),successfulResponseHandler:Pe(r1),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:d.data.map(h=>h.embedding),usage:d.usage?{tokens:d.usage.prompt_tokens}:void 0,providerMetadata:d.providerMetadata,response:{headers:c,body:m}}}},s(ir,"OpenAICompatibleEmbeddingModel"),ir),r1=v({data:B(v({embedding:B(A())})),usage:v({prompt_tokens:A()}).nullish(),providerMetadata:me(p(),me(p(),qe())).optional()}),o1=(sr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:a,seed:i,providerOptions:o,headers:u,abortSignal:l,files:c,mask:d}){var m,h,D,f,g,y,F;const w=[];a!=null&&w.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&w.push({type:"unsupported",feature:"seed"});const b=(D=(h=(m=this.config._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m))!=null?D:new Date;if(c!=null&&c.length>0){const{value:k,responseHeaders:C}=await si({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xe(this.config.headers(),u),formData:qc({model:this.modelId,prompt:t,image:await Promise.all(c.map(L=>Bm(L))),mask:d!=null?await Bm(d):void 0,n,size:r,...(f=o.openai)!=null?f:{}}),failedResponseHandler:rt((g=this.config.errorStructure)!=null?g:Pr),successfulResponseHandler:Pe(Tm),abortSignal:l,fetch:this.config.fetch});return{images:k.data.map(L=>L.b64_json),warnings:w,response:{timestamp:b,modelId:this.modelId,headers:C}}}const{value:E,responseHeaders:O}=await Se({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xe(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...(y=o.openai)!=null?y:{},response_format:"b64_json"},failedResponseHandler:rt((F=this.config.errorStructure)!=null?F:Pr),successfulResponseHandler:Pe(Tm),abortSignal:l,fetch:this.config.fetch});return{images:E.data.map(k=>k.b64_json),warnings:w,response:{timestamp:b,modelId:this.modelId,headers:O}}}},s(sr,"OpenAICompatibleImageModel"),sr),Tm=v({data:B(v({b64_json:p()}))});async function Bm(e){if(e.type==="url")return ei(e.url);const t=e.data instanceof Uint8Array?e.data:Ut(e.data);return new Blob([t],{type:e.mediaType})}s(Bm,"fileToBlob");var a1="2.0.4";function Si(e){const t=ui(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},a=s(()=>Gt(r,`ai-sdk/openai-compatible/${a1}`),"getHeaders"),i=s(h=>({provider:`${n}.${h}`,url:s(({path:D})=>{const f=new URL(`${t}${D}`);return e.queryParams&&(f.search=new URLSearchParams(e.queryParams).toString()),f.toString()},"url"),headers:a,fetch:e.fetch}),"getCommonModelConfig"),o=s(h=>u(h),"createLanguageModel"),u=s(h=>new Ww(h,{...i("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs}),"createChatModel"),l=s(h=>new Qw(h,{...i("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=s(h=>new n1(h,{...i("embedding")}),"createEmbeddingModel"),d=s(h=>new o1(h,i("image")),"createImageModel"),m=s(h=>o(h),"provider");return m.specificationVersion="v3",m.languageModel=o,m.chatModel=u,m.completionModel=l,m.embeddingModel=c,m.textEmbeddingModel=c,m.imageModel=d,m}s(Si,"createOpenAICompatible");const $o={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"},i1={"\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"},Sm={"":"<commit message>",conventional:"<type>[optional (<scope>)]: <commit message>",gitmoji:":emoji: <commit message>"},s1=s(e=>{if(!e)return $o;try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return $o;const n=Object.entries(t).filter(([r,a])=>typeof r=="string"&&r.trim().length>0&&typeof a=="string"&&a.trim().length>0).map(([r,a])=>[r.trim(),a.trim()]);return n.length===0?$o:Object.fromEntries(n)}catch{return $o}},"parseConventionalTypes"),u1=s((e,t)=>e==="conventional"?t?.trim()||Sm.conventional:Sm[e],"getCommitFormat"),Om=s((e,t)=>`The output response must be in format:
|
|
171
|
+
${u1(e,t)}`,"specifyCommitFormat"),Rm=s((e,t)=>e==="conventional"?`Choose a type from the type-to-description JSON below that best describes the git diff:
|
|
172
|
+
${JSON.stringify(s1(t),null,2)}`:e==="gitmoji"?`Choose an emoji from the emoji-to-description JSON below that best describes the git diff:
|
|
173
|
+
${JSON.stringify(i1,null,2)}`:"","getCommitTypeInstruction"),Nm=s(e=>e?["Provide both a title and a body.","Output format must be exactly:","<title>","","<body>","The body should summarize the important changes in 2-4 concise bullet points."].join(`
|
|
174
|
+
`):"Provide only the title, no description or body.","getDetailsInstruction"),Pm=s(e=>e?.trim()?`Additional instructions from user:
|
|
175
|
+
${e.trim()}`:"","getCustomInstructions"),l1=s((e,t,n,r={})=>["Generate a concise git commit message in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names.",Nm(r.includeDetails??!1),`Message language: ${e}`,`Commit title 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 title 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.",Rm(n,r.conventionalTypes),Om(n,r.conventionalFormat),Pm(r.instructions)].filter(Boolean).join(`
|
|
176
|
+
`),"generatePrompt"),c1=s((e,t,n={})=>["You are a tool that combines multiple partial git commit messages into one final commit message.","Input: Several commit messages separated by newlines.",n.includeDetails?"Output: A single commit message with title and body.":"Output: A single commit message title.",Nm(n.includeDetails??!1),`Commit title must be a maximum of ${e} characters.`,"Do not add thanks, explanations, code fences, or any text outside the commit message.",Rm(t,n.conventionalTypes),Om(t,n.conventionalFormat),Pm(n.instructions)].filter(Boolean).join(`
|
|
177
|
+
`),"generateCombinePrompt"),Mm=s(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),p1=s(e=>e.replace(/\r\n?/g,`
|
|
178
|
+
`),"normalizeLineEndings"),d1=s(e=>{const t=e.match(/```(?:[a-zA-Z0-9_-]+)?\n([\s\S]*?)```/);return t?.[1]?t[1].trim():e.replace(/```/g,"").trim()},"stripCodeFences"),jm=s(e=>e.trim().replace(/^title:\s*/i,"").replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeTitle"),To=s(e=>{const t=p1(e).trim();if(!t)return{title:"",body:""};const n=t.split(`
|
|
179
|
+
`).map(i=>i.replace(/\s+$/g,""));for(;n[0]?.trim()==="";)n.shift();const r=jm(n.shift()||"");for(;n[0]?.trim()==="";)n.shift();n[0]?.trim().toLowerCase().startsWith("body:")&&(n[0]=n[0].replace(/^body:\s*/i,""));const a=n.join(`
|
|
180
|
+
`).trim();return{title:r,body:a}},"splitCommitMessage"),Oi=s((e,t)=>t?`${e}
|
|
181
|
+
|
|
182
|
+
${t}`:e,"formatCommitMessage"),zm=s(e=>jm(Mm(e).trim().split(`
|
|
183
|
+
`)[0]),"sanitizeSimpleMessage"),m1=s(e=>{const t=d1(Mm(e)),{title:n,body:r}=To(t);return Oi(n,r)},"sanitizeDetailedMessage"),qm=s((e,t)=>t?m1(e):zm(e),"sanitizeMessage"),Zm=s(e=>Array.from(new Set(e)),"deduplicateMessages"),Lm=s(async(e,t,n,r,a)=>{const i=new AbortController,o=setTimeout(()=>i.abort(),a);try{const u=await Nr({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});return clearTimeout(o),zm(u.text)}catch(u){throw clearTimeout(o),u}},"shortenCommitMessage"),Um=s(async(e,t,n,r,a,i)=>{if(!i)return n.length<=r?n:Lm(e,t,n,r,a);const{title:o,body:u}=To(n);if(!o||o.length<=r)return Oi(o,u);const l=await Lm(e,t,o,r,a);return Oi(l,u)},"shortenTitleIfNeeded"),Ri=s(async(e,t,n,r,a,i,o,u,l,c={})=>{process.env.DEBUG&&(console.log("Diff being sent to AI:"),console.log(a));const d=c.includeDetails??!1;try{const m=e==="https://api.openai.com/v1"?ko({apiKey:t}):Si({name:"custom",apiKey:t,baseURL:e}),h=new AbortController,D=setTimeout(()=>h.abort(),l),f=Array.from({length:i},()=>Nr({model:m(n),system:l1(r,o,u,c),prompt:a,temperature:.4,maxRetries:2,maxOutputTokens:2e3}).finally(()=>clearTimeout(D))),g=await Promise.all(f);let y=Zm(g.map(b=>qm(b.text,d)).filter(Boolean));const F=3;for(let b=0;b<F;b++){let E=!1;const O=await Promise.all(y.map(async k=>{if((d?To(k).title:k).length<=o)return k;E=!0;try{return await Um(m,n,k,o,l,d)}catch{return k}}));if(y=Zm(O).filter(Boolean),!E)break}const w={prompt_tokens:g.reduce((b,E)=>b+(E.usage.promptTokens||0),0),completion_tokens:g.reduce((b,E)=>b+(E.usage.completionTokens||0),0),total_tokens:g.reduce((b,E)=>b+(E.usage.totalTokens||0),0)};return{messages:y,usage:w}}catch(m){const h=m;if(console.log(h),h.code==="ENOTFOUND")throw new se(`Error connecting to ${h.hostname} (${h.syscall}). Are you connected to the internet?`);if(h.status===429){const D=h.headers?.get("x-ratelimit-reset");let f="Rate limit exceeded";if(D){const g=parseInt(D),y=Date.now(),F=g-y,w=Math.ceil(F/1e3);if(w>0){let b;if(w<60)b=`${w} second${w===1?"":"s"}`;else if(w<3600){const E=Math.ceil(w/60);b=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(w/3600);b=`${E} hour${E===1?"":"s"}`}f+=`. Retry in ${b}.`}}throw new se(f)}throw h}},"generateCommitMessage"),f1=s(async(e,t,n,r,a,i,o,u,l={})=>{const c=l.includeDetails??!1;try{const d=t==="https://api.openai.com/v1"?ko({apiKey:n}):Si({name:"custom",apiKey:n,baseURL:t}),m=new AbortController,h=setTimeout(()=>m.abort(),u),D=await Nr({model:d(r),system:c1(i,o,l),prompt:e.join(`
|
|
184
|
+
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
`),temperature:.4,maxRetries:2,maxOutputTokens:2e3});clearTimeout(h);let f=qm(D.text,c);if((c?To(f).title:f).length>i)try{f=await Um(d,r,f,i,u,c)}catch{}return{messages:[f],usage:D.usage}}catch(d){const m=d;throw console.log(m),m}},"combineCommitMessages"),h1=s(async(e,t)=>{const{select:n,confirm:r,isCancel:a}=await Promise.resolve().then(function(){return gr}),{dim:i}=await Promise.resolve().then(function(){return QD}),o=s(c=>c.split(`
|
|
188
|
+
`)[0]||c,"getTitle"),u=process.stdout.isTTY&&!process.env.CI;if(e.length===1){const[c]=e;if(t)return c;if(!u)throw new se("Interactive terminal required for commit message confirmation. Use --confirm flag to skip confirmation.");console.log(`
|
|
189
|
+
\x1B[1m${c}\x1B[0m
|
|
190
|
+
`);const d=await r({message:"Use this commit message?"});return d&&!a(d)?c:null}if(t)return e[0];if(!u)throw new se("Interactive terminal required for commit message selection. Use --confirm flag to skip selection and use the first message.");const l=await n({message:`Pick a commit message to use: ${i("(Ctrl+c to exit)")}`,options:e.map(c=>({label:o(c),value:c,hint:c.includes(`
|
|
191
|
+
`)?"Includes details":void 0}))});return a(l)?null:l},"getCommitMessage");var D1=s(async(e,t,n,r,a,i,o,u,l,c,d,m)=>(async()=>{ro(Yr(Kr(" aicommits "))),await $a();const h=Mt();n&&await We("git",["add","--update"]),h.start("Detecting staged files");const D=await Ju(t);if(!D)throw h.stop("Detecting staged files"),new se("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");D.files.length<=10?h.stop(`\u{1F4C1} ${Ku(D.files)}:
|
|
192
|
+
${D.files.map($=>` ${$}`).join(`
|
|
193
|
+
`)}`):h.stop(`\u{1F4C1} ${Ku(D.files)}`);const{env:f}=process,g=await jt({generate:e?.toString(),type:r?.toString(),details:a?"true":void 0,instructions:i,"conventional-format":o,"conventional-types":u}),y={includeDetails:g.details,instructions:g.instructions,conventionalFormat:g["conventional-format"],conventionalTypes:g["conventional-types"]},F=ln(g);if(!F)if(process.stdout.isTTY&&!process.env.CI){console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),ve("Setup required. Please run: aicommits setup");return}else throw new se("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");const w=g.timeout||(F.name==="ollama"?3e4:1e4),b=F.validateConfig();if(!b.valid)throw new se(`Provider configuration issues: ${b.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);g.model=g.OPENAI_MODEL||F.getDefaultModel();const E=50,O=10;let k=!1;D.files.length>E&&(k=!0);const C=Mt();C.start(`\u{1F50D} Analyzing changes in ${D.files.length} file${D.files.length===1?"":"s"}`);const L=Date.now();let Q,S;try{const $=F.getBaseUrl(),M=F.getApiKey()||"";if(k){const Z=[];for(let ae=0;ae<D.files.length;ae+=O)Z.push(D.files.slice(ae,ae+O));const R=[];let q={promptTokens:0,completionTokens:0,totalTokens:0};for(const ae of Z){const V=await Pg(ae,t);if(V&&V.diff){let G=V.diff;G.length>3e4&&(G=G.substring(G.length-3e4)+`
|
|
194
|
+
|
|
195
|
+
[Diff truncated due to size]`);const te=await Ri($,M,g.model,g.locale,G,g.generate,g["max-length"],g.type,w,y);R.push(...te.messages),te.usage&&(q.promptTokens+=te.usage.promptTokens||0,q.completionTokens+=te.usage.completionTokens||0,q.totalTokens+=te.usage.totalTokens||0)}}const ee=await f1(R,$,M,g.model,g.locale,g["max-length"],g.type,w,y);Q=ee.messages,ee.usage&&(q.promptTokens+=ee.usage.promptTokens||0,q.completionTokens+=ee.usage.completionTokens||0,q.totalTokens+=ee.usage.totalTokens||0),S=q}else{let R=D.diff;R.length>3e4&&(R=R.substring(R.length-3e4)+`
|
|
196
|
+
|
|
197
|
+
[Diff truncated due to size]`);const q=await Ri($,M,g.model,g.locale,R,g.generate,g["max-length"],g.type,w,y);Q=q.messages,S=q.usage}}finally{const $=Date.now()-L;let M="";if(S?.total_tokens){const Z=S.total_tokens,R=Z>=1e3?`${(Z/1e3).toFixed(0)}k`:Z.toString(),q=Math.round(Z/($/1e3));M=`, ${R} tokens (${q} tokens/s)`}C.stop(`\u2705 Changes analyzed in ${($/1e3).toFixed(1)}s${M}`)}if(Q.length===0)throw new se("No commit messages were generated. Try again.");const P=await h1(Q,l);if(!P){ve("Commit cancelled");return}if(c){await wu(P)&&ve(`${ht("\u2714")} Message copied to clipboard`);return}try{const $=["-m",P];d&&$.push("--no-verify"),await We("git",["commit",...$,...m],{stdio:"inherit",cleanup:!0,timeout:1e4}),ve(`${ht("\u2714")} Successfully committed!`)}catch($){if($.timedOut){const M=await wu(P);ve(M?`${fa("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${fa("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw $}})().catch(oo),"aicommits");const[Bo,g1]=process.argv.slice(2);var v1=s(()=>(async()=>{if(!Bo)throw new se('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(g1)return;const e=await Ju();if(!e)return;ro(Yr(Kr(" aicommits ")));const t=await jt({}),n=ln(t);if(!n)throw new se("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const r=n.validateConfig();if(!r.valid)throw new se(`Provider configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const a=n.getBaseUrl(),i=n.getApiKey()||"",o=t.timeout||(n.name==="ollama"?3e4:1e4);let u=t.OPENAI_MODEL||n.getDefaultModel();const l=Mt();l.start("The AI is analyzing your changes");let c;try{const F={includeDetails:t.details,instructions:t.instructions,conventionalFormat:t["conventional-format"],conventionalTypes:t["conventional-types"]};c=(await Ri(a,i,u,t.locale,e.diff,t.generate,t["max-length"],t.type,o,F)).messages}finally{l.stop("Changes analyzed")}const m=await Ne.readFile(Bo,"utf8")!=="",h=c.length>1;let D="";const f=s(F=>F.split(`
|
|
198
|
+
`).map(w=>`# ${w}`).join(`
|
|
199
|
+
`),"commentOut");m&&(D=`# \u{1F916} AI generated commit${h?"s":""}
|
|
200
|
+
`),h?(m&&(D+=`# Select one of the following messages by uncommenting:
|
|
201
|
+
`),D+=`
|
|
202
|
+
${c.map(F=>f(F)).join(`
|
|
203
|
+
#
|
|
204
|
+
`)}`):(m&&(D+=`# Edit the message below and commit:
|
|
205
|
+
`),D+=`
|
|
206
|
+
${c[0]}
|
|
207
|
+
`);const g=await Ne.readFile(Bo,"utf8"),y=D+`
|
|
208
|
+
`+g;await Ne.writeFile(Bo,y),ve(`${ht("\u2714")} Saved commit message!`)})().catch(oo),"prepareCommitMessageHook"),y1=rn({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 jt({},{},!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 jt({},{},!0),a=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const i of n)if(Sa(r,i)){const o=r[i],u=a.includes(i)?`${String(o).substring(0,4)}****`:String(o);console.log(`${i}=${u}`)}return}if(t==="set"){await Ra(n.map(r=>r.split("=")));return}throw new se(`Invalid mode: ${t}`)})().catch(oo)}),_1=rn({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{let t=await jt();const n=lv(),r=await Vu({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Dr(r)){ve("Setup cancelled");return}const a=r;let i="";if(a==="custom"){const h=await Uu({message:"Enter your custom API endpoint:",validate:s(D=>{if(!D)return"Endpoint is required";try{new URL(D)}catch{return"Invalid URL format"}},"validate")});if(Dr(h)){ve("Setup cancelled");return}i=h}let o=i||cv(a);t.OPENAI_BASE_URL=o,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=ln({...t,provider:a});if(!u){ve("Invalid provider selected");return}try{const h=await u.setup();for(const[D,f]of h)t[D]=f}catch(h){if(h instanceof Error&&h.message==="Setup cancelled"){ve("Setup cancelled");return}throw h}if(u=ln({...t,provider:a}),!u){ve("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){ve(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return iv}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{ve("Model selection cancelled.");return}const m=Object.entries(t).filter(([h,D])=>h!=="provider"&&h!=="model"&&D!==void 0&&D!==""&&typeof D=="string");await Ra(m),ve(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(t=>{console.error(`\u274C Setup failed: ${t.message}`),process.exit(1)})}),F1=rn({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{const e=await jt();if(!e.provider){ve("No provider configured. Run `aicommits setup` first.");return}const t=ln(e);if(!t){ve("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}console.log(`Current provider: ${t.displayName}`);const n=e.OPENAI_MODEL;console.log(`Current model: ${n&&n!=="undefined"?n:"not set"}`);const r=t.validateConfig();if(!r.valid){ve(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const a=await rl(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition());a?(await Ra([["OPENAI_MODEL",a]]),ve(`\u2705 Model updated to: ${a}`)):ve("Model selection cancelled")})().catch(e=>{console.error(`\u274C Model selection failed: ${e.message}`),process.exit(1)})});const Vm="prepare-commit-msg",Gm=`.git/hooks/${Vm}`,So=hf(new URL("cli.mjs",import.meta.url)),C1=process.argv[1].replace(/\\/g,"/").endsWith(`/${Gm}`),Wm=process.platform==="win32",Hm=`
|
|
209
|
+
#!/usr/bin/env node
|
|
210
|
+
import(${JSON.stringify(Df(So))})
|
|
211
|
+
`.trim();var b1=rn({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 $a(),{installUninstall:n}=e._,r=it.join(t,Gm),a=await Ba(r);if(n==="install"){if(a){if(await Ne.realpath(r).catch(()=>{})===So){console.warn("The hook is already installed");return}throw new se(`A different ${Vm} hook seems to be installed. Please remove it before installing aicommits.`)}await Ne.mkdir(it.dirname(r),{recursive:!0}),Wm?await Ne.writeFile(r,Hm):(await Ne.symlink(So,r,"file"),await Ne.chmod(r,493)),console.log(`${ht("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!a){console.warn("Hook is not installed");return}if(Wm){if(await Ne.readFile(r,"utf8")!==Hm){console.warn("Hook is not installed");return}}else if(await Ne.realpath(r)!==So){console.warn("Hook is not installed");return}await Ne.rm(r),console.log(`${ht("\u2714")} Hook uninstalled`);return}throw new se(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${ma("\u2716")} ${t.message}`),Gu(t),process.exit(1)})}),E1=rn({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR on GitHub based on branch diff"}},()=>{(async()=>{ro(Yr(Kr(" aicommits pr "))),await $a();const{stdout:e}=await We("git",["branch","--show-current"]);if(!e.trim())throw new se("Not on a branch");const{stdout:t}=await We("git",["remote","get-url","origin"]),n=t.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(!n)throw new se("Could not determine GitHub repository from remote URL");const[,r,a]=n;let i="main";try{const{stdout:S}=await We("git",["symbolic-ref","refs/remotes/origin/HEAD"]);i=S.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===i)throw new se("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let o;try{const{stdout:S}=await We("git",["diff",`origin/${i}..HEAD`]);o=S}catch{throw new se(`Could not get diff from origin/${i}`)}if(!o)throw new se("No changes to create PR from");const u=o.split(`
|
|
212
|
+
`).filter(S=>S.startsWith("diff --git")).length,l=3e4;o.length>l&&(o=o.substring(0,l)+`
|
|
213
|
+
|
|
214
|
+
[Diff truncated due to size]`);const c=await jt(),d=await ln(c);if(!d)throw new se("No provider configured");let m=d.getBaseUrl();if(!m||m==="")throw new se("Base URL not configured. Please run `aicommits setup` to configure your provider.");m.endsWith("/v1")||(m+="/v1");const h=d.getApiKey();if(!h)throw new se("API key not configured. Please run `aicommits setup` to configure your provider.");const D=m==="https://api.openai.com/v1"?ko({apiKey:h}):Si({name:"custom",apiKey:h,baseURL:m}),f=Mt();f.start(`Generating PR title and description (${u} files changed)`);const g=Date.now(),F=(await Nr({model:D(c.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:o,maxRetries:2})).text,b=(await Nr({model:D(c.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:o,maxRetries:2})).text,E=Date.now(),O=Math.round((E-g)/1e3);f.stop(`Generated PR content for ${u} files in ${O}s`),console.log(`${ht("Title:")} ${F.replace(/\n/g," ")}`),console.log(`${ht("Body:")} ${b.length>100?b.substring(0,100)+"...":b}`);const{text:k}=await Promise.resolve().then(function(){return gr}),C=await k({message:"Press Enter to open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Dr(C)){ve("PR creation cancelled");return}const L=`https://github.com/${r}/${a}/compare/${i}...${e.trim()}?expand=1&title=${encodeURIComponent(F)}&body=${encodeURIComponent(b)}`,Q=Mt();Q.start("Opening PR creation page in browser");try{const S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await We(S,[L]),Q.stop("PR creation page opened in browser"),ve(ht("PR creation page opened! Please review and submit the PR."))}catch{Q.stop("Failed to open browser"),ve(`${ht("PR URL:")} ${L}`),ve("Please open the URL above in your browser to create the PR.")}})().catch(e=>{oo(e)})});const{description:w1,version:Oo}=Wo,A1=ef({pkg:Wo,distTag:Oo.includes("-")?"develop":"latest"});Oo!=="0.0.0-semantic-release"&&Oo.includes("-")&&A1.notify();const Jm=process.argv.slice(2);Js({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: conventional). Supports conventional and gitmoji",alias:"t"},details:{type:Boolean,description:"Generate commit message details/body in addition to the title (default: false)",default:!1},instructions:{type:String,description:"Additional custom prompt instructions (tone, detail level, style, etc.)"},conventionalFormat:{type:String,description:"Custom conventional commit format template (works with --type conventional)"},conventionalTypes:{type:String,description:"Custom conventional commit type map as JSON (works with --type conventional)"},confirm:{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},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[y1,_1,F1,b1,E1],help:{description:w1},ignoreArgv:s(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(Oo),process.exit(0)),C1?v1():D1(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.details,e.flags.instructions,e.flags.conventionalFormat,e.flags.conventionalTypes,e.flags.confirm,e.flags.clipboard,e.flags.noVerify,Jm)},Jm);export{St as g,up as r};
|