blink 0.1.54 → 0.1.56

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.
Files changed (55) hide show
  1. package/dist/api/index.cjs +16 -9
  2. package/dist/api/index.d.cts +2 -265
  3. package/dist/api/index.d.ts +2 -265
  4. package/dist/api/index.js +15 -8
  5. package/dist/build/index.cjs +7 -0
  6. package/dist/build/index.d.cts +107 -0
  7. package/dist/build/index.d.ts +107 -0
  8. package/dist/build/index.js +7 -0
  9. package/dist/chunk-___ucjiX.js +1 -0
  10. package/dist/chunk-hhQzssFb.cjs +1 -0
  11. package/dist/cli/auth-BUNIOupD.js +30 -0
  12. package/dist/cli/{chat-VT2y0Ejx.js → chat-L0VBV1Zr.js} +1 -1
  13. package/dist/cli/connect-BHyGYU8L.js +1 -0
  14. package/dist/cli/connect-Cxa-uIEb.js +26 -0
  15. package/dist/cli/{dev-DWe1-Qrm.js → dev-DEnRzFLe.js} +421 -352
  16. package/dist/cli/devtools-BS9tk1Y9.js +14 -14
  17. package/dist/cli/{dist-CN69Y-yA.js → dist-NqrnQGst.js} +1 -1
  18. package/dist/cli/esm-CeJfCMPI.js +1 -1
  19. package/dist/cli/index.js +10 -10
  20. package/dist/cli/{init-CyILyaVn.js → init-B61NlodJ.js} +2 -2
  21. package/dist/cli/login-DKW_KVCA.js +1 -0
  22. package/dist/cli/undici-BG07ys6c.js +6 -6
  23. package/dist/cli/util-cVEGIV3r.js +9 -0
  24. package/dist/cli/wrapper-B4vDwpOq.js +2 -2
  25. package/dist/cookie-C9-j7DLy.cjs +1 -0
  26. package/dist/cookie-vgkq7-5W.js +1 -0
  27. package/dist/http/api.cjs +1 -0
  28. package/dist/http/api.d.cts +186 -0
  29. package/dist/http/api.d.ts +186 -0
  30. package/dist/http/api.js +1 -0
  31. package/dist/http/index.cjs +1 -0
  32. package/dist/http/index.d.cts +3 -0
  33. package/dist/http/index.d.ts +3 -0
  34. package/dist/http/index.js +1 -0
  35. package/dist/http-DGkzwMDO.js +53 -0
  36. package/dist/http-DVkCunru.cjs +53 -0
  37. package/dist/index-BUiNoSbu.d.ts +286 -0
  38. package/dist/index-BgJpZoBy.d.cts +102 -0
  39. package/dist/index-DxJfaHIB.d.ts +102 -0
  40. package/dist/index-IWju3eNc.d.cts +286 -0
  41. package/dist/test.cjs +1 -4
  42. package/dist/test.d.cts +4 -1
  43. package/dist/test.d.ts +4 -1
  44. package/dist/test.js +1 -4
  45. package/package.json +17 -8
  46. package/dist/cli/auth-BP6XsB4o.js +0 -30
  47. package/dist/cli/connect-CUOPse6P.js +0 -1
  48. package/dist/cli/connect-CswVxp7Y.js +0 -26
  49. package/dist/cli/login-JR8bA13P.js +0 -1
  50. package/dist/cli/main-DqOlaYW2.js +0 -6
  51. package/dist/cli/serve-CEeYlO7w.js +0 -60
  52. package/dist/cli/serve-DY71nMqp.js +0 -1
  53. package/dist/cookie-CB9k3Awr.js +0 -11
  54. package/dist/cookie-Dx2Kx4Zh.cjs +0 -11
  55. /package/dist/cli/{open-Cr8lEmcs.js → open-CSMQaj0E.js} +0 -0
@@ -1,60 +0,0 @@
1
- import{__commonJSMin as e,__esmMin as t,__export as n,__require as r,__toCommonJS as i,__toESM as a}from"./chunk-ByIbJXPc.js";import{SpanStatusCode as o,init_esm as s,trace as c}from"./esm-CeJfCMPI.js";import{Emitter as l}from"./events-CWgtj8lb.js";import{createServer as u}from"http";import*as d from"node:path";import*as f from"node:fs";import{join as p,resolve as m}from"path";import{z as h}from"zod";import*as g from"zod/v4";import _,{z as v}from"zod/v4";import{ZodFirstPartyTypeKind as y}from"zod/v3";import{spawn as b}from"child_process";import x from"fs";import{tmpdir as S}from"os";const C=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`);function w(e){return e?.then!=null}function T(e){let t=e;return t&&t.then&&t.catch&&t.finally}function E(e,t,n,r){let i=D().then(e).then(t,n);return r&&(i=i.finally(r)),M(i)}function D(e){return e&&T(e)?e:w(e)?{then:(t,n)=>D(e.then(t,n)),catch:t=>D(e.then(e=>e,t)),finally:t=>D(t?j(e,t):e),[Symbol.toStringTag]:`Promise`}:{then(t){if(t)try{return D(t(e))}catch(e){return A(e)}return this},catch(){return this},finally(t){if(t)try{return D(t()).then(()=>e,()=>e)}catch(e){return A(e)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:e,[C]:`resolved`}}function O(){if(Promise.withResolvers)return Promise.withResolvers();let e,t,n=new Promise(function(n,r){e=n,t=r});return{promise:n,get resolve(){return e},get reject(){return t}}}function k(e,t,n){if(e?.length===0)return;let r=e[Symbol.iterator](),i=0;function a(){let{done:e,value:o}=r.next();if(e)return;let s=!1;function c(){s=!0}return E(function(){return t(o,c,i++)},function(e){if(e&&n?.push(e),!s)return a()})}return a()}function A(e){return{then(t,n){if(n)try{return D(n(e))}catch(e){return A(e)}return this},catch(t){if(t)try{return D(t(e))}catch(e){return A(e)}return this},finally(e){if(e)try{e()}catch(e){return A(e)}return this},__fakeRejectError:e,[Symbol.toStringTag]:`Promise`,[C]:`rejected`}}function ee(e){return e?.[C]===`resolved`}function te(e){return e?.[C]===`rejected`}function j(e,t){return`finally`in e?e.finally(t):e.then(e=>{let n=t();return w(n)?n.then(()=>e):e},e=>{let n=t();if(w(n))return n.then(()=>{throw e});throw e})}function M(e){if(ee(e))return e.__fakePromiseValue;if(te(e))throw e.__fakeRejectError;return e}function N(e,t){let n={...t,...e};for(let r of Object.keys(n))r in e&&r in t&&(n[r]=(n,i)=>e[r](n,()=>t[r](n,i)));return n}const P=e=>({fn(t,n){return t?(...r)=>{let i;return t(e,()=>{i=n(...r)}),i}:n},asyncFn(t,n){return t?(...r)=>{let i;return E(()=>t(e,()=>(i=n(...r),w(i)?i.then(()=>void 0):void 0)),()=>i)}:n}});var F=class extends Error{error;suppressed;constructor(e,t,n){super(n),this.error=e,this.suppressed=t,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}};const I={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}};function ne(e){return e?.[I.dispose]!=null}function re(e){return e?.[I.asyncDispose]!=null}const ie=globalThis.SuppressedError||F;var ae=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return re(e)?this.callbacks.push(()=>e[I.asyncDispose]()):ne(e)&&this.callbacks.push(()=>e[I.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}disposeAsync(){return this[I.asyncDispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e)return E(e,()=>this._iterateCallbacks(),e=>(this._error=this._error?new ie(e,this._error):e,this._iterateCallbacks()))}[I.asyncDispose](){let e=this._iterateCallbacks();if(e?.then)return e.then(()=>{if(this._error){let e=this._error;throw this._error=void 0,e}});if(this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`AsyncDisposableStack`};globalThis.SuppressedError,I.dispose,Symbol.toStringTag,globalThis.DisposableStack;const oe=globalThis.AsyncDisposableStack||ae;globalThis.SuppressedError;var se=e(((exports,t)=>{function n(){return Object.keys(globalThis).some(e=>e.startsWith(`__NEXT`))}t.exports=function(){return!!(globalThis.Deno||globalThis.Bun||n())}})),ce=e(((exports,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>n(e,`name`,{value:t,configurable:!0}),s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{URLPattern:()=>V}),t.exports=l(u);var d=class{type=3;name=``;prefix=``;value=``;suffix=``;modifier=3;constructor(e,t,n,r,i,a){this.type=e,this.name=t,this.prefix=n,this.value=r,this.suffix=i,this.modifier=a}hasCustomName(){return this.name!==``&&typeof this.name!=`number`}};o(d,`Part`);var f=/[$_\p{ID_Start}]/u,p=/[$_\u200C\u200D\p{ID_Continue}]/u,m=`.*`;function h(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}o(h,`isASCII`);function g(e,t=!1){let n=[],r=0;for(;r<e.length;){let i=e[r],a=o(function(i){if(!t)throw TypeError(i);n.push({type:`INVALID_CHAR`,index:r,value:e[r++]})},`ErrorOrInvalid`);if(i===`*`){n.push({type:`ASTERISK`,index:r,value:e[r++]});continue}if(i===`+`||i===`?`){n.push({type:`OTHER_MODIFIER`,index:r,value:e[r++]});continue}if(i===`\\`){n.push({type:`ESCAPED_CHAR`,index:r++,value:e[r++]});continue}if(i===`{`){n.push({type:`OPEN`,index:r,value:e[r++]});continue}if(i===`}`){n.push({type:`CLOSE`,index:r,value:e[r++]});continue}if(i===`:`){let t=``,i=r+1;for(;i<e.length;){let n=e.substr(i,1);if(i===r+1&&f.test(n)||i!==r+1&&p.test(n)){t+=e[i++];continue}break}if(!t){a(`Missing parameter name at ${r}`);continue}n.push({type:`NAME`,index:r,value:t}),r=i;continue}if(i===`(`){let t=1,i=``,o=r+1,s=!1;if(e[o]===`?`){a(`Pattern cannot start with "?" at ${o}`);continue}for(;o<e.length;){if(!h(e[o],!1)){a(`Invalid character '${e[o]}' at ${o}.`),s=!0;break}if(e[o]===`\\`){i+=e[o++]+e[o++];continue}if(e[o]===`)`){if(t--,t===0){o++;break}}else if(e[o]===`(`&&(t++,e[o+1]!==`?`)){a(`Capturing groups are not allowed at ${o}`),s=!0;break}i+=e[o++]}if(s)continue;if(t){a(`Unbalanced pattern at ${r}`);continue}if(!i){a(`Missing pattern at ${r}`);continue}n.push({type:`REGEX`,index:r,value:i}),r=o;continue}n.push({type:`CHAR`,index:r,value:e[r++]})}return n.push({type:`END`,index:r,value:``}),n}o(g,`lexer`);function _(e,t={}){let n=g(e);t.delimiter??=`/#?`,t.prefixes??=`./`;let r=`[^${v(t.delimiter)}]+?`,i=[],a=0,s=0,c=new Set,l=o(e=>{if(s<n.length&&n[s].type===e)return n[s++].value},`tryConsume`),u=o(()=>l(`OTHER_MODIFIER`)??l(`ASTERISK`),`tryConsumeModifier`),f=o(e=>{let t=l(e);if(t!==void 0)return t;let{type:r,index:i}=n[s];throw TypeError(`Unexpected ${r} at ${i}, expected ${e}`)},`mustConsume`),p=o(()=>{let e=``,t;for(;t=l(`CHAR`)??l(`ESCAPED_CHAR`);)e+=t;return e},`consumeText`),h=o(e=>e,`DefaultEncodePart`),_=t.encodePart||h,y=``,b=o(e=>{y+=e},`appendToPendingFixedValue`),x=o(()=>{y.length&&(i.push(new d(3,``,``,_(y),``,3)),y=``)},`maybeAddPartFromPendingFixedValue`),S=o((e,t,n,o,s)=>{let l=3;switch(s){case`?`:l=1;break;case`*`:l=0;break;case`+`:l=2;break}if(!t&&!n&&l===3){b(e);return}if(x(),!t&&!n){if(!e)return;i.push(new d(3,``,``,_(e),``,l));return}let u;u=n?n===`*`?m:n:r;let f=2;u===r?(f=1,u=``):u===m&&(f=0,u=``);let p;if(t?p=t:n&&(p=a++),c.has(p))throw TypeError(`Duplicate name '${p}'.`);c.add(p),i.push(new d(f,p,_(e),u,_(o),l))},`addPart`);for(;s<n.length;){let e=l(`CHAR`),n=l(`NAME`),r=l(`REGEX`);if(!n&&!r&&(r=l(`ASTERISK`)),n||r){let i=e??``;t.prefixes.indexOf(i)===-1&&(b(i),i=``),x();let a=u();S(i,n,r,``,a);continue}let i=e??l(`ESCAPED_CHAR`);if(i){b(i);continue}if(l(`OPEN`)){let e=p(),t=l(`NAME`),n=l(`REGEX`);!t&&!n&&(n=l(`ASTERISK`));let r=p();f(`CLOSE`);let i=u();S(e,t,n,r,i);continue}x(),f(`END`)}return i}o(_,`parse`);function v(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}o(v,`escapeString`);function y(e){return e&&e.ignoreCase?`ui`:`u`}o(y,`flags`);function b(e,t,n){return S(_(e,n),t,n)}o(b,`stringToRegexp`);function x(e){switch(e){case 0:return`*`;case 1:return`?`;case 2:return`+`;case 3:return``}}o(x,`modifierToString`);function S(e,t,n={}){n.delimiter??=`/#?`,n.prefixes??=`./`,n.sensitive??=!1,n.strict??=!1,n.end??=!0,n.start??=!0,n.endsWith=``;let r=n.start?`^`:``;for(let i of e){if(i.type===3){i.modifier===3?r+=v(i.value):r+=`(?:${v(i.value)})${x(i.modifier)}`;continue}t&&t.push(i.name);let e=`[^${v(n.delimiter)}]+?`,a=i.value;if(i.type===1?a=e:i.type===0&&(a=m),!i.prefix.length&&!i.suffix.length){i.modifier===3||i.modifier===1?r+=`(${a})${x(i.modifier)}`:r+=`((?:${a})${x(i.modifier)})`;continue}if(i.modifier===3||i.modifier===1){r+=`(?:${v(i.prefix)}(${a})${v(i.suffix)})`,r+=x(i.modifier);continue}r+=`(?:${v(i.prefix)}`,r+=`((?:${a})(?:`,r+=v(i.suffix),r+=v(i.prefix),r+=`(?:${a}))*)${v(i.suffix)})`,i.modifier===0&&(r+=`?`)}let i=`[${v(n.endsWith)}]|$`,a=`[${v(n.delimiter)}]`;if(n.end)return n.strict||(r+=`${a}?`),n.endsWith.length?r+=`(?=${i})`:r+=`$`,new RegExp(r,y(n));n.strict||(r+=`(?:${a}(?=${i}))?`);let o=!1;if(e.length){let t=e[e.length-1];t.type===3&&t.modifier===3&&(o=n.delimiter.indexOf(t)>-1)}return o||(r+=`(?=${a}|${i})`),new RegExp(r,y(n))}o(S,`partsToRegexp`);var C={delimiter:``,prefixes:``,sensitive:!0,strict:!0},w={delimiter:`.`,prefixes:``,sensitive:!0,strict:!0},T={delimiter:`/`,prefixes:`/`,sensitive:!0,strict:!0};function E(e,t){return e.length?e[0]===`/`?!0:!t||e.length<2?!1:(e[0]==`\\`||e[0]==`{`)&&e[1]==`/`:!1}o(E,`isAbsolutePathname`);function D(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}o(D,`maybeStripPrefix`);function O(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}o(O,`maybeStripSuffix`);function k(e){return!e||e.length<2?!1:e[0]===`[`||(e[0]===`\\`||e[0]===`{`)&&e[1]===`[`}o(k,`treatAsIPv6Hostname`);var A=[`ftp`,`file`,`http`,`https`,`ws`,`wss`];function ee(e){if(!e)return!0;for(let t of A)if(e.test(t))return!0;return!1}o(ee,`isSpecialScheme`);function te(e,t){if(e=D(e,`#`),t||e===``)return e;let n=new URL(`https://example.com`);return n.hash=e,n.hash?n.hash.substring(1,n.hash.length):``}o(te,`canonicalizeHash`);function j(e,t){if(e=D(e,`?`),t||e===``)return e;let n=new URL(`https://example.com`);return n.search=e,n.search?n.search.substring(1,n.search.length):``}o(j,`canonicalizeSearch`);function M(e,t){return t||e===``?e:k(e)?ce(e):se(e)}o(M,`canonicalizeHostname`);function N(e,t){if(t||e===``)return e;let n=new URL(`https://example.com`);return n.password=e,n.password}o(N,`canonicalizePassword`);function P(e,t){if(t||e===``)return e;let n=new URL(`https://example.com`);return n.username=e,n.username}o(P,`canonicalizeUsername`);function F(e,t,n){if(n||e===``)return e;if(t&&!A.includes(t))return new URL(`${t}:${e}`).pathname;let r=e[0]==`/`;return e=new URL(r?e:`/-`+e,`https://example.com`).pathname,r||(e=e.substring(2,e.length)),e}o(F,`canonicalizePathname`);function I(e,t,n){return re(t)===e&&(e=``),n||e===``?e:le(e)}o(I,`canonicalizePort`);function ne(e,t){return e=O(e,`:`),t||e===``?e:ie(e)}o(ne,`canonicalizeProtocol`);function re(e){switch(e){case`ws`:case`http`:return`80`;case`wws`:case`https`:return`443`;case`ftp`:return`21`;default:return``}}o(re,`defaultPortForProtocol`);function ie(e){if(e===``)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw TypeError(`Invalid protocol '${e}'.`)}o(ie,`protocolEncodeCallback`);function ae(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.username=e,t.username}o(ae,`usernameEncodeCallback`);function oe(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.password=e,t.password}o(oe,`passwordEncodeCallback`);function se(e){if(e===``)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw TypeError(`Invalid hostname '${e}'`);let t=new URL(`https://example.com`);return t.hostname=e,t.hostname}o(se,`hostnameEncodeCallback`);function ce(e){if(e===``)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}o(ce,`ipv6HostnameEncodeCallback`);function le(e){if(e===``||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw TypeError(`Invalid port '${e}'.`)}o(le,`portEncodeCallback`);function L(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.pathname=e[0]===`/`?e:`/-`+e,e[0]===`/`?t.pathname:t.pathname.substring(2,t.pathname.length)}o(L,`standardURLPathnameEncodeCallback`);function ue(e){return e===``?e:new URL(`data:${e}`).pathname}o(ue,`pathURLPathnameEncodeCallback`);function R(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.search=e,t.search.substring(1,t.search.length)}o(R,`searchEncodeCallback`);function de(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.hash=e,t.hash.substring(1,t.hash.length)}o(de,`hashEncodeCallback`);var fe=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#n=g(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type===`END`){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())--this.#d;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let e=7,t=1;this.#E()?(e=2,t=3):this.#g&&(e=2),this.#r(e,t)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&--this.#p,this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=``)}#r(e,t){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&e!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=``),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(e)&&(this.#t.pathname??=this.#g?`/`:``),[1,2,3,4,5,6,7].includes(this.#o)&&e===9&&(this.#t.search??=``)),this.#R(e,t)}#R(e,t){this.#o=e,this.#l=this.#e+t,this.#e+=t,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(e){this.#b(),this.#o=e}#m(e){return e<0&&(e=this.#n.length-e),e<this.#n.length?this.#n[e]:this.#n[this.#n.length-1]}#a(e,t){let n=this.#m(e);return n.value===t&&(n.type===`CHAR`||n.type===`ESCAPED_CHAR`||n.type===`INVALID_CHAR`)}#P(){return this.#a(this.#e,`:`)}#E(){return this.#a(this.#e+1,`/`)&&this.#a(this.#e+2,`/`)}#S(){return this.#a(this.#e,`@`)}#O(){return this.#a(this.#e,`:`)}#k(){return this.#a(this.#e,`:`)}#x(){return this.#a(this.#e,`/`)}#h(){if(this.#a(this.#e,`?`))return!0;if(this.#n[this.#e].value!==`?`)return!1;let e=this.#m(this.#e-1);return e.type!==`NAME`&&e.type!==`REGEX`&&e.type!==`CLOSE`&&e.type!==`ASTERISK`}#f(){return this.#a(this.#e,`#`)}#T(){return this.#n[this.#e].type==`OPEN`}#A(){return this.#n[this.#e].type==`CLOSE`}#y(){return this.#a(this.#e,`[`)}#w(){return this.#a(this.#e,`]`)}#c(){let e=this.#n[this.#e],t=this.#m(this.#l).index;return this.#i.substring(t,e.index)}#C(){let e={};Object.assign(e,C),e.encodePart=ie;let t=b(this.#c(),void 0,e);this.#g=ee(t)}};o(fe,`Parser`);var pe=[`protocol`,`username`,`password`,`hostname`,`port`,`pathname`,`search`,`hash`],me=`*`;function he(e,t){if(typeof e!=`string`)throw TypeError(`parameter 1 is not of type 'string'.`);let n=new URL(e,t);return{protocol:n.protocol.substring(0,n.protocol.length-1),username:n.username,password:n.password,hostname:n.hostname,port:n.port,pathname:n.pathname,search:n.search===``?void 0:n.search.substring(1,n.search.length),hash:n.hash===``?void 0:n.hash.substring(1,n.hash.length)}}o(he,`extractValues`);function z(e,t){return t?ge(e):e}o(z,`processBaseURLString`);function B(e,t,n){let r;if(typeof t.baseURL==`string`)try{r=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=z(r.protocol.substring(0,r.protocol.length-1),n)),!n&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=z(r.username,n)),!n&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=z(r.password,n)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=z(r.hostname,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=z(r.port,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=z(r.pathname,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=z(r.search.substring(1,r.search.length),n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=z(r.hash.substring(1,r.hash.length),n))}catch{throw TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol==`string`&&(e.protocol=ne(t.protocol,n)),typeof t.username==`string`&&(e.username=P(t.username,n)),typeof t.password==`string`&&(e.password=N(t.password,n)),typeof t.hostname==`string`&&(e.hostname=M(t.hostname,n)),typeof t.port==`string`&&(e.port=I(t.port,e.protocol,n)),typeof t.pathname==`string`){if(e.pathname=t.pathname,r&&!E(e.pathname,n)){let t=r.pathname.lastIndexOf(`/`);t>=0&&(e.pathname=z(r.pathname.substring(0,t+1),n)+e.pathname)}e.pathname=F(e.pathname,e.protocol,n)}return typeof t.search==`string`&&(e.search=j(t.search,n)),typeof t.hash==`string`&&(e.hash=te(t.hash,n)),e}o(B,`applyInit`);function ge(e){return e.replace(/([+*?:{}()\\])/g,`\\$1`)}o(ge,`escapePatternString`);function _e(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}o(_e,`escapeRegexpString`);function ve(e,t){t.delimiter??=`/#?`,t.prefixes??=`./`,t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=``;let n=`[^${_e(t.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,i=``;for(let a=0;a<e.length;++a){let o=e[a];if(o.type===3){if(o.modifier===3){i+=ge(o.value);continue}i+=`{${ge(o.value)}}${x(o.modifier)}`;continue}let s=o.hasCustomName(),c=!!o.suffix.length||!!o.prefix.length&&(o.prefix.length!==1||!t.prefixes.includes(o.prefix)),l=a>0?e[a-1]:null,u=a<e.length-1?e[a+1]:null;if(!c&&s&&o.type===1&&o.modifier===3&&u&&!u.prefix.length&&!u.suffix.length)if(u.type===3){let e=u.value.length>0?u.value[0]:``;c=r.test(e)}else c=!u.hasCustomName();if(!c&&!o.prefix.length&&l&&l.type===3){let e=l.value[l.value.length-1];c=t.prefixes.includes(e)}c&&(i+=`{`),i+=ge(o.prefix),s&&(i+=`:${o.name}`),o.type===2?i+=`(${o.value})`:o.type===1?s||(i+=`(${n})`):o.type===0&&(!s&&(!l||l.type===3||l.modifier!==3||c||o.prefix!==``)?i+=`*`:i+=`(.*)`),o.type===1&&s&&o.suffix.length&&r.test(o.suffix[0])&&(i+=`\\`),i+=ge(o.suffix),c&&(i+=`}`),o.modifier!==3&&(i+=x(o.modifier))}return i}o(ve,`partsToPattern`);var V=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(e={},t,n){try{let r;if(typeof t==`string`?r=t:n=t,typeof e==`string`){let t=new fe(e);if(t.parse(),e=t.result,r===void 0&&typeof e.protocol!=`string`)throw TypeError(`A base URL must be provided for a relative constructor string.`);e.baseURL=r}else{if(!e||typeof e!=`object`)throw TypeError(`parameter 1 is not of type 'string' and cannot convert to dictionary.`);if(r)throw TypeError(`parameter 1 is not of type 'string'.`)}typeof n>`u`&&(n={ignoreCase:!1});let i={ignoreCase:n.ignoreCase===!0},a={pathname:me,protocol:me,username:me,password:me,hostname:me,port:me,search:me,hash:me};this.#i=B(a,e,!0),re(this.#i.protocol)===this.#i.port&&(this.#i.port=``);let o;for(o of pe){if(!(o in this.#i))continue;let e={},t=this.#i[o];switch(this.#t[o]=[],o){case`protocol`:Object.assign(e,C),e.encodePart=ie;break;case`username`:Object.assign(e,C),e.encodePart=ae;break;case`password`:Object.assign(e,C),e.encodePart=oe;break;case`hostname`:Object.assign(e,w),k(t)?e.encodePart=ce:e.encodePart=se;break;case`port`:Object.assign(e,C),e.encodePart=le;break;case`pathname`:ee(this.#n.protocol)?(Object.assign(e,T,i),e.encodePart=L):(Object.assign(e,C,i),e.encodePart=ue);break;case`search`:Object.assign(e,C,i),e.encodePart=R;break;case`hash`:Object.assign(e,C,i),e.encodePart=de;break}try{this.#s[o]=_(t,e),this.#n[o]=S(this.#s[o],this.#t[o],e),this.#e[o]=ve(this.#s[o],e),this.#l=this.#l||this.#s[o].some(e=>e.type===2)}catch{throw TypeError(`invalid ${o} pattern '${this.#i[o]}'.`)}}}catch(e){throw TypeError(`Failed to construct 'URLPattern': ${e.message}`)}}get[Symbol.toStringTag](){return`URLPattern`}test(e={},t){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof e!=`string`&&t)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof e>`u`)return!1;try{n=typeof e==`object`?B(n,e,!1):B(n,he(e,t),!1)}catch{return!1}let r;for(r of pe)if(!this.#n[r].exec(n[r]))return!1;return!0}exec(e={},t){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof e!=`string`&&t)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof e>`u`)return;try{n=typeof e==`object`?B(n,e,!1):B(n,he(e,t),!1)}catch{return null}let r={};t?r.inputs=[e,t]:r.inputs=[e];let i;for(i of pe){let e=this.#n[i].exec(n[i]);if(!e)return null;let t={};for(let[n,r]of this.#t[i].entries())if(typeof r==`string`||typeof r==`number`){let i=e[n+1];t[r]=i}r[i]={input:n[i]??``,groups:t}}return r}static compareComponent(e,t,n){let r=o((e,t)=>{for(let n of[`type`,`modifier`,`prefix`,`value`,`suffix`]){if(e[n]<t[n])return-1;if(e[n]===t[n])continue;return 1}return 0},`comparePart`),i=new d(3,``,``,``,``,3),a=new d(0,``,``,``,``,3),s=o((e,t)=>{let n=0;for(;n<Math.min(e.length,t.length);++n){let i=r(e[n],t[n]);if(i)return i}return e.length===t.length?0:r(e[n]??i,t[n]??i)},`comparePartList`);return!t.#e[e]&&!n.#e[e]?0:t.#e[e]&&!n.#e[e]?s(t.#s[e],[a]):!t.#e[e]&&n.#e[e]?s([a],n.#s[e]):s(t.#s[e],n.#s[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};o(V,`URLPattern`)})),le=e(((exports,t)=>{let{URLPattern:n}=ce();t.exports={URLPattern:n},globalThis.URLPattern||(globalThis.URLPattern=n)})),L=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.isPromise=n,exports.isActualPromise=r,exports.handleMaybePromise=i,exports.fakePromise=a,exports.createDeferredPromise=o,exports.iterateAsync=s,exports.iterateAsyncVoid=s,exports.fakeRejectPromise=c,exports.mapMaybePromise=l,exports.mapAsyncIterator=u,exports.promiseLikeFinally=m,exports.unfakePromise=h;let t=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`);function n(e){return e?.then!=null}function r(e){let t=e;return t&&t.then&&t.catch&&t.finally}function i(e,t,n,r){let i=a().then(e).then(t,n);return r&&(i=i.finally(r)),h(i)}function a(e){return e&&r(e)?e:n(e)?{then:(t,n)=>a(e.then(t,n)),catch:t=>a(e.then(e=>e,t)),finally:t=>a(t?m(e,t):e),[Symbol.toStringTag]:`Promise`}:{then(t){if(t)try{return a(t(e))}catch(e){return c(e)}return this},catch(){return this},finally(t){if(t)try{return a(t()).then(()=>e,()=>e)}catch(e){return c(e)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:e,[t]:`resolved`}}function o(){if(Promise.withResolvers)return Promise.withResolvers();let e,t,n=new Promise(function(n,r){e=n,t=r});return{promise:n,get resolve(){return e},get reject(){return t}}}function s(e,t,n){if(e?.length===0)return;let r=e[Symbol.iterator](),a=0;function o(){let{done:e,value:s}=r.next();if(e)return;let c=!1;function l(){c=!0}return i(function(){return t(s,l,a++)},function(e){if(e&&n?.push(e),!c)return o()})}return o()}function c(e){return{then(t,n){if(n)try{return a(n(e))}catch(e){return c(e)}return this},catch(t){if(t)try{return a(t(e))}catch(e){return c(e)}return this},finally(e){if(e)try{e()}catch(e){return c(e)}return this},__fakeRejectError:e,[Symbol.toStringTag]:`Promise`,[t]:`rejected`}}function l(e,t,n){return i(()=>e,t,n)}function u(e,t,n,r){Symbol.asyncIterator in e&&(e=e[Symbol.asyncIterator]());let o,s,l;if(r){let e;l=t=>(e||=i(r,()=>t,()=>t),e)}typeof e.return==`function`&&(o=e.return,s=t=>{let n=()=>{throw t};return o.call(e).then(n,n)});function u(e){return e.done?l?l(e):e:i(()=>e.value,e=>i(()=>t(e),d,s))}let f;if(n){let e,t=n;f=n=>(e||=i(()=>n,e=>i(()=>t(e),d,s)),e)}return{next(){return e.next().then(u,f)},return(){let t=o?o.call(e).then(u,f):a({value:void 0,done:!0});return l?t.then(l):t},throw(t){return typeof e.throw==`function`?e.throw(t).then(u,f):s?s(t):c(t)},[Symbol.asyncIterator](){return this}}}function d(e){return{value:e,done:!1}}function f(e){return e?.[t]===`resolved`}function p(e){return e?.[t]===`rejected`}function m(e,t){return`finally`in e?e.finally(t):e.then(e=>{let r=t();return n(r)?r.then(()=>e):e},e=>{let r=t();if(n(r))return r.then(()=>{throw e});throw e})}function h(e){if(f(e))return e.__fakePromiseValue;if(p(e))throw e.__fakeRejectError;return e}})),ue=e(((exports,t)=>{let{EventEmitter:n}=r(`node:events`),{inherits:i}=r(`node:util`);function a(e){if(typeof e==`string`&&(e=Buffer.from(e)),!Buffer.isBuffer(e))throw TypeError(`The needle has to be a String or a Buffer.`);let t=e.length,n=t-1;if(t===0)throw Error(`The needle cannot be an empty String/Buffer.`);if(t>256)throw Error(`The needle cannot have a length bigger than 256.`);this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(t),this._lookbehind_size=0,this._needle=e,this._bufpos=0,this._lookbehind=Buffer.alloc(n);for(var r=0;r<n;++r)this._occ[e[r]]=n-r}i(a,n),a.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0},a.prototype.push=function(e,t){Buffer.isBuffer(e)||(e=Buffer.from(e,`binary`));let n=e.length;this._bufpos=t||0;let r;for(;r!==n&&this.matches<this.maxMatches;)r=this._sbmh_feed(e);return r},a.prototype._sbmh_feed=function(e){let t=e.length,n=this._needle,r=n.length,i=r-1,a=n[i],o=-this._lookbehind_size,s;if(o<0){for(;o<0&&o<=t-r;){if(s=e[o+i],s===a&&this._sbmh_memcmp(e,o,i))return this._lookbehind_size=0,++this.matches,this.emit(`info`,!0),this._bufpos=o+r;o+=this._occ[s]}for(;o<0&&!this._sbmh_memcmp(e,o,t-o);)++o;if(o>=0)this.emit(`info`,!1,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else{let n=this._lookbehind_size+o;return n>0&&this.emit(`info`,!1,this._lookbehind,0,n),this._lookbehind_size-=n,this._lookbehind.copy(this._lookbehind,0,n,this._lookbehind_size),e.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=t,this._bufpos=t,t}}if(o=e.indexOf(n,o+this._bufpos),o!==-1)return++this.matches,o===0?this.emit(`info`,!0):this.emit(`info`,!0,e,this._bufpos,o),this._bufpos=o+r;for(o=t-i,o<0&&(o=0);o!==t&&(e[o]!==n[0]||Buffer.compare(e.subarray(o+1,t),n.subarray(1,t-o))!==0);)++o;return o!==t&&(e.copy(this._lookbehind,0,o,t),this._lookbehind_size=t-o),o!==0&&this.emit(`info`,!1,e,this._bufpos,o),this._bufpos=t,t},a.prototype._sbmh_lookup_char=function(e,t){return t<0?this._lookbehind[this._lookbehind_size+t]:e[t]},a.prototype._sbmh_memcmp=function(e,t,n){for(var r=0;r<n;++r)if(this._sbmh_lookup_char(e,t+r)!==this._needle[r])return!1;return!0},t.exports=a})),R=e(((exports,t)=>{let n=r(`node:util`).inherits,i=r(`node:stream`).Readable;function a(e){i.call(this,e)}n(a,i),a.prototype._read=function(e){},t.exports=a})),de=e(((exports,t)=>{t.exports=function(e,t,n){if(!e||e[t]===void 0||e[t]===null)return n;if(typeof e[t]!=`number`||isNaN(e[t]))throw TypeError(`Limit `+t+` is not a valid number`);return e[t]}})),fe=e(((exports,t)=>{let n=r(`node:events`).EventEmitter,i=r(`node:util`).inherits,a=de(),o=ue(),s=Buffer.from(`\r
2
- \r
3
- `),c=/\r\n/g,l=/^([^:]+):[ \t]?([\x00-\xFF]+)?$/;function u(e){n.call(this),e||={};let t=this;this.nread=0,this.maxed=!1,this.npairs=0,this.maxHeaderPairs=a(e,`maxHeaderPairs`,2e3),this.maxHeaderSize=a(e,`maxHeaderSize`,80*1024),this.buffer=``,this.header={},this.finished=!1,this.ss=new o(s),this.ss.on(`info`,function(e,n,r,i){n&&!t.maxed&&(t.nread+i-r>=t.maxHeaderSize?(i=t.maxHeaderSize-t.nread+r,t.nread=t.maxHeaderSize,t.maxed=!0):t.nread+=i-r,t.buffer+=n.toString(`binary`,r,i)),e&&t._finish()})}i(u,n),u.prototype.push=function(e){let t=this.ss.push(e);if(this.finished)return t},u.prototype.reset=function(){this.finished=!1,this.buffer=``,this.header={},this.ss.reset()},u.prototype._finish=function(){this.buffer&&this._parseHeader(),this.ss.matches=this.ss.maxMatches;let e=this.header;this.header={},this.buffer=``,this.finished=!0,this.nread=this.npairs=0,this.maxed=!1,this.emit(`header`,e)},u.prototype._parseHeader=function(){if(this.npairs===this.maxHeaderPairs)return;let e=this.buffer.split(c),t=e.length,n,r;for(var i=0;i<t;++i){if(e[i].length===0)continue;if((e[i][0]===` `||e[i][0]===` `)&&r){this.header[r][this.header[r].length-1]+=e[i];continue}let t=e[i].indexOf(`:`);if(t===-1||t===0)return;if(n=l.exec(e[i]),r=n[1].toLowerCase(),this.header[r]=this.header[r]||[],this.header[r].push(n[2]||``),++this.npairs===this.maxHeaderPairs)break}},t.exports=u})),pe=e(((exports,t)=>{let n=r(`node:stream`).Writable,i=r(`node:util`).inherits,a=ue(),o=R(),s=fe(),c=Buffer.from(`-`),l=Buffer.from(`\r
4
- `),u=function(){};function d(e){if(!(this instanceof d))return new d(e);if(n.call(this,e),!e||!e.headerFirst&&typeof e.boundary!=`string`)throw TypeError(`Boundary required`);typeof e.boundary==`string`?this.setBoundary(e.boundary):this._bparser=void 0,this._headerFirst=e.headerFirst,this._dashes=0,this._parts=0,this._finished=!1,this._realFinish=!1,this._isPreamble=!0,this._justMatched=!1,this._firstWrite=!0,this._inHeader=!0,this._part=void 0,this._cb=void 0,this._ignoreData=!1,this._partOpts={highWaterMark:e.partHwm},this._pause=!1;let t=this;this._hparser=new s(e),this._hparser.on(`header`,function(e){t._inHeader=!1,t._part.emit(`header`,e)})}i(d,n),d.prototype.emit=function(e){if(e===`finish`&&!this._realFinish){if(!this._finished){let e=this;process.nextTick(function(){if(e.emit(`error`,Error(`Unexpected end of multipart data`)),e._part&&!e._ignoreData){let t=e._isPreamble?`Preamble`:`Part`;e._part.emit(`error`,Error(t+` terminated early due to unexpected end of multipart data`)),e._part.push(null),process.nextTick(function(){e._realFinish=!0,e.emit(`finish`),e._realFinish=!1});return}e._realFinish=!0,e.emit(`finish`),e._realFinish=!1})}}else n.prototype.emit.apply(this,arguments)},d.prototype._write=function(e,t,n){if(!this._hparser&&!this._bparser)return n();if(this._headerFirst&&this._isPreamble){this._part||(this._part=new o(this._partOpts),this.listenerCount(`preamble`)===0?this._ignore():this.emit(`preamble`,this._part));let t=this._hparser.push(e);if(!this._inHeader&&t!==void 0&&t<e.length)e=e.slice(t);else return n()}this._firstWrite&&=(this._bparser.push(l),!1),this._bparser.push(e),this._pause?this._cb=n:n()},d.prototype.reset=function(){this._part=void 0,this._bparser=void 0,this._hparser=void 0},d.prototype.setBoundary=function(e){let t=this;this._bparser=new a(`\r
5
- --`+e),this._bparser.on(`info`,function(e,n,r,i){t._oninfo(e,n,r,i)})},d.prototype._ignore=function(){this._part&&!this._ignoreData&&(this._ignoreData=!0,this._part.on(`error`,u),this._part.resume())},d.prototype._oninfo=function(e,t,n,r){let i,a=this,s=0,l,u=!0;if(!this._part&&this._justMatched&&t){for(;this._dashes<2&&n+s<r;)if(t[n+s]===45)++s,++this._dashes;else{this._dashes&&(i=c),this._dashes=0;break}if(this._dashes===2&&(n+s<r&&this.listenerCount(`trailer`)!==0&&this.emit(`trailer`,t.slice(n+s,r)),this.reset(),this._finished=!0,a._parts===0&&(a._realFinish=!0,a.emit(`finish`),a._realFinish=!1)),this._dashes)return}this._justMatched&&=!1,this._part||(this._part=new o(this._partOpts),this._part._read=function(e){a._unpause()},this._isPreamble&&this.listenerCount(`preamble`)!==0?this.emit(`preamble`,this._part):this._isPreamble!==!0&&this.listenerCount(`part`)!==0?this.emit(`part`,this._part):this._ignore(),this._isPreamble||(this._inHeader=!0)),t&&n<r&&!this._ignoreData&&(this._isPreamble||!this._inHeader?(i&&(u=this._part.push(i)),u=this._part.push(t.slice(n,r)),u||(this._pause=!0)):!this._isPreamble&&this._inHeader&&(i&&this._hparser.push(i),l=this._hparser.push(t.slice(n,r)),!this._inHeader&&l!==void 0&&l<r&&this._oninfo(!1,t,n+l,r))),e&&(this._hparser.reset(),this._isPreamble?this._isPreamble=!1:n!==r&&(++this._parts,this._part.on(`end`,function(){--a._parts===0&&(a._finished?(a._realFinish=!0,a.emit(`finish`),a._realFinish=!1):a._unpause())})),this._part.push(null),this._part=void 0,this._ignoreData=!1,this._justMatched=!0,this._dashes=0)},d.prototype._unpause=function(){if(this._pause&&(this._pause=!1,this._cb)){let e=this._cb;this._cb=void 0,e()}},t.exports=d})),me=e(((exports,t)=>{let n=new TextDecoder(`utf-8`),r=new Map([[`utf-8`,n],[`utf8`,n]]);function i(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return a.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return a.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return a.utf16le;case`base64`:return a.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return a.other.bind(e)}}let a={utf8:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.utf8Slice(0,e.length)),latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;if(typeof t==`string`&&(t=Buffer.from(t,n)),r.has(exports.toString()))try{return r.get(exports).decode(t)}catch{}return typeof t==`string`?t:t.toString()}};function o(e,t,n){return e&&i(n)(e,t)}t.exports=o})),he=e(((exports,t)=>{let n=me(),r=/%[a-fA-F0-9][a-fA-F0-9]/g,i={"%00":`\0`,"%01":``,"%02":``,"%03":``,"%04":``,"%05":``,"%06":``,"%07":`\x07`,"%08":`\b`,"%09":` `,"%0a":`
6
- `,"%0A":`
7
- `,"%0b":`\v`,"%0B":`\v`,"%0c":`\f`,"%0C":`\f`,"%0d":`\r`,"%0D":`\r`,"%0e":``,"%0E":``,"%0f":``,"%0F":``,"%10":``,"%11":``,"%12":``,"%13":``,"%14":``,"%15":``,"%16":``,"%17":``,"%18":``,"%19":``,"%1a":``,"%1A":``,"%1b":`\x1B`,"%1B":`\x1B`,"%1c":``,"%1C":``,"%1d":``,"%1D":``,"%1e":``,"%1E":``,"%1f":``,"%1F":``,"%20":` `,"%21":`!`,"%22":`"`,"%23":`#`,"%24":`$`,"%25":`%`,"%26":`&`,"%27":`'`,"%28":`(`,"%29":`)`,"%2a":`*`,"%2A":`*`,"%2b":`+`,"%2B":`+`,"%2c":`,`,"%2C":`,`,"%2d":`-`,"%2D":`-`,"%2e":`.`,"%2E":`.`,"%2f":`/`,"%2F":`/`,"%30":`0`,"%31":`1`,"%32":`2`,"%33":`3`,"%34":`4`,"%35":`5`,"%36":`6`,"%37":`7`,"%38":`8`,"%39":`9`,"%3a":`:`,"%3A":`:`,"%3b":`;`,"%3B":`;`,"%3c":`<`,"%3C":`<`,"%3d":`=`,"%3D":`=`,"%3e":`>`,"%3E":`>`,"%3f":`?`,"%3F":`?`,"%40":`@`,"%41":`A`,"%42":`B`,"%43":`C`,"%44":`D`,"%45":`E`,"%46":`F`,"%47":`G`,"%48":`H`,"%49":`I`,"%4a":`J`,"%4A":`J`,"%4b":`K`,"%4B":`K`,"%4c":`L`,"%4C":`L`,"%4d":`M`,"%4D":`M`,"%4e":`N`,"%4E":`N`,"%4f":`O`,"%4F":`O`,"%50":`P`,"%51":`Q`,"%52":`R`,"%53":`S`,"%54":`T`,"%55":`U`,"%56":`V`,"%57":`W`,"%58":`X`,"%59":`Y`,"%5a":`Z`,"%5A":`Z`,"%5b":`[`,"%5B":`[`,"%5c":`\\`,"%5C":`\\`,"%5d":`]`,"%5D":`]`,"%5e":`^`,"%5E":`^`,"%5f":`_`,"%5F":`_`,"%60":"`","%61":`a`,"%62":`b`,"%63":`c`,"%64":`d`,"%65":`e`,"%66":`f`,"%67":`g`,"%68":`h`,"%69":`i`,"%6a":`j`,"%6A":`j`,"%6b":`k`,"%6B":`k`,"%6c":`l`,"%6C":`l`,"%6d":`m`,"%6D":`m`,"%6e":`n`,"%6E":`n`,"%6f":`o`,"%6F":`o`,"%70":`p`,"%71":`q`,"%72":`r`,"%73":`s`,"%74":`t`,"%75":`u`,"%76":`v`,"%77":`w`,"%78":`x`,"%79":`y`,"%7a":`z`,"%7A":`z`,"%7b":`{`,"%7B":`{`,"%7c":`|`,"%7C":`|`,"%7d":`}`,"%7D":`}`,"%7e":`~`,"%7E":`~`,"%7f":``,"%7F":``,"%80":`€`,"%81":``,"%82":`‚`,"%83":`ƒ`,"%84":`„`,"%85":`…`,"%86":`†`,"%87":`‡`,"%88":`ˆ`,"%89":`‰`,"%8a":`Š`,"%8A":`Š`,"%8b":`‹`,"%8B":`‹`,"%8c":`Œ`,"%8C":`Œ`,"%8d":``,"%8D":``,"%8e":`Ž`,"%8E":`Ž`,"%8f":``,"%8F":``,"%90":``,"%91":`‘`,"%92":`’`,"%93":`“`,"%94":`”`,"%95":`•`,"%96":`–`,"%97":`—`,"%98":`˜`,"%99":`™`,"%9a":`š`,"%9A":`š`,"%9b":`›`,"%9B":`›`,"%9c":`œ`,"%9C":`œ`,"%9d":``,"%9D":``,"%9e":`ž`,"%9E":`ž`,"%9f":`Ÿ`,"%9F":`Ÿ`,"%a0":`\xA0`,"%A0":`\xA0`,"%a1":`¡`,"%A1":`¡`,"%a2":`¢`,"%A2":`¢`,"%a3":`£`,"%A3":`£`,"%a4":`¤`,"%A4":`¤`,"%a5":`¥`,"%A5":`¥`,"%a6":`¦`,"%A6":`¦`,"%a7":`§`,"%A7":`§`,"%a8":`¨`,"%A8":`¨`,"%a9":`©`,"%A9":`©`,"%aa":`ª`,"%Aa":`ª`,"%aA":`ª`,"%AA":`ª`,"%ab":`«`,"%Ab":`«`,"%aB":`«`,"%AB":`«`,"%ac":`¬`,"%Ac":`¬`,"%aC":`¬`,"%AC":`¬`,"%ad":`­`,"%Ad":`­`,"%aD":`­`,"%AD":`­`,"%ae":`®`,"%Ae":`®`,"%aE":`®`,"%AE":`®`,"%af":`¯`,"%Af":`¯`,"%aF":`¯`,"%AF":`¯`,"%b0":`°`,"%B0":`°`,"%b1":`±`,"%B1":`±`,"%b2":`²`,"%B2":`²`,"%b3":`³`,"%B3":`³`,"%b4":`´`,"%B4":`´`,"%b5":`µ`,"%B5":`µ`,"%b6":`¶`,"%B6":`¶`,"%b7":`·`,"%B7":`·`,"%b8":`¸`,"%B8":`¸`,"%b9":`¹`,"%B9":`¹`,"%ba":`º`,"%Ba":`º`,"%bA":`º`,"%BA":`º`,"%bb":`»`,"%Bb":`»`,"%bB":`»`,"%BB":`»`,"%bc":`¼`,"%Bc":`¼`,"%bC":`¼`,"%BC":`¼`,"%bd":`½`,"%Bd":`½`,"%bD":`½`,"%BD":`½`,"%be":`¾`,"%Be":`¾`,"%bE":`¾`,"%BE":`¾`,"%bf":`¿`,"%Bf":`¿`,"%bF":`¿`,"%BF":`¿`,"%c0":`À`,"%C0":`À`,"%c1":`Á`,"%C1":`Á`,"%c2":`Â`,"%C2":`Â`,"%c3":`Ã`,"%C3":`Ã`,"%c4":`Ä`,"%C4":`Ä`,"%c5":`Å`,"%C5":`Å`,"%c6":`Æ`,"%C6":`Æ`,"%c7":`Ç`,"%C7":`Ç`,"%c8":`È`,"%C8":`È`,"%c9":`É`,"%C9":`É`,"%ca":`Ê`,"%Ca":`Ê`,"%cA":`Ê`,"%CA":`Ê`,"%cb":`Ë`,"%Cb":`Ë`,"%cB":`Ë`,"%CB":`Ë`,"%cc":`Ì`,"%Cc":`Ì`,"%cC":`Ì`,"%CC":`Ì`,"%cd":`Í`,"%Cd":`Í`,"%cD":`Í`,"%CD":`Í`,"%ce":`Î`,"%Ce":`Î`,"%cE":`Î`,"%CE":`Î`,"%cf":`Ï`,"%Cf":`Ï`,"%cF":`Ï`,"%CF":`Ï`,"%d0":`Ð`,"%D0":`Ð`,"%d1":`Ñ`,"%D1":`Ñ`,"%d2":`Ò`,"%D2":`Ò`,"%d3":`Ó`,"%D3":`Ó`,"%d4":`Ô`,"%D4":`Ô`,"%d5":`Õ`,"%D5":`Õ`,"%d6":`Ö`,"%D6":`Ö`,"%d7":`×`,"%D7":`×`,"%d8":`Ø`,"%D8":`Ø`,"%d9":`Ù`,"%D9":`Ù`,"%da":`Ú`,"%Da":`Ú`,"%dA":`Ú`,"%DA":`Ú`,"%db":`Û`,"%Db":`Û`,"%dB":`Û`,"%DB":`Û`,"%dc":`Ü`,"%Dc":`Ü`,"%dC":`Ü`,"%DC":`Ü`,"%dd":`Ý`,"%Dd":`Ý`,"%dD":`Ý`,"%DD":`Ý`,"%de":`Þ`,"%De":`Þ`,"%dE":`Þ`,"%DE":`Þ`,"%df":`ß`,"%Df":`ß`,"%dF":`ß`,"%DF":`ß`,"%e0":`à`,"%E0":`à`,"%e1":`á`,"%E1":`á`,"%e2":`â`,"%E2":`â`,"%e3":`ã`,"%E3":`ã`,"%e4":`ä`,"%E4":`ä`,"%e5":`å`,"%E5":`å`,"%e6":`æ`,"%E6":`æ`,"%e7":`ç`,"%E7":`ç`,"%e8":`è`,"%E8":`è`,"%e9":`é`,"%E9":`é`,"%ea":`ê`,"%Ea":`ê`,"%eA":`ê`,"%EA":`ê`,"%eb":`ë`,"%Eb":`ë`,"%eB":`ë`,"%EB":`ë`,"%ec":`ì`,"%Ec":`ì`,"%eC":`ì`,"%EC":`ì`,"%ed":`í`,"%Ed":`í`,"%eD":`í`,"%ED":`í`,"%ee":`î`,"%Ee":`î`,"%eE":`î`,"%EE":`î`,"%ef":`ï`,"%Ef":`ï`,"%eF":`ï`,"%EF":`ï`,"%f0":`ð`,"%F0":`ð`,"%f1":`ñ`,"%F1":`ñ`,"%f2":`ò`,"%F2":`ò`,"%f3":`ó`,"%F3":`ó`,"%f4":`ô`,"%F4":`ô`,"%f5":`õ`,"%F5":`õ`,"%f6":`ö`,"%F6":`ö`,"%f7":`÷`,"%F7":`÷`,"%f8":`ø`,"%F8":`ø`,"%f9":`ù`,"%F9":`ù`,"%fa":`ú`,"%Fa":`ú`,"%fA":`ú`,"%FA":`ú`,"%fb":`û`,"%Fb":`û`,"%fB":`û`,"%FB":`û`,"%fc":`ü`,"%Fc":`ü`,"%fC":`ü`,"%FC":`ü`,"%fd":`ý`,"%Fd":`ý`,"%fD":`ý`,"%FD":`ý`,"%fe":`þ`,"%Fe":`þ`,"%fE":`þ`,"%FE":`þ`,"%ff":`ÿ`,"%Ff":`ÿ`,"%fF":`ÿ`,"%FF":`ÿ`};function a(e){return i[e]}function o(e){let t=[],i=0,o=``,s=!1,c=!1,l=0,u=``,d=e.length;for(var f=0;f<d;++f){let p=e[f];if(p===`\\`&&s)if(c)c=!1;else{c=!0;continue}else if(p===`"`)if(c)c=!1;else{if(s)for(s=!1,i=0;f+1<d&&e[f+1]!==`;`;)++f;else s=!0;continue}else if(c&&s&&(u+=`\\`),c=!1,(i===2||i===3)&&p===`'`){i===2?(i=3,o=u.substring(1)):i=1,u=``;continue}else if(i===0&&(p===`*`||p===`=`)&&t.length){i=p===`*`?2:1,t[l]=[u,void 0],u=``;continue}else if(!s&&p===`;`){i=0,o?(u.length&&(u=n(u.replace(r,a),`binary`,o)),o=``):u.length&&(u=n(u,`binary`,`utf8`)),t[l]===void 0?t[l]=u:t[l][1]=u,u=``,++l;continue}else if(!s&&(p===` `||p===` `))continue;u+=p}return o&&u.length?u=n(u.replace(r,a),`binary`,o):u&&=n(u,`binary`,`utf8`),t[l]===void 0?u&&(t[l]=u):t[l][1]=u,t}t.exports=o})),z=e(((exports,t)=>{t.exports=function(e){if(typeof e!=`string`)return``;for(var t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}})),B=e(((exports,t)=>{let{Readable:n}=r(`node:stream`),{inherits:i}=r(`node:util`),a=pe(),o=he(),s=me(),c=z(),l=de(),u=/^boundary$/i,d=/^form-data$/i,f=/^charset$/i,p=/^filename$/i,m=/^name$/i;h.detect=/^multipart\/form-data/i;function h(e,t){let n,r,i=this,h,v=t.limits,y=t.isPartAFile||((e,t,n)=>t===`application/octet-stream`||n!==void 0),b=t.parsedConType||[],x=t.defCharset||`utf8`,S=t.preservePath,C={highWaterMark:t.fileHwm};for(n=0,r=b.length;n<r;++n)if(Array.isArray(b[n])&&u.test(b[n][0])){h=b[n][1];break}function w(){M===0&&F&&!e._done&&(F=!1,i.end())}if(typeof h!=`string`)throw Error(`Multipart: Boundary not found`);let T=l(v,`fieldSize`,1*1024*1024),E=l(v,`fileSize`,1/0),D=l(v,`files`,1/0),O=l(v,`fields`,1/0),k=l(v,`parts`,1/0),A=l(v,`headerPairs`,2e3),ee=l(v,`headerSize`,80*1024),te=0,j=0,M=0,N,P,F=!1;this._needDrain=!1,this._pause=!1,this._cb=void 0,this._nparts=0,this._boy=e;let I={boundary:h,maxHeaderPairs:A,maxHeaderSize:ee,partHwm:C.highWaterMark,highWaterMark:t.highWaterMark};this.parser=new a(I),this.parser.on(`drain`,function(){if(i._needDrain=!1,i._cb&&!i._pause){let e=i._cb;i._cb=void 0,e()}}).on(`part`,function t(a){if(++i._nparts>k)return i.parser.removeListener(`part`,t),i.parser.on(`part`,g),e.hitPartsLimit=!0,e.emit(`partsLimit`),g(a);if(P){let e=P;e.emit(`end`),e.removeAllListeners(`end`)}a.on(`header`,function(t){let l,u,h,v,b,k,A=0;if(t[`content-type`]&&(h=o(t[`content-type`][0]),h[0])){for(l=h[0].toLowerCase(),n=0,r=h.length;n<r;++n)if(f.test(h[n][0])){v=h[n][1].toLowerCase();break}}if(l===void 0&&(l=`text/plain`),v===void 0&&(v=x),t[`content-disposition`]){if(h=o(t[`content-disposition`][0]),!d.test(h[0]))return g(a);for(n=0,r=h.length;n<r;++n)m.test(h[n][0])?u=h[n][1]:p.test(h[n][0])&&(k=h[n][1],S||(k=c(k)))}else return g(a);b=t[`content-transfer-encoding`]?t[`content-transfer-encoding`][0].toLowerCase():`7bit`;let ee,F;if(y(u,l,k)){if(te===D)return e.hitFilesLimit||(e.hitFilesLimit=!0,e.emit(`filesLimit`)),g(a);if(++te,e.listenerCount(`file`)===0){i.parser._ignore();return}++M;let t=new _(C);N=t,t.on(`end`,function(){if(--M,i._pause=!1,w(),i._cb&&!i._needDrain){let e=i._cb;i._cb=void 0,e()}}),t._read=function(e){if(i._pause&&(i._pause=!1,i._cb&&!i._needDrain)){let e=i._cb;i._cb=void 0,e()}},e.emit(`file`,u,t,k,b,l),ee=function(e){if((A+=e.length)>E){let n=E-A+e.length;n>0&&t.push(e.slice(0,n)),t.truncated=!0,t.bytesRead=E,a.removeAllListeners(`data`),t.emit(`limit`);return}else t.push(e)||(i._pause=!0);t.bytesRead=A},F=function(){N=void 0,t.push(null)}}else{if(j===O)return e.hitFieldsLimit||(e.hitFieldsLimit=!0,e.emit(`fieldsLimit`)),g(a);++j,++M;let t=``,n=!1;P=a,ee=function(e){if((A+=e.length)>T){let r=T-(A-e.length);t+=e.toString(`binary`,0,r),n=!0,a.removeAllListeners(`data`)}else t+=e.toString(`binary`)},F=function(){P=void 0,t.length&&(t=s(t,`binary`,v)),e.emit(`field`,u,t,!1,n,b,l),--M,w()}}a._readableState.sync=!1,a.on(`data`,ee),a.on(`end`,F)}).on(`error`,function(e){N&&N.emit(`error`,e)})}).on(`error`,function(t){e.emit(`error`,t)}).on(`finish`,function(){F=!0,w()})}h.prototype.write=function(e,t){let n=this.parser.write(e);n&&!this._pause?t():(this._needDrain=!n,this._cb=t)},h.prototype.end=function(){let e=this;e.parser.writable?e.parser.end():e._boy._done||process.nextTick(function(){e._boy._done=!0,e._boy.emit(`finish`)})};function g(e){e.resume()}function _(e){n.call(this,e),this.bytesRead=0,this.truncated=!1}i(_,n),_.prototype._read=function(e){},t.exports=h})),ge=e(((exports,t)=>{let n=/\+/g,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];function i(){this.buffer=void 0}i.prototype.write=function(e){e=e.replace(n,` `);let t=``,i=0,a=0,o=e.length;for(;i<o;++i)this.buffer===void 0?e[i]===`%`&&(i>a&&(t+=e.substring(a,i),a=i),this.buffer=``,++a):r[e.charCodeAt(i)]?(this.buffer+=e[i],++a,this.buffer.length===2&&(t+=String.fromCharCode(parseInt(this.buffer,16)),this.buffer=void 0)):(t+=`%`+this.buffer,this.buffer=void 0,--i);return a<o&&this.buffer===void 0&&(t+=e.substring(a)),t},i.prototype.reset=function(){this.buffer=void 0},t.exports=i})),_e=e(((exports,t)=>{let n=ge(),r=me(),i=de(),a=/^charset$/i;o.detect=/^application\/x-www-form-urlencoded/i;function o(e,t){let r=t.limits,o=t.parsedConType;this.boy=e,this.fieldSizeLimit=i(r,`fieldSize`,1*1024*1024),this.fieldNameSizeLimit=i(r,`fieldNameSize`,100),this.fieldsLimit=i(r,`fields`,1/0);let s;for(var c=0,l=o.length;c<l;++c)if(Array.isArray(o[c])&&a.test(o[c][0])){s=o[c][1].toLowerCase();break}s===void 0&&(s=t.defCharset||`utf8`),this.decoder=new n,this.charset=s,this._fields=0,this._state=`key`,this._checkingBytes=!0,this._bytesKey=0,this._bytesVal=0,this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._hitLimit=!1}o.prototype.write=function(e,t){if(this._fields===this.fieldsLimit)return this.boy.hitFieldsLimit||(this.boy.hitFieldsLimit=!0,this.boy.emit(`fieldsLimit`)),t();let n,i,a,o=0,s=e.length;for(;o<s;)if(this._state===`key`){for(n=i=void 0,a=o;a<s;++a){if(this._checkingBytes||++o,e[a]===61){n=a;break}else if(e[a]===38){i=a;break}if(this._checkingBytes&&this._bytesKey===this.fieldNameSizeLimit){this._hitLimit=!0;break}else this._checkingBytes&&++this._bytesKey}if(n!==void 0)n>o&&(this._key+=this.decoder.write(e.toString(`binary`,o,n))),this._state=`val`,this._hitLimit=!1,this._checkingBytes=!0,this._val=``,this._bytesVal=0,this._valTrunc=!1,this.decoder.reset(),o=n+1;else if(i!==void 0){++this._fields;let n,a=this._keyTrunc;if(n=i>o?this._key+=this.decoder.write(e.toString(`binary`,o,i)):this._key,this._hitLimit=!1,this._checkingBytes=!0,this._key=``,this._bytesKey=0,this._keyTrunc=!1,this.decoder.reset(),n.length&&this.boy.emit(`field`,r(n,`binary`,this.charset),``,a,!1),o=i+1,this._fields===this.fieldsLimit)return t()}else this._hitLimit?(a>o&&(this._key+=this.decoder.write(e.toString(`binary`,o,a))),o=a,(this._bytesKey=this._key.length)===this.fieldNameSizeLimit&&(this._checkingBytes=!1,this._keyTrunc=!0)):(o<s&&(this._key+=this.decoder.write(e.toString(`binary`,o))),o=s)}else{for(i=void 0,a=o;a<s;++a){if(this._checkingBytes||++o,e[a]===38){i=a;break}if(this._checkingBytes&&this._bytesVal===this.fieldSizeLimit){this._hitLimit=!0;break}else this._checkingBytes&&++this._bytesVal}if(i!==void 0){if(++this._fields,i>o&&(this._val+=this.decoder.write(e.toString(`binary`,o,i))),this.boy.emit(`field`,r(this._key,`binary`,this.charset),r(this._val,`binary`,this.charset),this._keyTrunc,this._valTrunc),this._state=`key`,this._hitLimit=!1,this._checkingBytes=!0,this._key=``,this._bytesKey=0,this._keyTrunc=!1,this.decoder.reset(),o=i+1,this._fields===this.fieldsLimit)return t()}else this._hitLimit?(a>o&&(this._val+=this.decoder.write(e.toString(`binary`,o,a))),o=a,(this._val===``&&this.fieldSizeLimit===0||(this._bytesVal=this._val.length)===this.fieldSizeLimit)&&(this._checkingBytes=!1,this._valTrunc=!0)):(o<s&&(this._val+=this.decoder.write(e.toString(`binary`,o))),o=s)}t()},o.prototype.end=function(){this.boy._done||(this._state===`key`&&this._key.length>0?this.boy.emit(`field`,r(this._key,`binary`,this.charset),``,this._keyTrunc,!1):this._state===`val`&&this.boy.emit(`field`,r(this._key,`binary`,this.charset),r(this._val,`binary`,this.charset),this._keyTrunc,this._valTrunc),this.boy._done=!0,this.boy.emit(`finish`))},t.exports=o})),ve=e(((exports,t)=>{let n=r(`node:stream`).Writable,{inherits:i}=r(`node:util`),a=pe(),o=B(),s=_e(),c=he();function l(e){if(!(this instanceof l))return new l(e);if(typeof e!=`object`)throw TypeError(`Busboy expected an options-Object.`);if(typeof e.headers!=`object`)throw TypeError(`Busboy expected an options-Object with headers-attribute.`);if(typeof e.headers[`content-type`]!=`string`)throw TypeError(`Missing Content-Type-header.`);let{headers:t,...r}=e;this.opts={autoDestroy:!1,...r},n.call(this,this.opts),this._done=!1,this._parser=this.getParserByHeaders(t),this._finished=!1}i(l,n),l.prototype.emit=function(e){if(e===`finish`){if(this._done){if(this._finished)return}else{this._parser?.end();return}this._finished=!0}n.prototype.emit.apply(this,arguments)},l.prototype.getParserByHeaders=function(e){let t=c(e[`content-type`]),n={defCharset:this.opts.defCharset,fileHwm:this.opts.fileHwm,headers:e,highWaterMark:this.opts.highWaterMark,isPartAFile:this.opts.isPartAFile,limits:this.opts.limits,parsedConType:t,preservePath:this.opts.preservePath};if(o.detect.test(t[0]))return new o(this,n);if(s.detect.test(t[0]))return new s(this,n);throw Error(`Unsupported Content-Type.`)},l.prototype._write=function(e,t,n){this._parser.write(e,n)},t.exports=l,t.exports.default=l,t.exports.Busboy=l,t.exports.Dicer=a})),V=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fakePromise=void 0,exports.getHeadersObj=i,exports.defaultHeadersSerializer=a,exports.isArrayBufferView=s,exports.isNodeReadable=c,exports.isIterable=l,exports.shouldRedirect=u,exports.pipeThrough=d,exports.endStream=f,exports.safeWrite=p;let t=r(`node:events`);function n(e){return e?.forEach!=null}function i(e){return e==null||!n(e)?e:e.headersInit&&!e._map&&!n(e.headersInit)?e.headersInit:Object.fromEntries(e.entries())}function a(e,t){let n=[];return e.forEach((e,r)=>{t&&r===`content-length`&&t(e),n.push(`${r}: ${e}`)}),n}var o=L();Object.defineProperty(exports,`fakePromise`,{enumerable:!0,get:function(){return o.fakePromise}});function s(e){return e!=null&&e.buffer!=null&&e.byteLength!=null&&e.byteOffset!=null}function c(e){return e!=null&&e.pipe!=null}function l(e){return e?.[Symbol.iterator]!=null}function u(e){return e===301||e===302||e===303||e===307||e===308}function d({src:e,dest:t,signal:n,onError:r}){if(r&&t.once(`error`,r),e.once(`error`,e=>{t.destroy(e)}),t.once(`close`,()=>{e.destroyed||e.destroy()}),n){let t=new WeakRef(e),r=new WeakRef(n);function i(){r.deref()?.removeEventListener(`abort`,a),t.deref()?.removeListener(`end`,i),t.deref()?.removeListener(`error`,i),t.deref()?.removeListener(`close`,i)}function a(){t.deref()?.destroy(new m),i()}n.addEventListener(`abort`,a,{once:!0}),e.once(`end`,i),e.once(`error`,i),e.once(`close`,i)}e.pipe(t,{end:!0})}function f(e){return e.end(null,null,null)}function p(e,n){let r=n.write(e);if(!r)return(0,t.once)(n,`drain`)}var m=class extends Error{constructor(e=`The operation was aborted`,t=void 0){super(e,t),this.name=`AbortError`}}})),ye=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillReadableStream=void 0;let t=r(`node:buffer`),n=r(`node:events`),i=r(`node:stream`),a=r(`node:stream/promises`),o=L(),s=V();function c(e,n){let r=[],i=!1,a=!1;return{desiredSize:e,enqueue(e){let i=typeof e==`string`?t.Buffer.from(e):e;a?n.push(i):r.push(i)},close(){r.length>0&&this._flush(),n.push(null),i=!0},error(e){r.length>0&&this._flush(),n.destroy(e)},get _closed(){return i},_flush(){if(a=!0,r.length>0){let e=r.length>1?t.Buffer.concat(r):r[0];n.push(e),r=[]}}}}function l(e){return e?.read!=null}function u(e){return e?.getReader!=null}var d=class e{readable;constructor(t){if(t instanceof e&&t.readable!=null)this.readable=t.readable;else if(l(t))this.readable=t;else if(u(t))this.readable=i.Readable.fromWeb(t);else{let e=!1,n=!1,r=n=>{if(!e){let r=c(n,this.readable);return e=!0,(0,o.handleMaybePromise)(()=>t?.start?.(r),()=>(r._flush(),!r._closed))}return!0},a=e=>(0,o.handleMaybePromise)(()=>r(e),r=>{if(!r)return;let i=c(e,this.readable);return(0,o.handleMaybePromise)(()=>t?.pull?.(i),()=>{i._flush(),n=!1})});this.readable=new i.Readable({read(e){if(!n)return n=!0,a(e)},destroy(e,n){if(t?.cancel)try{let r=t.cancel(e);if(r?.then)return r.then(()=>{n(null)},e=>{n(e)})}catch(e){n(e);return}n(null)}})}}cancel(e){return this.readable.destroy(e),(0,n.once)(this.readable,`close`)}locked=!1;getReader(e){let t=this.readable[Symbol.asyncIterator]();this.locked=!0;let r=this.readable;return{read(){return t.next()},releaseLock:()=>{if(t.return){let e=t.return();if(e.then){e.then(()=>{this.locked=!1});return}}this.locked=!1},cancel:e=>{if(t.return){let n=t.return(e);if(n.then)return n.then(()=>{this.locked=!1})}return this.locked=!1,(0,s.fakePromise)()},get closed(){return Promise.race([(0,n.once)(r,`end`),(0,n.once)(r,`error`).then(e=>Promise.reject(e))])}}}[Symbol.asyncIterator](){let e=this.readable[Symbol.asyncIterator]();return{[Symbol.asyncIterator](){return this},next:()=>e.next(),return:()=>(this.readable.destroyed||this.readable.destroy(),e.return?.()||(0,s.fakePromise)({done:!0,value:void 0})),throw:t=>(this.readable.destroyed||this.readable.destroy(t),e.throw?.(t)||(0,s.fakePromise)({done:!0,value:void 0}))}}tee(){throw Error(`Not implemented`)}async pipeToWriter(e){try{for await(let t of this)await e.write(t);await e.close()}catch(t){await e.abort(t)}}pipeTo(e){if(p(e))return(0,a.pipeline)(this.readable,e.writable,{end:!0});{let t=e.getWriter();return this.pipeToWriter(t)}}pipeThrough({writable:e,readable:t}){return this.pipeTo(e).catch(e=>{this.readable.destroy(e)}),f(t)&&(t.readable.once(`error`,e=>this.readable.destroy(e)),t.readable.once(`finish`,()=>this.readable.push(null)),t.readable.once(`close`,()=>this.readable.push(null))),t}static[Symbol.hasInstance](e){return u(e)}static from(t){return new e(i.Readable.from(t))}[Symbol.toStringTag]=`ReadableStream`};exports.PonyfillReadableStream=d;function f(e){return e?.readable!=null}function p(e){return e?.writable!=null}})),be=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillBlob=void 0,exports.hasBufferMethod=o,exports.hasArrayBufferMethod=s,exports.hasBytesMethod=c,exports.hasTextMethod=l,exports.hasSizeProperty=u,exports.hasStreamMethod=d,exports.hasBlobSignature=f,exports.isArrayBuffer=p;let t=r(`node:buffer`),n=ye(),i=V();function a(e){return typeof e==`string`?t.Buffer.from(e):t.Buffer.isBuffer(e)?e:(0,i.isArrayBufferView)(e)?t.Buffer.from(e.buffer,e.byteOffset,e.byteLength):t.Buffer.from(e)}function o(e){return e!=null&&e.buffer!=null&&typeof e.buffer==`function`}function s(e){return e!=null&&e.arrayBuffer!=null&&typeof e.arrayBuffer==`function`}function c(e){return e!=null&&e.bytes!=null&&typeof e.bytes==`function`}function l(e){return e!=null&&e.text!=null&&typeof e.text==`function`}function u(e){return e!=null&&typeof e.size==`number`}function d(e){return e!=null&&e.stream!=null&&typeof e.stream==`function`}function f(e){return e!=null&&e[Symbol.toStringTag]===`Blob`}function p(e){return e!=null&&e.byteLength!=null&&e.slice!=null}var m=class{blobParts;type;encoding;_size=null;constructor(e=[],t){if(this.blobParts=e,this.type=t?.type||`application/octet-stream`,this.encoding=t?.encoding||`utf8`,this._size=t?.size||null,e.length===1&&f(e[0]))return e[0]}_buffer=null;buffer(){if(this._buffer)return(0,i.fakePromise)(this._buffer);if(this.blobParts.length===1){let e=this.blobParts[0];return o(e)?e.buffer().then(e=>(this._buffer=e,this._buffer)):c(e)?e.bytes().then(e=>(this._buffer=t.Buffer.from(e),this._buffer)):s(e)?e.arrayBuffer().then(n=>(this._buffer=t.Buffer.from(n,void 0,e.size),this._buffer)):(this._buffer=a(e),(0,i.fakePromise)(this._buffer))}let e=[],n=this.blobParts.map((r,i)=>{if(o(r)){e.push(r.buffer().then(e=>{n[i]=e}));return}else if(s(r)){e.push(r.arrayBuffer().then(e=>{n[i]=t.Buffer.from(e,void 0,r.size)}));return}else if(c(r)){e.push(r.bytes().then(e=>{n[i]=t.Buffer.from(e)}));return}else return a(r)});return e.length>0?Promise.all(e).then(()=>t.Buffer.concat(n,this._size||void 0)):(0,i.fakePromise)(t.Buffer.concat(n,this._size||void 0))}arrayBuffer(){if(this._buffer)return(0,i.fakePromise)(this._buffer);if(this.blobParts.length===1){if(p(this.blobParts[0]))return(0,i.fakePromise)(this.blobParts[0]);if(s(this.blobParts[0]))return this.blobParts[0].arrayBuffer()}return this.buffer()}bytes(){if(this._buffer)return(0,i.fakePromise)(this._buffer);if(this.blobParts.length===1){if(t.Buffer.isBuffer(this.blobParts[0]))return this._buffer=this.blobParts[0],(0,i.fakePromise)(this._buffer);if(this.blobParts[0]instanceof Uint8Array)return this._buffer=t.Buffer.from(this.blobParts[0]),(0,i.fakePromise)(this._buffer);if(c(this.blobParts[0]))return this.blobParts[0].bytes();if(o(this.blobParts[0]))return this.blobParts[0].buffer()}return this.buffer()}_text=null;text(){if(this._text)return(0,i.fakePromise)(this._text);if(this.blobParts.length===1){let e=this.blobParts[0];if(typeof e==`string`)return this._text=e,(0,i.fakePromise)(this._text);if(l(e))return e.text().then(e=>(this._text=e,this._text));let t=a(e);return this._text=t.toString(this.encoding),(0,i.fakePromise)(this._text)}return this.buffer().then(e=>(this._text=e.toString(this.encoding),this._text))}_json=null;json(){return this._json?(0,i.fakePromise)(this._json):this.text().then(e=>(this._json=JSON.parse(e),this._json))}_formData=null;formData(){if(this._formData)return(0,i.fakePromise)(this._formData);throw Error(`Not implemented`)}get size(){if(this._size==null){this._size=0;for(let e of this.blobParts)typeof e==`string`?this._size+=t.Buffer.byteLength(e):u(e)?this._size+=e.size:(0,i.isArrayBufferView)(e)&&(this._size+=e.byteLength)}return this._size}stream(){if(this.blobParts.length===1){let e=this.blobParts[0];if(d(e))return e.stream();let t=a(e);return new n.PonyfillReadableStream({start:e=>{e.enqueue(t),e.close()}})}if(this._buffer!=null)return new n.PonyfillReadableStream({start:e=>{e.enqueue(this._buffer),e.close()}});let e;return new n.PonyfillReadableStream({start:t=>{if(this.blobParts.length===0){t.close();return}e=this.blobParts[Symbol.iterator]()},pull:n=>{let{value:r,done:i}=e.next();if(i){n.close();return}if(r){if(o(r))return r.buffer().then(e=>{n.enqueue(e)});if(c(r))return r.bytes().then(e=>{let r=t.Buffer.from(e);n.enqueue(r)});if(s(r))return r.arrayBuffer().then(e=>{let i=t.Buffer.from(e,void 0,r.size);n.enqueue(i)});let e=a(r);n.enqueue(e)}}})}slice(){throw Error(`Not implemented`)}};exports.PonyfillBlob=m})),xe=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillFile=void 0;let t=be();var n=class extends t.PonyfillBlob{name;lastModified;constructor(e,t,n){super(e,n),this.name=t,this.lastModified=n?.lastModified||Date.now()}webkitRelativePath=``};exports.PonyfillFile=n})),Se={};n(Se,{__addDisposableResource:()=>Xe,__assign:()=>et,__asyncDelegator:()=>He,__asyncGenerator:()=>Ve,__asyncValues:()=>Ue,__await:()=>Be,__awaiter:()=>Me,__classPrivateFieldGet:()=>qe,__classPrivateFieldIn:()=>Ye,__classPrivateFieldSet:()=>Je,__createBinding:()=>tt,__decorate:()=>Te,__disposeResources:()=>Ze,__esDecorate:()=>De,__exportStar:()=>Pe,__extends:()=>Ce,__generator:()=>Ne,__importDefault:()=>Ke,__importStar:()=>Ge,__makeTemplateObject:()=>We,__metadata:()=>je,__param:()=>Ee,__propKey:()=>ke,__read:()=>Ie,__rest:()=>we,__rewriteRelativeImportExtension:()=>Qe,__runInitializers:()=>Oe,__setFunctionName:()=>Ae,__spread:()=>Le,__spreadArray:()=>ze,__spreadArrays:()=>Re,__values:()=>Fe,default:()=>at});function Ce(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);$e(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function we(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Te(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function Ee(e,t){return function(n,r){t(n,r,e)}}function De(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function Oe(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function ke(e){return typeof e==`symbol`?e:`${e}`}function Ae(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,`name`,{configurable:!0,value:n?`${n} ${t}`:t})}function je(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function Me(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Ne(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function Pe(e,t){for(var n in e)n!==`default`&&!Object.prototype.hasOwnProperty.call(t,n)&&tt(t,e,n)}function Fe(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Ie(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Le(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Ie(arguments[t]));return e}function Re(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function ze(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function Be(e){return this instanceof Be?(this.v=e,this):new Be(e)}function Ve(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Be?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function He(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Be(e[r](t)),done:!1}:i?i(t):t}:i}}function Ue(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Fe==`function`?Fe(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function We(e,t){return Object.defineProperty?Object.defineProperty(e,`raw`,{value:t}):e.raw=t,e}function Ge(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=rt(e),r=0;r<n.length;r++)n[r]!==`default`&&tt(t,e,n[r]);return nt(t,e),t}function Ke(e){return e&&e.__esModule?e:{default:e}}function qe(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Je(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Ye(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function Xe(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Ze(e){function t(t){e.error=e.hasError?new it(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function Qe(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var $e,et,tt,nt,rt,it,at,ot=t((()=>{$e=function(e,t){return $e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},$e(e,t)},et=function(){return et=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},et.apply(this,arguments)},tt=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),nt=Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t},rt=function(e){return rt=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},rt(e)},it=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},at={__extends:Ce,__assign:et,__rest:we,__decorate:Te,__param:Ee,__esDecorate:De,__runInitializers:Oe,__propKey:ke,__setFunctionName:Ae,__metadata:je,__awaiter:Me,__generator:Ne,__createBinding:tt,__exportStar:Pe,__values:Fe,__read:Ie,__spread:Le,__spreadArrays:Re,__spreadArray:ze,__await:Be,__asyncGenerator:Ve,__asyncDelegator:He,__asyncValues:Ue,__makeTemplateObject:We,__importStar:Ge,__importDefault:Ke,__classPrivateFieldGet:qe,__classPrivateFieldSet:Je,__classPrivateFieldIn:Ye,__addDisposableResource:Xe,__disposeResources:Ze,__rewriteRelativeImportExtension:Qe}})),st=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillSuppressedError=void 0;var t=class extends Error{error;suppressed;constructor(e,t,n){super(n),this.error=e,this.suppressed=t,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}};exports.PonyfillSuppressedError=t})),ct=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.DisposableSymbols=void 0,exports.patchSymbols=t,exports.DisposableSymbols={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}};function t(){Symbol.dispose||=Symbol.for(`dispose`),Symbol.asyncDispose||=Symbol.for(`asyncDispose`)}})),lt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.isSyncDisposable=n,exports.isAsyncDisposable=r;let t=ct();function n(e){return e?.[t.DisposableSymbols.dispose]!=null}function r(e){return e?.[t.DisposableSymbols.asyncDispose]!=null}})),ut=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillAsyncDisposableStack=void 0;let t=L(),n=st(),r=ct(),i=lt(),a=globalThis.SuppressedError||n.PonyfillSuppressedError;var o=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return(0,i.isAsyncDisposable)(e)?this.callbacks.push(()=>e[r.DisposableSymbols.asyncDispose]()):(0,i.isSyncDisposable)(e)&&this.callbacks.push(()=>e[r.DisposableSymbols.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}disposeAsync(){return this[r.DisposableSymbols.asyncDispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e)return(0,t.handleMaybePromise)(e,()=>this._iterateCallbacks(),e=>(this._error=this._error?new a(e,this._error):e,this._iterateCallbacks()))}[r.DisposableSymbols.asyncDispose](){let e=this._iterateCallbacks();if(e?.then)return e.then(()=>{if(this._error){let e=this._error;throw this._error=void 0,e}});if(this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`AsyncDisposableStack`};exports.PonyfillAsyncDisposableStack=o})),dt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillDisposableStack=void 0;let t=st(),n=ct(),r=lt(),i=globalThis.SuppressedError||t.PonyfillSuppressedError;var a=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return(0,r.isSyncDisposable)(e)&&this.callbacks.push(()=>e[n.DisposableSymbols.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}dispose(){return this[n.DisposableSymbols.dispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e){try{e()}catch(e){this._error=this._error?new i(e,this._error):e}return this._iterateCallbacks()}}[n.DisposableSymbols.dispose](){if(this._iterateCallbacks(),this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`DisposableStack`};exports.PonyfillDisposableStack=a})),ft=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.SuppressedError=exports.AsyncDisposableStack=exports.DisposableStack=void 0;let t=(ot(),i(Se)),n=ut(),r=dt(),a=st();exports.DisposableStack=globalThis.DisposableStack||r.PonyfillDisposableStack,exports.AsyncDisposableStack=globalThis.AsyncDisposableStack||n.PonyfillAsyncDisposableStack,exports.SuppressedError=globalThis.SuppressedError||a.PonyfillSuppressedError,t.__exportStar(ct(),exports)})),pt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillIteratorObject=void 0;let t=r(`node:util`),n=ft(),i=V();var a=class{iterableIterator;[Symbol.toStringTag]=`IteratorObject`;constructor(e,t){this.iterableIterator=e,this[Symbol.toStringTag]=t}*map(e){let t=0;for(let n of this.iterableIterator)yield e(n,t++)}*filter(e){let t=0;for(let n of this.iterableIterator)e(n,t++)&&(yield n)}reduce(e,t){let n=0,r=t;for(let t of this.iterableIterator)r=e(r,t,n++);return r}forEach(e){let t=0;for(let n of this.iterableIterator)e(n,t++)}*take(e){let t=0;for(let n of this.iterableIterator){if(t>=e)break;yield n,t++}}*drop(e){let t=0;for(let n of this.iterableIterator)t>=e&&(yield n),t++}*flatMap(e){let t=0;for(let n of this.iterableIterator){let r=e(n,t++);if((0,i.isIterable)(r))for(let e of r)yield e;else for(let e of{[Symbol.iterator]:()=>r})yield e}}some(e){let t=0;for(let n of this.iterableIterator)if(e(n,t++))return!0;return!1}every(e){let t=0;for(let n of this.iterableIterator)if(!e(n,t++))return!1;return!0}find(e){let t=0;for(let n of this.iterableIterator)if(e(n,t++))return n}toArray(){return Array.from(this.iterableIterator)}[n.DisposableSymbols.dispose](){this.iterableIterator.return?.()}next(...[e]){return this.iterableIterator.next(e)}[Symbol.iterator](){return this}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};return this.forEach((n,r)=>{let i=(0,t.inspect)(n);e[r]=i.includes(`,`)?i.split(`,`).map(e=>e.trim()):i}),`${this[Symbol.toStringTag]} ${(0,t.inspect)(e)}`}};exports.PonyfillIteratorObject=a})),mt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillFormData=void 0,exports.getStreamFromFormData=o;let t=r(`node:buffer`),n=pt(),i=ye();var a=class{map=new Map;append(e,t,n){let r=this.map.get(e);r||(r=[],this.map.set(e,r));let i=c(t)?s(e,t,n):t;r.push(i)}delete(e){this.map.delete(e)}get(e){let t=this.map.get(e);return t?t[0]:null}getAll(e){return this.map.get(e)||[]}has(e){return this.map.has(e)}set(e,t,n){let r=c(t)?s(e,t,n):t;this.map.set(e,[r])}[Symbol.iterator](){return this._entries()}*_entries(){for(let[e,t]of this.map)for(let n of t)yield[e,n]}entries(){return new n.PonyfillIteratorObject(this._entries(),`FormDataIterator`)}_keys(){return this.map.keys()}keys(){return new n.PonyfillIteratorObject(this._keys(),`FormDataIterator`)}*_values(){for(let e of this.map.values())for(let t of e)yield t}values(){return new n.PonyfillIteratorObject(this._values(),`FormDataIterator`)}forEach(e){for(let[t,n]of this)e(n,t,this)}};exports.PonyfillFormData=a;function o(e,n=`---`){let r,a=!1,o,s=!1;function c(e){let{done:i,value:a}=r.next();if(i)return e.enqueue(t.Buffer.from(`\r\n--${n}--\r\n`)),e.close();if(s&&e.enqueue(t.Buffer.from(`\r\n--${n}\r\n`)),a){let[n,r]=a;if(typeof r==`string`)e.enqueue(t.Buffer.from(`Content-Disposition: form-data; name="${n}"\r\n\r\n`)),e.enqueue(t.Buffer.from(r));else{let i=``;r.name&&(i=`; filename="${r.name}"`),e.enqueue(t.Buffer.from(`Content-Disposition: form-data; name="${n}"${i}\r\n`)),e.enqueue(t.Buffer.from(`Content-Type: ${r.type||`application/octet-stream`}\r\n\r\n`));let a=r.stream();o=a[Symbol.asyncIterator]()}s=!0}}return new i.PonyfillReadableStream({start:()=>{r=e.entries()},pull:e=>a?o?o.next().then(({done:t,value:n})=>(t&&(o=void 0),n?e.enqueue(n):c(e))):c(e):(a=!0,e.enqueue(t.Buffer.from(`--${n}\r\n`))),cancel:e=>{r?.return?.(e),o?.return?.(e)}})}function s(e,t,n){return Object.defineProperty(t,`name`,{configurable:!0,enumerable:!0,value:n||t.name||e}),t}function c(e){return e?.arrayBuffer!=null}})),ht=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillBody=void 0;let t=r(`node:buffer`),n=r(`node:stream`),i=ve(),a=L(),o=be(),s=xe(),c=mt(),l=ye(),u=V();var d;(function(e){e.ReadableStream=`ReadableStream`,e.Blob=`Blob`,e.FormData=`FormData`,e.String=`String`,e.Readable=`Readable`,e.Buffer=`Buffer`,e.AsyncIterable=`AsyncIterable`})(d||={});var f=class{bodyInit;options;bodyUsed=!1;contentType=null;contentLength=null;constructor(e,t={}){this.bodyInit=e,this.options=t;let{bodyFactory:n,contentType:r,contentLength:i,bodyType:a,buffer:o}=p(e);this._bodyFactory=n,this.contentType=r,this.contentLength=i,this.bodyType=a,this._buffer=o,this._signal=t.signal}bodyType;_bodyFactory=()=>null;_generatedBody=null;_buffer;_signal;generateBody(){if(this._generatedBody?.readable?.destroyed&&this._buffer&&(this._generatedBody.readable=n.Readable.from(this._buffer)),this._generatedBody)return this._generatedBody;let e=this._bodyFactory();return this._generatedBody=e,e}handleContentLengthHeader(e=!1){let t=this.headers.get(`content-type`);t?this.contentType=t:this.contentType&&this.headers.set(`content-type`,this.contentType);let n=this.headers.get(`content-length`);e&&this.bodyInit==null&&!n&&(this.contentLength=0,this.headers.set(`content-length`,`0`)),n?this.contentLength=parseInt(n,10):this.contentLength&&this.headers.set(`content-length`,this.contentLength.toString())}get body(){let e=this.generateBody();if(e!=null){let t=e,n=e.readable;return new Proxy(e.readable,{get(e,r){if(r in t){let e=t[r];return typeof e==`function`?e.bind(t):e}if(r in n){let e=n[r];return typeof e==`function`?e.bind(n):e}}})}return null}_chunks=null;_doCollectChunksFromReadableJob(){if(this.bodyType===d.AsyncIterable){if(Array.fromAsync)return(0,a.handleMaybePromise)(()=>Array.fromAsync(this.bodyInit),e=>(this._chunks=e,this._chunks));let e=this.bodyInit[Symbol.asyncIterator](),t=[],n=()=>(0,a.handleMaybePromise)(()=>e.next(),({value:e,done:r})=>(e&&t.push(e),r?(this._chunks=t,this._chunks):n()));return n()}let e=this.generateBody();if(!e)return this._chunks=[],(0,u.fakePromise)(this._chunks);if(e.readable.destroyed)return(0,u.fakePromise)(this._chunks=[]);let t=[];return new Promise((n,r)=>{e.readable.on(`data`,e=>{t.push(e)}),e.readable.once(`error`,r),e.readable.once(`end`,()=>{n(this._chunks=t)})})}_collectChunksFromReadable(){return this._chunks?(0,u.fakePromise)(this._chunks):(this._chunks||=this._doCollectChunksFromReadableJob(),this._chunks)}_blob=null;blob(){return this._blob?(0,u.fakePromise)(this._blob):(this.bodyType===d.String&&(this._text=this.bodyInit,this._blob=new o.PonyfillBlob([this._text],{type:this.contentType||`text/plain;charset=UTF-8`,size:this.contentLength})),this.bodyType===d.Blob?(this._blob=this.bodyInit,(0,u.fakePromise)(this._blob)):this._buffer?(this._blob=new o.PonyfillBlob([this._buffer],{type:this.contentType||``,size:this.contentLength}),(0,u.fakePromise)(this._blob)):(0,u.fakePromise)((0,a.handleMaybePromise)(()=>this._collectChunksFromReadable(),e=>(this._blob=new o.PonyfillBlob(e,{type:this.contentType||``,size:this.contentLength}),this._blob))))}_formData=null;formData(e){if(this._formData)return(0,u.fakePromise)(this._formData);if(this.bodyType===d.FormData)return this._formData=this.bodyInit,(0,u.fakePromise)(this._formData);this._formData=new c.PonyfillFormData;let t=this.generateBody();if(t==null)return(0,u.fakePromise)(this._formData);let r={...this.options.formDataLimits,...e?.formDataLimits};return new Promise((e,t)=>{let a=this.body?.readable;if(!a)return t(Error(`No stream available`));let o=null,c=new i.Busboy({headers:{"content-length":typeof this.contentLength==`number`?this.contentLength.toString():this.contentLength||``,"content-type":this.contentType||``},limits:r,defCharset:`utf-8`});this._signal&&(0,n.addAbortSignal)(this._signal,c);let l=!1,u=n=>{l||(l=!0,a.unpipe(c),c.destroy(),o&&=(o.destroy(),null),n?t(n):e(this._formData))};a.on(`error`,u),c.on(`field`,(e,t,n,i)=>{if(n)return u(Error(`Field name size exceeded: ${r?.fieldNameSize} bytes`));if(i)return u(Error(`Field value size exceeded: ${r?.fieldSize} bytes`));this._formData.set(e,t)}),c.on(`file`,(e,t,n,i,a)=>{o=t;let c=[];t.on(`data`,e=>{c.push(e)}),t.on(`error`,u),t.on(`limit`,()=>{u(Error(`File size limit exceeded: ${r?.fileSize} bytes`))}),t.on(`close`,()=>{t.truncated&&u(Error(`File size limit exceeded: ${r?.fileSize} bytes`)),o=null;let i=new s.PonyfillFile(c,n,{type:a});this._formData.set(e,i)})}),c.on(`fieldsLimit`,()=>{u(Error(`Fields limit exceeded: ${r?.fields}`))}),c.on(`filesLimit`,()=>{u(Error(`Files limit exceeded: ${r?.files}`))}),c.on(`partsLimit`,()=>{u(Error(`Parts limit exceeded: ${r?.parts}`))}),c.on(`end`,u),c.on(`finish`,u),c.on(`close`,u),c.on(`error`,u),a.pipe(c)})}buffer(){if(this._buffer)return(0,u.fakePromise)(this._buffer);if(this._text)return this._buffer=t.Buffer.from(this._text,`utf-8`),(0,u.fakePromise)(this._buffer);if(this.bodyType===d.String)return this.text().then(e=>(this._text=e,this._buffer=t.Buffer.from(e,`utf-8`),this._buffer));if(this.bodyType===d.Blob){if((0,o.hasBufferMethod)(this.bodyInit))return this.bodyInit.buffer().then(e=>(this._buffer=e,this._buffer));if((0,o.hasBytesMethod)(this.bodyInit))return this.bodyInit.bytes().then(e=>(this._buffer=t.Buffer.from(e),this._buffer));if((0,o.hasArrayBufferMethod)(this.bodyInit))return this.bodyInit.arrayBuffer().then(e=>(this._buffer=t.Buffer.from(e,void 0,e.byteLength),this._buffer))}return(0,u.fakePromise)((0,a.handleMaybePromise)(()=>this._collectChunksFromReadable(),e=>e.length===1?(this._buffer=e[0],this._buffer):(this._buffer=t.Buffer.concat(e),this._buffer)))}bytes(){return this.buffer()}arrayBuffer(){return this.buffer()}_json=null;json(){return this._json?(0,u.fakePromise)(this._json):this.text().then(e=>{try{this._json=JSON.parse(e)}catch(t){throw t instanceof SyntaxError&&(t.message+=`, "${e}" is not valid JSON`),t}return this._json})}_text=null;text(){return this._text?(0,u.fakePromise)(this._text):this.bodyType===d.String?(this._text=this.bodyInit,(0,u.fakePromise)(this._text)):this.buffer().then(e=>(this._text=e.toString(`utf-8`),this._text))}};exports.PonyfillBody=f;function p(e){if(e==null)return{bodyFactory:()=>null,contentType:null,contentLength:null};if(typeof e==`string`){let r=t.Buffer.byteLength(e);return{bodyType:d.String,contentType:`text/plain;charset=UTF-8`,contentLength:r,bodyFactory(){let r=n.Readable.from(t.Buffer.from(e,`utf-8`));return new l.PonyfillReadableStream(r)}}}if(t.Buffer.isBuffer(e)){let t=e;return{bodyType:d.Buffer,contentType:null,contentLength:e.length,buffer:e,bodyFactory(){let e=n.Readable.from(t),r=new l.PonyfillReadableStream(e);return r}}}if((0,u.isArrayBufferView)(e)){let r=t.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{bodyType:d.Buffer,contentLength:e.byteLength,contentType:null,buffer:r,bodyFactory(){let e=n.Readable.from(r),t=new l.PonyfillReadableStream(e);return t}}}if(e instanceof l.PonyfillReadableStream&&e.readable!=null){let t=e;return{bodyType:d.ReadableStream,bodyFactory:()=>t,contentType:null,contentLength:null}}if(h(e)){let t=e;return{bodyType:d.Blob,contentType:e.type,contentLength:e.size,bodyFactory(){return t.stream()}}}if(e instanceof ArrayBuffer){let r=e.byteLength,i=t.Buffer.from(e,void 0,e.byteLength);return{bodyType:d.Buffer,contentType:null,contentLength:r,buffer:i,bodyFactory(){let e=n.Readable.from(i),t=new l.PonyfillReadableStream(e);return t}}}if(e instanceof n.Readable)return{bodyType:d.Readable,contentType:null,contentLength:null,bodyFactory(){let t=new l.PonyfillReadableStream(e);return t}};if(g(e))return{bodyType:d.String,contentType:`application/x-www-form-urlencoded;charset=UTF-8`,contentLength:null,bodyFactory(){let t=new l.PonyfillReadableStream(n.Readable.from(e.toString()));return t}};if(m(e)){let t=Math.random().toString(36).substr(2),n=`multipart/form-data; boundary=${t}`;return{bodyType:d.FormData,contentType:n,contentLength:null,bodyFactory(){return(0,c.getStreamFromFormData)(e,t)}}}if(_(e))return{contentType:null,contentLength:null,bodyFactory(){return new l.PonyfillReadableStream(e)}};if(e[Symbol.iterator]||e[Symbol.asyncIterator])return{contentType:null,contentLength:null,bodyType:d.AsyncIterable,bodyFactory(){let t=n.Readable.from(e);return new l.PonyfillReadableStream(t)}};throw Error(`Unknown body type`)}function m(e){return e?.forEach!=null}function h(e){return e?.stream!=null&&typeof e.stream==`function`}function g(e){return e?.sort!=null}function _(e){return e?.getReader!=null}})),gt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillHeaders=void 0,exports.isHeadersLike=i;let t=r(`node:util`),n=pt();function i(e){return e?.get&&e?.forEach}var a=class{headersInit;_map;objectNormalizedKeysOfHeadersInit=[];objectOriginalKeysOfHeadersInit=[];_setCookies;constructor(e){this.headersInit=e}_get(e){let t=e.toLowerCase();if(t===`set-cookie`&&this._setCookies?.length)return this._setCookies.join(`, `);if(this._map)return this._map.get(t)||null;if(this.headersInit==null)return null;if(Array.isArray(this.headersInit)){let e=this.headersInit.filter(([e])=>e.toLowerCase()===t);return e.length===0?null:e.length===1?e[0][1]:e.map(([,e])=>e).join(`, `)}else if(i(this.headersInit))return this.headersInit.get(t);else{let n=this.headersInit[e]||this.headersInit[t];if(n!=null)return n;this.objectNormalizedKeysOfHeadersInit.length||Object.keys(this.headersInit).forEach(e=>{this.objectOriginalKeysOfHeadersInit.push(e),this.objectNormalizedKeysOfHeadersInit.push(e.toLowerCase())});let r=this.objectNormalizedKeysOfHeadersInit.indexOf(t);if(r===-1)return null;let i=this.objectOriginalKeysOfHeadersInit[r];return this.headersInit[i]}}getMap(){if(!this._map)if(this._setCookies||=[],this.headersInit!=null)if(Array.isArray(this.headersInit)){this._map=new Map;for(let[e,t]of this.headersInit){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies.push(t);continue}this._map.set(n,t)}}else if(i(this.headersInit))this._map=new Map,this.headersInit.forEach((e,t)=>{if(t===`set-cookie`){this._setCookies||=[],this._setCookies.push(e);return}this._map.set(t,e)});else for(let e in this._map=new Map,this.headersInit){let t=this.headersInit[e];if(t!=null){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies||=[],this._setCookies.push(t);continue}this._map.set(n,t)}}else this._map=new Map;return this._map}append(e,t){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies||=[],this._setCookies.push(t);return}let r=this.getMap().get(n),i=r?`${r}, ${t}`:t;this.getMap().set(n,i)}get(e){let t=this._get(e);return t==null?null:t.toString()}has(e){let t=e.toLowerCase();return t===`set-cookie`?!!this._setCookies?.length:!!this._get(e)}set(e,t){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies=[t];return}if(!this._map&&this.headersInit!=null)if(Array.isArray(this.headersInit)){let e=this.headersInit.find(([e])=>e.toLowerCase()===n);e?e[1]=t:this.headersInit.push([n,t]);return}else if(i(this.headersInit)){this.headersInit.set(n,t);return}else{this.headersInit[n]=t;return}this.getMap().set(n,t)}delete(e){let t=e.toLowerCase();if(t===`set-cookie`){this._setCookies=[];return}this.getMap().delete(t)}forEach(e){if(this._setCookies?.forEach(t=>{e(t,`set-cookie`,this)}),!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){this.headersInit.forEach(([t,n])=>{e(n,t,this)});return}if(i(this.headersInit)){this.headersInit.forEach(e);return}Object.entries(this.headersInit).forEach(([t,n])=>{n!=null&&e(n,t,this)})}return}this.getMap().forEach((t,n)=>{e(t,n,this)})}*_keys(){if(this._setCookies?.length&&(yield`set-cookie`),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([e])=>e)[Symbol.iterator]();return}if(i(this.headersInit)){yield*this.headersInit.keys();return}yield*Object.keys(this.headersInit)[Symbol.iterator]();return}yield*this.getMap().keys()}keys(){return new n.PonyfillIteratorObject(this._keys(),`HeadersIterator`)}*_values(){if(this._setCookies?.length&&(yield*this._setCookies),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([,e])=>e)[Symbol.iterator]();return}if(i(this.headersInit)){yield*this.headersInit.values();return}yield*Object.values(this.headersInit)[Symbol.iterator]();return}yield*this.getMap().values()}values(){return new n.PonyfillIteratorObject(this._values(),`HeadersIterator`)}*_entries(){if(this._setCookies?.length&&(yield*this._setCookies.map(e=>[`set-cookie`,e])),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit;return}if(i(this.headersInit)){yield*this.headersInit.entries();return}yield*Object.entries(this.headersInit);return}yield*this.getMap().entries()}entries(){return new n.PonyfillIteratorObject(this._entries(),`HeadersIterator`)}getSetCookie(){return this._setCookies||this.getMap(),this._setCookies}[Symbol.iterator](){return this.entries()}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};return this.forEach((t,n)=>{n===`set-cookie`?e[`set-cookie`]=this._setCookies||[]:e[n]=t?.includes(`,`)?t.split(`,`).map(e=>e.trim()):t}),`Headers ${(0,t.inspect)(e)}`}};exports.PonyfillHeaders=a})),_t=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillResponse=void 0;let t=r(`node:http`),n=ht(),i=gt(),a=`application/json; charset=utf-8`;var o=class e extends n.PonyfillBody{headers;constructor(e,n){super(e||null,n),this.headers=n?.headers&&(0,i.isHeadersLike)(n.headers)?n.headers:new i.PonyfillHeaders(n?.headers),this.status=n?.status||200,this.statusText=n?.statusText||t.STATUS_CODES[this.status]||`OK`,this.url=n?.url||``,this.redirected=n?.redirected||!1,this.type=n?.type||`default`,this.handleContentLengthHeader()}get ok(){return this.status>=200&&this.status<300}status;statusText;url;redirected;type;clone(){return this}static error(){return new e(null,{status:500,statusText:`Internal Server Error`})}static redirect(t,n=302){if(n<300||n>399)throw RangeError(`Invalid status code`);return new e(null,{headers:{location:t},status:n})}static json(t,n){let r=JSON.stringify(t);if(!n)n={headers:{"content-type":a,"content-length":Buffer.byteLength(r).toString()}};else if(!n.headers)n.headers={"content-type":a,"content-length":Buffer.byteLength(r).toString()};else if((0,i.isHeadersLike)(n.headers))n.headers.has(`content-type`)||n.headers.set(`content-type`,a),n.headers.has(`content-length`)||n.headers.set(`content-length`,Buffer.byteLength(r).toString());else if(Array.isArray(n.headers)){let e=!1,t=!1;for(let[r]of n.headers){if(t&&e)break;!e&&r.toLowerCase()===`content-type`?e=!0:!t&&r.toLowerCase()===`content-length`&&(t=!0)}e||n.headers.push([`content-type`,a]),t||n.headers.push([`content-length`,Buffer.byteLength(r).toString()])}else typeof n.headers==`object`&&(n.headers?.[`content-type`]??(n.headers[`content-type`]=a),n.headers?.[`content-length`]??(n.headers[`content-length`]=Buffer.byteLength(r).toString()));return new e(r,n)}[Symbol.toStringTag]=`Response`};exports.PonyfillResponse=o})),vt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchCurl=s;let t=r(`node:stream`),n=r(`node:tls`),i=L(),a=_t(),o=V();function s(e){let{Curl:r,CurlFeature:s,CurlPause:c,CurlProgressFunc:l}=globalThis.libcurl,u=new r;u.enable(s.NoDataParsing),u.setOpt(`URL`,e.url),process.env.NODE_TLS_REJECT_UNAUTHORIZED===`0`&&u.setOpt(`SSL_VERIFYPEER`,!1),process.env.NODE_EXTRA_CA_CERTS?u.setOpt(`CAINFO`,process.env.NODE_EXTRA_CA_CERTS):u.setOpt(`CAINFO_BLOB`,n.rootCertificates.join(`
8
- `)),u.enable(s.StreamResponse);let d;if(e._signal===null?d=void 0:e._signal&&(d=e._signal),u.setStreamProgressCallback(function(){return d?.aborted?process.env.DEBUG?l.Continue:1:0}),e.bodyType===`String`)u.setOpt(`POSTFIELDS`,e.bodyInit);else{let n=e.body==null?null:(0,o.isNodeReadable)(e.body)?e.body:t.Readable.from(e.body);n&&(u.setOpt(`UPLOAD`,!0),u.setUploadStream(n))}process.env.DEBUG&&u.setOpt(`VERBOSE`,!0),u.setOpt(`TRANSFER_ENCODING`,!1),u.setOpt(`HTTP_TRANSFER_DECODING`,!0),u.setOpt(`FOLLOWLOCATION`,e.redirect===`follow`),u.setOpt(`MAXREDIRS`,20),u.setOpt(`ACCEPT_ENCODING`,``),u.setOpt(`CUSTOMREQUEST`,e.method);let f=e.headersSerializer||o.defaultHeadersSerializer,p,m=f(e.headers,e=>{p=Number(e)});p!=null&&u.setOpt(`INFILESIZE`,p),u.setOpt(`HTTPHEADER`,m),u.enable(s.NoHeaderParsing);let h=(0,i.createDeferredPromise)(),g;function _(){if(u.isOpen)try{u.pause(c.Recv)}catch(e){h.reject(e)}}return d?.addEventListener(`abort`,_,{once:!0}),u.once(`end`,function(){try{u.close()}catch(e){h.reject(e)}d?.removeEventListener(`abort`,_)}),u.once(`error`,function(e){g&&!g.closed&&!g.destroyed?g.destroy(e):(e.message===`Operation was aborted by an application callback`&&(e.message=`The operation was aborted.`),h.reject(e));try{u.close()}catch(e){h.reject(e)}}),u.once(`stream`,function(n,i,s){let c=n.pipe(new t.PassThrough,{end:!0}),l=s.toString(`utf8`).split(/\r?\n|\r/g).filter(t=>t&&!t.startsWith(`HTTP/`)?(e.redirect===`error`&&t.toLowerCase().includes(`location`)&&(0,o.shouldRedirect)(i)&&(n.destroyed||n.resume(),c.destroy(),h.reject(Error(`redirect is not allowed`))),!0):!1),d=l.map(e=>e.split(/:\s(.+)/).slice(0,2)),f=new a.PonyfillResponse(c,{status:i,headers:d,url:u.getInfo(r.info.REDIRECT_URL)?.toString()||e.url,redirected:Number(u.getInfo(r.info.REDIRECT_COUNT))>0});h.resolve(f),g=c}),setImmediate(()=>{u.perform()}),h.promise}})),yt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillURL=void 0;let t=(ot(),i(Se)),n=t.__importDefault(r(`node:buffer`)),a=r(`node:crypto`),o=globalThis.URL;var s=class extends o{static blobRegistry=new Map;static createObjectURL(e){let t=`blob:whatwgnode:${(0,a.randomUUID)()}`;return this.blobRegistry.set(t,e),t}static revokeObjectURL(e){this.blobRegistry.has(e)?this.blobRegistry.delete(e):o.revokeObjectURL(e)}static getBlobFromURL(e){return this.blobRegistry.get(e)||n.default?.resolveObjectURL?.(e)}};exports.PonyfillURL=s})),bt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillRequest=void 0;let t=r(`node:http`),n=r(`node:https`),i=ht(),a=gt(),o=yt();function s(e){return e[Symbol.toStringTag]===`Request`}function c(e){return e?.href!=null}var l=class extends i.PonyfillBody{constructor(e,r){let i,o,l=null,u;if(typeof e==`string`?i=e:c(e)?o=e:s(e)&&(e._parsedUrl?o=e._parsedUrl:i=e._url?e._url:e.url,l=e.body,u=e),r!=null&&(l=r.body||null,u=r),super(l,u),this._url=i,this._parsedUrl=o,this.cache=u?.cache||`default`,this.credentials=u?.credentials||`same-origin`,this.headers=u?.headers&&(0,a.isHeadersLike)(u.headers)?u.headers:new a.PonyfillHeaders(u?.headers),this.integrity=u?.integrity||``,this.keepalive=u?.keepalive==null?!1:u?.keepalive,this.method=u?.method?.toUpperCase()||`GET`,this.mode=u?.mode||`cors`,this.redirect=u?.redirect||`follow`,this.referrer=u?.referrer||`about:client`,this.referrerPolicy=u?.referrerPolicy||`no-referrer`,this.headersSerializer=u?.headersSerializer,this.duplex=u?.duplex||`half`,this.destination=`document`,this.priority=`auto`,this.method!==`GET`&&this.method!==`HEAD`&&this.handleContentLengthHeader(!0),u?.agent!=null){let e=o?.protocol||i||this.url;u.agent===!1?this.agent=!1:(e.startsWith(`http:`)&&u.agent instanceof t.Agent||e.startsWith(`https:`)&&u.agent instanceof n.Agent)&&(this.agent=u.agent)}}headersSerializer;cache;credentials;destination;headers;integrity;keepalive;method;mode;priority;redirect;referrer;referrerPolicy;_url;get signal(){return this._signal||=new AbortController().signal,this._signal}get url(){if(this._url==null)if(this._parsedUrl)this._url=this._parsedUrl.toString();else throw TypeError(`Invalid URL`);return this._url}_parsedUrl;get parsedUrl(){if(this._parsedUrl==null)if(this._url!=null)this._parsedUrl=new o.PonyfillURL(this._url,`http://localhost`);else throw TypeError(`Invalid URL`);return this._parsedUrl}duplex;agent;clone(){return this}[Symbol.toStringTag]=`Request`};exports.PonyfillRequest=l})),xt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchNodeHttp=f;let t=r(`node:http`),n=r(`node:https`),i=r(`node:stream`),a=r(`node:zlib`),o=L(),s=bt(),c=_t(),l=yt(),u=V();function d(e){if(e.startsWith(`http:`))return t.request;if(e.startsWith(`https:`))return n.request;throw Error(`Unsupported protocol: ${e.split(`:`)[0]||e}`)}function f(e){return new Promise((n,r)=>{try{let p=d(e.parsedUrl?.protocol||e.url),m=e.headersSerializer||u.getHeadersObj,h=m(e.headers);h[`accept-encoding`]??=`gzip, deflate, br`;let g;e._signal==null?g=void 0:e._signal&&(g=e._signal);let _;if(_=e.parsedUrl?p(e.parsedUrl,{method:e.method,headers:h,signal:g,agent:e.agent}):p(e.url,{method:e.method,headers:h,signal:g,agent:e.agent}),_.once(`error`,r),_.once(`response`,o=>{let d,p=o.headers[`content-encoding`];switch(p){case`x-gzip`:case`gzip`:d=(0,a.createGunzip)();break;case`x-deflate`:case`deflate`:d=(0,a.createInflate)();break;case`x-deflate-raw`:case`deflate-raw`:d=(0,a.createInflateRaw)();break;case`br`:d=(0,a.createBrotliDecompress)();break}if(o.headers.location&&(0,u.shouldRedirect)(o.statusCode)){if(e.redirect===`error`){let e=Error(`Redirects are not allowed`);r(e),o.resume();return}if(e.redirect===`follow`){let t=new l.PonyfillURL(o.headers.location,e.parsedUrl||e.url),r=f(new s.PonyfillRequest(t,e));n(r.then(e=>(e.redirected=!0,e))),o.resume();return}}d||=new i.PassThrough,(0,u.pipeThrough)({src:o,dest:d,signal:g,onError:e=>{o.destroyed||o.destroy(e),d.destroyed||d.destroy(e),r(e)}});let m=o.statusCode||200,h=o.statusMessage||t.STATUS_CODES[m];h??=``;let _=new c.PonyfillResponse(d||o,{status:m,statusText:h,headers:o.headers,url:e.url,signal:g});n(_)}),e._buffer!=null)(0,o.handleMaybePromise)(()=>(0,u.safeWrite)(e._buffer,_),()=>(0,u.endStream)(_),r);else{let t=e.body==null?null:(0,u.isNodeReadable)(e.body)?e.body:i.Readable.from(e.body);t?t.pipe(_):(0,u.endStream)(_)}}catch(e){r(e)}})}})),St=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchPonyfill=h;let t=r(`node:buffer`),n=r(`node:fs`),i=r(`node:url`),a=vt(),o=xt(),s=bt(),c=_t(),l=yt(),u=V();async function d(e){let t=(0,i.fileURLToPath)(e);try{await n.promises.access(t,n.promises.constants.R_OK);let e=await n.promises.stat(t,{bigint:!0}),r=(0,n.createReadStream)(t);return new c.PonyfillResponse(r,{status:200,statusText:`OK`,headers:{"content-type":`application/octet-stream`,"last-modified":e.mtime.toUTCString()}})}catch(e){if(e.code===`ENOENT`)return new c.PonyfillResponse(null,{status:404,statusText:`Not Found`});if(e.code===`EACCES`)return new c.PonyfillResponse(null,{status:403,statusText:`Forbidden`});throw e}}function f(e){let[n=`text/plain`,...r]=e.substring(5).split(`,`),i=decodeURIComponent(r.join(`,`));if(n.endsWith(`;base64`)){let e=t.Buffer.from(i,`base64url`),r=n.slice(0,-7);return new c.PonyfillResponse(e,{status:200,statusText:`OK`,headers:{"content-type":r}})}return new c.PonyfillResponse(i,{status:200,statusText:`OK`,headers:{"content-type":n}})}function p(e){let t=l.PonyfillURL.getBlobFromURL(e);if(!t)throw TypeError(`Invalid Blob URL`);return new c.PonyfillResponse(t,{status:200,headers:{"content-type":t.type,"content-length":t.size.toString()}})}function m(e){return e!=null&&e.href!=null}function h(e,t){if(typeof e==`string`||m(e)){let n=new s.PonyfillRequest(e,t);return h(n)}let n=e;if(n.url.startsWith(`data:`)){let e=f(n.url);return(0,u.fakePromise)(e)}if(n.url.startsWith(`file:`)){let e=d(n.url);return e}if(n.url.startsWith(`blob:`)){let e=p(n.url);return(0,u.fakePromise)(e)}return globalThis.libcurl&&!n.agent?(0,a.fetchCurl)(n):(0,o.fetchNodeHttp)(n)}})),Ct=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTextDecoder=exports.PonyfillTextEncoder=void 0,exports.PonyfillBtoa=o;let t=r(`node:buffer`),n=V();var i=class{encoding;constructor(e=`utf-8`){this.encoding=e}encode(e){return t.Buffer.from(e,this.encoding)}encodeInto(e,t){let n=this.encode(e),r=n.copy(t);return{read:r,written:r}}};exports.PonyfillTextEncoder=i;var a=class{encoding;fatal=!1;ignoreBOM=!1;constructor(e=`utf-8`,t){this.encoding=e,t&&(this.fatal=t.fatal||!1,this.ignoreBOM=t.ignoreBOM||!1)}decode(e){return t.Buffer.isBuffer(e)?e.toString(this.encoding):(0,n.isArrayBufferView)(e)?t.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(this.encoding):t.Buffer.from(e).toString(this.encoding)}};exports.PonyfillTextDecoder=a;function o(e){return t.Buffer.from(e,`binary`).toString(`base64`)}})),wt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillURLSearchParams=void 0,exports.PonyfillURLSearchParams=globalThis.URLSearchParams})),Tt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillWritableStream=void 0;let t=r(`node:events`),n=r(`node:stream`),i=L(),a=V();var o=class{writable;constructor(e){if(e instanceof n.Writable)this.writable=e;else if(e){let t=new n.Writable({write(t,n,r){try{let n=e.write?.(t,i);n instanceof Promise?n.then(()=>{r()},e=>{r(e)}):r()}catch(e){r(e)}},final(t){let n=e.close?.();n instanceof Promise?n.then(()=>{t()},e=>{t(e)}):t()}});this.writable=t;let r=new AbortController,i={signal:r.signal,error(e){t.destroy(e)}};t.once(`error`,e=>r.abort(e)),t.once(`close`,()=>r.abort())}else this.writable=new n.Writable}getWriter(){let e=this.writable;return{get closed(){return(0,t.once)(e,`close`)},get desiredSize(){return e.writableLength},get ready(){return(0,t.once)(e,`drain`)},releaseLock(){},write(t){let n=(0,a.fakePromise)();return t==null?n:n.then(()=>(0,a.safeWrite)(t,e))},close(){return!e.errored&&e.closed?(0,a.fakePromise)():e.errored?(0,i.fakeRejectPromise)(e.errored):(0,a.fakePromise)().then(()=>(0,a.endStream)(e))},abort(n){return e.destroy(n),(0,t.once)(e,`close`)}}}close(){return!this.writable.errored&&this.writable.closed?(0,a.fakePromise)():this.writable.errored?(0,i.fakeRejectPromise)(this.writable.errored):(0,a.fakePromise)().then(()=>(0,a.endStream)(this.writable))}abort(e){return this.writable.destroy(e),(0,t.once)(this.writable,`close`)}locked=!1};exports.PonyfillWritableStream=o})),Et=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTransformStream=void 0;let t=r(`node:stream`),n=ye(),i=V(),a=Tt();var o=class{transform;writable;readable;constructor(e){if(e instanceof t.Transform)this.transform=e;else if(e){let n={enqueue(e){r.push(e)},error(e){r.destroy(e)},terminate(){(0,i.endStream)(r)},get desiredSize(){return r.writableLength}},r=new t.Transform({read(){},write(t,r,i){try{let r=e.transform?.(t,n);r instanceof Promise?r.then(()=>{i()},e=>{i(e)}):i()}catch(e){i(e)}},final(t){try{let r=e.flush?.(n);r instanceof Promise?r.then(()=>{t()},e=>{t(e)}):t()}catch(e){t(e)}}});this.transform=r}else this.transform=new t.Transform;this.writable=new a.PonyfillWritableStream(this.transform),this.readable=new n.PonyfillReadableStream(this.transform)}};exports.PonyfillTransformStream=o})),Dt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillCompressionStream=void 0;let t=r(`node:zlib`),n=Et();var i=class extends n.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith(`v2`)?[`gzip`,`deflate`,`br`]:[`gzip`,`deflate`,`deflate-raw`,`br`];constructor(e){switch(e){case`x-gzip`:case`gzip`:super((0,t.createGzip)());break;case`x-deflate`:case`deflate`:super((0,t.createDeflate)());break;case`deflate-raw`:super((0,t.createDeflateRaw)());break;case`br`:super((0,t.createBrotliCompress)());break;default:throw Error(`Unsupported compression format: ${e}`)}}};exports.PonyfillCompressionStream=i})),Ot=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillDecompressionStream=void 0;let t=r(`node:zlib`),n=Et();var i=class extends n.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith(`v2`)?[`gzip`,`deflate`,`br`]:[`gzip`,`deflate`,`deflate-raw`,`br`];constructor(e){switch(e){case`x-gzip`:case`gzip`:super((0,t.createGunzip)());break;case`x-deflate`:case`deflate`:super((0,t.createInflate)());break;case`deflate-raw`:super((0,t.createInflateRaw)());break;case`br`:super((0,t.createBrotliDecompress)());break;default:throw TypeError(`Unsupported compression format: '${e}'`)}}};exports.PonyfillDecompressionStream=i})),kt=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTextEncoderStream=exports.PonyfillTextDecoderStream=void 0;let t=Ct(),n=Et();var r=class extends n.PonyfillTransformStream{textDecoder;constructor(e,n){super({transform:(e,t)=>t.enqueue(this.textDecoder.decode(e,{stream:!0}))}),this.textDecoder=new t.PonyfillTextDecoder(e,n)}get encoding(){return this.textDecoder.encoding}get fatal(){return this.textDecoder.fatal}get ignoreBOM(){return this.textDecoder.ignoreBOM}};exports.PonyfillTextDecoderStream=r;var i=class extends n.PonyfillTransformStream{textEncoder;constructor(e){super({transform:(e,t)=>t.enqueue(this.textEncoder.encode(e))}),this.textEncoder=new t.PonyfillTextEncoder(e)}get encoding(){return this.textEncoder.encoding}encode(e){return this.textEncoder.encode(e)}};exports.PonyfillTextEncoderStream=i})),At=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.TextEncoderStream=exports.TextDecoderStream=exports.IteratorObject=exports.DecompressionStream=exports.CompressionStream=exports.TransformStream=exports.WritableStream=exports.URLSearchParams=exports.URL=exports.btoa=exports.TextDecoder=exports.TextEncoder=exports.Blob=exports.FormData=exports.File=exports.ReadableStream=exports.Response=exports.Request=exports.Body=exports.Headers=exports.fetch=void 0;var t=St();Object.defineProperty(exports,`fetch`,{enumerable:!0,get:function(){return t.fetchPonyfill}});var n=gt();Object.defineProperty(exports,`Headers`,{enumerable:!0,get:function(){return n.PonyfillHeaders}});var r=ht();Object.defineProperty(exports,`Body`,{enumerable:!0,get:function(){return r.PonyfillBody}});var i=bt();Object.defineProperty(exports,`Request`,{enumerable:!0,get:function(){return i.PonyfillRequest}});var a=_t();Object.defineProperty(exports,`Response`,{enumerable:!0,get:function(){return a.PonyfillResponse}});var o=ye();Object.defineProperty(exports,`ReadableStream`,{enumerable:!0,get:function(){return o.PonyfillReadableStream}});var s=xe();Object.defineProperty(exports,`File`,{enumerable:!0,get:function(){return s.PonyfillFile}});var c=mt();Object.defineProperty(exports,`FormData`,{enumerable:!0,get:function(){return c.PonyfillFormData}});var l=be();Object.defineProperty(exports,`Blob`,{enumerable:!0,get:function(){return l.PonyfillBlob}});var u=Ct();Object.defineProperty(exports,`TextEncoder`,{enumerable:!0,get:function(){return u.PonyfillTextEncoder}}),Object.defineProperty(exports,`TextDecoder`,{enumerable:!0,get:function(){return u.PonyfillTextDecoder}}),Object.defineProperty(exports,`btoa`,{enumerable:!0,get:function(){return u.PonyfillBtoa}});var d=yt();Object.defineProperty(exports,`URL`,{enumerable:!0,get:function(){return d.PonyfillURL}});var f=wt();Object.defineProperty(exports,`URLSearchParams`,{enumerable:!0,get:function(){return f.PonyfillURLSearchParams}});var p=Tt();Object.defineProperty(exports,`WritableStream`,{enumerable:!0,get:function(){return p.PonyfillWritableStream}});var m=Et();Object.defineProperty(exports,`TransformStream`,{enumerable:!0,get:function(){return m.PonyfillTransformStream}});var h=Dt();Object.defineProperty(exports,`CompressionStream`,{enumerable:!0,get:function(){return h.PonyfillCompressionStream}});var g=Ot();Object.defineProperty(exports,`DecompressionStream`,{enumerable:!0,get:function(){return g.PonyfillDecompressionStream}});var _=pt();Object.defineProperty(exports,`IteratorObject`,{enumerable:!0,get:function(){return _.PonyfillIteratorObject}});var v=kt();Object.defineProperty(exports,`TextDecoderStream`,{enumerable:!0,get:function(){return v.PonyfillTextDecoderStream}}),Object.defineProperty(exports,`TextEncoderStream`,{enumerable:!0,get:function(){return v.PonyfillTextEncoderStream}})})),jt=e(((exports,t)=>{let n=se(),i;t.exports=function(e={}){let t={};if(t.URLPattern=globalThis.URLPattern,!t.URLPattern){let e=le();t.URLPattern=e.URLPattern}if(e.skipPonyfill||n())return{fetch:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response,FormData:globalThis.FormData,ReadableStream:globalThis.ReadableStream,WritableStream:globalThis.WritableStream,TransformStream:globalThis.TransformStream,CompressionStream:globalThis.CompressionStream,DecompressionStream:globalThis.DecompressionStream,TextDecoderStream:globalThis.TextDecoderStream,TextEncoderStream:globalThis.TextEncoderStream,Blob:globalThis.Blob,File:globalThis.File,crypto:globalThis.crypto,btoa:globalThis.btoa,TextEncoder:globalThis.TextEncoder,TextDecoder:globalThis.TextDecoder,URLPattern:t.URLPattern,URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams};if(i||=At(),t.fetch=i.fetch,t.Request=i.Request,t.Response=i.Response,t.Headers=i.Headers,t.FormData=i.FormData,t.ReadableStream=i.ReadableStream,t.URL=i.URL,t.URLSearchParams=i.URLSearchParams,t.WritableStream=i.WritableStream,t.TransformStream=i.TransformStream,t.CompressionStream=i.CompressionStream,t.DecompressionStream=i.DecompressionStream,t.TextDecoderStream=i.TextDecoderStream,t.TextEncoderStream=i.TextEncoderStream,t.Blob=i.Blob,t.File=i.File,t.crypto=globalThis.crypto,t.btoa=i.btoa,t.TextEncoder=i.TextEncoder,t.TextDecoder=i.TextDecoder,e.formDataLimits&&(t.Body=class extends i.Body{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}},t.Request=class extends i.Request{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}},t.Response=class extends i.Response{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}}),!t.crypto){let e=r(`crypto`);t.crypto=e.webcrypto}return t}})),Mt=e(((exports,t)=>{let n=jt(),i=se(),a=n();if(!i())try{globalThis.libcurl=globalThis.libcurl||r(`node-libcurl`)}catch{}t.exports.fetch=a.fetch,t.exports.Headers=a.Headers,t.exports.Request=a.Request,t.exports.Response=a.Response,t.exports.FormData=a.FormData,t.exports.ReadableStream=a.ReadableStream,t.exports.WritableStream=a.WritableStream,t.exports.TransformStream=a.TransformStream,t.exports.CompressionStream=a.CompressionStream,t.exports.DecompressionStream=a.DecompressionStream,t.exports.TextDecoderStream=a.TextDecoderStream,t.exports.TextEncoderStream=a.TextEncoderStream,t.exports.Blob=a.Blob,t.exports.File=a.File,t.exports.crypto=a.crypto,t.exports.btoa=a.btoa,t.exports.TextEncoder=a.TextEncoder,t.exports.TextDecoder=a.TextDecoder,t.exports.URLPattern=a.URLPattern,t.exports.URL=a.URL,t.exports.URLSearchParams=a.URLSearchParams,exports.createFetch=n}));function Nt(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function Pt(e){if(e.socket?.localPort)return e.socket?.localPort;let t=e.headers?.[`:authority`]||e.headers?.host,n=t?.split(`:`)?.[1];return n||80}function Ft(e){if(e.headers?.[`:authority`])return e.headers?.[`:authority`];if(e.headers?.host)return e.headers?.host;let t=Pt(e);if(e.hostname)return e.hostname+`:`+t;let n=e.socket?.localAddress;return n&&!n?.includes(`::`)&&!n?.includes(`ffff`)?`${n}:${t}`:`localhost`}function It(e){let t=Ft(e),n=e.protocol||(e.socket?.encrypted?`https`:`http`),r=e.originalUrl||e.url||`/graphql`;return`${n}://${t}${r}`}function Lt(e){let t=e[Symbol.toStringTag];return!!(typeof e==`string`||t===`Uint8Array`||t===`Blob`||t===`FormData`||t===`URLSearchParams`||Nt(e))}function Rt(e,t,n,r){let i=e.raw||e.req||e,a=It(i);if(e.query){let n=new t.URL(a);for(let t in e.query)n.searchParams.set(t,e.query[t]);a=n.toString()}let o=e.headers;if(e.headers?.[`:method`])for(let t in o={},e.headers)t.startsWith(`:`)||(o[t]=e.headers[t]);let s=r?cn():new AbortController;if(n?.once){let e=()=>{s.signal.aborted||(Object.defineProperty(i,`aborted`,{value:!0}),s.abort(n.errored??void 0))};n.once(`error`,e),n.once(`close`,e),n.once(`finish`,()=>{n.removeListener(`close`,e)})}if(e.method===`GET`||e.method===`HEAD`)return new t.Request(a,{method:e.method,headers:o,signal:s.signal});let c=e.body;if(c!=null&&Object.keys(c).length>0){if(Lt(c))return new t.Request(a,{method:e.method||`GET`,headers:o,body:c,signal:s.signal});let n=new t.Request(a,{method:e.method||`GET`,headers:o,signal:s.signal});return n.headers.get(`content-type`)?.includes(`json`)||n.headers.set(`content-type`,`application/json; charset=utf-8`),new Proxy(n,{get:(e,t,n)=>{switch(t){case`json`:return()=>D(c);case`text`:return()=>D(JSON.stringify(c));default:return globalThis.Bun?Reflect.get(e,t):Reflect.get(e,t,n)}}})}return new t.Request(a,{method:e.method,headers:o,signal:s.signal,body:i,duplex:`half`})}function zt(e){return e.read!=null}function Bt(e){return zt(e)}function Vt(e){return e!=null&&e.setHeader!=null&&e.end!=null&&e.once!=null&&e.write!=null}function Ht(e){return e!=null&&e.getReader!=null}function Ut(e){return e!=null&&e.request!=null&&e.respondWith!=null}function Wt(e){e?.socket?.setTimeout?.(0),e?.socket?.setNoDelay?.(!0),e?.socket?.setKeepAlive?.(!0)}function Gt(e){e.end(null,null,null)}function Kt(e,t){let n=!1,r=()=>{n=!0};e.once(`error`,r),e.once(`close`,r),e.once(`finish`,()=>{e.removeListener(`close`,r),e.removeListener(`error`,r)});let i=t[Symbol.asyncIterator](),a=()=>i.next().then(({done:t,value:r})=>{if(!(n||t))return E(()=>qt(r,e),()=>n?Gt(e):a())});return a()}function qt(e,t){let n=t.write(e);if(!n)return new Promise(e=>t.once(`drain`,e))}function Jt(e,t,n,r){if(t.closed||t.destroyed||t.writableEnded)return;if(!e){t.statusCode=404,Gt(t);return}if(r&&e.headers?.headersInit&&!Array.isArray(e.headers.headersInit)&&!e.headers.headersInit.get&&!e.headers._map&&!e.headers._setCookies?.length)t.writeHead(e.status,e.statusText,e.headers.headersInit);else{if(t.setHeaders)t.setHeaders(e.headers);else{let n=!1;e.headers.forEach((r,i)=>{if(i===`set-cookie`){if(n)return;n=!0;let r=e.headers.getSetCookie?.();if(r){t.setHeader(`set-cookie`,r);return}}t.setHeader(i,r)})}t.writeHead(e.status,e.statusText)}if(e.bodyType===`String`)return E(()=>qt(e.bodyInit,t),()=>Gt(t));let i=e._buffer;if(i)return E(()=>qt(i,t),()=>Gt(t));let a=e.body;if(a==null){Gt(t);return}if(a[Symbol.toStringTag]===`Uint8Array`)return E(()=>qt(a,t),()=>Gt(t));if(Wt(n),zt(a)){t.once(`close`,()=>{a.destroy()}),a.pipe(t,{end:!0});return}if(Ht(a))return Yt(n,t,a);if(Nt(a))return Kt(t,a)}function Yt(e,t,n){let r=n.getReader();e?.once?.(`error`,e=>{r.cancel(e)});function i(){return r.read().then(({done:e,value:n})=>e?Gt(t):E(()=>qt(n,t),i))}return i()}function Xt(e){return typeof e==`object`&&!!e&&(`body`in e||`cache`in e||`credentials`in e||`headers`in e||`integrity`in e||`keepalive`in e||`method`in e||`mode`in e||`redirect`in e||`referrer`in e||`referrerPolicy`in e||`signal`in e||`window`in e)}function Zt(...e){let[t,...n]=e.filter(e=>typeof e==`object`&&!!e);return n.forEach(e=>{let n=Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=Object.getOwnPropertyDescriptor(e,n);return r&&(t[n]=Object.getOwnPropertyDescriptor(e,n)),t},{});Object.getOwnPropertySymbols(e).forEach(t=>{let r=Object.getOwnPropertyDescriptor(e,t);r?.enumerable&&(n[t]=r)}),Object.defineProperties(t,n)}),t}function Qt(e,t){return new t(e.stack||e.message||e.toString(),{status:e.status||500})}function $t(e,t){return e==null?t==null?{}:{waitUntil:t}:Zt(Object.create(e),{waitUntil:t},e)}function en(e,t){if(t?.aborted)throw t.reason;if(w(e)&&t){let n=O();function r(){n.reject(t.reason)}return t.addEventListener(`abort`,r,{once:!0}),e.then(function(e){n.resolve(e)}).catch(function(e){n.reject(e)}).finally(()=>{t.removeEventListener(`abort`,r)}),n.promise}return e}const tn=[`SIGINT`,`exit`,`SIGTERM`],nn=new Set;let rn=!1;function an(){if(!rn){rn=!0;for(let e of tn)globalThis.process.once(e,function(){return Promise.allSettled([...nn].map(e=>!e.disposed&&e.disposeAsync()))})}}function on(e){globalThis.process&&(an(),nn.has(e)||(nn.add(e),e.defer(()=>{nn.delete(e)})))}var sn=class extends EventTarget{aborted=!1;_onabort=null;_reason;constructor(){super();let e=globalThis.process?.getBuiltinModule?.(`node:events`);e?.kMaxEventTargetListeners&&(this[e.kMaxEventTargetListeners]=0)}throwIfAborted(){if(this._nativeCtrl?.signal?.throwIfAborted)return this._nativeCtrl.signal.throwIfAborted();if(this.aborted)throw this._reason}_nativeCtrl;ensureNativeCtrl(){if(!this._nativeCtrl){let e=this.aborted;this._nativeCtrl=new AbortController,e&&this._nativeCtrl.abort(this._reason)}return this._nativeCtrl}abort(e){if(this._nativeCtrl?.abort)return this._nativeCtrl?.abort(e);this._reason=e||new DOMException(`This operation was aborted`,`AbortError`),this.aborted=!0,this.dispatchEvent(new Event(`abort`))}get signal(){return this._nativeCtrl?.signal?this._nativeCtrl.signal:this}get reason(){return this._nativeCtrl?.signal?this._nativeCtrl.signal.reason:this._reason}get onabort(){return this._onabort,this._onabort}set onabort(e){if(this._nativeCtrl?.signal){this._nativeCtrl.signal.onabort=e;return}this._onabort&&this.removeEventListener(`abort`,this._onabort),this._onabort=e,e&&this.addEventListener(`abort`,e)}};function cn(){return globalThis.Bun||globalThis.Deno?new AbortController:new Proxy(new sn,{get(e,t,n){if(t.toString().includes(`kDependantSignals`)){let n=e.ensureNativeCtrl();return Reflect.get(n.signal,t,n.signal)}return Reflect.get(e,t,n)},set(e,t,n,r){if(t.toString().includes(`kDependantSignals`)){let r=e.ensureNativeCtrl();return Reflect.set(r.signal,t,n,r.signal)}return Reflect.set(e,t,n,r)},getPrototypeOf(){return AbortSignal.prototype}})}function ln(e){return!!e.onData}function un({req:e,res:t,fetchAPI:n,controller:r}){let i=e.getMethod(),a,o=[],s=[e=>{o.push(e)}],c=e=>{for(let t of s)t(e)},l=!1,u=[()=>{l=!0}],d=()=>{for(let e of u)e()};t.onData(function(e,t){c(Buffer.from(Buffer.from(e,0,e.byteLength))),t&&d()});let f;if(i!==`get`&&i!==`head`){a=`half`,r.signal.addEventListener(`abort`,()=>{d()},{once:!0});let e;f=()=>(e||=new n.ReadableStream({start(e){for(let t of o)e.enqueue(t);if(l){e.close();return}s.push(t=>{e.enqueue(t)}),u.push(()=>{if(r.signal.reason){e.error(r.signal.reason);return}e.desiredSize&&e.close()})}}),e)}let p=new n.Headers;e.forEach((e,t)=>{p.append(e,t)});let m=`http://localhost${e.getUrl()}`,h=e.getQuery();h&&(m+=`?${h}`);let g;function _(){return f?l?y():f():null}let v=new n.Request(m,{method:i,headers:p,get body(){return _()},signal:r.signal,duplex:a});function y(){return g||=o.length===1?o[0]:Buffer.concat(o),g}function b(){return l?D(y()):new Promise((e,t)=>{try{u.push(()=>{e(y())})}catch(e){t(e)}})}return Object.defineProperties(v,{body:{get(){return _()},configurable:!0,enumerable:!0},json:{value(){return b().then(e=>e.toString(`utf8`)).then(e=>JSON.parse(e))},configurable:!0,enumerable:!0},text:{value(){return b().then(e=>e.toString(`utf8`))},configurable:!0,enumerable:!0},arrayBuffer:{value(){return b()},configurable:!0,enumerable:!0}}),v}function dn(e,t){return new t.WritableStream({write(t){e.cork(()=>{e.write(t)})},close(){e.cork(()=>{e.end()})}})}function fn(e,t,n,r){if(!t){e.writeStatus(`404 Not Found`),e.end();return}let i=t._buffer,a=t.bodyType===`String`?t.bodyInit:void 0;if(!n.signal.aborted&&(e.cork(()=>{e.writeStatus(`${t.status} ${t.statusText}`);for(let[n,r]of t.headers)if(n!==`content-length`){if(n===`set-cookie`){let r=t.headers.getSetCookie?.();if(r){for(let t of r)e.writeHeader(n,t);continue}}e.writeHeader(n,r)}a?e.end(a):i?e.end(i):t.body||e.end()}),!(a||i||!t.body)))return n.signal.addEventListener(`abort`,()=>{t.body?.locked||t.body?.cancel(n.signal.reason)},{once:!0}),t.body.pipeTo(dn(e,r),{signal:n.signal}).catch(e=>{if(!n.signal.aborted)throw e})}var pn=a(Mt(),1);function mn(e){try{return!!e?.request}catch{return!1}}const hn={};function gn(e,t){let n=t?.__useSingleWriteHead==null?!0:t.__useSingleWriteHead,r={...pn,...t?.fetchAPI},i=t?.__useCustomAbortCtrl==null?r.Request!==globalThis.Request:t.__useCustomAbortCtrl,a=typeof e==`function`?e:e.handle,o=[],s=[],c,l=new Set,u;function d(){return u||(u=new oe,t?.disposeOnProcessTerminate&&on(u),u.defer(()=>{if(l.size>0)return Promise.allSettled(l).then(()=>{l.clear()},()=>{l.clear()})})),u}function f(e){w(e)&&(d(),l.add(e),e.then(()=>{l.delete(e)},t=>{console.error(`Unexpected error while waiting: ${t.message||t}`),l.delete(e)}))}if(t?.plugins!=null)for(let e of t.plugins){e.instrumentation&&(c=c?N(c,e.instrumentation):e.instrumentation),e.onRequest&&o.push(e.onRequest),e.onResponse&&s.push(e.onResponse);let t=e[I.dispose];t&&d().defer(t);let n=e[I.asyncDispose];n&&d().defer(n),e.onDispose&&d().defer(e.onDispose)}let p=o.length>0||s.length>0?function(e,t){let n=a,i;if(o.length===0)return u();let c=e.parsedUrl||new Proxy(hn,{get(t,n,i){return c=new r.URL(e.url,`http://localhost`),Reflect.get(c,n,c)}});function l(n){return s.length===0?n:E(()=>k(s,i=>i({request:e,response:n,serverContext:t,setResponse(e){n=e},fetchAPI:r})),()=>n)}function u(){return i?l(i):E(()=>n(e,t),l)}return E(()=>k(o,(a,o)=>a({request:e,setRequest(t){e=t},serverContext:t,fetchAPI:r,url:c,requestHandler:n,setRequestHandler(e){n=e},endResponse(e){i=e,e&&o()}})),u)}:a;if(c?.request){let e=p;p=(t,n)=>P({request:t}).asyncFn(c.request,e)(t,n)}function m(e,...t){let n=t.length>1?Zt(...t):t[0]||{};n.waitUntil||=f;let a=Rt(e,r,void 0,i);return p(a,n)}function h(e,t,...n){let a=t.raw||t,o=n.length>1?Zt(...n):n[0]||{};o.waitUntil||=f;let s=Rt(e,r,a,i);return p(s,o)}function g(e,t,...i){let a={req:e,res:t,waitUntil:f};return M(D().then(()=>h(e,t,a,...i)).catch(e=>Qt(e,r.Response)).then(r=>Jt(r,t,e,n)).catch(e=>console.error(`Unexpected error while handling request: ${e.message||e}`)))}function _(e,t,...n){let a={res:e,req:t,waitUntil:f},o=n.filter(e=>e!=null),s=o.length>0?Zt(a,...n):a,c=i?cn():new AbortController,l=e.end.bind(e),u=!1;e.end=function(e){return u=!0,l(e)};let d=e.onAborted.bind(e);d(function(){c.abort()}),e.onAborted=function(e){c.signal.addEventListener(`abort`,e,{once:!0})};let m=un({req:t,res:e,fetchAPI:r,controller:c});return E(()=>E(()=>p(m,s),e=>e,e=>Qt(e,r.Response)),t=>{if(!c.signal.aborted&&!u)return E(()=>fn(e,t,c,r),e=>e,e=>{console.error(`Unexpected error while handling request: ${e.message||e}`)})})}function v(e,...t){if(!e.respondWith||!e.request)throw TypeError(`Expected FetchEvent, got ${e}`);let n=t.filter(e=>e!=null),r=n.length>0?Zt({},e,...n):$t(e),i=p(e.request,r);e.respondWith(i)}function y(e,...t){let n=t.filter(e=>e!=null),r=n.length>1?Zt({},...n):$t(n[0],n[0]==null||n[0].waitUntil==null?f:void 0);return p(e,r)}let b=(e,...t)=>{if(typeof e==`string`||`href`in e){let[n,...i]=t;if(Xt(n)){let t=new r.Request(e,n),a=y(t,...i),o=n.signal;return o?en(a,o):a}let a=new r.Request(e);return y(a,...t)}let n=y(e,...t);return en(n,e.signal)},x=(e,...t)=>{let[n,...r]=t;if(Bt(e)){if(!Vt(n))throw TypeError(`Expected ServerResponse, got ${n}`);return g(e,n,...r)}if(ln(e))return _(e,n,...r);if(Vt(n))throw TypeError(`Got Node response without Node request`);return mn(e)?Ut(e)?v(e,...t):y(e.request,e,...t):b(e,...t)},S={handleRequest:y,fetch:b,handleNodeRequest:m,handleNodeRequestAndResponse:h,requestListener:g,handleEvent:v,handleUWS:_,handle:x,get disposableStack(){return d()},[I.asyncDispose](){return u&&!u.disposed?u.disposeAsync():D()},dispose(){return u&&!u.disposed?u.disposeAsync():D()},waitUntil:f},C=new Proxy(x,{has:(t,n)=>n in S||n in x||e&&n in e,get:(t,n)=>{if(globalThis.Deno||n===Symbol.asyncDispose||n===Symbol.dispose){let e=Reflect.get(S,n,S);if(e)return e}let r=S[n];if(r)return r.bind?r.bind(S):r;let i=x[n];if(i)return i.bind?i.bind(x):i;if(e){let t=e[n];if(t)return t.bind?function(...t){let r=e[n](...t);return r===e?C:r}:t}},apply(e,t,n){return x(...n)}});return C}function _n(e){let t=r(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function vn(e){return gn(e.fetch)}function yn(e){return new bn(e)}var bn=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendRequest(e){let t=new URL(e.url),n=new Headers(e.headers),r=new URL(this.baseUrl);if(r.pathname=t.pathname,r.search=t.search,t.pathname.startsWith(`/_agent/`))throw Error(`The pathname "/_agent/" is reserved for agent-specific requests.`);return this.fetch(r,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},xn=`vercel.ai.error`,Sn=Symbol.for(xn),Cn,wn=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Cn]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,xn)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Cn=Sn;var H=wn,Tn=`AI_APICallError`,En=`vercel.ai.error.${Tn}`,Dn=Symbol.for(En),On,U=class extends H{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:Tn,message:e,cause:o}),this[On]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return H.hasMarker(e,En)}};On=Dn;var kn=`AI_EmptyResponseBodyError`,An=`vercel.ai.error.${kn}`,jn=Symbol.for(An),Mn,Nn=class extends H{constructor({message:e=`Empty response body`}={}){super({name:kn,message:e}),this[Mn]=!0}static isInstance(e){return H.hasMarker(e,An)}};Mn=jn;function Pn(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Fn=`AI_InvalidArgumentError`,In=`vercel.ai.error.${Fn}`,Ln=Symbol.for(In),Rn,zn=class extends H{constructor({message:e,cause:t,argument:n}){super({name:Fn,message:e,cause:t}),this[Rn]=!0,this.argument=n}static isInstance(e){return H.hasMarker(e,In)}};Rn=Ln;var Bn=`AI_InvalidPromptError`,Vn=`vercel.ai.error.${Bn}`,Hn=Symbol.for(Vn),Un,Wn=class extends H{constructor({prompt:e,message:t,cause:n}){super({name:Bn,message:`Invalid prompt: ${t}`,cause:n}),this[Un]=!0,this.prompt=e}static isInstance(e){return H.hasMarker(e,Vn)}};Un=Hn;var Gn=`AI_InvalidResponseDataError`,Kn=`vercel.ai.error.${Gn}`,qn=Symbol.for(Kn),Jn,Yn=class extends H{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Gn,message:t}),this[Jn]=!0,this.data=e}static isInstance(e){return H.hasMarker(e,Kn)}};Jn=qn;var Xn=`AI_JSONParseError`,Zn=`vercel.ai.error.${Xn}`,Qn=Symbol.for(Zn),$n,er=class extends H{constructor({text:e,cause:t}){super({name:Xn,message:`JSON parsing failed: Text: ${e}.
9
- Error message: ${Pn(t)}`,cause:t}),this[$n]=!0,this.text=e}static isInstance(e){return H.hasMarker(e,Zn)}};$n=Qn;var tr=`AI_LoadAPIKeyError`,nr=`vercel.ai.error.${tr}`,rr=Symbol.for(nr),ir,ar=class extends H{constructor({message:e}){super({name:tr,message:e}),this[ir]=!0}static isInstance(e){return H.hasMarker(e,nr)}};ir=rr;var or=`AI_LoadSettingError`,sr=`vercel.ai.error.${or}`,cr=Symbol.for(sr),lr;lr=cr;var ur=`AI_NoContentGeneratedError`,dr=`vercel.ai.error.${ur}`,fr=Symbol.for(dr),pr;pr=fr;var mr=`AI_NoSuchModelError`,hr=`vercel.ai.error.${mr}`,gr=Symbol.for(hr),_r,vr=class extends H{constructor({errorName:e=mr,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[_r]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return H.hasMarker(e,hr)}};_r=gr;var yr=`AI_TooManyEmbeddingValuesForCallError`,br=`vercel.ai.error.${yr}`,xr=Symbol.for(br),Sr,Cr=class extends H{constructor(e){super({name:yr,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Sr]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return H.hasMarker(e,br)}};Sr=xr;var wr=`AI_TypeValidationError`,Tr=`vercel.ai.error.${wr}`,Er=Symbol.for(Tr),Dr,Or=class e extends H{constructor({value:e,cause:t}){super({name:wr,message:`Type validation failed: Value: ${JSON.stringify(e)}.
10
- Error message: ${Pn(t)}`,cause:t}),this[Dr]=!0,this.value=e}static isInstance(e){return H.hasMarker(e,Tr)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Dr=Er;var kr=Or,Ar=`AI_UnsupportedFunctionalityError`,jr=`vercel.ai.error.${Ar}`,Mr=Symbol.for(jr),Nr,W=class extends H{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Ar,message:t}),this[Nr]=!0,this.functionality=e}static isInstance(e){return H.hasMarker(e,jr)}};Nr=Mr;var Pr=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Fr(e){}function Ir(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Fr,onError:n=Fr,onRetry:r=Fr,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Lr(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
11
- `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Pr(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Pr(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
12
- `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Lr(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
13
- `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
14
- `&&r++}}return[t,n]}var Rr=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Ir({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};function G(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}async function zr(e,t){if(e==null)return Promise.resolve();let n=t?.abortSignal;return new Promise((t,r)=>{if(n?.aborted){r(Br());return}let i=setTimeout(()=>{a(),t()},e),a=()=>{clearTimeout(i),n?.removeEventListener(`abort`,o)},o=()=>{a(),r(Br())};n?.addEventListener(`abort`,o)})}function Br(){return new DOMException(`Delay was aborted`,`AbortError`)}function Vr(e){return Object.fromEntries([...e.headers])}var Hr=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new zn({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},K=Hr();function Ur(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}function Wr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Gr=[`fetch failed`,`failed to fetch`];function Kr({error:e,url:t,requestBodyValues:n}){if(Wr(e))return e;if(e instanceof TypeError&&Gr.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new U({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function qr(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}var Jr=()=>globalThis.fetch,Yr=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:i,fetch:a=Jr()})=>{try{let o=await a(e,{method:`GET`,headers:qr(t),signal:i}),s=Vr(o);if(!o.ok){let t;try{t=await r({response:o,url:e,requestBodyValues:{}})}catch(t){throw Wr(t)||U.isInstance(t)?t:new U({message:`Failed to process error response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw t.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(t){throw t instanceof Error&&(Wr(t)||U.isInstance(t))?t:new U({message:`Failed to process successful response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(t){throw Kr({error:t,url:e,requestBodyValues:{}})}};function Xr({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([e,t])=>{let n=e.toLowerCase();return n===`*`||n===`*/*`?{mediaTypePrefix:``,regexes:t}:{mediaTypePrefix:n.replace(/\*/,``),regexes:t}}).filter(({mediaTypePrefix:t})=>e.startsWith(t)).flatMap(({regexes:e})=>e).some(e=>e.test(t))}function Zr({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new ar({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new ar({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 ar({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new ar({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Qr({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function $r(e){var t;let[n,r=``]=e.toLowerCase().split(`/`);return(t={mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[r])??r}var ei=/"__proto__"\s*:/,ti=/"constructor"\s*:/;function ni(e){let t=JSON.parse(e);return typeof t!=`object`||!t||ei.test(e)===!1&&ti.test(e)===!1?t:ri(t)}function ri(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function ii(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ni(e)}finally{Error.stackTraceLimit=t}}var ai=Symbol.for(`vercel.ai.validator`);function oi(e){return{[ai]:!0,validate:e}}function si(e){return typeof e==`object`&&!!e&&ai in e&&e[ai]===!0&&`validate`in e}function ci(e){return si(e)?e:li(e)}function li(e){return oi(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new kr({value:t,cause:n.issues})}})}async function ui({value:e,schema:t}){let n=await di({value:e,schema:t});if(!n.success)throw kr.wrap({value:e,cause:n.error});return n.value}async function di({value:e,schema:t}){let n=ci(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:kr.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:kr.wrap({value:e,cause:t}),rawValue:e}}}async function fi({text:e,schema:t}){try{let n=ii(e);return t==null?n:ui({value:n,schema:t})}catch(t){throw er.isInstance(t)||kr.isInstance(t)?t:new er({text:e,cause:t})}}async function pi({text:e,schema:t}){try{let n=ii(e);return t==null?{success:!0,value:n,rawValue:n}:await di({value:n,schema:t})}catch(t){return{success:!1,error:er.isInstance(t)?t:new er({text:e,cause:t}),rawValue:void 0}}}function mi(e){try{return ii(e),!0}catch{return!1}}function hi({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Rr).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await pi({text:e,schema:t}))}}))}async function q({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await di({value:t[e],schema:n});if(!r.success)throw new zn({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var gi=()=>globalThis.fetch,J=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>vi({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),_i=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>vi({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),vi=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=gi()})=>{try{let s=await o(e,{method:`POST`,headers:qr(t),body:n.content,signal:a}),c=Vr(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw Wr(t)||U.isInstance(t)?t:new U({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Wr(t)||U.isInstance(t))?t:new U({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Kr({error:t,url:e,requestBodyValues:n.values})}};function yi(e){return e}function bi({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>yi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function xi({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>yi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Si(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Ci=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=Vr(r);if(o.trim()===``)return{responseHeaders:s,value:new U({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await fi({text:o,schema:e});return{responseHeaders:s,value:new U({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new U({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},wi=e=>async({response:t})=>{let n=Vr(t);if(t.body==null)throw new Nn({});return{responseHeaders:n,value:hi({stream:t.body,schema:e})}},Y=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await pi({text:i,schema:e}),o=Vr(t);if(!a.success)throw new U({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},Ti=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=Vr(e);if(!e.body)throw new U({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new U({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},Ei=(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(`/`)},Di=Symbol(`Let zodToJsonSchema decide on which parser to use`),Oi={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`},ki=e=>typeof e==`string`?{...Oi,name:e}:{...Oi,...e};function Ai(){return{}}function ji(e,t){var n,r,i;let a={type:`array`};return(n=e.type)?._def&&(i=(r=e.type)?._def)?.typeName!==y.ZodAny&&(a.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(a.minItems=e.minLength.value),e.maxLength&&(a.maxItems=e.maxLength.value),e.exactLength&&(a.minItems=e.exactLength.value,a.maxItems=e.exactLength.value),a}function Mi(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let 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}function Ni(){return{type:`boolean`}}function Pi(e,t){return Z(e.type._def,t)}var Fi=(e,t)=>Z(e.innerType._def,t);function Ii(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Ii(e,t,n))};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 Li(e)}}var Li=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value;break}return t};function Ri(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}function zi(e,t){return t.effectStrategy===`input`?Z(e.schema._def,t):Ai()}function Bi(e){return{type:`string`,enum:Array.from(e.values)}}var Vi=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Hi(e,t){let n=[Z(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(Vi(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function Ui(e){let 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}}var Wi=void 0,Gi={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:()=>(Wi===void 0&&(Wi=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Wi),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 Ki(e,t){let n={type:`string`};if(e.checks)for(let 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`:Xi(n,`email`,r.message,t);break;case`format:idn-email`:Xi(n,`idn-email`,r.message,t);break;case`pattern:zod`:X(n,Gi.email,r.message,t);break}break;case`url`:Xi(n,`uri`,r.message,t);break;case`uuid`:Xi(n,`uuid`,r.message,t);break;case`regex`:X(n,r.regex,r.message,t);break;case`cuid`:X(n,Gi.cuid,r.message,t);break;case`cuid2`:X(n,Gi.cuid2,r.message,t);break;case`startsWith`:X(n,RegExp(`^${qi(r.value,t)}`),r.message,t);break;case`endsWith`:X(n,RegExp(`${qi(r.value,t)}$`),r.message,t);break;case`datetime`:Xi(n,`date-time`,r.message,t);break;case`date`:Xi(n,`date`,r.message,t);break;case`time`:Xi(n,`time`,r.message,t);break;case`duration`:Xi(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`:X(n,RegExp(qi(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Xi(n,`ipv4`,r.message,t),r.version!==`v4`&&Xi(n,`ipv6`,r.message,t);break;case`base64url`:X(n,Gi.base64url,r.message,t);break;case`jwt`:X(n,Gi.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&X(n,Gi.ipv4Cidr,r.message,t),r.version!==`v4`&&X(n,Gi.ipv6Cidr,r.message,t);break;case`emoji`:X(n,Gi.emoji(),r.message,t);break;case`ulid`:X(n,Gi.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Xi(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:X(n,Gi.base64,r.message,t);break}break;case`nanoid`:X(n,Gi.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function qi(e,t){return t.patternStrategy===`escape`?Yi(e):e}var Ji=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Yi(e){let t=``;for(let n=0;n<e.length;n++)Ji.has(e[n])||(t+=`\\`),t+=e[n];return t}function Xi(e,t,n,r){var i;e.format||(i=e.anyOf)?.some(e=>e.format)?(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}function X(e,t,n,r){var i;e.pattern||(i=e.allOf)?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Zi(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Zi(t,r)}function Zi(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},i=r.i?e.source.toLowerCase():e.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&(n=i[e+2])?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
15
- ]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
16
- ]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r
17
- `:`[${i[e]}\r
18
- ]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}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 a}function Qi(e,t){var n,r,i,a,o,s;let c={type:`object`,additionalProperties:(n=Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]}))??t.allowedAdditionalProperties};if((r=e.keyType)?._def.typeName===y.ZodString&&(i=e.keyType._def.checks)?.length){let{type:n,...r}=Ki(e.keyType._def,t);return{...c,propertyNames:r}}else if((a=e.keyType)?._def.typeName===y.ZodEnum)return{...c,propertyNames:{enum:e.keyType._def.values}};else if((o=e.keyType)?._def.typeName===y.ZodBranded&&e.keyType._def.type._def.typeName===y.ZodString&&(s=e.keyType._def.type._def.checks)?.length){let{type:n,...r}=Pi(e.keyType._def,t);return{...c,propertyNames:r}}return c}function $i(e,t){if(t.mapStrategy===`record`)return Qi(e,t);let n=Z(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Ai(),r=Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Ai();return{type:`array`,maxItems:125,items:{type:`array`,items:[n,r],minItems:2,maxItems:2}}}function ea(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`),r=n.map(e=>t[e]),i=Array.from(new Set(r.map(e=>typeof e)));return{type:i.length===1?i[0]===`string`?`string`:`number`:[`string`,`number`],enum:r}}function ta(){return{not:Ai()}}function na(){return{type:`null`}}var ra={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ia(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ra&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ra[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];case`symbol`:case`undefined`:case`function`:default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return aa(e,t)}var aa=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function oa(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ra[e.innerType._def.typeName],`null`]};let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function sa(e){let t={type:`number`};if(!e.checks)return t;for(let 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}function ca(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=ua(a),s=Z(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});if(s===void 0)continue;n.properties[e]=s,o||r.push(e)}r.length&&(n.required=r);let a=la(e,t);return a!==void 0&&(n.additionalProperties=a),n}function la(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Z(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}}function ua(e){try{return e.isOptional()}catch{return!0}}var da=(e,t)=>{var n;if(t.currentPath.toString()===(n=t.propertyPath)?.toString())return Z(e.innerType._def,t);let r=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return r?{anyOf:[{not:Ai()},r]}:Ai()},fa=(e,t)=>{if(t.pipeStrategy===`input`)return Z(e.in._def,t);if(t.pipeStrategy===`output`)return Z(e.out._def,t);let n=Z(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),r=Z(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]});return{allOf:[n,r].filter(e=>e!==void 0)}};function pa(e,t){return Z(e.type._def,t)}function ma(e,t){let n=Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]}),r={type:`array`,uniqueItems:!0,items:n};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function ha(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function ga(){return{not:Ai()}}function _a(){return Ai()}var va=(e,t)=>Z(e.innerType._def,t),ya=(e,t,n)=>{switch(t){case y.ZodString:return Ki(e,n);case y.ZodNumber:return sa(e);case y.ZodObject:return ca(e,n);case y.ZodBigInt:return Mi(e);case y.ZodBoolean:return Ni();case y.ZodDate:return Ii(e,n);case y.ZodUndefined:return ga();case y.ZodNull:return na();case y.ZodArray:return ji(e,n);case y.ZodUnion:case y.ZodDiscriminatedUnion:return ia(e,n);case y.ZodIntersection:return Hi(e,n);case y.ZodTuple:return ha(e,n);case y.ZodRecord:return Qi(e,n);case y.ZodLiteral:return Ui(e);case y.ZodEnum:return Bi(e);case y.ZodNativeEnum:return ea(e);case y.ZodNullable:return oa(e,n);case y.ZodOptional:return da(e,n);case y.ZodMap:return $i(e,n);case y.ZodSet:return ma(e,n);case y.ZodLazy:return()=>e.getter()._def;case y.ZodPromise:return pa(e,n);case y.ZodNaN:case y.ZodNever:return ta();case y.ZodEffects:return zi(e,n);case y.ZodAny:return Ai();case y.ZodUnknown:return _a();case y.ZodDefault:return Ri(e,n);case y.ZodBranded:return Pi(e,n);case y.ZodReadonly:return va(e,n);case y.ZodCatch:return Fi(e,n);case y.ZodPipeline:return fa(e,n);case y.ZodFunction:case y.ZodVoid:case y.ZodSymbol:return;default:return(e=>void 0)(t)}};function Z(e,t,n=!1){var r;let i=t.seen.get(e);if(t.override){let a=(r=t.override)?.call(t,e,t,i,n);if(a!==Di)return a}if(i&&!n){let e=ba(i,t);if(e!==void 0)return e}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let o=ya(e,e.typeName,t),s=typeof o==`function`?Z(o(),t):o;if(s&&xa(e,t,s),t.postProcess){let n=t.postProcess(s,e,t);return a.jsonSchema=s,n}return a.jsonSchema=s,s}var ba=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Ei(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Ai()):t.$refStrategy===`seen`?Ai():void 0}},xa=(e,t,n)=>(e.description&&(n.description=e.description),n),Sa=e=>{let t=ki(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Ca=(e,t)=>{var n;let r=Sa(t),i=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>{var i;return{...e,[t]:(i=Z(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0))??Ai()}},{}):void 0,a=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,o=(n=Z(e._def,a===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,a]},!1))??Ai(),s=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;s!==void 0&&(o.title=s);let c=a===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy===`relative`?[]:r.basePath,r.definitionPath,a].join(`/`),[r.definitionPath]:{...i,[a]:o}};return c.$schema=`http://json-schema.org/draft-07/schema#`,c},wa=Ca;function Ta(e,t){var n;let r=(n=t?.useReferences)??!1;return Aa(wa(e,{$refStrategy:r?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Ea(e,t){var n;let r=(n=t?.useReferences)??!1,i=g.toJSONSchema(e,{target:`draft-7`,io:`output`,reused:r?`ref`:`inline`});return Aa(i,{validate:async t=>{let n=await g.safeParseAsync(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Da(e){return`_zod`in e}function Oa(e,t){return Da(e)?Ea(e,t):Ta(e,t)}var ka=Symbol.for(`vercel.ai.schema`);function Aa(e,{validate:t}={}){return{[ka]:!0,_type:void 0,[ai]:!0,jsonSchema:e,validate:t}}function ja(e){return typeof e==`object`&&!!e&&ka in e&&e[ka]===!0&&`jsonSchema`in e&&`validate`in e}function Ma(e){return e==null?Aa({properties:{},additionalProperties:!1}):ja(e)?e:Oa(e)}var{btoa:Na,atob:Pa}=globalThis;function Fa(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=Pa(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function Ia(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Na(t)}function La(e){return e instanceof Uint8Array?Ia(e):e}function Ra(e){return e?.replace(/\/$/,``)}function za(e){return e!=null&&typeof e[Symbol.asyncIterator]==`function`}async function*Ba({execute:e,input:t,options:n}){let r=e(t,n);if(za(r)){let e;for await(let t of r)e=t,yield{type:`preliminary`,output:t};yield{type:`final`,output:e}}else yield{type:`final`,output:await r}}var Va=`vercel.ai.gateway.error`,Ha=Symbol.for(Va),Ua,Wa,Ga=class e extends (Wa=Error,Ua=Ha,Wa){constructor({message:e,statusCode:t=500,cause:n}){super(e),this[Ua]=!0,this.statusCode=t,this.cause=n}static isInstance(t){return e.hasMarker(t)}static hasMarker(e){return typeof e==`object`&&!!e&&Ha in e&&e[Ha]===!0}},Ka=`GatewayAuthenticationError`,qa=`vercel.ai.gateway.error.${Ka}`,Ja=Symbol.for(qa),Ya,Xa,Za=class e extends (Xa=Ga,Ya=Ja,Xa){constructor({message:e=`Authentication failed`,statusCode:t=401,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ya]=!0,this.name=Ka,this.type=`authentication_error`}static isInstance(e){return Ga.hasMarker(e)&&Ja in e}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r=`Authentication failed`,statusCode:i=401,cause:a}){let o;return o=t?`AI Gateway authentication failed: Invalid API key provided.
19
-
20
- The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?`AI Gateway authentication failed: Invalid OIDC token provided.
21
-
22
- The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
23
- - make sure your Vercel project settings have OIDC enabled
24
- - if running locally with 'vercel dev', the token is automatically obtained and refreshed
25
- - if running locally with your own dev server, run 'vercel env pull' to fetch the token
26
- - in production/preview, the token is automatically obtained and refreshed
27
-
28
- Alternative: Provide an API key via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:`AI Gateway authentication failed: No authentication provided.
29
-
30
- Provide either an API key or OIDC token.
31
-
32
- API key instructions:
33
-
34
- The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
35
-
36
- OIDC token instructions:
37
-
38
- The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
39
- - make sure your Vercel project settings have OIDC enabled
40
- - if running locally with 'vercel dev', the token is automatically obtained and refreshed
41
- - if running locally with your own dev server, run 'vercel env pull' to fetch the token
42
- - in production/preview, the token is automatically obtained and refreshed`,new e({message:o,statusCode:i,cause:a})}},Qa=`GatewayInvalidRequestError`,$a=`vercel.ai.gateway.error.${Qa}`,eo=Symbol.for($a),to,no,ro=class extends (no=Ga,to=eo,no){constructor({message:e=`Invalid request`,statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[to]=!0,this.name=Qa,this.type=`invalid_request_error`}static isInstance(e){return Ga.hasMarker(e)&&eo in e}},io=`GatewayRateLimitError`,ao=`vercel.ai.gateway.error.${io}`,oo=Symbol.for(ao),so,co,lo=class extends (co=Ga,so=oo,co){constructor({message:e=`Rate limit exceeded`,statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[so]=!0,this.name=io,this.type=`rate_limit_exceeded`}static isInstance(e){return Ga.hasMarker(e)&&oo in e}},uo=`GatewayModelNotFoundError`,fo=`vercel.ai.gateway.error.${uo}`,po=Symbol.for(fo),mo=v.object({modelId:v.string()}),ho,go,_o=class extends (go=Ga,ho=po,go){constructor({message:e=`Model not found`,statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[ho]=!0,this.name=uo,this.type=`model_not_found`,this.modelId=n}static isInstance(e){return Ga.hasMarker(e)&&po in e}},vo=`GatewayInternalServerError`,yo=`vercel.ai.gateway.error.${vo}`,bo=Symbol.for(yo),xo,So,Co=class extends (So=Ga,xo=bo,So){constructor({message:e=`Internal server error`,statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[xo]=!0,this.name=vo,this.type=`internal_server_error`}static isInstance(e){return Ga.hasMarker(e)&&bo in e}},wo=`GatewayResponseError`,To=`vercel.ai.gateway.error.${wo}`,Eo=Symbol.for(To),Do,Oo,ko=class extends (Oo=Ga,Do=Eo,Oo){constructor({message:e=`Invalid response from Gateway`,statusCode:t=502,response:n,validationError:r,cause:i}={}){super({message:e,statusCode:t,cause:i}),this[Do]=!0,this.name=wo,this.type=`response_error`,this.response=n,this.validationError=r}static isInstance(e){return Ga.hasMarker(e)&&Eo in e}};function Ao({response:e,statusCode:t,defaultMessage:n=`Gateway request failed`,cause:r,authMethod:i}){let a=jo.safeParse(e);if(!a.success)return new ko({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r});let o=a.data,s=o.error.type,c=o.error.message;switch(s){case`authentication_error`:return Za.createContextualError({apiKeyProvided:i===`api-key`,oidcTokenProvided:i===`oidc`,statusCode:t,cause:r});case`invalid_request_error`:return new ro({message:c,statusCode:t,cause:r});case`rate_limit_exceeded`:return new lo({message:c,statusCode:t,cause:r});case`model_not_found`:{let e=mo.safeParse(o.error.param);return new _o({message:c,statusCode:t,modelId:e.success?e.data.modelId:void 0,cause:r})}case`internal_server_error`:return new Co({message:c,statusCode:t,cause:r});default:return new Co({message:c,statusCode:t,cause:r})}}var jo=v.object({error:v.object({message:v.string(),type:v.string().nullish(),param:v.unknown().nullish(),code:v.union([v.string(),v.number()]).nullish()})});function Mo(e,t){var n;return Ga.isInstance(e)?e:U.isInstance(e)?Ao({response:No(e),statusCode:(n=e.statusCode)??500,defaultMessage:`Gateway request failed`,cause:e,authMethod:t}):Ao({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:`Unknown Gateway error`,cause:e,authMethod:t})}function No(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Po=`ai-gateway-auth-method`;function Fo(e){let t=Io.safeParse(e[Po]);return t.success?t.data:void 0}var Io=v.union([v.literal(`api-key`),v.literal(`oidc`)]),Lo=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Yr({url:`${this.config.baseURL}/config`,headers:await Si(this.config.headers()),successfulResponseHandler:Y(Vo),failedResponseHandler:Ci({errorSchema:v.any(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw Mo(e)}}},Ro=v.object({specificationVersion:v.literal(`v2`),provider:v.string(),modelId:v.string()}),zo=v.object({input:v.string(),output:v.string(),input_cache_read:v.string().nullish(),input_cache_write:v.string().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})),Bo=v.object({id:v.string(),name:v.string(),description:v.string().nullish(),pricing:zo.nullish(),specification:Ro,modelType:v.enum([`language`,`embedding`,`image`]).nullish()}),Vo=v.object({models:v.array(Bo)}),Ho=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await Si(this.config.headers());try{let{responseHeaders:a,value:o,rawValue:s}=await J({url:this.getUrl(),headers:G(i,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Si(this.config.o11yHeaders)),body:t,successfulResponseHandler:Y(v.any()),failedResponseHandler:Ci({errorSchema:v.any(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...o,request:{body:t},response:{headers:a,body:s},warnings:n}}catch(e){throw Mo(e,Fo(i))}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await Si(this.config.headers());try{let{value:a,responseHeaders:o}=await J({url:this.getUrl(),headers:G(i,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Si(this.config.o11yHeaders)),body:t,successfulResponseHandler:wi(v.any()),failedResponseHandler:Ci({errorSchema:v.any(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(e){n.length>0&&e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(t.success){let r=t.value;if(r.type===`raw`&&!e.includeRawChunks)return;r.type===`response-metadata`&&r.timestamp&&typeof r.timestamp==`string`&&(r.timestamp=new Date(r.timestamp)),n.enqueue(r)}else n.error(t.error)}})),request:{body:t},response:{headers:o}}}catch(e){throw Mo(e,Fo(i))}}isFilePart(e){return e&&typeof e==`object`&&`type`in e&&e.type===`file`}maybeEncodeFileParts(e){for(let t of e.prompt)for(let e of t.content)if(this.isFilePart(e)){let t=e;if(t.data instanceof Uint8Array){let e=Uint8Array.from(t.data),n=Buffer.from(e).toString(`base64`);t.data=new URL(`data:${t.mediaType||`application/octet-stream`};base64,${n}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Uo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;let a=await Si(this.config.headers());try{let{responseHeaders:o,value:s,rawValue:c}=await J({url:this.getUrl(),headers:G(a,t??{},this.getModelConfigHeaders(),await Si(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Y(Wo),failedResponseHandler:Ci({errorSchema:v.any(),errorToMessage:e=>e}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(i=s.usage)??void 0,providerMetadata:s.providerMetadata,response:{headers:o,body:c}}}catch(e){throw Mo(e,Fo(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},Wo=v.object({embeddings:v.array(v.array(v.number())),usage:v.object({tokens:v.number()}).nullish(),providerMetadata:v.record(v.string(),v.record(v.string(),v.unknown())).optional()});async function Go(){var e,t;let n=(t=(e=Jo().headers)?.[`x-vercel-oidc-token`])??process.env.VERCEL_OIDC_TOKEN;if(!n)throw new Za({message:`OIDC token not available`,statusCode:401});return n}async function Ko(){var e;return(e=Jo().headers)?.[`x-vercel-id`]}var qo=Symbol.for(`@vercel/request-context`);function Jo(){var e,t,n;let r=globalThis;return(n=(t=(e=r[qo])?.get)?.call(e))??{}}var Yo=`0.0.1`;function Xo(e={}){var t,n;let r=null,i=null,a=(t=e.metadataCacheRefreshMillis)??1e3*60*5,o=0,s=(n=Ra(e.baseURL))??`https://ai-gateway.vercel.sh/v1/ai`,c=async()=>{let t=await Qo(e);if(t)return{Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":Yo,[Po]:t.authMethod,...e.headers};throw Za.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{let e=Qr({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),t=Qr({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),n=Qr({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let r=await Ko();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...n&&{"ai-o11y-region":n},...r&&{"ai-o11y-request-id":r}}}},u=t=>new Ho(t,{provider:`gateway`,baseURL:s,headers:c,fetch:e.fetch,o11yHeaders:l()}),d=async()=>{var t,n,l;let u=(l=(n=(t=e._internal)?.currentDate)?.call(t).getTime())??Date.now();return(!r||u-o>a)&&(o=u,r=new Lo({baseURL:s,headers:c,fetch:e.fetch}).getAvailableModels().then(e=>(i=e,e)).catch(async e=>{throw Mo(e,Fo(await c()))})),i?Promise.resolve(i):r},f=function(e){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return u(e)};return f.getAvailableModels=d,f.imageModel=e=>{throw new vr({modelId:e,modelType:`imageModel`})},f.languageModel=u,f.textEmbeddingModel=t=>new Uo(t,{provider:`gateway`,baseURL:s,headers:c,fetch:e.fetch,o11yHeaders:l()}),f}var Zo=Xo();async function Qo(e){let t=Qr({settingValue:e.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(t)return{token:t,authMethod:`api-key`};try{let e=await Go();return{token:e,authMethod:`oidc`}}catch{return null}}s();var $o=Object.defineProperty,es=(e,t)=>{for(var n in t)$o(e,n,{get:t[n],enumerable:!0})},ts=`AI_NoOutputSpecifiedError`,ns=`vercel.ai.error.${ts}`,rs=Symbol.for(ns),os,ss=class extends H{constructor({message:e=`No output specified.`}={}){super({name:ts,message:e}),this[os]=!0}static isInstance(e){return H.hasMarker(e,ns)}};os=rs;function cs(e){let t=`AI SDK Warning:`;switch(e.type){case`unsupported-setting`:{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case`unsupported-tool`:{let n=`name`in e.tool?e.tool.name:`unknown tool`,r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case`other`:return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var ls=`AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.`,us=!1,ds=e=>{if(e.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t==`function`){t(e);return}us||(us=!0,console.info(ls));for(let t of e)console.warn(cs(t))}},fs=`AI_InvalidArgumentError`,ps=`vercel.ai.error.${fs}`,ms=Symbol.for(ps),hs,gs=class extends H{constructor({parameter:e,value:t,message:n}){super({name:fs,message:`Invalid argument for parameter ${e}: ${n}`}),this[hs]=!0,this.parameter=e,this.value=t}static isInstance(e){return H.hasMarker(e,ps)}};hs=ms;var _s=`AI_InvalidStreamPartError`,vs=`vercel.ai.error.${_s}`,ys=Symbol.for(vs),bs;bs=ys;var xs=`AI_InvalidToolInputError`,Ss=`vercel.ai.error.${xs}`,Cs=Symbol.for(Ss),ws,Ts=class extends H{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${Pn(n)}`}){super({name:xs,message:r,cause:n}),this[ws]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return H.hasMarker(e,Ss)}};ws=Cs;var Es=`AI_MCPClientError`,Ds=`vercel.ai.error.${Es}`,Os=Symbol.for(Ds),ks;ks=Os;var As=`AI_NoImageGeneratedError`,js=`vercel.ai.error.${As}`,Ms=Symbol.for(js),Ns;Ns=Ms;var Ps=`AI_NoObjectGeneratedError`,Fs=`vercel.ai.error.${Ps}`,Is=Symbol.for(Fs),Ls,Rs=class extends H{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:Ps,message:e,cause:t}),this[Ls]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return H.hasMarker(e,Fs)}};Ls=Is;var zs=`AI_NoOutputGeneratedError`,Bs=`vercel.ai.error.${zs}`,Vs=Symbol.for(Bs),Hs,Us=class extends H{constructor({message:e=`No output generated.`,cause:t}={}){super({name:zs,message:e,cause:t}),this[Hs]=!0}static isInstance(e){return H.hasMarker(e,Bs)}};Hs=Vs;var Ws=`AI_NoSuchToolError`,Gs=`vercel.ai.error.${Ws}`,Ks=Symbol.for(Gs),qs,Js=class extends H{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?`No tools are available.`:`Available tools: ${t.join(`, `)}.`}`}){super({name:Ws,message:n}),this[qs]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return H.hasMarker(e,Gs)}};qs=Ks;var Ys=`AI_ToolCallRepairError`,Xs=`vercel.ai.error.${Ys}`,Zs=Symbol.for(Xs),Qs,$s=class extends H{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Pn(e)}`}){super({name:Ys,message:n,cause:e}),this[Qs]=!0,this.originalError=t}static isInstance(e){return H.hasMarker(e,Xs)}};Qs=Zs;var ec=class extends H{constructor(e){super({name:`AI_UnsupportedModelVersionError`,message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},tc=`AI_InvalidDataContentError`,nc=`vercel.ai.error.${tc}`,rc=Symbol.for(nc),ic;ic=rc;var ac=`AI_InvalidMessageRoleError`,oc=`vercel.ai.error.${ac}`,sc=Symbol.for(oc),cc,lc=class extends H{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:ac,message:t}),this[cc]=!0,this.role=e}static isInstance(e){return H.hasMarker(e,oc)}};cc=sc;var uc=`AI_MessageConversionError`,dc=`vercel.ai.error.${uc}`,fc=Symbol.for(dc),pc;pc=fc;var mc=`AI_DownloadError`,hc=`vercel.ai.error.${mc}`,gc=Symbol.for(hc),_c,vc=class extends H{constructor({url:e,statusCode:t,statusText:n,cause:r,message:i=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:mc,message:i,cause:r}),this[_c]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return H.hasMarker(e,hc)}};_c=gc;var yc=`AI_RetryError`,bc=`vercel.ai.error.${yc}`,xc=Symbol.for(bc),Sc,Cc=class extends H{constructor({message:e,reason:t,errors:n}){super({name:yc,message:e}),this[Sc]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return H.hasMarker(e,bc)}};Sc=xc;function wc(e){if(typeof e!=`string`){if(e.specificationVersion!==`v2`)throw new ec({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Tc().languageModel(e)}function Tc(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)??Zo}var Ec=[{mediaType:`image/gif`,bytesPrefix:[71,73,70],base64Prefix:`R0lG`},{mediaType:`image/png`,bytesPrefix:[137,80,78,71],base64Prefix:`iVBORw`},{mediaType:`image/jpeg`,bytesPrefix:[255,216],base64Prefix:`/9j/`},{mediaType:`image/webp`,bytesPrefix:[82,73,70,70],base64Prefix:`UklGRg`},{mediaType:`image/bmp`,bytesPrefix:[66,77],base64Prefix:`Qk`},{mediaType:`image/tiff`,bytesPrefix:[73,73,42,0],base64Prefix:`SUkqAA`},{mediaType:`image/tiff`,bytesPrefix:[77,77,0,42],base64Prefix:`TU0AKg`},{mediaType:`image/avif`,bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:`AAAAIGZ0eXBhdmlm`},{mediaType:`image/heic`,bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:`AAAAIGZ0eXBoZWlj`}],Dc=e=>{let t=typeof e==`string`?Fa(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Oc(e){let t=typeof e==`string`&&e.startsWith(`SUQz`)||typeof e!=`string`&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51;return t?Dc(e):e}function kc({data:e,signatures:t}){let n=Oc(e);for(let e of t)if(typeof n==`string`?n.startsWith(e.base64Prefix):n.length>=e.bytesPrefix.length&&e.bytesPrefix.every((e,t)=>n[t]===e))return e.mediaType}var Ac=async({url:e})=>{var t;let n=e.toString();try{let e=await fetch(n);if(!e.ok)throw new vc({url:n,statusCode:e.status,statusText:e.statusText});return{data:new Uint8Array(await e.arrayBuffer()),mediaType:(t=e.headers.get(`content-type`))??void 0}}catch(e){throw vc.isInstance(e)?e:new vc({url:n,cause:e})}},jc=(e=Ac)=>t=>Promise.all(t.map(async t=>t.isUrlSupportedByModel?null:e(t)));function Mc(e){try{let[t,n]=e.split(`,`);return{mediaType:t.split(`;`)[0].split(`:`)[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Nc=v.union([v.string(),v.instanceof(Uint8Array),v.instanceof(ArrayBuffer),v.custom(e=>{var t,n;return(n=(t=globalThis.Buffer)?.isBuffer(e))??!1},{message:`Must be a Buffer`})]);function Pc(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:`){let{mediaType:t,base64Content:n}=Mc(e.toString());if(t==null||n==null)throw new H({name:`InvalidDataContentError`,message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Fc(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Ia(new Uint8Array(e)):Ia(e)}async function Ic({prompt:e,supportedUrls:t,download:n=jc()}){let r=await Rc(e.messages,n,t);return[...e.system==null?[]:[{role:`system`,content:e.system}],...e.messages.map(e=>Lc({message:e,downloadedAssets:r}))]}function Lc({message:e,downloadedAssets:t}){let 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(e=>zc(e,t)).filter(e=>e.type!==`text`||e.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(e=>e.type!==`text`||e.text!==``).map(e=>{let t=e.providerOptions;switch(e.type){case`file`:{let{data:n,mediaType:r}=Pc(e.data);return{type:`file`,data:n,filename:e.filename,mediaType:r??e.mediaType,providerOptions:t}}case`reasoning`:return{type:`reasoning`,text:e.text,providerOptions:t};case`text`:return{type:`text`,text:e.text,providerOptions:t};case`tool-call`:return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:t};case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,providerOptions:t}}}),providerOptions:e.providerOptions};case`tool`:return{role:`tool`,content:e.content.map(e=>({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,providerOptions:e.providerOptions})),providerOptions:e.providerOptions};default:{let e=n;throw new lc({role:e})}}}async function Rc(e,t,n){let r=e.filter(e=>e.role===`user`).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>e.type===`image`||e.type===`file`).map(e=>{var t;let n=(t=e.mediaType)??(e.type===`image`?`image/*`:void 0),r=e.type===`image`?e.image:e.data;if(typeof r==`string`)try{r=new URL(r)}catch{}return{mediaType:n,data:r}}).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:e.mediaType!=null&&Xr({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:n})})),i=await t(r);return Object.fromEntries(i.filter(e=>e?.data!=null).map(({data:e,mediaType:t},n)=>[r[n].url.toString(),{data:e,mediaType:t}]))}function zc(e,t){var n;if(e.type===`text`)return{type:`text`,text:e.text,providerOptions:e.providerOptions};let r,i=e.type;switch(i){case`image`:r=e.image;break;case`file`:r=e.data;break;default:throw Error(`Unsupported part type: ${i}`)}let{data:a,mediaType:o}=Pc(r),s=o??e.mediaType,c=a;if(c instanceof URL){let e=t[c.toString()];e&&(c=e.data,s??=e.mediaType)}switch(i){case`image`:return(c instanceof Uint8Array||typeof c==`string`)&&(s=(n=kc({data:c,signatures:Ec}))??s),{type:`file`,mediaType:s??`image/*`,filename:void 0,data:c,providerOptions:e.providerOptions};case`file`:if(s==null)throw Error(`Media type is missing for file part`);return{type:`file`,mediaType:s,filename:e.filename,data:c,providerOptions:e.providerOptions}}}function Bc({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,seed:o,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new gs({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be an integer`});if(e<1)throw new gs({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be >= 1`})}if(t!=null&&typeof t!=`number`)throw new gs({parameter:`temperature`,value:t,message:`temperature must be a number`});if(n!=null&&typeof n!=`number`)throw new gs({parameter:`topP`,value:n,message:`topP must be a number`});if(r!=null&&typeof r!=`number`)throw new gs({parameter:`topK`,value:r,message:`topK must be a number`});if(i!=null&&typeof i!=`number`)throw new gs({parameter:`presencePenalty`,value:i,message:`presencePenalty must be a number`});if(a!=null&&typeof a!=`number`)throw new gs({parameter:`frequencyPenalty`,value:a,message:`frequencyPenalty must be a number`});if(o!=null&&!Number.isInteger(o))throw new gs({parameter:`seed`,value:o,message:`seed must be an integer`});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,stopSequences:s,seed:o}}function Vc(e){return e!=null&&Object.keys(e).length>0}function Hc({tools:e,toolChoice:t,activeTools:n}){if(!Vc(e))return{tools:void 0,toolChoice:void 0};let r=n==null?Object.entries(e):Object.entries(e).filter(([e])=>n.includes(e));return{tools:r.map(([e,t])=>{let n=t.type;switch(n){case void 0:case`dynamic`:case`function`:return{type:`function`,name:e,description:t.description,inputSchema:Ma(t.inputSchema).jsonSchema,providerOptions:t.providerOptions};case`provider-defined`:return{type:`provider-defined`,name:e,id:t.id,args:t.args};default:{let e=n;throw Error(`Unsupported tool type: ${e}`)}}}),toolChoice:t==null?{type:`auto`}:typeof t==`string`?{type:t}:{type:`tool`,toolName:t.toolName}}}var Uc=v.lazy(()=>v.union([v.null(),v.string(),v.number(),v.boolean(),v.record(v.string(),Uc),v.array(Uc)])),Q=v.record(v.string(),v.record(v.string(),Uc)),Wc=v.object({type:v.literal(`text`),text:v.string(),providerOptions:Q.optional()}),Gc=v.object({type:v.literal(`image`),image:v.union([Nc,v.instanceof(URL)]),mediaType:v.string().optional(),providerOptions:Q.optional()}),Kc=v.object({type:v.literal(`file`),data:v.union([Nc,v.instanceof(URL)]),filename:v.string().optional(),mediaType:v.string(),providerOptions:Q.optional()}),qc=v.object({type:v.literal(`reasoning`),text:v.string(),providerOptions:Q.optional()}),Jc=v.object({type:v.literal(`tool-call`),toolCallId:v.string(),toolName:v.string(),input:v.unknown(),providerOptions:Q.optional(),providerExecuted:v.boolean().optional()}),Yc=v.discriminatedUnion(`type`,[v.object({type:v.literal(`text`),value:v.string()}),v.object({type:v.literal(`json`),value:Uc}),v.object({type:v.literal(`error-text`),value:v.string()}),v.object({type:v.literal(`error-json`),value:Uc}),v.object({type:v.literal(`content`),value:v.array(v.union([v.object({type:v.literal(`text`),text:v.string()}),v.object({type:v.literal(`media`),data:v.string(),mediaType:v.string()})]))})]),Xc=v.object({type:v.literal(`tool-result`),toolCallId:v.string(),toolName:v.string(),output:Yc,providerOptions:Q.optional()}),Zc=v.object({role:v.literal(`system`),content:v.string(),providerOptions:Q.optional()}),Qc=v.object({role:v.literal(`user`),content:v.union([v.string(),v.array(v.union([Wc,Gc,Kc]))]),providerOptions:Q.optional()}),$c=v.object({role:v.literal(`assistant`),content:v.union([v.string(),v.array(v.union([Wc,Kc,qc,Jc,Xc]))]),providerOptions:Q.optional()}),el=v.object({role:v.literal(`tool`),content:v.array(Xc),providerOptions:Q.optional()}),tl=v.union([Zc,Qc,$c,el]);async function nl(e){if(e.prompt==null&&e.messages==null)throw new Wn({prompt:e,message:`prompt or messages must be defined`});if(e.prompt!=null&&e.messages!=null)throw new Wn({prompt:e,message:`prompt and messages cannot be defined at the same time`});if(e.system!=null&&typeof e.system!=`string`)throw new Wn({prompt:e,message:`system must be a string`});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 Wn({prompt:e,message:`prompt or messages must be defined`});if(t.length===0)throw new Wn({prompt:e,message:`messages must not be empty`});let n=await di({value:t,schema:v.array(tl)});if(!n.success)throw new Wn({prompt:e,message:`The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.`,cause:n.error});return{messages:t,system:e.system}}function rl(e){return Za.isInstance(e)||_o.isInstance(e)?new H({name:`GatewayError`,message:`Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.`,cause:e}):e}function il({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}}function al({model:e,settings:t,telemetry:n,headers:r}){var i;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...Object.entries((i=n?.metadata)??{}).reduce((e,[t,n])=>(e[`ai.telemetry.metadata.${t}`]=n,e),{}),...Object.entries(r??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}var ol={startSpan(){return sl},startActiveSpan(e,t,n,r){if(typeof t==`function`)return t(sl);if(typeof n==`function`)return n(sl);if(typeof r==`function`)return r(sl)}},sl={spanContext(){return cl},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}},cl={traceId:``,spanId:``,traceFlags:0};function ll({isEnabled:e=!1,tracer:t}={}){return e?t||c.getTracer(`ai`):ol}function ul({name:e,tracer:t,attributes:n,fn:r,endWhenDone:i=!0}){return t.startActiveSpan(e,{attributes:n},async e=>{try{let t=await r(e);return i&&e.end(),t}catch(t){try{dl(e,t)}finally{e.end()}throw t}})}function dl(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:o.ERROR,message:t.message})):e.setStatus({code:o.ERROR})}function fl({telemetry:e,attributes:t}){return e?.isEnabled===!0?Object.entries(t).reduce((t,[n,r])=>{if(r==null)return t;if(typeof r==`object`&&`input`in r&&typeof r.input==`function`){if(e?.recordInputs===!1)return t;let i=r.input();return i==null?t:{...t,[n]:i}}if(typeof r==`object`&&`output`in r&&typeof r.output==`function`){if(e?.recordOutputs===!1)return t;let i=r.output();return i==null?t:{...t,[n]:i}}return{...t,[n]:r}},{}):{}}function pl(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:e.data instanceof Uint8Array?Fc(e.data):e.data}:e)})))}function ml(e,t){return{inputTokens:hl(e.inputTokens,t.inputTokens),outputTokens:hl(e.outputTokens,t.outputTokens),totalTokens:hl(e.totalTokens,t.totalTokens),reasoningTokens:hl(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:hl(e.cachedInputTokens,t.cachedInputTokens)}}function hl(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function gl(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function _l({error:e,exponentialBackoffDelay:t}){let n=e.responseHeaders;if(!n)return t;let r,i=n[`retry-after-ms`];if(i){let e=parseFloat(i);Number.isNaN(e)||(r=e)}let a=n[`retry-after`];if(a&&r===void 0){let e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():e*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var vl=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async i=>yl(i,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function yl(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:i},a=[]){try{return await e()}catch(o){if(Wr(o)||t===0)throw o;let s=Ur(o),c=[...a,o],l=c.length;if(l>t)throw new Cc({message:`Failed after ${l} attempts. Last error: ${s}`,reason:`maxRetriesExceeded`,errors:c});if(o instanceof Error&&U.isInstance(o)&&o.isRetryable===!0&&l<=t)return await zr(_l({error:o,exponentialBackoffDelay:n}),{abortSignal:i}),yl(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:i},c);throw l===1?o:new Cc({message:`Failed after ${l} attempts with non-retryable error: '${s}'`,reason:`errorNotRetryable`,errors:c})}}function bl({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new gs({parameter:`maxRetries`,value:e,message:`maxRetries must be an integer`});if(e<0)throw new gs({parameter:`maxRetries`,value:e,message:`maxRetries must be >= 0`})}let n=e??2;return{maxRetries:n,retry:vl({maxRetries:n,abortSignal:t})}}var xl=class{constructor({data:e,mediaType:t}){let n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data??=Ia(this.uint8ArrayData),this.base64Data}get uint8Array(){return this.uint8ArrayData??=Fa(this.base64Data),this.uint8ArrayData}},Sl=class extends xl{constructor(e){super(e),this.type=`file`}};async function Cl({toolCall:e,tools:t,repairToolCall:n,system:r,messages:i}){try{if(t==null)throw new Js({toolName:e.toolName});try{return await wl({toolCall:e,tools:t})}catch(a){if(n==null||!(Js.isInstance(a)||Ts.isInstance(a)))throw a;let o=null;try{o=await n({toolCall:e,tools:t,inputSchema:({toolName:e})=>{let{inputSchema:n}=t[e];return Ma(n).jsonSchema},system:r,messages:i,error:a})}catch(e){throw new $s({cause:e,originalError:a})}if(o==null)throw a;return await wl({toolCall:o,tools:t})}}catch(t){let n=await pi({text:e.input}),r=n.success?n.value:e.input;return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:r,dynamic:!0,invalid:!0,error:t}}}async function wl({toolCall:e,tools:t}){let n=e.toolName,r=t[n];if(r==null)throw new Js({toolName:e.toolName,availableTools:Object.keys(t)});let i=Ma(r.inputSchema),a=e.input.trim()===``?await di({value:{},schema:i}):await pi({text:e.input,schema:i});if(a.success===!1)throw new Ts({toolName:n,toolInput:e.input,cause:a.error});return r.type===`dynamic`?{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:`tool-call`,toolCallId:e.toolCallId,toolName:n,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var Tl=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:i,response:a,providerMetadata:o}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=i,this.response=a,this.providerMetadata=o}get text(){return this.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}get reasoning(){return this.content.filter(e=>e.type===`reasoning`)}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join(``)}get files(){return this.content.filter(e=>e.type===`file`).map(e=>e.file)}get sources(){return this.content.filter(e=>e.type===`source`)}get toolCalls(){return this.content.filter(e=>e.type===`tool-call`)}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!1)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type===`tool-result`)}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic===!1)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function El(e){return({steps:t})=>t.length===e}async function Dl({stopConditions:e,steps:t}){return(await Promise.all(e.map(e=>e({steps:t})))).some(e=>e)}function Ol({output:e,tool:t,errorMode:n}){return n===`text`?{type:`error-text`,value:Pn(e)}:n===`json`?{type:`error-json`,value:kl(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e==`string`?{type:`text`,value:e}:{type:`json`,value:kl(e)}}function kl(e){return e===void 0?null:e}function Al({content:e,tools:t}){let n=[],r=e.filter(e=>e.type!==`source`).filter(e=>(e.type!==`tool-result`||e.providerExecuted)&&(e.type!==`tool-error`||e.providerExecuted)).filter(e=>e.type!==`text`||e.text.length>0).map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,providerOptions:e.providerMetadata};case`reasoning`:return{type:`reasoning`,text:e.text,providerOptions:e.providerMetadata};case`file`:return{type:`file`,data:e.file.base64,mediaType:e.file.mediaType,providerOptions:e.providerMetadata};case`tool-call`:return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata};case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:Ol({tool:t?.[e.toolName],output:e.output,errorMode:`none`}),providerExecuted:!0,providerOptions:e.providerMetadata};case`tool-error`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:Ol({tool:t?.[e.toolName],output:e.error,errorMode:`json`}),providerOptions:e.providerMetadata}}});r.length>0&&n.push({role:`assistant`,content:r});let i=e.filter(e=>e.type===`tool-result`||e.type===`tool-error`).filter(e=>!e.providerExecuted).map(e=>({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:Ol({tool:t?.[e.toolName],output:e.type===`tool-result`?e.output:e.error,errorMode:e.type===`tool-error`?`text`:`none`})}));return i.length>0&&n.push({role:`tool`,content:i}),n}Hr({prefix:`aitxt`,size:24});function jl(e,t){let n=new Headers(e??{});for(let[e,r]of Object.entries(t))n.has(e)||n.set(e,r);return n}function Ml({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:jl(n,{"content-type":`text/plain; charset=utf-8`})})}function Nl({response:e,status:t,statusText:n,headers:r,stream:i}){e.writeHead(t??200,n,r);let a=i.getReader(),o=async()=>{try{for(;;){let{done:t,value:n}=await a.read();if(t)break;e.write(n)}}catch(e){throw e}finally{e.end()}};o()}function Pl({response:e,status:t,statusText:n,headers:r,textStream:i}){Nl({response:e,status:t,statusText:n,headers:Object.fromEntries(jl(r,{"content-type":`text/plain; charset=utf-8`}).entries()),stream:i.pipeThrough(new TextEncoderStream)})}var Fl=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
43
-
44
- `)},flush(e){e.enqueue(`data: [DONE]
45
-
46
- `)}})}},Il={"content-type":`text/event-stream`,"cache-control":`no-cache`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`};function Ll({status:e,statusText:t,headers:n,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new Fl);if(i){let[e,t]=a.tee();a=e,i({stream:t})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:jl(n,Il)})}function Rl({originalMessages:e,responseMessageId:t}){if(e==null)return;let n=e[e.length-1];return n?.role===`assistant`?n.id:typeof t==`function`?t():t}v.union([v.strictObject({type:v.literal(`text-start`),id:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`text-delta`),id:v.string(),delta:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`text-end`),id:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`error`),errorText:v.string()}),v.strictObject({type:v.literal(`tool-input-start`),toolCallId:v.string(),toolName:v.string(),providerExecuted:v.boolean().optional(),dynamic:v.boolean().optional()}),v.strictObject({type:v.literal(`tool-input-delta`),toolCallId:v.string(),inputTextDelta:v.string()}),v.strictObject({type:v.literal(`tool-input-available`),toolCallId:v.string(),toolName:v.string(),input:v.unknown(),providerExecuted:v.boolean().optional(),providerMetadata:Q.optional(),dynamic:v.boolean().optional()}),v.strictObject({type:v.literal(`tool-input-error`),toolCallId:v.string(),toolName:v.string(),input:v.unknown(),providerExecuted:v.boolean().optional(),providerMetadata:Q.optional(),dynamic:v.boolean().optional(),errorText:v.string()}),v.strictObject({type:v.literal(`tool-output-available`),toolCallId:v.string(),output:v.unknown(),providerExecuted:v.boolean().optional(),dynamic:v.boolean().optional(),preliminary:v.boolean().optional()}),v.strictObject({type:v.literal(`tool-output-error`),toolCallId:v.string(),errorText:v.string(),providerExecuted:v.boolean().optional(),dynamic:v.boolean().optional()}),v.strictObject({type:v.literal(`reasoning`),text:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`reasoning-start`),id:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`reasoning-delta`),id:v.string(),delta:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`reasoning-end`),id:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`reasoning-part-finish`)}),v.strictObject({type:v.literal(`source-url`),sourceId:v.string(),url:v.string(),title:v.string().optional(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`source-document`),sourceId:v.string(),mediaType:v.string(),title:v.string(),filename:v.string().optional(),providerMetadata:Q.optional()}),v.strictObject({type:v.literal(`file`),url:v.string(),mediaType:v.string(),providerMetadata:Q.optional()}),v.strictObject({type:v.string().startsWith(`data-`),id:v.string().optional(),data:v.unknown(),transient:v.boolean().optional()}),v.strictObject({type:v.literal(`start-step`)}),v.strictObject({type:v.literal(`finish-step`)}),v.strictObject({type:v.literal(`start`),messageId:v.string().optional(),messageMetadata:v.unknown().optional()}),v.strictObject({type:v.literal(`finish`),messageMetadata:v.unknown().optional()}),v.strictObject({type:v.literal(`abort`)}),v.strictObject({type:v.literal(`message-metadata`),messageMetadata:v.unknown()})]);function zl(e){return e.type.startsWith(`data-`)}function Bl(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=Bl(a,i):n[r]=i}return n}function Vl(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),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=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s],l=t[t.length-1];switch(l){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,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`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`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=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;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=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--){let i=t[n];switch(i){case`INSIDE_STRING`:s+=`"`;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`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}}return s}async function Hl(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await pi({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await pi({text:Vl(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}function Ul(e){return e.type.startsWith(`tool-`)}function Wl(e){return e.type===`dynamic-tool`}function Gl(e){return Ul(e)||Wl(e)}function Kl(e){return e.type.split(`-`).slice(1).join(`-`)}function ql(e){return Wl(e)?e.toolName:Kl(e)}function Jl({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Yl({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{var l,u,d,f;function p(e){let t=r.message.parts.filter(Ul),n=t.find(t=>t.toolCallId===e);if(n==null)throw Error(`tool-output-error must be preceded by a tool-input-available`);return n}function m(e){let t=r.message.parts.filter(e=>e.type===`dynamic-tool`),n=t.find(t=>t.toolCallId===e);if(n==null)throw Error(`tool-output-error must be preceded by a tool-input-available`);return n}function h(e){var t;let n=r.message.parts.find(t=>Ul(t)&&t.toolCallId===e.toolCallId),i=e,a=n;n==null?r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata==null?{}:{callProviderMetadata:i.providerMetadata}}):(n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,a.providerExecuted=(t=i.providerExecuted)??n.providerExecuted,i.providerMetadata!=null&&n.state===`input-available`&&(n.callProviderMetadata=i.providerMetadata))}function g(e){var t;let n=r.message.parts.find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;n==null?r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,...i.providerMetadata==null?{}:{callProviderMetadata:i.providerMetadata}}):(n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=(t=i.rawInput)??a.rawInput,a.preliminary=i.preliminary,i.providerMetadata!=null&&n.state===`input-available`&&(n.callProviderMetadata=i.providerMetadata))}async function _(e){if(e!=null){let n=r.message.metadata==null?e:Bl(r.message.metadata,e);t!=null&&await ui({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=(l=e.providerMetadata)??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];t.state=`done`,t.providerMetadata=(u=e.providerMetadata)??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=(d=e.providerMetadata)??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];t.providerMetadata=(f=e.providerMetadata)??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:r.message.parts.push({type:`file`,mediaType:e.mediaType,url:e.url}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=r.message.parts.filter(Ul);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;let{value:n}=await Hl(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n}):h({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n}),c();break}case`tool-input-available`:e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c();break;case`tool-output-available`:if(e.dynamic){let t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary})}else{let t=p(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Kl(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}c();break;case`tool-output-error`:if(e.dynamic){let t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText})}else{let t=p(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Kl(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText})}c();break;case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts={},r.activeReasoningParts={};break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await _(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:await _(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await _(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(zl(e)){n?.[e.type]!=null&&await ui({value:e.data,schema:n[e.type]});let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}function Xl({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:i}){let a=t?.[t.length-1];a?.role===`assistant`?e=a.id:a=void 0;let o=!1,s=i.pipeThrough(new TransformStream({transform(t,n){if(t.type===`start`){let n=t;n.messageId==null&&e!=null&&(n.messageId=e)}t.type===`abort`&&(o=!0),n.enqueue(t)}}));if(n==null)return s;let c=Jl({lastMessage:a?structuredClone(a):void 0,messageId:e??``}),l=async e=>{await e({state:c,write:()=>{}})},u=!1,d=async()=>{if(u||!n)return;u=!0;let e=c.message.id===a?.id;await n({isAborted:o,isContinuation:e,responseMessage:c.message,messages:[...e?t.slice(0,-1):t,c.message]})};return Yl({stream:s,runUpdateMessageJob:l,onError:r}).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e)},async cancel(){await d()},async flush(){await d()}}))}function Zl({response:e,status:t,statusText:n,headers:r,stream:i,consumeSseStream:a}){let o=i.pipeThrough(new Fl);if(a){let[e,t]=o.tee();o=e,a({stream:t})}Nl({response:e,status:t,statusText:n,headers:Object.fromEntries(jl(r,Il).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function Ql(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){var r;t=!0;try{n&&await(r=e.cancel)?.call(e)}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}async function $l({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}function eu(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return{promise:n,resolve:e,reject:t}}function tu(){let e=[],t=null,n=!1,r=eu(),i=()=>{n=!0,r.resolve(),e.forEach(e=>e.cancel()),e=[],t?.close()},a=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return r=eu(),await r.promise,a();try{let{value:r,done:i}=await e[0].read();i?(e.shift(),e.length>0?await a():n&&t?.close()):t?.enqueue(r)}catch(n){t?.error(n),e.shift(),i()}};return{stream:new ReadableStream({start(e){t=e},pull:a,async cancel(){for(let t of e)await t.cancel();e=[],n=!0}}),addStream:t=>{if(n)throw Error(`Cannot add inner stream: outer stream is closed`);e.push(t.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&t?.close()},terminate:i}}var nu=class{constructor(){this.status={type:`pending`},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise||=new Promise((e,t)=>{this.status.type===`resolved`?e(this.status.value):this.status.type===`rejected`&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise}resolve(e){var t;this.status={type:`resolved`,value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:`rejected`,error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function ru(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)?.now())??Date.now()}function iu({tools:e,generatorStream:t,tracer:n,telemetry:r,system:i,messages:a,abortSignal:o,repairToolCall:s,experimental_context:c}){let l=null,u=new ReadableStream({start(e){l=e}}),d=new Set,f=new Map,p=!1,m;function h(){p&&d.size===0&&(m!=null&&l.enqueue(m),l.close())}let g=new TransformStream({async transform(t,u){let p=t.type;switch(p){case`stream-start`:case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:case`tool-input-start`:case`tool-input-delta`:case`tool-input-end`:case`source`:case`response-metadata`:case`error`:case`raw`:u.enqueue(t);break;case`file`:u.enqueue({type:`file`,file:new Sl({data:t.data,mediaType:t.mediaType})});break;case`finish`:m={type:`finish`,finishReason:t.finishReason,usage:t.usage,providerMetadata:t.providerMetadata};break;case`tool-call`:try{let p=await Cl({toolCall:t,tools:e,repairToolCall:s,system:i,messages:a});if(u.enqueue(p),p.invalid){l.enqueue({type:`tool-error`,toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,error:Ur(p.error),dynamic:!0});break}let m=e[p.toolName];if(f.set(p.toolCallId,p.input),m.onInputAvailable!=null&&await m.onInputAvailable({input:p.input,toolCallId:p.toolCallId,messages:a,abortSignal:o,experimental_context:c}),m.execute!=null&&p.providerExecuted!==!0){let e=K();d.add(e),ul({name:`ai.toolCall`,attributes:fl({telemetry:r,attributes:{...il({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":p.toolName,"ai.toolCall.id":p.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(p.input)}}}),tracer:n,fn:async t=>{let n;try{let e=Ba({execute:m.execute.bind(m),input:p.input,options:{toolCallId:p.toolCallId,messages:a,abortSignal:o,experimental_context:c}});for await(let t of e)l.enqueue({...p,type:`tool-result`,output:t.output,...t.type===`preliminary`&&{preliminary:!0}}),t.type===`final`&&(n=t.output)}catch(n){dl(t,n),l.enqueue({...p,type:`tool-error`,error:n}),d.delete(e),h();return}d.delete(e),h();try{t.setAttributes(fl({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(n)}}}))}catch{}}})}}catch(e){l.enqueue({type:`error`,error:e})}break;case`tool-result`:{let e=t.toolName;t.isError?l.enqueue({type:`tool-error`,toolCallId:t.toolCallId,toolName:e,input:f.get(t.toolCallId),providerExecuted:t.providerExecuted,error:t.result}):u.enqueue({type:`tool-result`,toolCallId:t.toolCallId,toolName:e,input:f.get(t.toolCallId),output:t.result,providerExecuted:t.providerExecuted});break}default:{let e=p;throw Error(`Unhandled chunk type: ${e}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(e){return Promise.all([t.pipeThrough(g).pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){}})),u.pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){e.close()}}))])}})}var au=Hr({prefix:`aitxt`,size:24});function ou({model:e,tools:t,toolChoice:n,system:r,prompt:i,messages:a,maxRetries:o,abortSignal:s,headers:c,stopWhen:l=El(1),experimental_output:u,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:m,activeTools:h=m,experimental_repairToolCall:g,experimental_transform:_,experimental_download:v,includeRawChunks:y=!1,onChunk:b,onError:x=({error:e})=>{console.error(e)},onFinish:S,onAbort:C,onStepFinish:w,experimental_context:T,_internal:{now:E=ru,generateId:D=au,currentDate:O=()=>new Date}={},...k}){return new cu({model:wc(e),telemetry:d,headers:c,settings:k,maxRetries:o,abortSignal:s,system:r,prompt:i,messages:a,tools:t,toolChoice:n,transforms:gl(_),activeTools:h,repairToolCall:g,stopConditions:gl(l),output:u,providerOptions:p,prepareStep:f,includeRawChunks:y,onChunk:b,onError:x,onFinish:S,onAbort:C,onStepFinish:w,now:E,currentDate:O,generateId:D,experimental_context:T,download:v})}function su(e){if(!e)return new TransformStream({transform(e,t){t.enqueue({part:e,partialOutput:void 0})}});let t,n=``,r=``,i=``;function a({controller:e,partialOutput:n=void 0}){e.enqueue({part:{type:`text-delta`,id:t,text:r},partialOutput:n}),r=``}return new TransformStream({async transform(o,s){if(o.type===`finish-step`&&r.length>0&&a({controller:s}),o.type!==`text-delta`&&o.type!==`text-start`&&o.type!==`text-end`){s.enqueue({part:o,partialOutput:void 0});return}if(t==null)t=o.id;else if(o.id!==t){s.enqueue({part:o,partialOutput:void 0});return}if(o.type===`text-start`){s.enqueue({part:o,partialOutput:void 0});return}if(o.type===`text-end`){r.length>0&&a({controller:s}),s.enqueue({part:o,partialOutput:void 0});return}n+=o.text,r+=o.text;let c=await e.parsePartial({text:n});if(c!=null){let e=JSON.stringify(c.partial);e!==i&&(a({controller:s,partialOutput:c.partial}),i=e)}}})}var cu=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:i,abortSignal:a,system:o,prompt:s,messages:c,tools:l,toolChoice:u,transforms:d,activeTools:f,repairToolCall:p,stopConditions:m,output:h,providerOptions:g,prepareStep:_,includeRawChunks:v,now:y,currentDate:b,generateId:x,onChunk:S,onError:C,onFinish:w,onAbort:T,onStepFinish:E,experimental_context:D,download:O}){this._totalUsage=new nu,this._finishReason=new nu,this._steps=new nu,this.output=h,this.includeRawChunks=v,this.tools=l;let k,A=[],ee=[],te,j,M={},N=[],P=[],F,I={},ne={},re=new TransformStream({async transform(e,t){var n,r,i;t.enqueue(e);let{part:a}=e;if((a.type===`text-delta`||a.type===`reasoning-delta`||a.type===`source`||a.type===`tool-call`||a.type===`tool-result`||a.type===`tool-input-start`||a.type===`tool-input-delta`||a.type===`raw`)&&await S?.({chunk:a}),a.type===`error`&&await C({error:rl(a.error)}),a.type===`text-start`&&(I[a.id]={type:`text`,text:``,providerMetadata:a.providerMetadata},A.push(I[a.id])),a.type===`text-delta`){let e=I[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`text part ${a.id} not found`},partialOutput:void 0});return}e.text+=a.text,e.providerMetadata=(n=a.providerMetadata)??e.providerMetadata}if(a.type===`text-end`&&delete I[a.id],a.type===`reasoning-start`&&(ne[a.id]={type:`reasoning`,text:``,providerMetadata:a.providerMetadata},A.push(ne[a.id])),a.type===`reasoning-delta`){let e=ne[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`reasoning part ${a.id} not found`},partialOutput:void 0});return}e.text+=a.text,e.providerMetadata=(r=a.providerMetadata)??e.providerMetadata}if(a.type===`reasoning-end`){let e=ne[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`reasoning part ${a.id} not found`},partialOutput:void 0});return}e.providerMetadata=(i=a.providerMetadata)??e.providerMetadata,delete ne[a.id]}if(a.type===`file`&&A.push({type:`file`,file:a.file}),a.type===`source`&&A.push(a),a.type===`tool-call`&&A.push(a),a.type===`tool-result`&&!a.preliminary&&A.push(a),a.type===`tool-error`&&A.push(a),a.type===`start-step`&&(M=a.request,N=a.warnings),a.type===`finish-step`){let e=Al({content:A,tools:l}),t=new Tl({content:A,finishReason:a.finishReason,usage:a.usage,warnings:N,request:M,response:{...a.response,messages:[...ee,...e]},providerMetadata:a.providerMetadata});await E?.(t),ds(N),P.push(t),A=[],ne={},I={},ee.push(...e),k.resolve()}a.type===`finish`&&(j=a.totalUsage,te=a.finishReason)},async flush(e){try{if(P.length===0){let e=new Us({message:`No output generated. Check the stream for errors.`});R._finishReason.reject(e),R._totalUsage.reject(e),R._steps.reject(e);return}let e=te??`unknown`,n=j??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};R._finishReason.resolve(e),R._totalUsage.resolve(n),R._steps.resolve(P);let r=P[P.length-1];await w?.({finishReason:e,totalUsage:n,usage:r.usage,content:r.content,text:r.text,reasoningText:r.reasoningText,reasoning:r.reasoning,files:r.files,sources:r.sources,toolCalls:r.toolCalls,staticToolCalls:r.staticToolCalls,dynamicToolCalls:r.dynamicToolCalls,toolResults:r.toolResults,staticToolResults:r.staticToolResults,dynamicToolResults:r.dynamicToolResults,request:r.request,response:r.response,warnings:r.warnings,providerMetadata:r.providerMetadata,steps:P}),F.setAttributes(fl({telemetry:t,attributes:{"ai.response.finishReason":e,"ai.response.text":{output:()=>r.text},"ai.response.toolCalls":{output:()=>{var e;return(e=r.toolCalls)?.length?JSON.stringify(r.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(r.providerMetadata),"ai.usage.inputTokens":n.inputTokens,"ai.usage.outputTokens":n.outputTokens,"ai.usage.totalTokens":n.totalTokens,"ai.usage.reasoningTokens":n.reasoningTokens,"ai.usage.cachedInputTokens":n.cachedInputTokens}}))}catch(t){e.error(t)}finally{F.end()}}}),ie=tu();this.addStream=ie.addStream,this.closeStream=ie.close;let ae=ie.stream.getReader(),oe=new ReadableStream({async start(e){e.enqueue({type:`start`})},async pull(e){function t(){T?.({steps:P}),e.enqueue({type:`abort`}),e.close()}try{let{done:n,value:r}=await ae.read();if(n){e.close();return}if(a?.aborted){t();return}e.enqueue(r)}catch(n){Wr(n)&&a?.aborted?t():e.error(n)}},cancel(e){return ie.stream.cancel(e)}});for(let e of d)oe=oe.pipeThrough(e({tools:l,stopStream(){ie.terminate()}}));this.baseStream=oe.pipeThrough(su(h)).pipeThrough(re);let{maxRetries:se,retry:ce}=bl({maxRetries:i,abortSignal:a}),le=ll(t),L=Bc(r),ue=al({model:e,telemetry:t,headers:n,settings:{...L,maxRetries:se}}),R=this;ul({name:`ai.streamText`,attributes:fl({telemetry:t,attributes:{...il({operationId:`ai.streamText`,telemetry:t}),...ue,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:s,messages:c})}}}),tracer:le,endWhenDone:!1,fn:async r=>{F=r;async function i({currentStep:r,responseMessages:d,usage:v}){var S,C,w,T,E;let A=R.includeRawChunks;k=new nu;let ee=await nl({system:o,prompt:s,messages:c}),te=[...ee.messages,...d],j=await _?.({model:e,steps:P,stepNumber:P.length,messages:te}),M=await Ic({prompt:{system:(S=j?.system)??ee.system,messages:(C=j?.messages)??te},supportedUrls:await e.supportedUrls,download:O}),N=wc((w=j?.model)??e),{toolChoice:F,tools:I}=Hc({tools:l,toolChoice:(T=j?.toolChoice)??u,activeTools:(E=j?.activeTools)??f}),{result:{stream:ne,response:re,request:ie},doStreamSpan:ae,startTimestampMs:oe}=await ce(()=>ul({name:`ai.streamText.doStream`,attributes:fl({telemetry:t,attributes:{...il({operationId:`ai.streamText.doStream`,telemetry:t}),...ue,"ai.model.provider":N.provider,"ai.model.id":N.modelId,"ai.prompt.messages":{input:()=>pl(M)},"ai.prompt.tools":{input:()=>I?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>F==null?void 0:JSON.stringify(F)},"gen_ai.system":N.provider,"gen_ai.request.model":N.modelId,"gen_ai.request.frequency_penalty":L.frequencyPenalty,"gen_ai.request.max_tokens":L.maxOutputTokens,"gen_ai.request.presence_penalty":L.presencePenalty,"gen_ai.request.stop_sequences":L.stopSequences,"gen_ai.request.temperature":L.temperature,"gen_ai.request.top_k":L.topK,"gen_ai.request.top_p":L.topP}}),tracer:le,endWhenDone:!1,fn:async e=>({startTimestampMs:y(),doStreamSpan:e,result:await N.doStream({...L,tools:I,toolChoice:F,responseFormat:h?.responseFormat,prompt:M,providerOptions:g,abortSignal:a,headers:n,includeRawChunks:A})})})),se=iu({tools:l,generatorStream:ne,tracer:le,telemetry:t,system:o,messages:te,repairToolCall:p,abortSignal:a,experimental_context:D}),de=ie??{},fe=[],pe=[],me,he={},z=`unknown`,B={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},ge,_e=!0,ve={id:x(),timestamp:b(),modelId:e.modelId},V=``;R.addStream(se.pipeThrough(new TransformStream({async transform(e,t){var n,r,i,o;if(e.type===`stream-start`){me=e.warnings;return}if(_e){let e=y()-oe;_e=!1,ae.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e}),ae.setAttributes({"ai.response.msToFirstChunk":e}),t.enqueue({type:`start-step`,request:de,warnings:me??[]})}let s=e.type;switch(s){case`text-start`:case`text-end`:t.enqueue(e);break;case`text-delta`:e.delta.length>0&&(t.enqueue({type:`text-delta`,id:e.id,text:e.delta,providerMetadata:e.providerMetadata}),V+=e.delta);break;case`reasoning-start`:case`reasoning-end`:t.enqueue(e);break;case`reasoning-delta`:t.enqueue({type:`reasoning-delta`,id:e.id,text:e.delta,providerMetadata:e.providerMetadata});break;case`tool-call`:t.enqueue(e),fe.push(e);break;case`tool-result`:t.enqueue(e),e.preliminary||pe.push(e);break;case`tool-error`:t.enqueue(e),pe.push(e);break;case`response-metadata`:ve={id:(n=e.id)??ve.id,timestamp:(r=e.timestamp)??ve.timestamp,modelId:(i=e.modelId)??ve.modelId};break;case`finish`:{B=e.usage,z=e.finishReason,ge=e.providerMetadata;let t=y()-oe;ae.addEvent(`ai.stream.finish`),ae.setAttributes({"ai.response.msToFinish":t,"ai.response.avgOutputTokensPerSecond":1e3*((o=B.outputTokens)??0)/t});break}case`file`:t.enqueue(e);break;case`source`:t.enqueue(e);break;case`tool-input-start`:{he[e.id]=e.toolName;let n=l?.[e.toolName];n?.onInputStart!=null&&await n.onInputStart({toolCallId:e.id,messages:te,abortSignal:a,experimental_context:D}),t.enqueue({...e,dynamic:n?.type===`dynamic`});break}case`tool-input-end`:delete he[e.id],t.enqueue(e);break;case`tool-input-delta`:{let n=he[e.id],r=l?.[n];r?.onInputDelta!=null&&await r.onInputDelta({inputTextDelta:e.delta,toolCallId:e.id,messages:te,abortSignal:a,experimental_context:D}),t.enqueue(e);break}case`error`:t.enqueue(e),z=`error`;break;case`raw`:A&&t.enqueue(e);break;default:{let e=s;throw Error(`Unknown chunk type: ${e}`)}}},async flush(e){let n=fe.length>0?JSON.stringify(fe):void 0;try{ae.setAttributes(fl({telemetry:t,attributes:{"ai.response.finishReason":z,"ai.response.text":{output:()=>V},"ai.response.toolCalls":{output:()=>n},"ai.response.id":ve.id,"ai.response.model":ve.modelId,"ai.response.timestamp":ve.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ge),"ai.usage.inputTokens":B.inputTokens,"ai.usage.outputTokens":B.outputTokens,"ai.usage.totalTokens":B.totalTokens,"ai.usage.reasoningTokens":B.reasoningTokens,"ai.usage.cachedInputTokens":B.cachedInputTokens,"gen_ai.response.finish_reasons":[z],"gen_ai.response.id":ve.id,"gen_ai.response.model":ve.modelId,"gen_ai.usage.input_tokens":B.inputTokens,"gen_ai.usage.output_tokens":B.outputTokens}}))}catch{}finally{ae.end()}e.enqueue({type:`finish-step`,finishReason:z,usage:B,providerMetadata:ge,response:{...ve,headers:re?.headers}});let a=ml(v,B);await k.promise;let o=fe.filter(e=>e.providerExecuted!==!0),s=pe.filter(e=>e.providerExecuted!==!0);if(o.length>0&&s.length===o.length&&!await Dl({stopConditions:m,steps:P})){d.push(...Al({content:P[P.length-1].content,tools:l}));try{await i({currentStep:r+1,responseMessages:d,usage:a})}catch(t){e.enqueue({type:`error`,error:t}),R.closeStream()}}else e.enqueue({type:`finish`,finishReason:z,totalUsage:a}),R.closeStream()}})))}await i({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(e=>{R.addStream(new ReadableStream({start(t){t.enqueue({type:`error`,error:e}),t.close()}})),R.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ql(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type===`text-delta`&&t.enqueue(e.text)}})))}get fullStream(){return Ql(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await $l({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new ss;return Ql(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i=!0,sendSources:a=!1,sendStart:o=!0,sendFinish:s=!0,onError:c=Pn}={}){let l=t==null?void 0:Rl({originalMessages:e,responseMessageId:t}),u={},d=e=>{var t,n;let r=u[e],i=(n=(t=this.tools)?.[r])?.type===`dynamic`;return i?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(e,t)=>{let n=r?.({part:e}),f=e.type;switch(f){case`text-start`:t.enqueue({type:`text-start`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`text-delta`:t.enqueue({type:`text-delta`,id:e.id,delta:e.text,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`text-end`:t.enqueue({type:`text-end`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-start`:t.enqueue({type:`reasoning-start`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-delta`:i&&t.enqueue({type:`reasoning-delta`,id:e.id,delta:e.text,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-end`:t.enqueue({type:`reasoning-end`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`file`:t.enqueue({type:`file`,mediaType:e.file.mediaType,url:`data:${e.file.mediaType};base64,${e.file.base64}`});break;case`source`:a&&e.sourceType===`url`&&t.enqueue({type:`source-url`,sourceId:e.id,url:e.url,title:e.title,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),a&&e.sourceType===`document`&&t.enqueue({type:`source-document`,sourceId:e.id,mediaType:e.mediaType,title:e.title,filename:e.filename,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`tool-input-start`:{u[e.id]=e.toolName;let n=d(e.id);t.enqueue({type:`tool-input-start`,toolCallId:e.id,toolName:e.toolName,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...n==null?{}:{dynamic:n}});break}case`tool-input-delta`:t.enqueue({type:`tool-input-delta`,toolCallId:e.id,inputTextDelta:e.delta});break;case`tool-call`:{u[e.toolCallId]=e.toolName;let n=d(e.toolCallId);e.invalid?t.enqueue({type:`tool-input-error`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata},...n==null?{}:{dynamic:n},errorText:c(e.error)}):t.enqueue({type:`tool-input-available`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata},...n==null?{}:{dynamic:n}});break}case`tool-result`:{let n=d(e.toolCallId);t.enqueue({type:`tool-output-available`,toolCallId:e.toolCallId,output:e.output,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.preliminary==null?{}:{preliminary:e.preliminary},...n==null?{}:{dynamic:n}});break}case`tool-error`:{let n=d(e.toolCallId);t.enqueue({type:`tool-output-error`,toolCallId:e.toolCallId,errorText:c(e.error),...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...n==null?{}:{dynamic:n}});break}case`error`:t.enqueue({type:`error`,errorText:c(e.error)});break;case`start-step`:t.enqueue({type:`start-step`});break;case`finish-step`:t.enqueue({type:`finish-step`});break;case`start`:o&&t.enqueue({type:`start`,...n==null?{}:{messageMetadata:n},...l==null?{}:{messageId:l}});break;case`finish`:s&&t.enqueue({type:`finish`,...n==null?{}:{messageMetadata:n}});break;case`abort`:t.enqueue(e);break;case`tool-input-end`:break;case`raw`:break;default:{let e=f;throw Error(`Unknown chunk type: ${e}`)}}n!=null&&f!==`start`&&f!==`finish`&&t.enqueue({type:`message-metadata`,messageMetadata:n})}}));return Ql(Xl({stream:f,messageId:l??t?.(),originalMessages:e,onFinish:n,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:i,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:c,onError:l,...u}={}){Zl({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:i,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:c,onError:l}),...u})}pipeTextStreamToResponse(e,t){Pl({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:o,sendStart:s,onError:c,...l}={}){return Ll({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:o,sendStart:s,onError:c}),...l})}toTextStreamResponse(e){return Ml({textStream:this.textStream,...e})}};Hr({prefix:`aiobj`,size:24}),Hr({prefix:`aiobj`,size:24});var lu={};es(lu,{object:()=>du,text:()=>uu});var uu=()=>({type:`text`,responseFormat:{type:`text`},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),du=({schema:e})=>{let t=Ma(e);return{type:`object`,responseFormat:{type:`json`,schema:t.jsonSchema},async parsePartial({text:e}){let t=await Hl(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value};default:{let e=t.state;throw Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){let r=await pi({text:e});if(!r.success)throw new Rs({message:`No object generated: could not parse the response.`,cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=await di({value:r.value,schema:t});if(!i.success)throw new Rs({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},fu=`AI_NoSuchProviderError`,pu=`vercel.ai.error.${fu}`,mu=Symbol.for(pu),hu;hu=mu;var gu=v.looseObject({name:v.string(),version:v.string()}),_u=v.looseObject({_meta:v.optional(v.object({}).loose())}),vu=_u,yu=v.object({method:v.string(),params:v.optional(_u)}),bu=v.looseObject({experimental:v.optional(v.object({}).loose()),logging:v.optional(v.object({}).loose()),prompts:v.optional(v.looseObject({listChanged:v.optional(v.boolean())})),resources:v.optional(v.looseObject({subscribe:v.optional(v.boolean()),listChanged:v.optional(v.boolean())})),tools:v.optional(v.looseObject({listChanged:v.optional(v.boolean())}))});vu.extend({protocolVersion:v.string(),capabilities:bu,serverInfo:gu,instructions:v.optional(v.string())});var xu=vu.extend({nextCursor:v.optional(v.string())}),Su=v.object({name:v.string(),description:v.optional(v.string()),inputSchema:v.object({type:v.literal(`object`),properties:v.optional(v.object({}).loose())}).loose()}).loose();xu.extend({tools:v.array(Su)});var Cu=v.object({type:v.literal(`text`),text:v.string()}).loose(),wu=v.object({type:v.literal(`image`),data:v.base64(),mimeType:v.string()}).loose(),Tu=v.object({uri:v.string(),mimeType:v.optional(v.string())}).loose(),Eu=Tu.extend({text:v.string()}),Du=Tu.extend({blob:v.base64()}),Ou=v.object({type:v.literal(`resource`),resource:v.union([Eu,Du])}).loose();vu.extend({content:v.array(v.union([Cu,wu,Ou])),isError:v.boolean().default(!1).optional()}).or(vu.extend({toolResult:v.unknown()}));var ku=`2.0`,Au=v.object({jsonrpc:v.literal(ku),id:v.union([v.string(),v.number().int()])}).merge(yu).strict(),ju=v.object({jsonrpc:v.literal(ku),id:v.union([v.string(),v.number().int()]),result:vu}).strict(),Mu=v.object({jsonrpc:v.literal(ku),id:v.union([v.string(),v.number().int()]),error:v.object({code:v.number().int(),message:v.string(),data:v.optional(v.unknown())})}).strict(),Nu=v.object({jsonrpc:v.literal(ku)}).merge(v.object({method:v.string(),params:v.optional(_u)})).strict();v.union([Au,Nu,ju,Mu]);var Pu=v.object({type:v.literal(`text`),text:v.string(),state:v.enum([`streaming`,`done`]).optional(),providerMetadata:Q.optional()}),Fu=v.object({type:v.literal(`reasoning`),text:v.string(),state:v.enum([`streaming`,`done`]).optional(),providerMetadata:Q.optional()}),Iu=v.object({type:v.literal(`source-url`),sourceId:v.string(),url:v.string(),title:v.string().optional(),providerMetadata:Q.optional()}),Lu=v.object({type:v.literal(`source-document`),sourceId:v.string(),mediaType:v.string(),title:v.string(),filename:v.string().optional(),providerMetadata:Q.optional()}),Ru=v.object({type:v.literal(`file`),mediaType:v.string(),filename:v.string().optional(),url:v.string(),providerMetadata:Q.optional()}),zu=v.object({type:v.literal(`step-start`)}),Bu=v.object({type:v.string().startsWith(`data-`),id:v.string().optional(),data:v.unknown()}),Vu=[v.object({type:v.literal(`dynamic-tool`),toolName:v.string(),toolCallId:v.string(),state:v.literal(`input-streaming`),input:v.unknown().optional(),output:v.never().optional(),errorText:v.never().optional()}),v.object({type:v.literal(`dynamic-tool`),toolName:v.string(),toolCallId:v.string(),state:v.literal(`input-available`),input:v.unknown(),output:v.never().optional(),errorText:v.never().optional(),callProviderMetadata:Q.optional()}),v.object({type:v.literal(`dynamic-tool`),toolName:v.string(),toolCallId:v.string(),state:v.literal(`output-available`),input:v.unknown(),output:v.unknown(),errorText:v.never().optional(),callProviderMetadata:Q.optional(),preliminary:v.boolean().optional()}),v.object({type:v.literal(`dynamic-tool`),toolName:v.string(),toolCallId:v.string(),state:v.literal(`output-error`),input:v.unknown(),output:v.never().optional(),errorText:v.string(),callProviderMetadata:Q.optional()})],Hu=[v.object({type:v.string().startsWith(`tool-`),toolCallId:v.string(),state:v.literal(`input-streaming`),input:v.unknown().optional(),output:v.never().optional(),errorText:v.never().optional()}),v.object({type:v.string().startsWith(`tool-`),toolCallId:v.string(),state:v.literal(`input-available`),input:v.unknown(),output:v.never().optional(),errorText:v.never().optional(),callProviderMetadata:Q.optional()}),v.object({type:v.string().startsWith(`tool-`),toolCallId:v.string(),state:v.literal(`output-available`),input:v.unknown(),output:v.unknown(),errorText:v.never().optional(),callProviderMetadata:Q.optional(),preliminary:v.boolean().optional()}),v.object({type:v.string().startsWith(`tool-`),toolCallId:v.string(),state:v.literal(`output-error`),input:v.unknown(),output:v.never().optional(),errorText:v.string(),callProviderMetadata:Q.optional()})];v.object({id:v.string(),role:v.enum([`system`,`user`,`assistant`]),metadata:v.unknown().optional(),parts:v.array(v.union([Pu,Fu,Iu,Lu,Ru,zu,Bu,...Vu,...Hu]))});function Uu({message:e,stream:t,onError:n,terminateOnError:r=!1}){var i;let a,o=!1,s=new ReadableStream({start(e){a=e}}),c=Jl({messageId:(i=e?.id)??``,lastMessage:e}),l=e=>{n?.(e),!o&&r&&(o=!0,a?.error(e))};return $l({stream:Yl({stream:t,runUpdateMessageJob(e){return e({state:c,write:()=>{a?.enqueue(structuredClone(c.message))}})},onError:l}),onError:l}).finally(()=>{o||a?.close()}),Ql(s)}var Wu=v.object({type:v.literal(`error`),error:v.object({type:v.string(),message:v.string()})}),Gu=Ci({errorSchema:Wu,errorToMessage:e=>e.error.message}),Ku=v.object({citations:v.object({enabled:v.boolean()}).optional(),title:v.string().optional(),context:v.string().optional()}),qu=v.object({sendReasoning:v.boolean().optional(),thinking:v.object({type:v.union([v.literal(`enabled`),v.literal(`disabled`)]),budgetTokens:v.number().optional()}).optional(),disableParallelToolUse:v.boolean().optional()});function Ju(e){var t;let n=e?.anthropic,r=(t=n?.cacheControl)??n?.cache_control;return r}var Yu=v.object({maxUses:v.number().optional(),allowedDomains:v.array(v.string()).optional(),blockedDomains:v.array(v.string()).optional(),userLocation:v.object({type:v.literal(`approximate`),city:v.string().optional(),region:v.string().optional(),country:v.string().optional(),timezone:v.string().optional()}).optional()}),Xu=v.array(v.object({url:v.string(),title:v.string(),pageAge:v.string().nullable(),encryptedContent:v.string(),type:v.string()})),Zu=xi({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:v.object({query:v.string()}),outputSchema:Xu}),Qu=(e={})=>Zu(e);function $u(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`web_search_20250305`}function ed({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e){if($u(t)){a.push(t);continue}switch(t.type){case`function`:let e=Ju(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break;case`provider-defined`:switch(t.id){case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_search_20250305`:{let e=Yu.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:{let e=o;throw new W({functionality:`tool choice type: ${e}`})}}}var td=v.object({type:v.literal(`code_execution_result`),stdout:v.string(),stderr:v.string(),return_code:v.number()}),nd=xi({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:v.object({code:v.string()}),outputSchema:td}),rd=(e={})=>nd(e);function id(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new W({functionality:`URL-based text documents are not supported for citations`}):new W({functionality:`unsupported data type for text documents: ${typeof e}`})}async function ad({prompt:e,sendReasoning:t,warnings:n}){var r,i,a,o,s;let c=new Set,l=od(e),u,d=[];async function f(e){var t,n;let r=await q({provider:`anthropic`,providerOptions:e,schema:Ku});return(n=(t=r?.citations)?.enabled)??!1}async function p(e){let t=await q({provider:`anthropic`,providerOptions:e,schema:Ku});return{title:t?.title,context:t?.context}}for(let e=0;e<l.length;e++){let m=l[e],h=e===l.length-1,g=m.type;switch(g){case`system`:if(u!=null)throw new W({functionality:`Multiple system messages that are separated by user/assistant messages`});u=m.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Ju(t)}));break;case`user`:{let e=[];for(let t of m.messages){let{role:n,content:s}=t;switch(n){case`user`:for(let n=0;n<s.length;n++){let o=s[n],l=n===s.length-1,u=(r=Ju(o.providerOptions))??(l?Ju(t.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:La(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){c.add(`pdfs-2024-09-25`);let t=await f(o.providerOptions),n=await p(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:La(o.data)},title:(i=n.title)??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await f(o.providerOptions),n=await p(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:id(o.data)},title:(a=n.title)??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new W({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let n=0;n<s.length;n++){let r=s[n],i=n===s.length-1,a=(o=Ju(r.providerOptions))??(i?Ju(t.providerOptions):void 0),c=r.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new W({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:a})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}d.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<m.messages.length;r++){let i=m.messages[r],a=r===m.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let c=o[r],l=r===o.length-1,u=(s=Ju(c.providerOptions))??(l?Ju(i.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:h&&a&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(t){let t=await q({provider:`anthropic`,providerOptions:c.providerOptions,schema:hd});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:t.signature,cache_control:u})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){if(c.toolName===`web_search`){e.push({type:`server_tool_use`,id:c.toolCallId,name:`web_search`,input:c.input,cache_control:u});break}if(c.toolName===`code_execution`){e.push({type:`server_tool_use`,id:c.toolCallId,name:`code_execution`,input:c.input,cache_control:u});break}n.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let r=Xu.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let r=td.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:u});break}n.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}d.push({role:`assistant`,content:e});break}default:{let e=g;throw Error(`content type: ${e}`)}}}return{prompt:{system:u,messages:d},betas:c}}function od(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function sd({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var cd={webSearchResult:v.object({type:v.literal(`web_search_result_location`),cited_text:v.string(),url:v.string(),title:v.string(),encrypted_index:v.string()}),pageLocation:v.object({type:v.literal(`page_location`),cited_text:v.string(),document_index:v.number(),document_title:v.string().nullable(),start_page_number:v.number(),end_page_number:v.number()}),charLocation:v.object({type:v.literal(`char_location`),cited_text:v.string(),document_index:v.number(),document_title:v.string().nullable(),start_char_index:v.number(),end_char_index:v.number()})},ld=v.discriminatedUnion(`type`,[cd.webSearchResult,cd.pageLocation,cd.charLocation]);v.discriminatedUnion(`type`,[cd.pageLocation,cd.charLocation]);function ud(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=dd(e,t,n);i&&r(i)}}function dd(e,t,n){var r;let i=t[e.document_index];if(!i)return null;let a=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:i.mediaType,title:(r=e.document_title)??i.title,filename:i.filename,providerMetadata:{anthropic:a}}}var fd=class{constructor(e,t){this.specificationVersion=`v2`;var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)??K}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)?.call(e))??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m,h;let g=[];a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&g.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let _=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,v=await q({provider:`anthropic`,providerOptions:f,schema:qu}),{prompt:y,betas:b}=await ad({prompt:e,sendReasoning:(p=v?.sendReasoning)??!0,warnings:g}),x=(m=v?.thinking)?.type===`enabled`,S=(h=v?.thinking)?.budgetTokens,C={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...x&&{thinking:{type:`enabled`,budget_tokens:S}},system:y.system,messages:y.messages};if(x){if(S==null)throw new W({functionality:`thinking requires a budget`});C.temperature!=null&&(C.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(C.top_k=void 0,g.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(C.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),C.max_tokens=t+S}let{tools:w,toolChoice:T,toolWarnings:E,betas:D}=ed(_==null?{tools:u??[],toolChoice:d,disableParallelToolUse:v?.disableParallelToolUse}:{tools:[_],toolChoice:{type:`tool`,toolName:_.name},disableParallelToolUse:!0});return{args:{...C,tools:w,tool_choice:T},warnings:[...g,...E],betas:new Set([...b,...D]),usesJsonResponseTool:_!=null}}async getHeaders({betas:e,headers:t}){return G(await Si(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t,n,r;return(r=(n=(t=this.config).buildRequestUrl)?.call(t,this.config.baseURL,e))??`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return(r=(n=(t=this.config).transformRequestBody)?.call(t,e))??e}extractCitationDocuments(e){let t=e=>{var t,n;if(e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`)return!1;let r=(t=e.providerOptions)?.anthropic,i=r?.citations;return(n=i?.enabled)??!1};return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(t).map(e=>{var t;let n=e;return{title:(t=n.filename)??`Untitled Document`,filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,n,r,i,a;let{args:o,warnings:s,betas:c,usesJsonResponseTool:l}=await this.getArgs(e),u=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:f,rawValue:p}=await J({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:c,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Gu,successfulResponseHandler:Y(pd),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=[];for(let e of f.content)switch(e.type){case`text`:if(!l&&(m.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)ud(t,u,this.generateId,e=>m.push(e));break;case`thinking`:m.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:m.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:m.push(l?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`)&&m.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:(t=e.page_age)??null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(let n of e.content)m.push({type:`source`,sourceType:`url`,id:this.generateId(),url:n.url,title:n.title,providerMetadata:{anthropic:{pageAge:(t=n.page_age)??null}}})}else m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:m,finishReason:sd({finishReason:f.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:f.usage.input_tokens,outputTokens:f.usage.output_tokens,totalTokens:f.usage.input_tokens+f.usage.output_tokens,cachedInputTokens:(n=f.usage.cache_read_input_tokens)??void 0},request:{body:o},response:{id:(r=f.id)??void 0,modelId:(i=f.model)??void 0,headers:d,body:p},warnings:s,providerMetadata:{anthropic:{usage:f.usage,cacheCreationInputTokens:(a=f.usage.cache_creation_input_tokens)??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await J({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Gu,successfulResponseHandler:wi(md),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p,m=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,o,s,c,h,g,_;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let v=t.value;switch(v.type){case`ping`:return;case`content_block_start`:{let e=v.content_block.type;switch(p=e,e){case`text`:d[v.index]={type:`text`},n.enqueue({type:`text-start`,id:String(v.index)});return;case`thinking`:d[v.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(v.index)});return;case`redacted_thinking`:d[v.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(v.index),providerMetadata:{anthropic:{redactedData:v.content_block.data}}});return;case`tool_use`:d[v.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:v.content_block.id,toolName:v.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(v.index)}:{type:`tool-input-start`,id:v.content_block.id,toolName:v.content_block.name});return;case`server_tool_use`:(v.content_block.name===`web_search`||v.content_block.name===`code_execution`)&&(d[v.index]={type:`tool-call`,toolCallId:v.content_block.id,toolName:v.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:v.content_block.id,toolName:v.content_block.name,providerExecuted:!0}));return;case`web_search_tool_result`:{let e=v.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:(t=e.page_age)??null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:m(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:(r=t.page_age)??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=v.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[v.index]!=null){let e=d[v.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(v.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(v.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[v.index]}p=void 0;return;case`content_block_delta`:{let e=v.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(v.index),delta:v.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(v.index),delta:v.delta.thinking});return;case`signature_delta`:p===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(v.index),delta:``,providerMetadata:{anthropic:{signature:v.delta.signature}}});return;case`input_json_delta`:{let e=d[v.index],t=v.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(v.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=v.delta.citation;ud(e,a,m,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=v.message.usage.input_tokens,u.cachedInputTokens=(o=v.message.usage.cache_read_input_tokens)??void 0,f={anthropic:{usage:v.message.usage,cacheCreationInputTokens:(s=v.message.usage.cache_creation_input_tokens)??null}},n.enqueue({type:`response-metadata`,id:(c=v.message.id)??void 0,modelId:(h=v.message.model)??void 0});return;case`message_delta`:u.outputTokens=v.usage.output_tokens,u.totalTokens=((g=u.inputTokens)??0)+((_=v.usage.output_tokens)??0),l=sd({finishReason:v.delta.stop_reason,isJsonResponseFromTool:i});return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:f});return;case`error`:n.enqueue({type:`error`,error:v.error});return;default:{let e=v;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},pd=v.object({type:v.literal(`message`),id:v.string().nullish(),model:v.string().nullish(),content:v.array(v.discriminatedUnion(`type`,[v.object({type:v.literal(`text`),text:v.string(),citations:v.array(ld).optional()}),v.object({type:v.literal(`thinking`),thinking:v.string(),signature:v.string()}),v.object({type:v.literal(`redacted_thinking`),data:v.string()}),v.object({type:v.literal(`tool_use`),id:v.string(),name:v.string(),input:v.unknown()}),v.object({type:v.literal(`server_tool_use`),id:v.string(),name:v.string(),input:v.record(v.string(),v.unknown()).nullish()}),v.object({type:v.literal(`web_search_tool_result`),tool_use_id:v.string(),content:v.union([v.array(v.object({type:v.literal(`web_search_result`),url:v.string(),title:v.string(),encrypted_content:v.string(),page_age:v.string().nullish()})),v.object({type:v.literal(`web_search_tool_result_error`),error_code:v.string()})])}),v.object({type:v.literal(`code_execution_tool_result`),tool_use_id:v.string(),content:v.union([v.object({type:v.literal(`code_execution_result`),stdout:v.string(),stderr:v.string(),return_code:v.number()}),v.object({type:v.literal(`code_execution_tool_result_error`),error_code:v.string()})])})])),stop_reason:v.string().nullish(),usage:v.looseObject({input_tokens:v.number(),output_tokens:v.number(),cache_creation_input_tokens:v.number().nullish(),cache_read_input_tokens:v.number().nullish()})}),md=v.discriminatedUnion(`type`,[v.object({type:v.literal(`message_start`),message:v.object({id:v.string().nullish(),model:v.string().nullish(),usage:v.looseObject({input_tokens:v.number(),output_tokens:v.number(),cache_creation_input_tokens:v.number().nullish(),cache_read_input_tokens:v.number().nullish()})})}),v.object({type:v.literal(`content_block_start`),index:v.number(),content_block:v.discriminatedUnion(`type`,[v.object({type:v.literal(`text`),text:v.string()}),v.object({type:v.literal(`thinking`),thinking:v.string()}),v.object({type:v.literal(`tool_use`),id:v.string(),name:v.string()}),v.object({type:v.literal(`redacted_thinking`),data:v.string()}),v.object({type:v.literal(`server_tool_use`),id:v.string(),name:v.string(),input:v.record(v.string(),v.unknown()).nullish()}),v.object({type:v.literal(`web_search_tool_result`),tool_use_id:v.string(),content:v.union([v.array(v.object({type:v.literal(`web_search_result`),url:v.string(),title:v.string(),encrypted_content:v.string(),page_age:v.string().nullish()})),v.object({type:v.literal(`web_search_tool_result_error`),error_code:v.string()})])}),v.object({type:v.literal(`code_execution_tool_result`),tool_use_id:v.string(),content:v.union([v.object({type:v.literal(`code_execution_result`),stdout:v.string(),stderr:v.string(),return_code:v.number()}),v.object({type:v.literal(`code_execution_tool_result_error`),error_code:v.string()})])})])}),v.object({type:v.literal(`content_block_delta`),index:v.number(),delta:v.discriminatedUnion(`type`,[v.object({type:v.literal(`input_json_delta`),partial_json:v.string()}),v.object({type:v.literal(`text_delta`),text:v.string()}),v.object({type:v.literal(`thinking_delta`),thinking:v.string()}),v.object({type:v.literal(`signature_delta`),signature:v.string()}),v.object({type:v.literal(`citations_delta`),citation:ld})])}),v.object({type:v.literal(`content_block_stop`),index:v.number()}),v.object({type:v.literal(`error`),error:v.object({type:v.string(),message:v.string()})}),v.object({type:v.literal(`message_delta`),delta:v.object({stop_reason:v.string().nullish()}),usage:v.object({output_tokens:v.number()})}),v.object({type:v.literal(`message_stop`)}),v.object({type:v.literal(`ping`)})]),hd=v.object({signature:v.string().optional(),redactedData:v.string().optional()}),gd=bi({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:_.object({command:_.string(),restart:_.boolean().optional()})}),_d=bi({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:_.object({command:_.string(),restart:_.boolean().optional()})}),vd=bi({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:v.object({action:v.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:v.array(v.number().int()).optional(),text:v.string().optional()})}),yd=bi({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:v.object({action:v.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:v.tuple([v.number().int(),v.number().int()]).optional(),duration:v.number().optional(),scroll_amount:v.number().optional(),scroll_direction:v.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:v.tuple([v.number().int(),v.number().int()]).optional(),text:v.string().optional()})}),bd=bi({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:v.object({command:v.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:v.string(),file_text:v.string().optional(),insert_line:v.number().int().optional(),new_str:v.string().optional(),old_str:v.string().optional(),view_range:v.array(v.number().int()).optional()})}),xd=bi({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:v.object({command:v.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:v.string(),file_text:v.string().optional(),insert_line:v.number().int().optional(),new_str:v.string().optional(),old_str:v.string().optional(),view_range:v.array(v.number().int()).optional()})}),Sd=bi({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:v.object({command:v.enum([`view`,`create`,`str_replace`,`insert`]),path:v.string(),file_text:v.string().optional(),insert_line:v.number().int().optional(),new_str:v.string().optional(),old_str:v.string().optional(),view_range:v.array(v.number().int()).optional()})}),Cd={bash_20241022:gd,bash_20250124:_d,codeExecution_20250522:rd,computer_20241022:vd,computer_20250124:yd,textEditor_20241022:bd,textEditor_20250124:xd,textEditor_20250429:Sd,webSearch_20250305:Qu};function wd(e={}){var t;let n=(t=Ra(e.baseURL))??`https://api.anthropic.com/v1`,r=()=>({"anthropic-version":`2023-06-01`,"x-api-key":Zr({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers}),i=t=>{var i;return new fd(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:(i=e.generateId)??K,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new vr({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new vr({modelId:e,modelType:`imageModel`})},a.tools=Cd,a}wd();var Td=v.object({error:v.object({code:v.number().nullable(),message:v.string(),status:v.string()})}),Ed=Ci({errorSchema:Td,errorToMessage:e=>e.error.message}),Dd=v.object({outputDimensionality:v.number().optional(),taskType:v.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Od=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await q({provider:`google`,providerOptions:r,schema:Dd});if(e.length>this.maxEmbeddingsPerCall)throw new Cr({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=G(await Si(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await J({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Ed,successfulResponseHandler:Y(Ad),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await J({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Ed,successfulResponseHandler:Y(kd),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},kd=v.object({embeddings:v.array(v.object({values:v.array(v.number())}))}),Ad=v.object({embedding:v.object({values:v.array(v.number())})});function jd(e){if(e==null||Md(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=jd(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(jd):jd(a)),o&&(p.allOf=o.map(jd)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=jd(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(jd),p.nullable=!0}else p.anyOf=s.map(jd);return c&&(p.oneOf=c.map(jd)),d!==void 0&&(p.minLength=d),p}function Md(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Nd(e,t){var n;let r=[],i=[],a=!0,o=(n=t?.isGemmaModel)??!1;for(let{role:t,content:n}of e)switch(t){case`system`:if(!a)throw new W({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:n});break;case`user`:{a=!1;let e=[];for(let t of n)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:La(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:n.map(e=>{var t,n,r,i,a,o;switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:(n=(t=e.providerOptions)?.google)?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:(i=(r=e.providerOptions)?.google)?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new W({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new W({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:La(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:(o=(a=e.providerOptions)?.google)?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of n){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
47
-
48
- `);i[0].parts.unshift({text:e+`
49
-
50
- `})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function Pd(e){return e.includes(`/`)?e:`models/${e}`}var Fd=v.object({responseModalities:v.array(v.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:v.object({thinkingBudget:v.number().optional(),includeThoughts:v.boolean().optional()}).optional(),cachedContent:v.string().optional(),structuredOutputs:v.boolean().optional(),safetySettings:v.array(v.object({category:v.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:v.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:v.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:v.boolean().optional(),labels:v.record(v.string(),v.string()).optional()});function Id({tools:e,toolChoice:t,modelId:n}){var r;e=e?.length?e:void 0;let i=[],a=n.includes(`gemini-2`),o=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let s=e.some(e=>e.type===`function`),c=e.some(e=>e.type===`provider-defined`);if(s&&c&&i.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),c){let t={},n=e.filter(e=>e.type===`provider-defined`);return n.forEach(e=>{switch(e.id){case`google.google_search`:a?t.googleSearch={}:o?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:a?t.urlContext={}:i.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:a?t.codeExecution={}:i.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:i.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}let l=[];for(let t of e)switch(t.type){case`function`:l.push({name:t.name,description:(r=t.description)??``,parameters:jd(t.inputSchema)});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:i};let u=t.type;switch(u){case`auto`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:i};case`none`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:i};case`tool`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:{let e=u;throw new W({functionality:`tool choice type: ${e}`})}}}function Ld({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var Rd=v.object({web:v.object({uri:v.string(),title:v.string()}).nullish(),retrievedContext:v.object({uri:v.string(),title:v.string()}).nullish()}),zd=v.object({webSearchQueries:v.array(v.string()).nullish(),retrievalQueries:v.array(v.string()).nullish(),searchEntryPoint:v.object({renderedContent:v.string()}).nullish(),groundingChunks:v.array(Rd).nullish(),groundingSupports:v.array(v.object({segment:v.object({startIndex:v.number().nullish(),endIndex:v.number().nullish(),text:v.string().nullish()}),segment_text:v.string().nullish(),groundingChunkIndices:v.array(v.number()).nullish(),supportChunkIndices:v.array(v.number()).nullish(),confidenceScores:v.array(v.number()).nullish(),confidenceScore:v.array(v.number()).nullish()})).nullish(),retrievalMetadata:v.union([v.object({webDynamicRetrievalScore:v.number()}),v.object({})]).nullish()}),Bd=bi({id:`google.google_search`,name:`google_search`,inputSchema:v.object({mode:v.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:v.number().default(1)})}),Vd=v.object({retrievedUrl:v.string(),urlRetrievalStatus:v.string()}),Hd=v.object({urlMetadata:v.array(Vd)}),Ud=bi({id:`google.url_context`,name:`url_context`,inputSchema:v.object({})}),Wd=class{constructor(e,t){this.specificationVersion=`v2`;var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)??K}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)?.call(e))??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m;let h=[],g=await q({provider:`google`,providerOptions:f,schema:Fd});(p=g?.thinkingConfig)?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&h.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:v,systemInstruction:y}=Nd(e,{isGemmaModel:_}),{tools:b,toolConfig:x,toolWarnings:S}=Id({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&((m=g?.structuredOutputs)??!0)?jd(c.schema):void 0,...g?.audioTimestamp&&{audioTimestamp:g.audioTimestamp},responseModalities:g?.responseModalities,thinkingConfig:g?.thinkingConfig},contents:v,systemInstruction:_?void 0:y,safetySettings:g?.safetySettings,tools:b,toolConfig:x,cachedContent:g?.cachedContent,labels:g?.labels},warnings:[...h,...S]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f;let{args:p,warnings:m}=await this.getArgs(e),h=JSON.stringify(p),g=G(await Si(this.config.headers),e.headers),{responseHeaders:_,value:v,rawValue:y}=await J({url:`${this.config.baseURL}/${Pd(this.modelId)}:generateContent`,headers:g,body:p,failedResponseHandler:Ed,successfulResponseHandler:Y(Zd),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.candidates[0],x=[],S=(n=(t=b.content)?.parts)??[],C=v.usageMetadata,w;for(let e of S)if(`executableCode`in e&&(r=e.executableCode)?.code){let t=this.config.generateId();w=t,x.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(x.push({type:`tool-result`,toolCallId:w,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),w=void 0):`text`in e&&e.text!=null&&e.text.length>0?x.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?x.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&x.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let T=(i=qd({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))??[];for(let e of T)x.push(e);return{content:x,finishReason:Ld({finishReason:b.finishReason,hasToolCalls:x.some(e=>e.type===`tool-call`)}),usage:{inputTokens:(a=C?.promptTokenCount)??void 0,outputTokens:(o=C?.candidatesTokenCount)??void 0,totalTokens:(s=C?.totalTokenCount)??void 0,reasoningTokens:(c=C?.thoughtsTokenCount)??void 0,cachedInputTokens:(l=C?.cachedContentTokenCount)??void 0},warnings:m,providerMetadata:{google:{groundingMetadata:(u=b.groundingMetadata)??null,urlContextMetadata:(d=b.urlContextMetadata)??null,safetyRatings:(f=b.safetyRatings)??null,usageMetadata:C??null}},request:{body:h},response:{headers:_,body:y}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=G(await Si(this.config.headers),e.headers),{responseHeaders:a,value:o}=await J({url:`${this.config.baseURL}/${Pd(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Ed,successfulResponseHandler:wi(Qd),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,i,a,o,_,v,y,b,x,S,C;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let w=t.value,T=w.usageMetadata;T!=null&&(c.inputTokens=(r=T.promptTokenCount)??void 0,c.outputTokens=(i=T.candidatesTokenCount)??void 0,c.totalTokens=(a=T.totalTokenCount)??void 0,c.reasoningTokens=(o=T.thoughtsTokenCount)??void 0,c.cachedInputTokens=(_=T.cachedContentTokenCount)??void 0);let E=(v=w.candidates)?.[0];if(E==null)return;let D=E.content,O=qd({groundingMetadata:E.groundingMetadata,generateId:u});if(O!=null)for(let e of O)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(D!=null){let e=(y=D.parts)??[];for(let t of e)if(`executableCode`in t&&(b=t.executableCode)?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Kd(D.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=Gd({parts:D.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}E.finishReason!=null&&(s=Ld({finishReason:E.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:(x=E.groundingMetadata)??null,urlContextMetadata:(S=E.urlContextMetadata)??null,safetyRatings:(C=E.safetyRatings)??null}},T!=null&&(l.google.usageMetadata=T))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function Gd({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Kd(e){return e?.filter(e=>`inlineData`in e)}function qd({groundingMetadata:e,generateId:t}){var n;return(n=e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var Jd=v.object({parts:v.array(v.union([v.object({functionCall:v.object({name:v.string(),args:v.unknown()}),thoughtSignature:v.string().nullish()}),v.object({inlineData:v.object({mimeType:v.string(),data:v.string()})}),v.object({executableCode:v.object({language:v.string(),code:v.string()}).nullish(),codeExecutionResult:v.object({outcome:v.string(),output:v.string()}).nullish(),text:v.string().nullish(),thought:v.boolean().nullish(),thoughtSignature:v.string().nullish()})])).nullish()}),Yd=v.object({category:v.string().nullish(),probability:v.string().nullish(),probabilityScore:v.number().nullish(),severity:v.string().nullish(),severityScore:v.number().nullish(),blocked:v.boolean().nullish()}),Xd=v.object({cachedContentTokenCount:v.number().nullish(),thoughtsTokenCount:v.number().nullish(),promptTokenCount:v.number().nullish(),candidatesTokenCount:v.number().nullish(),totalTokenCount:v.number().nullish()}),Zd=v.object({candidates:v.array(v.object({content:Jd.nullish().or(v.object({}).strict()),finishReason:v.string().nullish(),safetyRatings:v.array(Yd).nullish(),groundingMetadata:zd.nullish(),urlContextMetadata:Hd.nullish()})),usageMetadata:Xd.nullish()}),Qd=v.object({candidates:v.array(v.object({content:Jd.nullish(),finishReason:v.string().nullish(),safetyRatings:v.array(Yd).nullish(),groundingMetadata:zd.nullish(),urlContextMetadata:Hd.nullish()})).nullish(),usageMetadata:Xd.nullish()}),$d=xi({id:`google.code_execution`,name:`code_execution`,inputSchema:v.object({language:v.string().describe(`The programming language of the code.`),code:v.string().describe(`The code to be executed.`)}),outputSchema:v.object({outcome:v.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:v.string().describe(`The output from the code execution.`)})}),ef={googleSearch:Bd,urlContext:Ud,codeExecution:$d},tf=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=this.settings.maxImagesPerCall)??4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;let{prompt:i,n:a=1,size:o=`1024x1024`,aspectRatio:s=`1:1`,seed:c,providerOptions:l,headers:u,abortSignal:d}=e,f=[];o!=null&&f.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),c!=null&&f.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await q({provider:`google`,providerOptions:l,schema:rf}),m=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,h={sampleCount:a};s!=null&&(h.aspectRatio=s),p&&Object.assign(h,p);let g={instances:[{prompt:i}],parameters:h},{responseHeaders:_,value:v}=await J({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:G(await Si(this.config.headers),u),body:g,failedResponseHandler:Ed,successfulResponseHandler:Y(nf),abortSignal:d,fetch:this.config.fetch});return{images:v.predictions.map(e=>e.bytesBase64Encoded),warnings:f??[],providerMetadata:{google:{images:v.predictions.map(e=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:_}}}},nf=v.object({predictions:v.array(v.object({bytesBase64Encoded:v.string()})).default([])}),rf=v.object({personGeneration:v.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:v.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function af(e={}){var t;let n=(t=Ra(e.baseURL))??`https://generativelanguage.googleapis.com/v1beta`,r=()=>({"x-goog-api-key":Zr({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers}),i=t=>{var i;return new Wd(t,{provider:`google.generative-ai`,baseURL:n,headers:r,generateId:(i=e.generateId)??K,supportedUrls:()=>({"*":[RegExp(`^${n}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch})},a=t=>new Od(t,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),o=(t,i={})=>new tf(t,i,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),s=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return s.languageModel=i,s.chat=i,s.generativeAI=i,s.embedding=a,s.textEmbedding=a,s.textEmbeddingModel=a,s.image=o,s.imageModel=o,s.tools=ef,s}af();var sf=v.object({error:v.object({message:v.string(),type:v.string().nullish(),param:v.any().nullish(),code:v.union([v.string(),v.number()]).nullish()})}),cf=Ci({errorSchema:sf,errorToMessage:e=>e.error.message});function lf({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{var n,r,i;switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${La(e.data)}`,detail:(r=(n=e.providerOptions)?.openai)?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new W({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:La(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:La(e.data),format:`mp3`}};default:throw new W({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new W({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:(i=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${La(e.data)}`}}}else throw new W({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function uf({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function df(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`unknown`}}var ff=v.object({logitBias:v.record(v.coerce.number(),v.number()).optional(),logprobs:v.union([v.boolean(),v.number()]).optional(),parallelToolCalls:v.boolean().optional(),user:v.string().optional(),reasoningEffort:v.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:v.number().optional(),store:v.boolean().optional(),metadata:v.record(v.string().max(64),v.string().max(512)).optional(),prediction:v.record(v.string(),v.any()).optional(),structuredOutputs:v.boolean().optional(),serviceTier:v.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:v.boolean().optional(),textVerbosity:v.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:v.string().optional(),safetyIdentifier:v.string().optional()}),pf=v.object({key:v.string(),type:v.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:v.union([v.string(),v.number(),v.boolean()])}),mf=v.object({type:v.enum([`and`,`or`]),filters:v.array(v.union([pf,v.lazy(()=>mf)]))}),hf=v.union([pf,mf]),gf=v.object({vectorStoreIds:v.array(v.string()).optional(),maxNumResults:v.number().optional(),ranking:v.object({ranker:v.enum([`auto`,`default-2024-08-21`]).optional()}).optional(),filters:hf.optional()}),_f=bi({id:`openai.file_search`,name:`file_search`,inputSchema:v.object({query:v.string()})}),vf=v.object({searchContextSize:v.enum([`low`,`medium`,`high`]).optional(),userLocation:v.object({type:v.literal(`approximate`),country:v.string().optional(),city:v.string().optional(),region:v.string().optional(),timezone:v.string().optional()}).optional()}),yf=bi({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:v.object({action:v.discriminatedUnion(`type`,[v.object({type:v.literal(`search`),query:v.string().nullish()}),v.object({type:v.literal(`open_page`),url:v.string()}),v.object({type:v.literal(`find`),url:v.string(),pattern:v.string()})]).nullish()})});function bf({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=gf.parse(t.args);a.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=vf.parse(t.args);a.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:{let e=o;throw new W({functionality:`tool choice type: ${e}`})}}}var xf=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m,h,g;let _=[],v=(p=await q({provider:`openai`,providerOptions:f,schema:ff}))??{},y=(m=v.structuredOutputs)??!0;i!=null&&_.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!y&&_.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:b,warnings:x}=lf({prompt:e,systemMessageMode:Of(this.modelId)});_.push(...x);let S=(h=v.strictJsonSchema)??!1,C={model:this.modelId,logit_bias:v.logitBias,logprobs:v.logprobs===!0||typeof v.logprobs==`number`?!0:void 0,top_logprobs:typeof v.logprobs==`number`?v.logprobs:typeof v.logprobs==`boolean`&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?y&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:S,name:(g=c.name)??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,safety_identifier:v.safetyIdentifier,messages:b};Tf(this.modelId)?(C.temperature!=null&&(C.temperature=void 0,_.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),C.top_p!=null&&(C.top_p=void 0,_.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),C.frequency_penalty!=null&&(C.frequency_penalty=void 0,_.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),C.presence_penalty!=null&&(C.presence_penalty=void 0,_.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),C.logit_bias!=null&&(C.logit_bias=void 0,_.push({type:`other`,message:`logitBias is not supported for reasoning models`})),C.logprobs!=null&&(C.logprobs=void 0,_.push({type:`other`,message:`logprobs is not supported for reasoning models`})),C.top_logprobs!=null&&(C.top_logprobs=void 0,_.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),C.max_tokens!=null&&(C.max_completion_tokens??=C.max_tokens,C.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&C.temperature!=null&&(C.temperature=void 0,_.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),v.serviceTier===`flex`&&!Ef(this.modelId)&&(_.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),C.service_tier=void 0),v.serviceTier===`priority`&&!Df(this.modelId)&&(_.push({type:`unsupported-setting`,setting:`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`}),C.service_tier=void 0);let{tools:w,toolChoice:T,toolWarnings:E}=bf({tools:u,toolChoice:d,structuredOutputs:y,strictJsonSchema:S});return{args:{...C,tools:w,tool_choice:T},warnings:[..._,...E]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f,p,m;let{args:h,warnings:g}=await this.getArgs(e),{responseHeaders:_,value:v,rawValue:y}=await J({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:h,failedResponseHandler:cf,successfulResponseHandler:Y(Cf),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.choices[0],x=[],S=b.message.content;S!=null&&S.length>0&&x.push({type:`text`,text:S});for(let e of(t=b.message.tool_calls)??[])x.push({type:`tool-call`,toolCallId:(n=e.id)??K(),toolName:e.function.name,input:e.function.arguments});for(let e of(r=b.message.annotations)??[])x.push({type:`source`,sourceType:`url`,id:K(),url:e.url,title:e.title});let C=(i=v.usage)?.completion_tokens_details,w=(a=v.usage)?.prompt_tokens_details,T={openai:{}};return C?.accepted_prediction_tokens!=null&&(T.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(T.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),(o=b.logprobs)?.content!=null&&(T.openai.logprobs=b.logprobs.content),{content:x,finishReason:df(b.finish_reason),usage:{inputTokens:(c=(s=v.usage)?.prompt_tokens)??void 0,outputTokens:(u=(l=v.usage)?.completion_tokens)??void 0,totalTokens:(f=(d=v.usage)?.total_tokens)??void 0,reasoningTokens:(p=C?.reasoning_tokens)??void 0,cachedInputTokens:(m=w?.cached_tokens)??void 0},request:{body:h},response:{...uf(v),headers:_,body:y},warnings:g,providerMetadata:T}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await J({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:r,failedResponseHandler:cf,successfulResponseHandler:wi(wf),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,i,a,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,ee,te;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let j=t.value;if(`error`in j){s=`error`,n.enqueue({type:`error`,error:j.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...uf(j)})),j.usage!=null&&(c.inputTokens=(r=j.usage.prompt_tokens)??void 0,c.outputTokens=(i=j.usage.completion_tokens)??void 0,c.totalTokens=(a=j.usage.total_tokens)??void 0,c.reasoningTokens=(p=(f=j.usage.completion_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(h=(m=j.usage.prompt_tokens_details)?.cached_tokens)??void 0,(g=j.usage.completion_tokens_details)?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=(_=j.usage.completion_tokens_details)?.accepted_prediction_tokens),(v=j.usage.completion_tokens_details)?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=(y=j.usage.completion_tokens_details)?.rejected_prediction_tokens));let M=j.choices[0];if(M?.finish_reason!=null&&(s=df(M.finish_reason)),(b=M?.logprobs)?.content!=null&&(d.openai.logprobs=M.logprobs.content),M?.delta==null)return;let N=M.delta;if(N.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:N.content})),N.tool_calls!=null)for(let e of N.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new Yn({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new Yn({data:e,message:`Expected 'id' to be a string.`});if((x=e.function)?.name==null)throw new Yn({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:(S=e.function.arguments)??``},hasFinished:!1};let r=o[t];(C=r.function)?.name!=null&&(w=r.function)?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:(T=r.id)??K(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];if(r.hasFinished)continue;(E=e.function)?.arguments!=null&&(r.function.arguments+=(O=(D=e.function)?.arguments)??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:(k=e.function.arguments)??``}),(A=r.function)?.name!=null&&(ee=r.function)?.arguments!=null&&mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:(te=r.id)??K(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0)}if(N.annotations!=null)for(let e of N.annotations)n.enqueue({type:`source`,sourceType:`url`,id:K(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Sf=v.object({prompt_tokens:v.number().nullish(),completion_tokens:v.number().nullish(),total_tokens:v.number().nullish(),prompt_tokens_details:v.object({cached_tokens:v.number().nullish()}).nullish(),completion_tokens_details:v.object({reasoning_tokens:v.number().nullish(),accepted_prediction_tokens:v.number().nullish(),rejected_prediction_tokens:v.number().nullish()}).nullish()}).nullish(),Cf=v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({message:v.object({role:v.literal(`assistant`).nullish(),content:v.string().nullish(),tool_calls:v.array(v.object({id:v.string().nullish(),type:v.literal(`function`),function:v.object({name:v.string(),arguments:v.string()})})).nullish(),annotations:v.array(v.object({type:v.literal(`url_citation`),start_index:v.number(),end_index:v.number(),url:v.string(),title:v.string()})).nullish()}),index:v.number(),logprobs:v.object({content:v.array(v.object({token:v.string(),logprob:v.number(),top_logprobs:v.array(v.object({token:v.string(),logprob:v.number()}))})).nullish()}).nullish(),finish_reason:v.string().nullish()})),usage:Sf}),wf=v.union([v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({delta:v.object({role:v.enum([`assistant`]).nullish(),content:v.string().nullish(),tool_calls:v.array(v.object({index:v.number(),id:v.string().nullish(),type:v.literal(`function`).nullish(),function:v.object({name:v.string().nullish(),arguments:v.string().nullish()})})).nullish(),annotations:v.array(v.object({type:v.literal(`url_citation`),start_index:v.number(),end_index:v.number(),url:v.string(),title:v.string()})).nullish()}).nullish(),logprobs:v.object({content:v.array(v.object({token:v.string(),logprob:v.number(),top_logprobs:v.array(v.object({token:v.string(),logprob:v.number()}))})).nullish()}).nullish(),finish_reason:v.string().nullish(),index:v.number()})),usage:Sf}),sf]);function Tf(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Ef(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Df(e){return 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`)}function Of(e){var t,n;return Tf(e)?(n=(t=kf[e])?.systemMessageMode)??`developer`:`system`}var kf={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function Af({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
51
-
52
- `,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new Wn({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
53
- ${e}
54
-
55
- `;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new W({functionality:`tool-call messages`})}}).join(``);r+=`${n}:
56
- ${e}
57
-
58
- `;break}case`tool`:throw new W({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
59
- `,{prompt:r,stopSequences:[`
60
- ${t}:`]}}function jf({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Mf(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`unknown`}}var Nf=v.object({echo:v.boolean().optional(),logitBias:v.record(v.string(),v.number()).optional(),suffix:v.string().optional(),user:v.string().optional(),logprobs:v.union([v.boolean(),v.number()]).optional()}),Pf=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await q({provider:`openai`,providerOptions:f,schema:Nf}),...await q({provider:this.providerOptionsName,providerOptions:f,schema:Nf})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=Af({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await J({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:i,failedResponseHandler:cf,successfulResponseHandler:Y(If),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:`text`,text:l.text}],usage:{inputTokens:(t=s.usage)?.prompt_tokens,outputTokens:(n=s.usage)?.completion_tokens,totalTokens:(r=s.usage)?.total_tokens},finishReason:Mf(l.finish_reason),request:{body:i},response:{...jf(s),headers:o,body:c},providerMetadata:u,warnings:a}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await J({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:r,failedResponseHandler:cf,successfulResponseHandler:wi(Lf),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...jf(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Mf(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},Ff=v.object({prompt_tokens:v.number(),completion_tokens:v.number(),total_tokens:v.number()}),If=v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({text:v.string(),finish_reason:v.string(),logprobs:v.object({tokens:v.array(v.string()),token_logprobs:v.array(v.number()),top_logprobs:v.array(v.record(v.string(),v.number())).nullish()}).nullish()})),usage:Ff.nullish()}),Lf=v.union([v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({text:v.string(),finish_reason:v.string().nullish(),index:v.number(),logprobs:v.object({tokens:v.array(v.string()),token_logprobs:v.array(v.number()),top_logprobs:v.array(v.record(v.string(),v.number())).nullish()}).nullish()})),usage:Ff.nullish()}),sf]),Rf=v.object({dimensions:v.number().optional(),user:v.string().optional()}),zf=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new Cr({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await q({provider:`openai`,providerOptions:r,schema:Rf}))??{},{responseHeaders:o,value:s,rawValue:c}=await J({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:G(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:cf,successfulResponseHandler:Y(Bf),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},Bf=v.object({data:v.array(v.object({embedding:v.array(v.number())})),usage:v.object({prompt_tokens:v.number()}).nullish()}),Vf={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Hf=new Set([`gpt-image-1`]),Uf=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=Vf[this.modelId])??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d;let f=[];r!=null&&f.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&f.push({type:`unsupported-setting`,setting:`seed`});let p=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:m,responseHeaders:h}=await J({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:G(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},...Hf.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:cf,successfulResponseHandler:Y(Wf),abortSignal:s,fetch:this.config.fetch});return{images:m.data.map(e=>e.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:m.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},Wf=v.object({data:v.array(v.object({b64_json:v.string(),revised_prompt:v.string().optional()}))}),Gf=v.object({container:v.union([v.string(),v.object({fileIds:v.array(v.string()).optional()})]).optional()}),Kf=bi({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:v.object({})}),qf=(e={})=>Kf(e),Jf=v.object({filters:v.object({allowedDomains:v.array(v.string()).optional()}).optional(),searchContextSize:v.enum([`low`,`medium`,`high`]).optional(),userLocation:v.object({type:v.literal(`approximate`),country:v.string().optional(),city:v.string().optional(),region:v.string().optional(),timezone:v.string().optional()}).optional()}),Yf=bi({id:`openai.web_search`,name:`web_search`,inputSchema:v.object({action:v.discriminatedUnion(`type`,[v.object({type:v.literal(`search`),query:v.string().nullish()}),v.object({type:v.literal(`open_page`),url:v.string()}),v.object({type:v.literal(`find`),url:v.string(),pattern:v.string()})]).nullish()})}),Xf=(e={})=>Yf(e),Zf={codeInterpreter:qf,fileSearch:_f,webSearchPreview:yf,webSearch:Xf};function Qf(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function $f({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,a,o,s,c;let l=[],u=[];for(let{role:d,content:f}of e)switch(d){case`system`:switch(t){case`system`:l.push({role:`system`,content:f});break;case`developer`:l.push({role:`developer`,content:f});break;case`remove`:u.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:l.push({role:`user`,content:f.map((e,t)=>{var r,i,a;switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Qf(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${La(e.data)}`},detail:(i=(r=e.providerOptions)?.openai)?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Qf(e.data,n)?{file_id:e.data}:{filename:(a=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${La(e.data)}`}};else throw new W({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={};for(let t of f)switch(t.type){case`text`:l.push({role:`assistant`,content:[{type:`output_text`,text:t.text}],id:(a=(i=(r=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-call`:if(t.providerExecuted)break;l.push({type:`function_call`,call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:(c=(s=(o=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-result`:u.push({type:`other`,message:`tool result parts in assistant messages are not supported for OpenAI responses`});break;case`reasoning`:{let n=await q({provider:`openai`,providerOptions:t.providerOptions,schema:ep}),r=n?.itemId;if(r!=null){let i=e[r],a=[];t.text.length>0?a.push({type:`summary_text`,text:t.text}):i!==void 0&&u.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),i===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:n?.reasoningEncryptedContent,summary:a},l.push(e[r])):i.summary.push(...a)}else u.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case`tool`:for(let e of f){let t=e.output,n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}l.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=d;throw Error(`Unsupported role: ${e}`)}}return{messages:l,warnings:u}}var ep=v.object({itemId:v.string().nullish(),reasoningEncryptedContent:v.string().nullish()});function tp({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`:`unknown`}}function np({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=gf.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=vf.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Jf.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=Gf.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:{let e=a;throw new W({functionality:`tool choice type: ${e}`})}}}var rp=v.object({type:v.literal(`web_search_call`),id:v.string(),status:v.string(),action:v.discriminatedUnion(`type`,[v.object({type:v.literal(`search`),query:v.string().nullish()}),v.object({type:v.literal(`open_page`),url:v.string()}),v.object({type:v.literal(`find`),url:v.string(),pattern:v.string()})]).nullish()}),ip=20,ap=v.array(v.object({token:v.string(),logprob:v.number(),top_logprobs:v.array(v.object({token:v.string(),logprob:v.number()}))})),op=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){var p,m,h;let g=[],_=jp(this.modelId);i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`});let{messages:v,warnings:y}=await $f({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await q({provider:`openai`,providerOptions:l,schema:Mp}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?ip:void 0;S=C?Array.isArray(S)?[...S,`message.output_text.logprobs`]:[`message.output_text.logprobs`]:S;let w=(m=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`)))?.name;S=w?Array.isArray(S)?[...S,`web_search_call.action.sources`]:[`web_search_call.action.sources`]:S;let T={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||b?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:x,name:(h=f.name)??`response`,description:f.description,schema:f.schema}},...b?.textVerbosity&&{verbosity:b.textVerbosity}}},metadata:b?.metadata,parallel_tool_calls:b?.parallelToolCalls,previous_response_id:b?.previousResponseId,store:b?.store,user:b?.user,instructions:b?.instructions,service_tier:b?.serviceTier,include:S,prompt_cache_key:b?.promptCacheKey,safety_identifier:b?.safetyIdentifier,top_logprobs:C,..._.isReasoningModel&&(b?.reasoningEffort!=null||b?.reasoningSummary!=null)&&{reasoning:{...b?.reasoningEffort!=null&&{effort:b.reasoningEffort},...b?.reasoningSummary!=null&&{summary:b.reasoningSummary}}},..._.requiredAutoTruncation&&{truncation:`auto`}};_.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),T.top_p!=null&&(T.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(b?.reasoningEffort!=null&&g.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),b?.reasoningSummary!=null&&g.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),b?.serviceTier===`flex`&&!_.supportsFlexProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete T.service_tier),b?.serviceTier===`priority`&&!_.supportsPriorityProcessing&&(g.push({type:`unsupported-setting`,setting:`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 T.service_tier);let{tools:E,toolChoice:D,toolWarnings:O}=np({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_;let{args:y,warnings:b,webSearchToolName:x}=await this.getArgs(e),S=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:C,value:w,rawValue:T}=await J({url:S,headers:G(this.config.headers(),e.headers),body:y,failedResponseHandler:cf,successfulResponseHandler:Y(v.object({id:v.string(),created_at:v.number(),error:v.object({code:v.string(),message:v.string()}).nullish(),model:v.string(),output:v.array(v.discriminatedUnion(`type`,[v.object({type:v.literal(`message`),role:v.literal(`assistant`),id:v.string(),content:v.array(v.object({type:v.literal(`output_text`),text:v.string(),logprobs:ap.nullish(),annotations:v.array(v.discriminatedUnion(`type`,[v.object({type:v.literal(`url_citation`),start_index:v.number(),end_index:v.number(),url:v.string(),title:v.string()}),v.object({type:v.literal(`file_citation`),file_id:v.string(),filename:v.string().nullish(),index:v.number().nullish(),start_index:v.number().nullish(),end_index:v.number().nullish(),quote:v.string().nullish()}),v.object({type:v.literal(`container_file_citation`)})]))}))}),v.object({type:v.literal(`code_interpreter_call`)}),v.object({type:v.literal(`function_call`),call_id:v.string(),name:v.string(),arguments:v.string(),id:v.string()}),rp,v.object({type:v.literal(`computer_call`),id:v.string(),status:v.string().optional()}),v.object({type:v.literal(`file_search_call`),id:v.string(),status:v.string().optional(),queries:v.array(v.string()).nullish(),results:v.array(v.object({attributes:v.object({file_id:v.string(),filename:v.string(),score:v.number(),text:v.string()})})).nullish()}),v.object({type:v.literal(`reasoning`),id:v.string(),encrypted_content:v.string().nullish(),summary:v.array(v.object({type:v.literal(`summary_text`),text:v.string()}))})])),service_tier:v.string().nullish(),incomplete_details:v.object({reason:v.string()}).nullable(),usage:sp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(w.error)throw new U({message:w.error.message,url:S,requestBodyValues:y,statusCode:400,responseHeaders:C,responseBody:T,isRetryable:!1});let E=[],D=[],O=!1;for(let p of w.output)switch(p.type){case`reasoning`:p.summary.length===0&&p.summary.push({type:`summary_text`,text:``});for(let e of p.summary)E.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:p.id,reasoningEncryptedContent:(t=p.encrypted_content)??null}}});break;case`message`:for(let t of p.content){(r=(n=e.providerOptions)?.openai)?.logprobs&&t.logprobs&&D.push(t.logprobs),E.push({type:`text`,text:t.text,providerMetadata:{openai:{itemId:p.id}}});for(let e of t.annotations)e.type===`url_citation`?E.push({type:`source`,sourceType:`url`,id:(o=(a=(i=this.config).generateId)?.call(i))??K(),url:e.url,title:e.title}):e.type===`file_citation`&&E.push({type:`source`,sourceType:`document`,id:(l=(c=(s=this.config).generateId)?.call(s))??K(),mediaType:`text/plain`,title:(d=(u=e.quote)??e.filename)??`Document`,filename:(f=e.filename)??e.file_id})}break;case`function_call`:O=!0,E.push({type:`tool-call`,toolCallId:p.call_id,toolName:p.name,input:p.arguments,providerMetadata:{openai:{itemId:p.id}}});break;case`web_search_call`:E.push({type:`tool-call`,toolCallId:p.id,toolName:x??`web_search`,input:JSON.stringify({action:p.action}),providerExecuted:!0}),E.push({type:`tool-result`,toolCallId:p.id,toolName:x??`web_search`,result:{status:p.status},providerExecuted:!0});break;case`computer_call`:E.push({type:`tool-call`,toolCallId:p.id,toolName:`computer_use`,input:``,providerExecuted:!0}),E.push({type:`tool-result`,toolCallId:p.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:p.status||`completed`},providerExecuted:!0});break;case`file_search_call`:E.push({type:`tool-call`,toolCallId:p.id,toolName:`file_search`,input:``,providerExecuted:!0}),E.push({type:`tool-result`,toolCallId:p.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:p.status||`completed`,...p.queries&&{queries:p.queries},...p.results&&{results:p.results}},providerExecuted:!0});break}let k={openai:{responseId:w.id}};return D.length>0&&(k.openai.logprobs=D),typeof w.service_tier==`string`&&(k.openai.serviceTier=w.service_tier),{content:E,finishReason:tp({finishReason:(p=w.incomplete_details)?.reason,hasFunctionCall:O}),usage:{inputTokens:w.usage.input_tokens,outputTokens:w.usage.output_tokens,totalTokens:w.usage.input_tokens+w.usage.output_tokens,reasoningTokens:(h=(m=w.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(_=(g=w.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:y},response:{id:w.id,timestamp:new Date(w.created_at*1e3),modelId:w.model,headers:C,body:T},providerMetadata:k,warnings:b}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await J({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:cf,successfulResponseHandler:wi(vp),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,ee,te,j;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let M=t.value;if(Tp(M))M.item.type===`function_call`?(d[M.output_index]={toolName:M.item.name,toolCallId:M.item.call_id},n.enqueue({type:`tool-input-start`,id:M.item.call_id,toolName:M.item.name})):M.item.type===`web_search_call`?(d[M.output_index]={toolName:r??`web_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:r??`web_search`})):M.item.type===`computer_call`?(d[M.output_index]={toolName:`computer_use`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`computer_use`})):M.item.type===`file_search_call`?(d[M.output_index]={toolName:`file_search`,toolCallId:M.item.id},n.enqueue({type:`tool-input-start`,id:M.item.id,toolName:`file_search`})):M.item.type===`message`?n.enqueue({type:`text-start`,id:M.item.id,providerMetadata:{openai:{itemId:M.item.id}}}):Ep(M)&&(p[M.item.id]={encryptedContent:M.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${M.item.id}:0`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(i=M.item.encrypted_content)??null}}}));else if(bp(M)){if(M.item.type===`function_call`)d[M.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:M.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:M.item.call_id,toolName:M.item.name,input:M.item.arguments,providerMetadata:{openai:{itemId:M.item.id}}});else if(M.item.type===`web_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`web_search`,input:JSON.stringify({action:M.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`web_search`,result:{status:M.item.status},providerExecuted:!0});else if(M.item.type===`computer_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:M.item.status||`completed`},providerExecuted:!0});else if(M.item.type===`file_search_call`)d[M.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:M.item.id}),n.enqueue({type:`tool-call`,toolCallId:M.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:M.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:M.item.status||`completed`,...M.item.queries&&{queries:M.item.queries},...M.item.results&&{results:M.item.results}},providerExecuted:!0});else if(M.item.type===`message`)n.enqueue({type:`text-end`,id:M.item.id});else if(xp(M)){let e=p[M.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${M.item.id}:${t}`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:(a=M.item.encrypted_content)??null}}});delete p[M.item.id]}}else if(wp(M)){let e=d[M.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:M.delta})}else Cp(M)?(u=M.response.id,n.enqueue({type:`response-metadata`,id:M.response.id,timestamp:new Date(M.response.created_at*1e3),modelId:M.response.model})):yp(M)?(n.enqueue({type:`text-delta`,id:M.item_id,delta:M.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&M.logprobs&&l.push(M.logprobs)):Op(M)?M.summary_index>0&&((_=p[M.item_id])==null||_.summaryParts.push(M.summary_index),n.enqueue({type:`reasoning-start`,id:`${M.item_id}:${M.summary_index}`,providerMetadata:{openai:{itemId:M.item_id,reasoningEncryptedContent:(y=(v=p[M.item_id])?.encryptedContent)??null}}})):kp(M)?n.enqueue({type:`reasoning-delta`,id:`${M.item_id}:${M.summary_index}`,delta:M.delta,providerMetadata:{openai:{itemId:M.item_id}}}):Sp(M)?(s=tp({finishReason:(b=M.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=M.response.usage.input_tokens,c.outputTokens=M.response.usage.output_tokens,c.totalTokens=M.response.usage.input_tokens+M.response.usage.output_tokens,c.reasoningTokens=(S=(x=M.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=M.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof M.response.service_tier==`string`&&(m=M.response.service_tier)):Dp(M)?M.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??K(),url:M.annotation.url,title:M.annotation.title}):M.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??K(),mediaType:`text/plain`,title:(te=(ee=M.annotation.quote)??M.annotation.filename)??`Document`,filename:(j=M.annotation.filename)??M.annotation.file_id}):Ap(M)&&n.enqueue({type:`error`,error:M})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},sp=v.object({input_tokens:v.number(),input_tokens_details:v.object({cached_tokens:v.number().nullish()}).nullish(),output_tokens:v.number(),output_tokens_details:v.object({reasoning_tokens:v.number().nullish()}).nullish()}),cp=v.object({type:v.literal(`response.output_text.delta`),item_id:v.string(),delta:v.string(),logprobs:ap.nullish()}),lp=v.object({type:v.literal(`error`),code:v.string(),message:v.string(),param:v.string().nullish(),sequence_number:v.number()}),up=v.object({type:v.enum([`response.completed`,`response.incomplete`]),response:v.object({incomplete_details:v.object({reason:v.string()}).nullish(),usage:sp,service_tier:v.string().nullish()})}),dp=v.object({type:v.literal(`response.created`),response:v.object({id:v.string(),created_at:v.number(),model:v.string(),service_tier:v.string().nullish()})}),fp=v.object({type:v.literal(`response.output_item.added`),output_index:v.number(),item:v.discriminatedUnion(`type`,[v.object({type:v.literal(`message`),id:v.string()}),v.object({type:v.literal(`reasoning`),id:v.string(),encrypted_content:v.string().nullish()}),v.object({type:v.literal(`function_call`),id:v.string(),call_id:v.string(),name:v.string(),arguments:v.string()}),v.object({type:v.literal(`web_search_call`),id:v.string(),status:v.string(),action:v.object({type:v.literal(`search`),query:v.string().optional()}).nullish()}),v.object({type:v.literal(`computer_call`),id:v.string(),status:v.string()}),v.object({type:v.literal(`file_search_call`),id:v.string(),status:v.string(),queries:v.array(v.string()).nullish(),results:v.array(v.object({attributes:v.object({file_id:v.string(),filename:v.string(),score:v.number(),text:v.string()})})).optional()})])}),pp=v.object({type:v.literal(`response.output_item.done`),output_index:v.number(),item:v.discriminatedUnion(`type`,[v.object({type:v.literal(`message`),id:v.string()}),v.object({type:v.literal(`reasoning`),id:v.string(),encrypted_content:v.string().nullish()}),v.object({type:v.literal(`function_call`),id:v.string(),call_id:v.string(),name:v.string(),arguments:v.string(),status:v.literal(`completed`)}),rp,v.object({type:v.literal(`computer_call`),id:v.string(),status:v.literal(`completed`)}),v.object({type:v.literal(`file_search_call`),id:v.string(),status:v.literal(`completed`),queries:v.array(v.string()).nullish(),results:v.array(v.object({attributes:v.object({file_id:v.string(),filename:v.string(),score:v.number(),text:v.string()})})).nullish()})])}),mp=v.object({type:v.literal(`response.function_call_arguments.delta`),item_id:v.string(),output_index:v.number(),delta:v.string()}),hp=v.object({type:v.literal(`response.output_text.annotation.added`),annotation:v.discriminatedUnion(`type`,[v.object({type:v.literal(`url_citation`),url:v.string(),title:v.string()}),v.object({type:v.literal(`file_citation`),file_id:v.string(),filename:v.string().nullish(),index:v.number().nullish(),start_index:v.number().nullish(),end_index:v.number().nullish(),quote:v.string().nullish()})])}),gp=v.object({type:v.literal(`response.reasoning_summary_part.added`),item_id:v.string(),summary_index:v.number()}),_p=v.object({type:v.literal(`response.reasoning_summary_text.delta`),item_id:v.string(),summary_index:v.number(),delta:v.string()}),vp=v.union([cp,up,dp,fp,pp,mp,hp,gp,_p,lp,v.object({type:v.string()}).loose()]);function yp(e){return e.type===`response.output_text.delta`}function bp(e){return e.type===`response.output_item.done`}function xp(e){return bp(e)&&e.item.type===`reasoning`}function Sp(e){return e.type===`response.completed`||e.type===`response.incomplete`}function Cp(e){return e.type===`response.created`}function wp(e){return e.type===`response.function_call_arguments.delta`}function Tp(e){return e.type===`response.output_item.added`}function Ep(e){return Tp(e)&&e.item.type===`reasoning`}function Dp(e){return e.type===`response.output_text.annotation.added`}function Op(e){return e.type===`response.reasoning_summary_part.added`}function kp(e){return e.type===`response.reasoning_summary_text.delta`}function Ap(e){return e.type===`error`}function jp(e){let 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={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Mp=v.object({metadata:v.any().nullish(),parallelToolCalls:v.boolean().nullish(),previousResponseId:v.string().nullish(),store:v.boolean().nullish(),user:v.string().nullish(),reasoningEffort:v.string().nullish(),strictJsonSchema:v.boolean().nullish(),instructions:v.string().nullish(),reasoningSummary:v.string().nullish(),serviceTier:v.enum([`auto`,`flex`,`priority`]).nullish(),include:v.array(v.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:v.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:v.string().nullish(),safetyIdentifier:v.string().nullish(),logprobs:v.union([v.boolean(),v.number().min(1).max(ip)]).optional()}),Np=v.object({instructions:v.string().nullish(),speed:v.number().min(.25).max(4).default(1).nullish()}),Pp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await q({provider:`openai`,providerOptions:o,schema:Np}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t,n,r;let i=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{requestBody:a,warnings:o}=await this.getArgs(e),{value:s,responseHeaders:c,rawValue:l}=await J({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),body:a,failedResponseHandler:cf,successfulResponseHandler:Ti(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:o,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:l}}}},Fp=v.object({include:v.array(v.string()).optional(),language:v.string().optional(),prompt:v.string().optional(),temperature:v.number().min(0).max(1).default(0).optional(),timestampGranularities:v.array(v.enum([`word`,`segment`])).default([`segment`]).optional()}),Ip={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`},Lp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await q({provider:`openai`,providerOptions:n,schema:Fp}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Fa(e)]);a.append(`model`,this.modelId);let s=$r(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={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(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t,n,r,i,a,o,s,c;let l=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{formData:u,warnings:d}=await this.getArgs(e),{value:f,responseHeaders:p,rawValue:m}=await _i({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:G(this.config.headers(),e.headers),formData:u,failedResponseHandler:cf,successfulResponseHandler:Y(Rp),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in Ip?Ip[f.language]:void 0;return{text:f.text,segments:(s=(o=(i=f.segments)?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))??(a=f.words)?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))??[],language:h,durationInSeconds:(c=f.duration)??void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:p,body:m}}}},Rp=v.object({text:v.string(),language:v.string().nullish(),duration:v.number().nullish(),words:v.array(v.object({word:v.string(),start:v.number(),end:v.number()})).nullish(),segments:v.array(v.object({id:v.number(),seek:v.number(),start:v.number(),end:v.number(),text:v.string(),tokens:v.array(v.number()),temperature:v.number(),avg_logprob:v.number(),compression_ratio:v.number(),no_speech_prob:v.number()})).nullish()});function zp(e={}){var t,n;let r=(t=Ra(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Zr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new xf(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new Pf(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new zf(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new Uf(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new Lp(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new Pp(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),f=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return p(e)},p=t=>new op(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch,fileIdPrefixes:[`file-`]}),m=function(e){return f(e)};return m.languageModel=f,m.chat=o,m.completion=s,m.responses=p,m.embedding=c,m.textEmbedding=c,m.textEmbeddingModel=c,m.image=l,m.imageModel=l,m.transcription=u,m.transcriptionModel=u,m.speech=d,m.speechModel=d,m.tools=Zf,m}zp(),v.object({user:v.string().optional(),reasoningEffort:v.string().optional()});var Bp=v.object({error:v.object({message:v.string(),type:v.string().nullish(),param:v.any().nullish(),code:v.union([v.string(),v.number()]).nullish()})}),Vp={errorSchema:Bp,errorToMessage:e=>e.error.message},Hp=v.object({prompt_tokens:v.number().nullish(),completion_tokens:v.number().nullish(),total_tokens:v.number().nullish(),prompt_tokens_details:v.object({cached_tokens:v.number().nullish()}).nullish(),completion_tokens_details:v.object({reasoning_tokens:v.number().nullish(),accepted_prediction_tokens:v.number().nullish(),rejected_prediction_tokens:v.number().nullish()}).nullish()}).nullish();v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({message:v.object({role:v.literal(`assistant`).nullish(),content:v.string().nullish(),reasoning_content:v.string().nullish(),reasoning:v.string().nullish(),tool_calls:v.array(v.object({id:v.string().nullish(),function:v.object({name:v.string(),arguments:v.string()})})).nullish()}),finish_reason:v.string().nullish()})),usage:Hp}),v.object({echo:v.boolean().optional(),logitBias:v.record(v.string(),v.number()).optional(),suffix:v.string().optional(),user:v.string().optional()});var Up=v.object({prompt_tokens:v.number(),completion_tokens:v.number(),total_tokens:v.number()});v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({text:v.string(),finish_reason:v.string()})),usage:Up.nullish()}),v.object({dimensions:v.number().optional(),user:v.string().optional()}),v.object({data:v.array(v.object({embedding:v.array(v.number())})),usage:v.object({prompt_tokens:v.number()}).nullish(),providerMetadata:v.record(v.string(),v.record(v.string(),v.any())).optional()});var Wp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d,f;let p=[];r!=null&&p.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&p.push({type:`unsupported-setting`,setting:`seed`});let m=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:h,responseHeaders:g}=await J({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:G(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},response_format:`b64_json`},failedResponseHandler:Ci((f=this.config.errorStructure)??Vp),successfulResponseHandler:Y(Gp),abortSignal:s,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g}}}},Gp=v.object({data:v.array(v.object({b64_json:v.string()}))});function Kp(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${La(e.data)}`}}}else throw new W({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function qp({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Jp(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var Yp=v.object({type:v.literal(`web`),country:v.string().length(2).optional(),excludedWebsites:v.array(v.string()).max(5).optional(),allowedWebsites:v.array(v.string()).max(5).optional(),safeSearch:v.boolean().optional()}),Xp=v.object({type:v.literal(`x`),xHandles:v.array(v.string()).optional()}),Zp=v.object({type:v.literal(`news`),country:v.string().length(2).optional(),excludedWebsites:v.array(v.string()).max(5).optional(),safeSearch:v.boolean().optional()}),Qp=v.object({type:v.literal(`rss`),links:v.array(v.string().url()).max(1)}),$p=v.discriminatedUnion(`type`,[Yp,Xp,Zp,Qp]),em=v.object({reasoningEffort:v.enum([`low`,`high`]).optional(),searchParameters:v.object({mode:v.enum([`off`,`auto`,`on`]),returnCitations:v.boolean().optional(),fromDate:v.string().optional(),toDate:v.string().optional(),maxSearchResults:v.number().min(1).max(50).optional(),sources:v.array($p).optional()}).optional()}),tm=v.object({error:v.object({message:v.string(),type:v.string().nullish(),param:v.any().nullish(),code:v.union([v.string(),v.number()]).nullish()})}),nm=Ci({errorSchema:tm,errorToMessage:e=>e.error.message});function rm({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:{let e=i;throw new W({functionality:`tool choice type: ${e}`})}}}var im=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){var p,m,h;let g=[],_=(p=await q({provider:`xai`,providerOptions:u,schema:em}))??{};i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:v,warnings:y}=Kp(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=rm({tools:d,toolChoice:f});g.push(...S);let C={model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:_.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:(m=l.name)??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:_.searchParameters?{mode:_.searchParameters.mode,return_citations:_.searchParameters.returnCitations,from_date:_.searchParameters.fromDate,to_date:_.searchParameters.toDate,max_search_results:_.searchParameters.maxSearchResults,sources:(h=_.searchParameters.sources)?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{x_handles:e.xHandles},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:v,tools:b,tool_choice:x};return{args:C,warnings:g}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await J({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:G(this.config.headers(),e.headers),body:i,failedResponseHandler:nm,successfulResponseHandler:Y(om),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u=[];if(l.message.content!=null&&l.message.content.length>0){let e=l.message.content,t=i.messages[i.messages.length-1];t?.role===`assistant`&&e===t.content&&(e=``),e.length>0&&u.push({type:`text`,text:e})}if(l.message.reasoning_content!=null&&l.message.reasoning_content.length>0&&u.push({type:`reasoning`,text:l.message.reasoning_content}),l.message.tool_calls!=null)for(let e of l.message.tool_calls)u.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(s.citations!=null)for(let e of s.citations)u.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:u,finishReason:Jp(l.finish_reason),usage:{inputTokens:s.usage.prompt_tokens,outputTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,reasoningTokens:(r=(n=s.usage.completion_tokens_details)?.reasoning_tokens)??void 0},request:{body:i},response:{...qp(s),headers:o,body:c},warnings:a}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await J({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:G(this.config.headers(),e.headers),body:i,failedResponseHandler:nm,successfulResponseHandler:wi(sm),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l={},u={},d=this;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){var r,a;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let o=t.value;if(n.enqueue({type:`response-metadata`,...qp(o)}),o.citations!=null)for(let e of o.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});o.usage!=null&&(c.inputTokens=o.usage.prompt_tokens,c.outputTokens=o.usage.completion_tokens,c.totalTokens=o.usage.total_tokens,c.reasoningTokens=(a=(r=o.usage.completion_tokens_details)?.reasoning_tokens)??void 0);let f=o.choices[0];if(f?.finish_reason!=null&&(s=Jp(f.finish_reason)),f?.delta==null)return;let p=f.delta,m=f.index;if(p.content!=null&&p.content.length>0){let e=p.content,t=i.messages[i.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let r=`text-${o.id||m}`;l[r]??(l[r]={type:`text`},n.enqueue({type:`text-start`,id:r})),n.enqueue({type:`text-delta`,id:r,delta:e})}if(p.reasoning_content!=null&&p.reasoning_content.length>0){let e=`reasoning-${o.id||m}`;if(u[e]===p.reasoning_content)return;u[e]=p.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:p.reasoning_content})}if(p.tool_calls!=null)for(let e of p.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:s,usage:c})}})),request:{body:i},response:{headers:a}}}},am=v.object({prompt_tokens:v.number(),completion_tokens:v.number(),total_tokens:v.number(),completion_tokens_details:v.object({reasoning_tokens:v.number().nullish()}).nullish()}),om=v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({message:v.object({role:v.literal(`assistant`),content:v.string().nullish(),reasoning_content:v.string().nullish(),tool_calls:v.array(v.object({id:v.string(),type:v.literal(`function`),function:v.object({name:v.string(),arguments:v.string()})})).nullish()}),index:v.number(),finish_reason:v.string().nullish()})),object:v.literal(`chat.completion`),usage:am,citations:v.array(v.string().url()).nullish()}),sm=v.object({id:v.string().nullish(),created:v.number().nullish(),model:v.string().nullish(),choices:v.array(v.object({delta:v.object({role:v.enum([`assistant`]).optional(),content:v.string().nullish(),reasoning_content:v.string().nullish(),tool_calls:v.array(v.object({id:v.string(),type:v.literal(`function`),function:v.object({name:v.string(),arguments:v.string()})})).nullish()}),finish_reason:v.string().nullish(),index:v.number()})),usage:am.nullish(),citations:v.array(v.string().url()).nullish()}),cm={errorSchema:tm,errorToMessage:e=>e.error.message};function lm(e={}){var t;let n=Ra((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Zr({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new im(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:K,fetch:e.fetch}),a=t=>new Wp(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:cm}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new vr({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}lm();const um=`BLINK_API_SERVER_URL`;function dm(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(`x-blink-stream-response-format`);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new Rr).pipeThrough(new TransformStream({async transform(e,t){if(e.data===`[DONE]`)return;let n=await pi({text:e.data});n.success?t.enqueue(n.value):t.error(n.error)}}));let n=e=>ou({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(zp({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(zp({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(wd({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(af({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(lm({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var fm=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},pm=Symbol(),mm=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof Lm?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?hm(e,{all:n,dot:r}):{}};async function hm(e,t){let n=await e.formData();return n?gm(n,t):{}}function gm(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?_m(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(vm(n,e,t),delete n[e])}),n}var _m=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},vm=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},ym=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},bm=e=>{let{groups:t,path:n}=xm(e),r=ym(n);return Sm(r,t)},xm=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},Sm=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},Cm={},wm=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return Cm[r]||(n[2]?Cm[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:Cm[r]=[e,n[1],!0]),Cm[r]}return null},Tm=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Em=e=>Tm(e,decodeURI),Dm=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return Em(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},Om=e=>{let t=Dm(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},km=(e,t,...n)=>(n.length&&(t=km(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),Am=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},jm=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:Tm(e,Fm)):e,Mm=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return jm(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=jm(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=jm(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},Nm=Mm,Pm=(e,t)=>Mm(e,t,!0),Fm=decodeURIComponent,Im=e=>Tm(e,Fm),Lm=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?Im(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?Im(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return Nm(this.url,e)}queries(e){return Pm(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await mm(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[pm](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},Rm={Stringify:1,BeforeStream:2,Stream:3},zm=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Bm=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Bm(e,t,!1,r,i))).then(()=>i[0]));return n?zm(await o,a):o},Vm=`text/plain; charset=UTF-8`,Hm=(e,t)=>({"Content-Type":e,...t}),Um=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new Lm(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,Hm(Vm,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,Hm(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,Hm(`text/html; charset=UTF-8`,n));return typeof e==`object`?Bm(e,Rm.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},$=`ALL`,Wm=`all`,Gm=[`get`,`post`,`put`,`delete`,`options`,`patch`],Km=`Can not add a route since the matcher is already built.`,qm=class extends Error{},Jm=`__COMPOSED_HANDLER`,Ym=e=>e.text(`404 Not Found`,404),Xm=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Zm=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...Gm,Wm];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute($,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??Dm:Om}#clone(){let e=new Zm({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=Ym;errorHandler=Xm;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Xm?r=e.handler:(r=async(n,r)=>(await fm([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Jm]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=km(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=km(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute($,km(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=km(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new Um(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=fm(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${km(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},Qm=`[^/]+`,$m=`.*`,eh=`(?:|/.*)`,th=Symbol(),nh=new Set(`.\\+*[^]$()`);function rh(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===$m||e===eh?1:t===$m||t===eh?-1:e===Qm?1:t===Qm?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ih=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw th;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,$m]:[``,``,Qm]:a===`/*`?[``,``,eh]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||Qm;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw th;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==$m&&e!==eh))throw th;if(i)return;c=this.#children[t]=new ih,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==$m&&e!==eh))throw th;if(i)return;c=this.#children[a]=new ih}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(rh),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:nh.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ah=class{#context={varIndex:0};#root=new ih;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},oh=[],sh=[/^$/,[],Object.create(null)],ch=Object.create(null);function lh(e){return ch[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function uh(){ch=Object.create(null)}function dh(e){let t=new ah,n=[];if(e.length===0)return sh;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),oh]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===th?new qm(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function fh(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(lh(n).test(t))return[...e[n]]}}var ph=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[$]:Object.create(null)},this.#routes={[$]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(Km);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[$]).forEach(n=>{t[e][n]=[...t[$][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=lh(t);e===$?Object.keys(r).forEach(e=>{r[e][t]||=fh(r[e],t)||fh(r[$],t)||[]}):r[e][t]||=fh(r[e],t)||fh(r[$],t)||[],Object.keys(r).forEach(t=>{(e===$||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===$||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=Am(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===$||e===o)&&(i[o][c]||=[...fh(r[o],c)||fh(r[$],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){uh();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[$],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],oh];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===$;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==$&&t.push(...Object.keys(r[$]).map(e=>[e,r[$][e]])):(n||=!0,t.push(...i))}),n?dh(t):null}},mh=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(Km);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof qm)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},hh=Object.create(null),gh=class{#methods;#children;#patterns;#order=0;#params=hh;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=bm(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=wm(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new gh,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[$],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==hh||r&&r!==hh))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=hh;let r=this,i=[r],a=ym(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===hh?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},_h=class{name=`TrieRouter`;#node;constructor(){this.#node=new gh}add(e,t,n){let r=Am(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},vh=class extends Zm{constructor(e={}){super(e),this.router=e.router??new mh({routers:[new ph,new _h]})}},yh=/^[\w!#$%&'*.^`|~+-]+$/,bh=/^[ !#-:<-[\]-~]*$/,xh=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!yh.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),bh.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:Tm(a,Fm),t))break}return r},Sh=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},Ch=(e,t,n)=>(t=encodeURIComponent(t),Sh(e,t,n)),wh=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=xh(r,e);return i[e]}if(!r)return{};let i=xh(r);return i},Th=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Eh=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},Dh=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Oh=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,kh=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Ah=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Dh.test(a))break;try{i=await n.req.json()}catch{throw new Th(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(Oh.test(a)||kh.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Eh(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new Th(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=wh(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const jh=()=>new vh,Mh=(e,t)=>e.json({error:t},400),Nh=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Ph=jh().get(`/kv/:key`,async e=>{let{key:t,err:n}=Nh(e);if(n)return Mh(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Ah(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Mh(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Mh(t,`Value must be a string`):Mh(t,`Value is required`)}),async e=>{let{key:t,err:n}=Nh(e);if(n)return Mh(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Nh(e);return n?Mh(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),Fh=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Ih=jh().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=Fh(e);if(n)return Mh(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Ah(`json`,(e,t)=>{let n=e.messages;if(!n)return Mh(t,`Messages are required`);if(!Array.isArray(n))return Mh(t,`Messages must be an array`);if(n.length===0)return Mh(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Mh(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=Fh(e);if(n)return Mh(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),Lh=new vh().route(`/storage`,Ph).route(`/chat`,Ih);var Rh=Lh;function zh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Bh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Vh=/^\.+(\\|\/)|^\.+$/,Hh=/[. ]+$/,Uh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Wh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Gh=e=>e===`‍`,Kh=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,qh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Jh;function Yh(){return Jh??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Jh}function Xh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(zh().test(n)||[...n].some(e=>Wh.test(e)&&!Gh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(qh,` `),n.length>0&&(e=e.replaceAll(Kh,`$1`)),e=e.replace(Hh,``),e=e.replace(Vh,n),e=e.replace(zh(),n),e=e.replaceAll(Uh,e=>Gh(e)?e:n),e.length===0&&(e=n),e=Bh().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Zh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Zh(n,a)+i}}return e}function Zh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Yh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}const Qh=(e,t,n)=>{let r,i=new Map,a=e=>{f.mkdirSync(e,{recursive:!0})},o=e=>{let t=f.statSync(e,{throwIfNoEntry:!1});if(t)return JSON.parse(f.readFileSync(e,`utf-8`))},s=e=>{try{f.fdatasyncSync(e)}catch{}try{f.closeSync(e)}catch{}},c=e=>{try{let t=f.openSync(e,`r`);try{f.fsyncSync(t)}finally{f.closeSync(t)}}catch{}},l=(e,t)=>{let n=d.dirname(e);a(n);let r=d.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i=JSON.stringify(t,null,2),o;try{o=f.openSync(r,`w`),f.writeFileSync(o,i,`utf-8`),s(o),o=void 0,f.renameSync(r,e),c(e),c(n)}catch(e){if(o!==void 0)try{f.closeSync(o)}catch{}try{f.rmSync(r,{force:!0})}catch{}throw e}},u=()=>{if(r)return r;let t=d.join(e,`index.json`),n=o(t)??{ids:{}};return n.ids||={},r=n,n},p=t=>{let n=d.join(e,`index.json`);l(n,t),r=t},m=t=>{let r=i.get(t);if(r)return r;let a=u(),o=a.ids[t];if(!o)return;let s=d.join(e,o),c=f.statSync(s,{throwIfNoEntry:!1});if(!c)return;let l=JSON.parse(f.readFileSync(s,`utf-8`));return i.set(t,n?.hydrate?n.hydrate(l):l),l},h=(r,a)=>{let o=i.get(r);if(n?.shouldWriteToDisk&&o&&!n.shouldWriteToDisk(o,a)){i.set(r,a);return}let s=a,c=s[t],f=String(c),m=Xh(f,{replacement:`_`}),h=m+`.json`,g=u();g.ids[f]=h,g.current=f;let _=d.join(e,h);l(_,n?.serialize?.(a)??a),p(g),i.set(r,a)};return{get(e){return m(e)},set(e,t){h(e,t)},update(e,t){let n=this.get(e);if(!n)throw Error(`Key ${e} not found`);h(e,{...n,...t})},delete(t){let n=u(),r=n.ids[t];if(r){let i=d.join(e,r);try{f.rmSync(i,{force:!0}),c(e)}catch{}delete n.ids[t],n.current===t&&(n.current=void 0),p(n)}i.delete(t)},list(){let t=f.statSync(e,{throwIfNoEntry:!1});if(!t)return[];let n=u();return Object.keys(n.ids)}}};function $h(e){e.dataDirectory||=x.mkdtempSync(S());let t=Qh(p(e.dataDirectory,`chats`),`id`,{hydrate:e=>({...e,status:`idle`,queuedMessages:[],streamingMessage:void 0}),serialize:t=>(e.serializeChat&&(t=e.serializeChat(t)),{id:t.id,created_at:t.created_at,updated_at:t.updated_at,messages:t.messages}),shouldWriteToDisk:(e,t)=>e.updated_at!==t.updated_at||e.status!==t.status||e.messages.length!==t.messages.length}),n=new l,r=t.set;t.set=(e,i)=>{r.call(t,e,i),n.emit(i)};let i=t.update;t.update=(e,r)=>{i.call(t,e,r),n.emit(t.get(e))};let a={},o=p(e.dataDirectory,`storage.json`);x.existsSync(o)&&(a=JSON.parse(x.readFileSync(o,`utf-8`)));let s=new AbortController,c=new Map,d=e=>{let t=c.get(e);t?.signal.aborted||t?.abort()},f,m=(e,t=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata}),h=async(n,r)=>{let i=t.get(n);if(!i)return;let a=r?[...i.messages,...r.map(e=>m(e))]:i.messages;t.update(n,{status:`streaming`,updated_at:new Date().toISOString(),messages:a});let o=new AbortController;c.set(n,o);let l;try{l=await e.sendMessages({messages:[...a],chat:{id:n}},AbortSignal.any([s.signal,o.signal]))}catch(e){t.update(n,{status:`error`,error:e instanceof Error?e:Error(String(e)),streamingMessage:void 0});return}let u=dm(l),d=Uu({stream:u}),f=crypto.randomUUID(),p;if(i=t.get(n),!i)return;try{for await(let e of d){if(o.signal.aborted)break;p=e,t.update(n,{streamingMessage:m(e,f)})}}catch(e){let r=!1;if(e instanceof Error&&e.message.includes(`Controller is already closed`)&&(r=!0),e instanceof Error&&e.name===`AbortError`&&(r=!0),r){if(p){if(i=t.get(n),!i)return;t.update(n,{status:`idle`,messages:[...i.messages,m(p,f)],streamingMessage:void 0});return}throw e}}if(i=t.get(n),!i)return;let g=[...i.messages];if(p&&g.push(m(p,f)),i?.queuedMessages.length){t.update(n,{messages:[...i.messages,...i.queuedMessages.map(e=>m(e))],queuedMessages:[]}),await h(n);return}if(p&&e.shouldLoop&&e.shouldLoop({messages:g})){t.update(n,{messages:g,streamingMessage:void 0}),await h(n);return}t.update(n,{status:`idle`,streamingMessage:void 0,messages:g})},g={chat:{async upsert(e){let n=await t.get(e);return n?await t.set(e,{...n,updated_at:new Date().toISOString(),status:`idle`}):await t.set(e,{id:e,messages:[],created_at:new Date().toISOString(),updated_at:new Date().toISOString(),status:`idle`,streamingMessage:void 0,queuedMessages:[]}),{id:e}},async sendMessages(e,n){let r=t.get(e);if(!r)throw Error(`Chat not found`);if(n.behavior===`append`){t.set(e,{...r,messages:[...r.messages,...n.messages.map(e=>m(e))]});return}if(r.status===`streaming`){if(n.behavior===`enqueue`){t.set(e,{...r,queuedMessages:[...r.queuedMessages,...n.messages]});return}d(e),await f}f=h(e,n.messages)}},storage:{kv:{get(e){return Promise.resolve(a[e])},set(e,t){return a[e]=t,x.writeFileSync(o,JSON.stringify(a),`utf-8`),Promise.resolve()},del(e){return delete a[e],x.writeFileSync(o,JSON.stringify(a),`utf-8`),Promise.resolve()}}}},_=u(gn(e=>Rh.fetch(e,g)));return _.listen(e.port),{url:`http://127.0.0.1:${_.address().port}`,runtime:g,onChatChanged:n.event,listChats:()=>t.list(),getChat:e=>t.get(e),stopChat:e=>{d(e)},upsertChatMessage:(e,n)=>{let r=t.get(e);if(!r)throw Error(`Chat not found`);let i=r.messages.length>0?r.messages.at(-1):void 0;if(i&&JSON.stringify(i.parts)===JSON.stringify(n.parts))return;let a=[...r.messages,m(n)];t.set(e,{...r,messages:a})},updateChatMessage:(e,n)=>{let r=t.get(e);if(!r)throw Error(`Chat not found`);let i=[...r.messages];i[i.length-1]=m(n),t.set(e,{...r,messages:i})},resetChat:e=>{t.set(e,{id:e,messages:[],status:`idle`,queuedMessages:[],streamingMessage:void 0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),d(e)},upsertChat:e=>{let n=t.get(e);if(n)return n;let r={id:e,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[],status:`idle`,queuedMessages:[],streamingMessage:void 0};return t.set(e,r),r},dispose:()=>{_.close(),s.abort()}}}const eg=h.object({host:h.string(),port:h.number(),supportsRequests:h.boolean()});async function tg(e){let t=m(e),n=_n(t),r=vn(n),i=process.env.HOST||`127.0.0.1`,a=process.env.PORT?parseInt(process.env.PORT):3e3,o=u(r);o.listen(a,i,()=>{let e={host:i,port:a,supportsRequests:n.supportsRequests??!1};console.log(JSON.stringify(e))}).on(`error`,e=>{console.error(e),process.exit(1)})}async function ng(e){let t=process.argv[0];if(!t)throw Error(`Executable not found`);let n=process.argv[1];if(!n)throw Error(`Entrypoint not found`);n.endsWith(`.ts`)&&(n=p(import.meta.dirname,`index.ts`));let r=e.port;r||=await rg();let i=e.host;i||=`127.0.0.1`;let a=b(t,[n,`serve`,e.entrypoint],{stdio:`pipe`,env:{...process.env,...e.env,[um]:e.apiServerUrl,PORT:r.toString(),HOST:i}}),o,s,c=new Promise((e,t)=>{o=e,s=t});a.stdout.on(`data`,t=>{let n=Buffer.from(t).toString().trim();try{let e=eg.parse(JSON.parse(n));o(e);return}catch{}e.onStdout?.(Buffer.from(t).toString())}),a.stderr.on(`data`,t=>{e.onStderr?.(Buffer.from(t).toString())}),a.on(`error`,e=>{d.emit(e),s(e)}),a.on(`exit`,e=>{u.emit(e),s(Error(`Server exited with code ${e}`))}),a.on(`close`,e=>{u.emit(e)});let u=new l,d=new l,f=await c;return{info:f,onError:d.event,onExit:u.event,url:`http://${i}:${r}`,dispose:()=>{a.kill()},[Symbol.dispose](){a.kill()}}}async function rg(){let e=u();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}export{um as APIServerURLEnvironmentVariable,Rr as EventSourceParserStream,yn as createAgentClient,Ir as createParser,ng as createServeClient,$h as createServer,ql as getToolOrDynamicToolName,Gl as isToolOrDynamicToolUIPart,Ul as isToolUIPart,Ch as serialize,tg as serve};