@chaibuilder/pages 0.15.22 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{2AITGKQY-BQI4o1xG.js → 2AITGKQY-BFankGad.js} +2 -2
- package/dist/{2AITGKQY-DXm3iqhg.cjs → 2AITGKQY-BxEty5Ow.cjs} +1 -1
- package/dist/{NCMVHL6D-B3kd8MpE.js → NCMVHL6D-DFMKkQPN.js} +4 -4
- package/dist/{NCMVHL6D-C0TW9XJH.cjs → NCMVHL6D-DP-qw6yT.cjs} +1 -1
- package/dist/{ZDWCUMSJ-DzyqbIEt.cjs → ZDWCUMSJ-Cu1VTliO.cjs} +1 -1
- package/dist/{ZDWCUMSJ-IN3g-SXd.js → ZDWCUMSJ-DU81uAQq.js} +1 -1
- package/dist/{add-new-language-page-NXyJYXG-.js → add-new-language-page-0zC1CJZK.js} +2 -2
- package/dist/{add-new-language-page-zZoQgh6M.cjs → add-new-language-page-DQ46xqnc.cjs} +1 -1
- package/dist/{add-new-page-C7Kw3sZO.js → add-new-page-CUtZhDvi.js} +1 -1
- package/dist/{add-new-page-Cf_zoJPL.cjs → add-new-page-Ca2H2J-2.cjs} +1 -1
- package/dist/ai-panel-content-CV-HTsAs.cjs +1 -0
- package/dist/ai-panel-content-r2jlUBoR.js +52 -0
- package/dist/ai-panel-default-lang-D6RAQW1X.js +173 -0
- package/dist/ai-panel-default-lang-EH3w6g25.cjs +1 -0
- package/dist/ai-panel-message-bubble-Bl-aUeU4.cjs +1 -0
- package/dist/ai-panel-message-bubble-DPAaAMAZ.js +38 -0
- package/dist/ai-panel-other-lang-BeTdv7yM.js +133 -0
- package/dist/ai-panel-other-lang-_gGQTjZQ.cjs +1 -0
- package/dist/ai-panel-quick-prompts-CpzN48cl.js +46 -0
- package/dist/ai-panel-quick-prompts-DiNVPPAn.cjs +1 -0
- package/dist/ai-prompt-input-D-F23bdc.cjs +1 -0
- package/dist/ai-prompt-input-vAcIZSB1.js +133 -0
- package/dist/ai-translation-prompt-AImJlmDg.cjs +1 -0
- package/dist/ai-translation-prompt-BKyp1IW2.js +63 -0
- package/dist/{delete-page-CyqJ6iqb.js → delete-page-BS10zPLU.js} +1 -1
- package/dist/{delete-page-qrzBuLu5.cjs → delete-page-ClgtvB6n.cjs} +1 -1
- package/dist/{digital-asset-manager-BxM02CBp.js → digital-asset-manager-D_FFLECK.js} +1 -1
- package/dist/{digital-asset-manager-BfDE0iUu.cjs → digital-asset-manager-MK8ZL6Nd.cjs} +1 -1
- package/dist/{duplicate-page-CGKrJ-pm.cjs → duplicate-page-BaZrekqu.cjs} +1 -1
- package/dist/{duplicate-page-BGXDNCfU.js → duplicate-page-C1r4cCIJ.js} +9 -9
- package/dist/{dynamic-page-selector-C1ENQo3c.cjs → dynamic-page-selector-C4R_vhhz.cjs} +1 -1
- package/dist/{dynamic-page-selector-D0H0U30o.js → dynamic-page-selector-CjtnFkxO.js} +1 -1
- package/dist/index-C64wG61b.cjs +5 -0
- package/dist/{index-D2g32O6h.js → index-D_qadcqD.js} +869 -862
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +7 -7
- package/dist/{json-diff-viewer-XF3MMhkA.js → json-diff-viewer-BURQmaIL.js} +1 -1
- package/dist/{json-diff-viewer-D03TdwEh.cjs → json-diff-viewer-CyZVbnpL.cjs} +1 -1
- package/dist/{lang-panel-8pMYi4Fn.js → lang-panel-C8yx7PSU.js} +33 -33
- package/dist/{lang-panel-BQiWaq2_.cjs → lang-panel-SUARS5YU.cjs} +1 -1
- package/dist/{mark-as-template-BGe_QmNY.js → mark-as-template-CUHypMlj.js} +1 -1
- package/dist/{mark-as-template-DwgrP1Vj.cjs → mark-as-template-DS-nfI06.cjs} +1 -1
- package/dist/{no-language-page-content-BiiD91y6.cjs → no-language-page-content-DZj3cmtM.cjs} +1 -1
- package/dist/{no-language-page-content-Cr6wq4o8.js → no-language-page-content-qoHrlxwD.js} +1 -1
- package/dist/{page-creator-PSrGtRIm.js → page-creator-C8VQGfap.js} +2 -2
- package/dist/{page-creator-Di9A1gxS.cjs → page-creator-HwE9ST54.cjs} +1 -1
- package/dist/{page-lock-request-DQT5Ur0g.js → page-lock-request-CBVKtxVj.js} +10 -10
- package/dist/{page-lock-request-Reyb6vZo.cjs → page-lock-request-Db7-x_EI.cjs} +1 -1
- package/dist/{page-locked-by-dialog-DF1_jPao.cjs → page-locked-by-dialog-CvRDaBcN.cjs} +1 -1
- package/dist/{page-locked-by-dialog-DgIr4-Gd.js → page-locked-by-dialog-DEC58QPA.js} +1 -1
- package/dist/{page-manager-new-BuLz6042.js → page-manager-new-B1PDwz2w.js} +67 -67
- package/dist/{page-manager-new-COui-em5.cjs → page-manager-new-CBxSkcYY.cjs} +1 -1
- package/dist/{page-manager-search-and-filter-DxqVJw_A.js → page-manager-search-and-filter-0eTSE1C1.js} +1 -1
- package/dist/{page-manager-search-and-filter-6_CVqZc_.cjs → page-manager-search-and-filter-BRLPHE64.cjs} +1 -1
- package/dist/{page-revisions-content-DagDCr7w.js → page-revisions-content-CKcp4He4.js} +10 -10
- package/dist/{page-revisions-content-BlM1X20k.cjs → page-revisions-content-CTrVTQ_s.cjs} +1 -1
- package/dist/prompt-helper-BtijECyh.cjs +51 -0
- package/dist/prompt-helper-CfyAlam9.js +175 -0
- package/dist/{publish-pages-content-6L8onxVt.cjs → publish-pages-content-B6HGaUtO.cjs} +1 -1
- package/dist/{publish-pages-content-eAcMLyLi.js → publish-pages-content-BMaeNHV2.js} +2 -2
- package/dist/{save-to-lib-BUen2a0-.cjs → save-to-lib-BKKTPv4h.cjs} +1 -1
- package/dist/{save-to-lib-C43iGfOH.js → save-to-lib-CccnzwO8.js} +1 -1
- package/dist/{seo-panel-DdE8DfMt.js → seo-panel-4KK4r-BP.js} +1 -1
- package/dist/{seo-panel-BseSTxFf.cjs → seo-panel-DL_rcWwC.cjs} +1 -1
- package/dist/server.cjs +238 -1
- package/dist/server.d.ts +50 -6
- package/dist/server.js +10324 -290
- package/dist/{shared-json-ld-D-S-SwbU.cjs → shared-json-ld-BuYzbmKx.cjs} +1 -1
- package/dist/{shared-json-ld-OwSauSop.js → shared-json-ld-DGW40Ccy.js} +41 -41
- package/dist/{slug-input-DYne39yC.cjs → slug-input--8SgDwYu.cjs} +1 -1
- package/dist/{slug-input-Bh4d19p2.js → slug-input-DH5w0H22.js} +1 -1
- package/dist/{theme-panel-footer-BnxQBiM2.js → theme-panel-footer-CHR7J97n.js} +1 -1
- package/dist/{theme-panel-footer-DLSf7QAN.cjs → theme-panel-footer-Co5VI_i9.cjs} +1 -1
- package/dist/{unmark-as-template-BTY-g4LE.cjs → unmark-as-template-B3h10oHA.cjs} +1 -1
- package/dist/{unmark-as-template-B9xuxdYK.js → unmark-as-template-DlA879QF.js} +1 -1
- package/dist/{unpublish-page-D0FunHFp.cjs → unpublish-page-Bfo_DuW5.cjs} +1 -1
- package/dist/{unpublish-page-CYmJyQH9.js → unpublish-page-JzGl35pF.js} +1 -1
- package/dist/{web-preview-y7dB2S91.js → web-preview-CJ6JyhJD.js} +1 -1
- package/dist/{web-preview-DDnJlhVc.cjs → web-preview-oG2epixb.cjs} +1 -1
- package/package.json +12 -12
- package/dist/ai-panel-content-BXnMSm-N.js +0 -614
- package/dist/ai-panel-content-xcOgRnxG.cjs +0 -142
- package/dist/index-CZxeSGRk.cjs +0 -5
package/dist/server.cjs
CHANGED
|
@@ -1 +1,238 @@
|
|
|
1
|
-
"use strict";var I=Object.defineProperty;var O=(i,a,t)=>a in i?I(i,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[a]=t;var C=(i,a,t)=>O(i,typeof a!="symbol"?a+"":a,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("lodash-es"),B=require("@chaibuilder/runtime");let G=async i=>({...i});const M=i=>{G=i},y=async i=>{try{return await G(i)}catch(a){return console.error(a),{}}},p={},T=()=>Object.values(p),A=i=>p[i],v=(i,a)=>{p[i]={key:i,...a,hasSlug:!0}},U=(i,a)=>{p[i]={key:i,...a,hasSlug:!1}},P={};function N(i,a){c.has(P,i)&&console.warn(`Collection ${i} already registered`),P[i]={...a,id:i}}const L=()=>Object.values(P),_=i=>c.get(P,i);class R{constructor(a){this.backend=a}async upload({file:a,folderId:t,name:s},e){var o,h;return await((h=(o=this.backend).handleAssetsAction)==null?void 0:h.call(o,{action:"UPLOAD_ASSET",data:{name:s,file:a,folderId:t}},e))}async getAsset({id:a},t){var s,e;return(e=(s=this.backend).handleAssetsAction)==null?void 0:e.call(s,{action:"GET_ASSET",data:{id:a}},t)}async getAssets(a,t){var s,e;return(e=(s=this.backend).handleAssetsAction)==null?void 0:e.call(s,{action:"GET_ASSETS",data:a},t)}async deleteAsset({id:a},t){var s,e;return(e=(s=this.backend).handleAssetsAction)==null?void 0:e.call(s,{action:"DELETE_ASSET",data:{id:a}},t)}async updateAsset({id:a,file:t,description:s},e){var r,o;return(o=(r=this.backend).handleAssetsAction)==null?void 0:o.call(r,{action:"UPDATE_ASSET",data:{id:a,file:t,description:s}},e)}}class b{constructor(a){this.backend=a}async refreshToken(a){var s,e;const t=await((e=(s=this.backend).handleUsersAction)==null?void 0:e.call(s,{action:"REFRESH_TOKEN",data:a}));return t.error?{error:t.error}:t}async login({email:a,password:t}){var e,r;const s=await((r=(e=this.backend).handleUsersAction)==null?void 0:r.call(e,{action:"LOGIN",data:{email:a,password:t}}));return s.error?{error:s.error}:s}async logout(){var a,t;await((t=(a=this.backend).handleUsersAction)==null?void 0:t.call(a,{action:"LOGOUT"}))}async isUserActive(a){var s,e;return(await((e=(s=this.backend).handleUsersAction)==null?void 0:e.call(s,{action:"CHECK_USER_STATUS"},a))).success}async getUserRoleAndPermissions(a){var s,e;return await((e=(s=this.backend).handleUsersAction)==null?void 0:e.call(s,{action:"GET_ROLE_AND_PERMISSIONS"},a))}async getUserInfo(a,t){var e,r;return await((r=(e=this.backend).handleUsersAction)==null?void 0:r.call(e,{action:"GET_CHAI_USER",data:t},a))}}class H{constructor(a,t,s){C(this,"fallbackLang","");C(this,"draftMode",!1);this.backend=a,this.chaiUsers=t,this.chaiAssets=s,this._registerDefaultPageTypes(),this.chaiUsers=t??new b(this.backend),this.chaiAssets=s??new R(this.backend)}_registerDefaultPageTypes(){v("page",{name:"Static Page",icon:'<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M5 8V20H19V8H5ZM5 6H19V4H5V6ZM20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22ZM7 10H11V14H7V10ZM7 16H17V18H7V16ZM13 11H17V13H13V11Z"></path></svg>'}),U("global",{name:"Global Block",helpText:"A global block can be reused in multiple pages.",icon:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-hash-icon lucide-hash"><line x1="4" x2="20" y1="9" y2="9"/><line x1="4" x2="20" y1="15" y2="15"/><line x1="10" x2="8" y1="3" y2="21"/><line x1="16" x2="14" y1="3" y2="21"/></svg>'})}setFallbackLang(a){if(c.isEmpty(a))throw new Error("Fallback language cannot be empty");this.fallbackLang=a}getFallbackLang(){return this.fallbackLang}setDraftMode(a){this.draftMode=a}isDraftMode(){return this.draftMode}async handle(a,t){var e,r,o,h,f,m,E,S,d,w,l;switch(a.action){case"UPLOAD_ASSET":return(e=this.chaiAssets)==null?void 0:e.upload({file:a.data.file,name:a.data.name,folderId:a.data.folderId??null,optimize:a.data.optimize??!0},t);case"GET_ASSET":return(r=this.chaiAssets)==null?void 0:r.getAsset(a.data,t);case"GET_ASSETS":return(o=this.chaiAssets)==null?void 0:o.getAssets(a.data,t);case"DELETE_ASSET":return(h=this.chaiAssets)==null?void 0:h.deleteAsset(a.data,t);case"UPDATE_ASSET":return(f=this.chaiAssets)==null?void 0:f.updateAsset(a.data,t);case"REFRESH_TOKEN":return(m=this.chaiUsers)==null?void 0:m.refreshToken(a.data);case"LOGIN":return(E=this.chaiUsers)==null?void 0:E.login(a.data);case"LOGOUT":return(S=this.chaiUsers)==null?void 0:S.logout();case"CHECK_USER_STATUS":return(d=this.chaiUsers)==null?void 0:d.isUserActive(t);case"GET_ROLE_AND_PERMISSIONS":return(w=this.chaiUsers)==null?void 0:w.getUserRoleAndPermissions(t);case"GET_CHAI_USER":return(l=this.chaiUsers)==null?void 0:l.getUserInfo(t,a.data)}if(a.action==="GET_BUILDER_PAGE_DATA"){const n=await y({lang:a.data.lang,draft:!0,inBuilder:!0}),u=A(a.data.pageType);return u?{...u.dataProvider?await u.dataProvider({lang:a.data.lang,draft:!0,inBuilder:!0,pageProps:a.data.pageProps??{}}):{},global:n}:{global:n}}if(a.action==="GET_PAGE_TYPES")return Promise.all(T().map(async n=>({key:n.key,helpText:n.helpText??"",icon:n.icon??"",dynamicSegments:n.dynamicSegments??"",dynamicSlug:n.dynamicSlug??"",hasSlug:n.hasSlug??!0,name:typeof n.name=="function"?await n.name():n.name,...c.isFunction(n.defaultTrackingInfo)?{trackingDefault:n.defaultTrackingInfo()}:{},...c.isFunction(n.defaultSeo)?{defaultSeo:n.defaultSeo()}:{},...c.isFunction(n.defaultJSONLD)?{defaultJSONLD:n.defaultJSONLD()}:{}})));if(a.action==="SEARCH_PAGE_TYPE_ITEMS"){const n=A(a.data.pageType);return n?n.search?await n.search(a.data.query):this.backend.handleAction(a,t):{error:"Page type not found"}}if(a.action==="GET_DYNAMIC_PAGES"){const n=A(a.data.pageType);return n?n.getDynamicPages?await n.getDynamicPages(a.data):[]:{error:"Page type not found"}}if(a.action==="GET_COLLECTIONS")return L().map(n=>c.omit(n,"fetch"));if(a.action==="GET_BLOCK_ASYNC_PROPS"){const n=a.data.block,u=n._type;if(u==="Repeater"&&(n!=null&&n.repeaterItems.includes("{{#"))){const g=n.repeaterItems.replace("{{#","").replace("}}",""),k=_(g);return k?await(k==null?void 0:k.fetch({block:n,pageProps:a.data.pageProps,lang:a.data.lang,draft:!0,inBuilder:!0}))??[]:[]}else{const g=B.getRegisteredChaiBlock(u);return!g||!c.isFunction(g.dataProvider)?{}:await g.dataProvider({block:n,pageProps:a.data.pageProps,lang:a.data.lang,draft:!0,inBuilder:!0})??{}}}const s=await this.backend.handleAction(a,t);return this.emit(a.action,s),s}emit(a,t){var r,o,h;if(!["CREATE_PAGE","UPDATE_PAGE","DELETE_PAGE"].includes(a))return;const s=c.get(t,"page");if(!s)return;const e=A(s.pageType);if(e)switch(a){case"CREATE_PAGE":return(r=e.onCreate)==null?void 0:r.call(e,s);case"UPDATE_PAGE":return(o=e.onUpdate)==null?void 0:o.call(e,s);case"DELETE_PAGE":return(h=e.onDelete)==null?void 0:h.call(e,s)}}async resolvePageLink(a,t){if(!c.startsWith(a,"pageType:"))return a;const s=a.split(":")[1],e=a.split(":")[2],r=A(s);return r?await this.resolveLink(r.key,e,t):a}async resolveLink(a,t,s){const e=A(a);if(!e)return"/not-found";const r=this.isDraftMode();return e.resolveLink?await e.resolveLink(t,r,s):await this.backend.handleAction({action:"GET_LINK",data:{pageType:a,id:t,draft:r,lang:s===this.getFallbackLang()?"":s}})}async getPageBySlug(a){const t=this.isDraftMode(),s={};return T().forEach(e=>{c.has(e,"dynamicSegments")&&e.dynamicSegments&&(s[e.key]=e.dynamicSegments)}),await this.backend.handleAction({action:"GET_PAGE_META",data:{slug:a,draft:t,dynamicSegments:s}})}async getFullPage(a){const t=this.isDraftMode();return await this.backend.handleAction({action:"GET_PAGE",data:{id:a,draft:t,mergePartials:!0}})}async getRevisionPage({id:a,type:t,lang:s}){const e=this.getFallbackLang()===s?"":s;return await this.backend.handleAction({action:"GET_REVISION_PAGE",data:{id:a,type:t,...e?{lang:e}:{}}})}async getSiteSettings(){const a=this.isDraftMode();return await this.backend.handleAction({action:"GET_WEBSITE_SETTINGS",data:{draft:a}})}async getPageData({blocks:a,pageType:t,pageProps:s,lang:e}){var S;const r=this.isDraftMode(),o=A(t),h=a.filter(d=>d._type==="Repeater"&&(d==null?void 0:d.repeaterItems.includes("{{#")));let f={};if(h.length>0){const d=h.map(l=>({collectionId:l.repeaterItems.replace("{{#","").replace("}}",""),block:l}));f=(await Promise.all(d.map(async({collectionId:l,block:n})=>{const u=_(l);try{const g=await(u==null?void 0:u.fetch({lang:e,draft:r,inBuilder:!1,pageProps:s,block:n}));return Promise.resolve({[`#${l}/${n._id}`]:c.get(g,"items",[])??[],[`#${l}/${n._id}/totalItems`]:c.get(g,"totalItems",-1)??-1})}catch{return Promise.resolve({[`#${l}/${n._id}`]:[],[`#${l}/${n._id}/totalItems`]:-1})}}))).reduce((l,n)=>({...l,...n}),{})}const[m,E]=await Promise.all([this.getGlobalData(e),((S=o==null?void 0:o.dataProvider)==null?void 0:S.call(o,{lang:e,draft:r,inBuilder:!1,pageProps:s}))||Promise.resolve({})]);return o?{...E,global:m,...f}:{global:m,...f}}async getGlobalData(a){return await y({lang:a,draft:this.isDraftMode(),inBuilder:!1})}async request(a){return await this.backend.handleAction(a)}}class K{constructor(a="",t=D){this.apiKey=a,this.apiUrl=t}async handleUsersAction(a,t){const s=await fetch(`${this.apiUrl}/v1/api/users`,{method:"POST",body:JSON.stringify(a),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":t}}),e=await s.json();return c.has(e,"error")?{...e,status:s.status}:e}async handleAction(a,t){const s=await fetch(`${this.apiUrl}/v1/api/chai`,{method:"POST",body:JSON.stringify(a),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":t}}),e=await s.json();return c.has(e,"error")?{...e,status:s.status}:e}async handleAssetsAction(a,t){return await(await fetch(`${this.apiUrl}/v1/api/assets`,{method:"POST",body:JSON.stringify(a),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":t}})).json()}}const x={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},D="https://api.chaibuilder.com";exports.API_URL=D;exports.ChaiBuilderPages=H;exports.ChaiBuilderPagesBackend=K;exports.ChaiBuilderPagesUserManagement=b;exports.LANGUAGES=x;exports.getChaiCollection=_;exports.getChaiCollections=L;exports.getChaiPageType=A;exports.getChaiPageTypes=T;exports.registerChaiCollection=N;exports.registerChaiGlobalDataProvider=M;exports.registerChaiPageType=v;exports.registerChaiPartialType=U;
|
|
1
|
+
"use strict";var oi=Object.defineProperty;var si=(e,t,r)=>t in e?oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _e=(e,t,r)=>si(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("lodash-es"),ii=require("@chaibuilder/runtime"),ui=`You are an expert language translator specializing in preserving data structure integrity while translating content.
|
|
2
|
+
|
|
3
|
+
TASK: Translate all text content within the provided JSON structure to the target language.
|
|
4
|
+
|
|
5
|
+
TRANSLATION PATTERN:
|
|
6
|
+
1. Content Translation Strategy:
|
|
7
|
+
- Identify text content properties (e.g., 'content', 'label', 'text', 'title', 'description')
|
|
8
|
+
- Preserve the original property as the default language content
|
|
9
|
+
- Add language-specific variants using the pattern: '{propertyName}-{languageCode}'
|
|
10
|
+
|
|
11
|
+
2. Property Naming Convention:
|
|
12
|
+
- Original: 'content' (default language)
|
|
13
|
+
- Translated: 'content-fr', 'content-es', 'content-de', etc.
|
|
14
|
+
- Examples: 'label' → 'label-fr', 'title' → 'title-es', 'description' → 'description-de'
|
|
15
|
+
|
|
16
|
+
3. Implementation Rules:
|
|
17
|
+
- NEVER override or remove the original property
|
|
18
|
+
- Language code is provided in the user request
|
|
19
|
+
- If there is already a property with the same name as the translated property, replace it with the translated property.
|
|
20
|
+
|
|
21
|
+
REQUIREMENTS (Common):
|
|
22
|
+
1. Return ONLY the translated JSON structure - no markdown formatting, code blocks, or explanations
|
|
23
|
+
2. Preserve the exact JSON structure, keys, and data types
|
|
24
|
+
3. Maintain proper grammar, tone, and cultural context in the target language
|
|
25
|
+
4. Maintain the original structure and data types
|
|
26
|
+
5. Translate ONLY human-readable text content - do NOT translate:
|
|
27
|
+
- JSON keys/property names
|
|
28
|
+
- Data binding placeholders (format: {{dataBindingId}})
|
|
29
|
+
- HTML attributes (class, id, data-*, etc.)
|
|
30
|
+
- URLs, file paths, or technical identifiers
|
|
31
|
+
- Code snippets or technical values
|
|
32
|
+
6. Ensure translated text fits naturally within the original context
|
|
33
|
+
7. Keep numbers, dates, and technical terms unchanged unless culturally appropriate to translate
|
|
34
|
+
|
|
35
|
+
OUTPUT FORMAT: Valid JSON only, ready to be parsed directly.`,ci=`You are an expert language translator and content editor specializing in preserving data structure integrity while modifying content.
|
|
36
|
+
|
|
37
|
+
TASK: Modify content within the provided JSON structure according to user request for the target language.
|
|
38
|
+
|
|
39
|
+
CONTENT MODIFICATION STRATEGY:
|
|
40
|
+
1. Language Property Selection:
|
|
41
|
+
- First, check if '{propertyName}-{languageCode}' exists (e.g., 'content-fr', 'label-es', 'title-de')
|
|
42
|
+
- If language-specific property exists: Use and modify that property's content
|
|
43
|
+
- If language-specific property does NOT exist: Use the default language property content, translate it to the target language, and create the '{propertyName}-{languageCode}' property with the translated content
|
|
44
|
+
|
|
45
|
+
2. Property Naming Convention:
|
|
46
|
+
- Default language: 'content', 'label', 'text', 'title', 'description'
|
|
47
|
+
- Language-specific: 'content-{languageCode}', 'label-{languageCode}', etc.
|
|
48
|
+
- Examples: 'content-fr', 'label-es', 'title-de', 'description-ja'
|
|
49
|
+
|
|
50
|
+
3. Implementation Rules:
|
|
51
|
+
- NEVER modify the original default language property
|
|
52
|
+
- Only modify or create the language-specific property ('{propertyName}-{languageCode}')
|
|
53
|
+
- Language code is provided in the user request
|
|
54
|
+
- Preserve all other language variants unchanged
|
|
55
|
+
|
|
56
|
+
REQUIREMENTS (Common):
|
|
57
|
+
1. Return ONLY the modified JSON structure - no markdown formatting, code blocks, or explanations
|
|
58
|
+
2. Preserve the exact JSON structure, keys, and data types
|
|
59
|
+
3. Maintain proper grammar, tone, and cultural context in the target language
|
|
60
|
+
4. Maintain the original structure and data types
|
|
61
|
+
|
|
62
|
+
CRITICAL REQUIREMENTS (Content Modification):
|
|
63
|
+
1. Apply user-requested modifications (improve, lengthen, shorten, fix grammar, change tone, rephrase, etc.) to the language-specific property
|
|
64
|
+
2. If language-specific property exists: Modify its content according to user request
|
|
65
|
+
3. If language-specific property does NOT exist: Translate default content to target language first, then apply modifications
|
|
66
|
+
4. Do NOT translate or modify:
|
|
67
|
+
- JSON keys/property names
|
|
68
|
+
- Data binding placeholders (format: {{dataBindingId}})
|
|
69
|
+
- HTML attributes (class, id, data-*, etc.)
|
|
70
|
+
- URLs, file paths, or technical identifiers
|
|
71
|
+
- Code snippets or technical values
|
|
72
|
+
5. Preserve all other language variants and properties unchanged
|
|
73
|
+
6. Apply changes consistently across related properties when applicable
|
|
74
|
+
|
|
75
|
+
OUTPUT FORMAT: Valid JSON only, ready to be parsed directly.`,mn=`You are an expert HTML/CSS developer specializing in Tailwind CSS and shadcn/ui design patterns.
|
|
76
|
+
|
|
77
|
+
Create pure HTML code only. Make it fully responsive using Tailwind CSS v3 classes exclusively - no custom CSS or classes allowed. Implement container queries (@container) where appropriate for enhanced responsive behavior.
|
|
78
|
+
|
|
79
|
+
### CRITICAL REQUIREMENTS:
|
|
80
|
+
1. Return ONLY the HTML code without any markdown formatting, code blocks, or explanations
|
|
81
|
+
2. Use ONLY Tailwind CSS v3+ utility classes - absolutely no custom CSS or classes
|
|
82
|
+
3. Use shadcn/ui design system theming and styling patterns (neutral colors, proper spacing, modern aesthetics)
|
|
83
|
+
4. Apply semantic HTML structure with proper accessibility attributes (ARIA labels, alt texts, proper heading hierarchy)
|
|
84
|
+
5. Add 'chai-name' attributes to parent containers only - use concise, descriptive labels that clearly indicate content purpose (e.g., "Navigation", "Hero Section", "Footer", "Product Grid", "Testimonials"). These help identify sections during editing and AI-assisted modifications.
|
|
85
|
+
6. Ensure mobile-first responsive design approach
|
|
86
|
+
7. Implement container queries using @container classes where appropriate for enhanced responsive behavior
|
|
87
|
+
8. Do NOT include <!DOCTYPE>, <html>, <head>, or <body> tags - only the content HTML
|
|
88
|
+
9. Use proper contrast ratios for accessibility
|
|
89
|
+
10. Keep the code clean, well-structured, and semantic
|
|
90
|
+
11. Think about UI randomly. Do not generate the same layout every time.
|
|
91
|
+
12. For accordion style ui, use html details and summary tags. eg: accordions, mobile menu etc.
|
|
92
|
+
13. If UI generated based on provided image, make sure to make it responsive for all screens.
|
|
93
|
+
14. In Tailwindcss, do not use container queries.
|
|
94
|
+
|
|
95
|
+
## HTML Tags (EXTREMELY IMPORTANT):
|
|
96
|
+
- For mobile menu (<details><summary>) visible only on smaller screen:
|
|
97
|
+
* Hamburger icon in summary (proper SVG with width/height)
|
|
98
|
+
* Menu overlay example: 'absolute right-1 mt-2 min-w-64 bg-card border border-border rounded-lg shadow-lg z-50 p-4'
|
|
99
|
+
* Vertical menu items example: 'block py-2 px-4 hover:bg-accent rounded-md transition-colors'
|
|
100
|
+
* Proper spacing and touch targets (min 44px height)
|
|
101
|
+
- For accordion, faq style ui, use html details and summary tags.
|
|
102
|
+
- For nested menu, use html details and summary tags with dropdown style menu items.
|
|
103
|
+
- For SVG, always add tailwind class with width and height. eg: 'w-6 h-6'
|
|
104
|
+
- For summary add list-none where not needed, like mobile-menu summary.
|
|
105
|
+
- For input tags, add bg-background if want to make it look like shadcn/ui input.
|
|
106
|
+
|
|
107
|
+
## Custom Web components(CRITICAL)
|
|
108
|
+
- Html can have custom web components. All web components starts with <chai- prefix.
|
|
109
|
+
- Use about-component attribute to understand what the component does.
|
|
110
|
+
- Check for can-move and can-delete attribute to check if the component can be moved or deleted.
|
|
111
|
+
- If an attribute value starts with #styles: treat it like class attribute with tailwind classes.
|
|
112
|
+
Use the attribute key to understand what the attribute does and apply classes. Maintain the #styles: at start followed by tailwind classes.
|
|
113
|
+
- Do not change the chai-type attribute. Do not remove any attributes.
|
|
114
|
+
|
|
115
|
+
## Handling SVG Icons
|
|
116
|
+
- <chai-icon> is the web component to handle svg.
|
|
117
|
+
- To add a svg code add an icon attribute to the chai-icon component only if prompt demands it. Else do not add any icon attribute
|
|
118
|
+
- You must generate svg code only if prompt demands it. Else do not generate svg code.
|
|
119
|
+
|
|
120
|
+
## Generating SVG
|
|
121
|
+
- Ensure the svg has appropriate width and height.
|
|
122
|
+
- Ensure the svg has appropriate viewBox.
|
|
123
|
+
|
|
124
|
+
## THEME RULES (MANDATORY - SHADCN + TAILWIND ONLY) [EXTREMELY IMPORTANT]
|
|
125
|
+
- MANDATORY: Use ONLY ShadCN semantic tokens + Tailwind utilities for ALL colors.
|
|
126
|
+
* COLOR TOKENS (Light Mode Reference):
|
|
127
|
+
- bg-background (#ffffff) + text-foreground (#0a0a0a) - Default page
|
|
128
|
+
- bg-card (#ffffff) + text-card-foreground (#0a0a0a) - Elevated containers
|
|
129
|
+
- bg-primary (#171717) + text-primary-foreground (#fafafa) - Primary actions
|
|
130
|
+
- bg-secondary (#f5f5f5) + text-secondary-foreground (#171717) - Secondary actions
|
|
131
|
+
- bg-muted (#f5f5f5) + text-muted-foreground (#737373) - Subdued elements
|
|
132
|
+
- bg-accent (#f5f5f5) + text-accent-foreground (#171717) - Hover/focus states
|
|
133
|
+
- bg-destructive (#e7000b) + text-destructive-foreground (#ffffff) - Errors/warnings
|
|
134
|
+
- border-border (#e5e5e5), border-input (#e5e5e5) - Borders
|
|
135
|
+
- ring-ring (#a1a1a1) - Focus rings
|
|
136
|
+
|
|
137
|
+
* CONTRAST RULES (CRITICAL):
|
|
138
|
+
- ALWAYS pair background with correct foreground token
|
|
139
|
+
- bg-background → text-foreground (NOT text-card-foreground)
|
|
140
|
+
- bg-card → text-card-foreground (NOT text-foreground)
|
|
141
|
+
- bg-primary → text-primary-foreground (NOT text-foreground)
|
|
142
|
+
- bg-accent → text-accent-foreground
|
|
143
|
+
- NEVER use same token family for bg and text (e.g., bg-primary + text-primary)
|
|
144
|
+
|
|
145
|
+
* HOVER STATE RULES:
|
|
146
|
+
- Primary buttons: bg-primary hover:bg-primary/90 text-primary-foreground (NO hover text change)
|
|
147
|
+
- Card hovers: hover:bg-accent hover:text-accent-foreground transition-colors
|
|
148
|
+
- Link hovers: text-muted-foreground hover:text-foreground transition-colors
|
|
149
|
+
- Nav links: text-foreground/80 hover:text-foreground transition-colors
|
|
150
|
+
- NEVER use hover:text-primary-foreground on bg-primary (already same color)
|
|
151
|
+
- Hover text must be visibly different and contrast well
|
|
152
|
+
|
|
153
|
+
* USAGE EXAMPLES:
|
|
154
|
+
✓ bg-background text-foreground
|
|
155
|
+
✓ bg-card text-card-foreground border-border
|
|
156
|
+
✓ bg-primary text-primary-foreground hover:bg-primary/90
|
|
157
|
+
✓ bg-accent text-accent-foreground
|
|
158
|
+
✓ text-muted-foreground hover:text-foreground transition-colors
|
|
159
|
+
|
|
160
|
+
* STRICTLY AVOID:
|
|
161
|
+
✗ bg-muted text-muted (low contrast)
|
|
162
|
+
✗ bg-primary hover:text-primary-foreground (redundant, no visible change)
|
|
163
|
+
✗ Arbitrary colors (bg-blue-500, text-red-600, etc.)
|
|
164
|
+
✗ Same token for bg and text (bg-foreground text-foreground)
|
|
165
|
+
|
|
166
|
+
# MOBILE-FIRST APPROACH:
|
|
167
|
+
- Mobile-first design with proper breakpoints (sm:640px, md:768px, lg:1024px, xl:1280px)
|
|
168
|
+
- Smooth responsive transitions between breakpoints
|
|
169
|
+
- MD breakpoint (768px-1023px) needs special attention:
|
|
170
|
+
* Reduce grid columns gracefully (lg:4 → md:2 → sm:1)
|
|
171
|
+
* Adjust padding/spacing for tablet view
|
|
172
|
+
* Test navigation menu behavior at md breakpoint
|
|
173
|
+
* Ensure cards don't break layout at md size
|
|
174
|
+
|
|
175
|
+
IMAGE USAGE RULES:
|
|
176
|
+
- VERY IMPORTANT: Do not use broken or unavailable images
|
|
177
|
+
- Use Picsum Photos with descriptive seeds for context-relevant images
|
|
178
|
+
- Format: https://picsum.photos/seed/{DESCRIPTIVE-SEED}/{WIDTH}/{HEIGHT}
|
|
179
|
+
- Create meaningful seeds based on content (e.g., "workspace-modern", "tech-innovation", "team-office")
|
|
180
|
+
- Same seed = same image (ensures consistency)
|
|
181
|
+
- Choose appropriate dimensions: Hero (1200x600), Cards (400x300), Team (300x300)
|
|
182
|
+
- Always include descriptive alt text for accessibility
|
|
183
|
+
|
|
184
|
+
OUTPUT
|
|
185
|
+
- The final output should be clean, semantic HTML that works across all devices and screen sizes.
|
|
186
|
+
- Return the complete updated HTML (not just modified parts)
|
|
187
|
+
- Focus only on the user's request without adding extra features or elements or sections
|
|
188
|
+
- Do not add any comments in the code
|
|
189
|
+
- Keep the output simple, minimal and precisely targeted to the request
|
|
190
|
+
- NO EXPLANATION - JUST HTML!`.trim();function Ea(e=null){if(e)switch(e){case"TRANSLATE_CONTENT":return ui;case"UPDATE_CONTENT":return ci;default:return mn}return mn}let Ia=async e=>({...e});const li=e=>{Ia=e},hn=async e=>{try{return await Ia(e)}catch(t){return console.error(t),{}}},Lt={},Tr=()=>Object.values(Lt),be=e=>Lt[e],xa=(e,t)=>{Lt[e]={key:e,...t,hasSlug:!0}},Aa=(e,t)=>{Lt[e]={key:e,...t,hasSlug:!1}},Rt={};function di(e,t){W.has(Rt,e)&&console.warn(`Collection ${e} already registered`),Rt[e]={...t,id:e}}const ka=()=>Object.values(Rt),Sr=e=>W.get(Rt,e);var Oa="vercel.ai.error",pi=Symbol.for(Oa),Na,fi=class Ca extends Error{constructor({name:t,message:r,cause:n}){super(r),this[Na]=!0,this.name=t,this.cause=n}static isInstance(t){return Ca.hasMarker(t,Oa)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};Na=pi;var C=fi,Ra="AI_APICallError",Pa=`vercel.ai.error.${Ra}`,mi=Symbol.for(Pa),$a,Q=class extends C{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:a,responseBody:o,cause:s,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:u}){super({name:Ra,message:e,cause:s}),this[$a]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=a,this.responseBody=o,this.isRetryable=i,this.data=u}static isInstance(e){return C.hasMarker(e,Pa)}};$a=mi;var Ma="AI_EmptyResponseBodyError",za=`vercel.ai.error.${Ma}`,hi=Symbol.for(za),Za,gi=class extends C{constructor({message:e="Empty response body"}={}){super({name:Ma,message:e}),this[Za]=!0}static isInstance(e){return C.hasMarker(e,za)}};Za=hi;function qe(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Da="AI_InvalidArgumentError",Ua=`vercel.ai.error.${Da}`,vi=Symbol.for(Ua),ja,yi=class extends C{constructor({message:t,cause:r,argument:n}){super({name:Da,message:t,cause:r}),this[ja]=!0,this.argument=n}static isInstance(t){return C.hasMarker(t,Ua)}};ja=vi;var La="AI_InvalidPromptError",Fa=`vercel.ai.error.${La}`,_i=Symbol.for(Fa),Va,Le=class extends C{constructor({prompt:e,message:t,cause:r}){super({name:La,message:`Invalid prompt: ${t}`,cause:r}),this[Va]=!0,this.prompt=e}static isInstance(e){return C.hasMarker(e,Fa)}};Va=_i;var Ba="AI_JSONParseError",Ga=`vercel.ai.error.${Ba}`,bi=Symbol.for(Ga),qa,Pt=class extends C{constructor({text:e,cause:t}){super({name:Ba,message:`JSON parsing failed: Text: ${e}.
|
|
191
|
+
Error message: ${qe(t)}`,cause:t}),this[qa]=!0,this.text=e}static isInstance(e){return C.hasMarker(e,Ga)}};qa=bi;var Ja="AI_NoSuchModelError",Ha=`vercel.ai.error.${Ja}`,wi=Symbol.for(Ha),Ya,Ti=class extends C{constructor({errorName:e=Ja,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Ya]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return C.hasMarker(e,Ha)}};Ya=wi;var Wa="AI_TypeValidationError",Ka=`vercel.ai.error.${Wa}`,Si=Symbol.for(Ka),Xa,Ei=class Er extends C{constructor({value:t,cause:r}){super({name:Wa,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
192
|
+
Error message: ${qe(r)}`,cause:r}),this[Xa]=!0,this.value=t}static isInstance(t){return C.hasMarker(t,Ka)}static wrap({value:t,cause:r}){return Er.isInstance(r)&&r.value===t?r:new Er({value:t,cause:r})}};Xa=Si;var ut=Ei;class gn extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function ur(e){}function Ii(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ur,onError:r=ur,onRetry:n=ur,onComment:a}=e;let o="",s=!0,i,u="",c="";function m(w){const v=s?w.replace(/^\xEF\xBB\xBF/,""):w,[l,g]=xi(`${o}${v}`);for(const y of l)_(y);o=g,s=!1}function _(w){if(w===""){p();return}if(w.startsWith(":")){a&&a(w.slice(w.startsWith(": ")?2:1));return}const v=w.indexOf(":");if(v!==-1){const l=w.slice(0,v),g=w[v+1]===" "?2:1,y=w.slice(v+g);b(l,y,w);return}b(w,"",w)}function b(w,v,l){switch(w){case"event":c=v;break;case"data":u=`${u}${v}
|
|
193
|
+
`;break;case"id":i=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?n(parseInt(v,10)):r(new gn(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:l}));break;default:r(new gn(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:v,line:l}));break}}function p(){u.length>0&&t({id:i,event:c||void 0,data:u.endsWith(`
|
|
194
|
+
`)?u.slice(0,-1):u}),i=void 0,u="",c=""}function f(w={}){o&&w.consume&&_(o),s=!0,i=void 0,u="",c="",o=""}return{feed:m,reset:f}}function xi(e){const t=[];let r="",n=0;for(;n<e.length;){const a=e.indexOf("\r",n),o=e.indexOf(`
|
|
195
|
+
`,n);let s=-1;if(a!==-1&&o!==-1?s=Math.min(a,o):a!==-1?a===e.length-1?s=-1:s=a:o!==-1&&(s=o),s===-1){r=e.slice(n);break}else{const i=e.slice(n,s);t.push(i),n=s+1,e[n-1]==="\r"&&e[n]===`
|
|
196
|
+
`&&n++}}return[t,r]}class Ai extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(o){a=Ii({onEvent:s=>{o.enqueue(s)},onError(s){t==="terminate"?o.error(s):typeof t=="function"&&t(s)},onRetry:r,onComment:n})},transform(o){a.feed(o)}})}}function h(e,t,r){function n(i,u){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,u);for(const m in s.prototype)m in i||Object.defineProperty(i,m,{value:s.prototype[m].bind(i)});i._zod.constr=s,i._zod.def=u}const a=(r==null?void 0:r.Parent)??Object;class o extends a{}Object.defineProperty(o,"name",{value:e});function s(i){var u;const c=r!=null&&r.Parent?new o:this;n(c,i),(u=c._zod).deferred??(u.deferred=[]);for(const m of c._zod.deferred)m();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:i=>{var u,c;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(c=(u=i==null?void 0:i._zod)==null?void 0:u.traits)==null?void 0:c.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}class ct extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Qa={};function Te(e){return Qa}function eo(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,a])=>t.indexOf(+n)===-1).map(([n,a])=>a)}function Ir(e,t){return typeof t=="bigint"?t.toString():t}function Dr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ur(e){return e==null}function jr(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ki(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let a=(n.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(n)){const u=n.match(/\d?e-(\d?)/);u!=null&&u[1]&&(a=Number.parseInt(u[1]))}const o=r>a?r:a,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}const vn=Symbol("evaluating");function R(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==vn)return n===void 0&&(n=vn,n=r()),n},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function to(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Ae(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Je(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function yn(e){return JSON.stringify(e)}const ro="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function $t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Oi=Dr(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function lt(e){if($t(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!($t(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function no(e){return lt(e)?{...e}:e}const Ni=new Set(["string","number","symbol"]);function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $e(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r!=null&&r.parent)&&(n._zod.parent=e),n}function E(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ci(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Ri={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Pi(e,t){const r=e._zod.def,n=Je(e._zod.def,{get shape(){const a={};for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(a[o]=r.shape[o])}return Ae(this,"shape",a),a},checks:[]});return $e(e,n)}function $i(e,t){const r=e._zod.def,n=Je(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete a[o]}return Ae(this,"shape",a),a},checks:[]});return $e(e,n)}function Mi(e,t){if(!lt(t))throw new Error("Invalid input to extend: expected a plain object");const r=Je(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ae(this,"shape",n),n},checks:[]});return $e(e,r)}function zi(e,t){const r=Je(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ae(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return $e(e,r)}function Zi(e,t,r){const n=Je(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"optional",innerType:a[s]}))}else for(const s in a)o[s]=new e({type:"optional",innerType:a[s]});return Ae(this,"shape",o),o},checks:[]});return $e(t,n)}function Di(e,t,r){const n=Je(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:a[s]}))}else for(const s in a)o[s]=new e({type:"nonoptional",innerType:a[s]});return Ae(this,"shape",o),o},checks:[]});return $e(t,n)}function st(e,t=0){var r;for(let n=t;n<e.issues.length;n++)if(((r=e.issues[n])==null?void 0:r.continue)!==!0)return!0;return!1}function Fe(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function It(e){return typeof e=="string"?e:e==null?void 0:e.message}function Se(e,t,r){var a,o,s,i,u,c;const n={...e,path:e.path??[]};if(!e.message){const m=It((s=(o=(a=e.inst)==null?void 0:a._zod.def)==null?void 0:o.error)==null?void 0:s.call(o,e))??It((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??It((u=r.customError)==null?void 0:u.call(r,e))??It((c=r.localeError)==null?void 0:c.call(r,e))??"Invalid input";n.message=m}return delete n.inst,delete n.continue,t!=null&&t.reportInput||delete n.input,n}function Lr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function dt(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const ao=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ir,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},oo=h("$ZodError",ao),so=h("$ZodError",ao,{Parent:Error});function Ui(e,t=r=>r.message){const r={},n=[];for(const a of e.issues)a.path.length>0?(r[a.path[0]]=r[a.path[0]]||[],r[a.path[0]].push(t(a))):n.push(t(a));return{formErrors:n,fieldErrors:r}}function ji(e,t){const r=t||function(o){return o.message},n={_errors:[]},a=o=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>a({issues:i}));else if(s.code==="invalid_key")a({issues:s.issues});else if(s.code==="invalid_element")a({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let i=n,u=0;for(;u<s.path.length;){const c=s.path[u];u===s.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(s))):i[c]=i[c]||{_errors:[]},i=i[c],u++}}};return a(e),n}const Li=e=>(t,r,n,a)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ct;if(s.issues.length){const i=new((a==null?void 0:a.Err)??e)(s.issues.map(u=>Se(u,o,Te())));throw ro(i,a==null?void 0:a.callee),i}return s.value},Fi=e=>async(t,r,n,a)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const i=new((a==null?void 0:a.Err)??e)(s.issues.map(u=>Se(u,o,Te())));throw ro(i,a==null?void 0:a.callee),i}return s.value},io=e=>(t,r,n)=>{const a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new ct;return o.issues.length?{success:!1,error:new(e??oo)(o.issues.map(s=>Se(s,a,Te())))}:{success:!0,data:o.value}},Vi=io(so),uo=e=>async(t,r,n)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>Se(s,a,Te())))}:{success:!0,data:o.value}},Bi=uo(so),Gi=/^[cC][^\s-]{8,}$/,qi=/^[0-9a-z]+$/,Ji=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Hi=/^[0-9a-vA-V]{20}$/,Yi=/^[A-Za-z0-9]{27}$/,Wi=/^[a-zA-Z0-9_-]{21}$/,Ki=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_n=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Qi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,eu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function tu(){return new RegExp(eu,"u")}const ru=/^(?:(?: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])$/,nu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,au=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ou=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,su=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,co=/^[A-Za-z0-9_-]*$/,iu=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,uu=/^\+(?:[0-9]){6,14}[0-9]$/,lo="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",cu=new RegExp(`^${lo}$`);function po(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function lu(e){return new RegExp(`^${po(e)}$`)}function du(e){const t=po({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${lo}T(?:${n})$`)}const pu=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},fu=/^\d+$/,mu=/^-?\d+(?:\.\d+)?/i,hu=/true|false/i,gu=/null/i,vu=/^[^A-Z]*$/,yu=/^[^a-z]*$/,ee=h("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),fo={number:"number",bigint:"bigint",object:"date"},mo=h("$ZodCheckLessThan",(e,t)=>{ee.init(e,t);const r=fo[typeof t.value];e._zod.onattach.push(n=>{const a=n._zod.bag,o=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ho=h("$ZodCheckGreaterThan",(e,t)=>{ee.init(e,t);const r=fo[typeof t.value];e._zod.onattach.push(n=>{const a=n._zod.bag,o=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_u=h("$ZodCheckMultipleOf",(e,t)=>{ee.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ki(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),bu=h("$ZodCheckNumberFormat",(e,t)=>{var s;ee.init(e,t),t.format=t.format||"float64";const r=(s=t.format)==null?void 0:s.includes("int"),n=r?"int":"number",[a,o]=Ri[t.format];e._zod.onattach.push(i=>{const u=i._zod.bag;u.format=t.format,u.minimum=a,u.maximum=o,r&&(u.pattern=fu)}),e._zod.check=i=>{const u=i.value;if(r){if(!Number.isInteger(u)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?i.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}u<a&&i.issues.push({origin:"number",input:u,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),u>o&&i.issues.push({origin:"number",input:u,code:"too_big",maximum:o,inst:e})}}),wu=h("$ZodCheckMaxLength",(e,t)=>{var r;ee.init(e,t),(r=e._zod.def).when??(r.when=n=>{const a=n.value;return!Ur(a)&&a.length!==void 0}),e._zod.onattach.push(n=>{const a=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const a=n.value;if(a.length<=t.maximum)return;const s=Lr(a);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),Tu=h("$ZodCheckMinLength",(e,t)=>{var r;ee.init(e,t),(r=e._zod.def).when??(r.when=n=>{const a=n.value;return!Ur(a)&&a.length!==void 0}),e._zod.onattach.push(n=>{const a=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const a=n.value;if(a.length>=t.minimum)return;const s=Lr(a);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),Su=h("$ZodCheckLengthEquals",(e,t)=>{var r;ee.init(e,t),(r=e._zod.def).when??(r.when=n=>{const a=n.value;return!Ur(a)&&a.length!==void 0}),e._zod.onattach.push(n=>{const a=n._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=n=>{const a=n.value,o=a.length;if(o===t.length)return;const s=Lr(a),i=o>t.length;n.issues.push({origin:s,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ft=h("$ZodCheckStringFormat",(e,t)=>{var r,n;ee.init(e,t),e._zod.onattach.push(a=>{const o=a._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Eu=h("$ZodCheckRegex",(e,t)=>{Ft.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Iu=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vu),Ft.init(e,t)}),xu=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yu),Ft.init(e,t)}),Au=h("$ZodCheckIncludes",(e,t)=>{ee.init(e,t);const r=Ge(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),ku=h("$ZodCheckStartsWith",(e,t)=>{ee.init(e,t);const r=new RegExp(`^${Ge(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const a=n._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ou=h("$ZodCheckEndsWith",(e,t)=>{ee.init(e,t);const r=new RegExp(`.*${Ge(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const a=n._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Nu=h("$ZodCheckOverwrite",(e,t)=>{ee.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Cu{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
|
|
197
|
+
`).filter(s=>s),a=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(a)).map(s=>" ".repeat(this.indent*2)+s);for(const s of o)this.content.push(s)}compile(){const t=Function,r=this==null?void 0:this.args,a=[...((this==null?void 0:this.content)??[""]).map(o=>` ${o}`)];return new t(...r,a.join(`
|
|
198
|
+
`))}}const Ru={major:4,minor:0,patch:17},Z=h("$ZodType",(e,t)=>{var a;var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ru;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),(a=e._zod.deferred)==null||a.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,i,u)=>{let c=st(s),m;for(const _ of i){if(_._zod.def.when){if(!_._zod.def.when(s))continue}else if(c)continue;const b=s.issues.length,p=_._zod.check(s);if(p instanceof Promise&&(u==null?void 0:u.async)===!1)throw new ct;if(m||p instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await p,s.issues.length!==b&&(c||(c=st(s,b)))});else{if(s.issues.length===b)continue;c||(c=st(s,b))}}return m?m.then(()=>s):s};e._zod.run=(s,i)=>{const u=e._zod.parse(s,i);if(u instanceof Promise){if(i.async===!1)throw new ct;return u.then(c=>o(c,n,i))}return o(u,n,i)}}e["~standard"]={validate:o=>{var s;try{const i=Vi(e,o);return i.success?{value:i.data}:{issues:(s=i.error)==null?void 0:s.issues}}catch{return Bi(e,o).then(u=>{var c;return u.success?{value:u.data}:{issues:(c=u.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Fr=h("$ZodString",(e,t)=>{var r;Z.init(e,t),e._zod.pattern=[...((r=e==null?void 0:e._zod.bag)==null?void 0:r.patterns)??[]].pop()??pu(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),U=h("$ZodStringFormat",(e,t)=>{Ft.init(e,t),Fr.init(e,t)}),Pu=h("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xi),U.init(e,t)}),$u=h("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=_n(n))}else t.pattern??(t.pattern=_n());U.init(e,t)}),Mu=h("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Qi),U.init(e,t)}),zu=h("$ZodURL",(e,t)=>{U.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),a=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:iu.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=a.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Zu=h("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=tu()),U.init(e,t)}),Du=h("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Wi),U.init(e,t)}),Uu=h("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Gi),U.init(e,t)}),ju=h("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qi),U.init(e,t)}),Lu=h("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ji),U.init(e,t)}),Fu=h("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Hi),U.init(e,t)}),Vu=h("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Yi),U.init(e,t)}),Bu=h("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=du(t)),U.init(e,t)}),Gu=h("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=cu),U.init(e,t)}),qu=h("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=lu(t)),U.init(e,t)}),Ju=h("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ki),U.init(e,t)}),Hu=h("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ru),U.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),Yu=h("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nu),U.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Wu=h("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=au),U.init(e,t)}),Ku=h("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ou),U.init(e,t),e._zod.check=r=>{const[n,a]=r.value.split("/");try{if(!a)throw new Error;const o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function go(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Xu=h("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=su),U.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{go(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Qu(e){if(!co.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return go(r)}const ec=h("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=co),U.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Qu(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),tc=h("$ZodE164",(e,t)=>{t.pattern??(t.pattern=uu),U.init(e,t)});function rc(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const a=JSON.parse(atob(n));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const nc=h("$ZodJWT",(e,t)=>{U.init(e,t),e._zod.check=r=>{rc(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),vo=h("$ZodNumber",(e,t)=>{Z.init(e,t),e._zod.pattern=e._zod.bag.pattern??mu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const a=r.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return r;const o=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...o?{received:o}:{}}),r}}),ac=h("$ZodNumber",(e,t)=>{bu.init(e,t),vo.init(e,t)}),oc=h("$ZodBoolean",(e,t)=>{Z.init(e,t),e._zod.pattern=hu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const a=r.value;return typeof a=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),r}}),sc=h("$ZodNull",(e,t)=>{Z.init(e,t),e._zod.pattern=gu,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const a=r.value;return a===null||r.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),r}}),ic=h("$ZodAny",(e,t)=>{Z.init(e,t),e._zod.parse=r=>r}),uc=h("$ZodUnknown",(e,t)=>{Z.init(e,t),e._zod.parse=r=>r}),cc=h("$ZodNever",(e,t)=>{Z.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function bn(e,t,r){e.issues.length&&t.issues.push(...Fe(r,e.issues)),t.value[r]=e.value}const lc=h("$ZodArray",(e,t)=>{Z.init(e,t),e._zod.parse=(r,n)=>{const a=r.value;if(!Array.isArray(a))return r.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),r;r.value=Array(a.length);const o=[];for(let s=0;s<a.length;s++){const i=a[s],u=t.element._zod.run({value:i,issues:[]},n);u instanceof Promise?o.push(u.then(c=>bn(c,r,s))):bn(u,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function xt(e,t,r,n){e.issues.length&&t.issues.push(...Fe(r,e.issues)),e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const dc=h("$ZodObject",(e,t)=>{Z.init(e,t);const r=Dr(()=>{const _=Object.keys(t.shape);for(const p of _)if(!t.shape[p]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);const b=Ci(t.shape);return{shape:t.shape,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(b)}});R(e._zod,"propValues",()=>{const _=t.shape,b={};for(const p in _){const f=_[p]._zod;if(f.values){b[p]??(b[p]=new Set);for(const w of f.values)b[p].add(w)}}return b});const n=_=>{const b=new Cu(["shape","payload","ctx"]),p=r.value,f=g=>{const y=yn(g);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};b.write("const input = payload.value;");const w=Object.create(null);let v=0;for(const g of p.keys)w[g]=`key_${v++}`;b.write("const newResult = {}");for(const g of p.keys){const y=w[g],d=yn(g);b.write(`const ${y} = ${f(g)};`),b.write(`
|
|
199
|
+
if (${y}.issues.length) {
|
|
200
|
+
payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
201
|
+
...iss,
|
|
202
|
+
path: iss.path ? [${d}, ...iss.path] : [${d}]
|
|
203
|
+
})));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (${y}.value === undefined) {
|
|
207
|
+
if (${d} in input) {
|
|
208
|
+
newResult[${d}] = undefined;
|
|
209
|
+
}
|
|
210
|
+
} else {
|
|
211
|
+
newResult[${d}] = ${y}.value;
|
|
212
|
+
}
|
|
213
|
+
`)}b.write("payload.value = newResult;"),b.write("return payload;");const l=b.compile();return(g,y)=>l(_,g,y)};let a;const o=$t,s=!Qa.jitless,u=s&&Oi.value,c=t.catchall;let m;e._zod.parse=(_,b)=>{m??(m=r.value);const p=_.value;if(!o(p))return _.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),_;const f=[];if(s&&u&&(b==null?void 0:b.async)===!1&&b.jitless!==!0)a||(a=n(t.shape)),_=a(_,b);else{_.value={};const y=m.shape;for(const d of m.keys){const I=y[d]._zod.run({value:p[d],issues:[]},b);I instanceof Promise?f.push(I.then(x=>xt(x,_,d,p))):xt(I,_,d,p)}}if(!c)return f.length?Promise.all(f).then(()=>_):_;const w=[],v=m.keySet,l=c._zod,g=l.def.type;for(const y of Object.keys(p)){if(v.has(y))continue;if(g==="never"){w.push(y);continue}const d=l.run({value:p[y],issues:[]},b);d instanceof Promise?f.push(d.then(S=>xt(S,_,y,p))):xt(d,_,y,p)}return w.length&&_.issues.push({code:"unrecognized_keys",keys:w,input:p,inst:e}),f.length?Promise.all(f).then(()=>_):_}});function wn(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const a=e.filter(o=>!st(o));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>Se(s,n,Te())))}),t)}const yo=h("$ZodUnion",(e,t)=>{Z.init(e,t),R(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),R(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),R(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),R(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${a.map(o=>jr(o.source)).join("|")})$`)}});const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(a,o)=>{if(r)return n(a,o);let s=!1;const i=[];for(const u of t.options){const c=u._zod.run({value:a.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(u=>wn(u,a,e,o)):wn(i,a,e,o)}}),pc=h("$ZodDiscriminatedUnion",(e,t)=>{yo.init(e,t);const r=e._zod.parse;R(e._zod,"propValues",()=>{const a={};for(const o of t.options){const s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const[i,u]of Object.entries(s)){a[i]||(a[i]=new Set);for(const c of u)a[i].add(c)}}return a});const n=Dr(()=>{var s;const a=t.options,o=new Map;for(const i of a){const u=(s=i._zod.propValues)==null?void 0:s[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const c of u){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});e._zod.parse=(a,o)=>{const s=a.value;if(!$t(s))return a.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),a;const i=n.value.get(s==null?void 0:s[t.discriminator]);return i?i._zod.run(a,o):t.unionFallback?r(a,o):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),a)}}),fc=h("$ZodIntersection",(e,t)=>{Z.init(e,t),e._zod.parse=(r,n)=>{const a=r.value,o=t.left._zod.run({value:a,issues:[]},n),s=t.right._zod.run({value:a,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([u,c])=>Tn(r,u,c)):Tn(r,o,s)}});function xr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(lt(e)&<(t)){const r=Object.keys(t),n=Object.keys(e).filter(o=>r.indexOf(o)!==-1),a={...e,...t};for(const o of n){const s=xr(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};a[o]=s.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const a=e[n],o=t[n],s=xr(a,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Tn(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),st(e))return e;const n=xr(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const mc=h("$ZodRecord",(e,t)=>{Z.init(e,t),e._zod.parse=(r,n)=>{const a=r.value;if(!lt(a))return r.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),r;const o=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;r.value={};for(const u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){const c=t.valueType._zod.run({value:a[u],issues:[]},n);c instanceof Promise?o.push(c.then(m=>{m.issues.length&&r.issues.push(...Fe(u,m.issues)),r.value[u]=m.value})):(c.issues.length&&r.issues.push(...Fe(u,c.issues)),r.value[u]=c.value)}let i;for(const u in a)s.has(u)||(i=i??[],i.push(u));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:i})}else{r.value={};for(const s of Reflect.ownKeys(a)){if(s==="__proto__")continue;const i=t.keyType._zod.run({value:s,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(c=>Se(c,n,Te())),input:s,path:[s],inst:e}),r.value[i.value]=i.value;continue}const u=t.valueType._zod.run({value:a[s],issues:[]},n);u instanceof Promise?o.push(u.then(c=>{c.issues.length&&r.issues.push(...Fe(s,c.issues)),r.value[i.value]=c.value})):(u.issues.length&&r.issues.push(...Fe(s,u.issues)),r.value[i.value]=u.value)}}return o.length?Promise.all(o).then(()=>r):r}}),hc=h("$ZodEnum",(e,t)=>{Z.init(e,t);const r=eo(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(a=>Ni.has(typeof a)).map(a=>typeof a=="string"?Ge(a):a.toString()).join("|")})$`),e._zod.parse=(a,o)=>{const s=a.value;return n.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:e}),a}}),gc=h("$ZodLiteral",(e,t)=>{if(Z.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Ge(r):r?Ge(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const a=r.value;return e._zod.values.has(a)||r.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),r}}),vc=h("$ZodTransform",(e,t)=>{Z.init(e,t),e._zod.parse=(r,n)=>{const a=t.transform(r.value,r);if(n.async)return(a instanceof Promise?a:Promise.resolve(a)).then(s=>(r.value=s,r));if(a instanceof Promise)throw new ct;return r.value=a,r}});function Sn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const yc=h("$ZodOptional",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",R(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),R(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${jr(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(o=>Sn(o,r.value)):Sn(a,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),_c=h("$ZodNullable",(e,t)=>{Z.init(e,t),R(e._zod,"optin",()=>t.innerType._zod.optin),R(e._zod,"optout",()=>t.innerType._zod.optout),R(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${jr(r.source)}|null)$`):void 0}),R(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),bc=h("$ZodDefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(o=>En(o,t)):En(a,t)}});function En(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const wc=h("$ZodPrefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Tc=h("$ZodNonOptional",(e,t)=>{Z.init(e,t),R(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(o=>In(o,e)):In(a,e)}});function In(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Sc=h("$ZodCatch",(e,t)=>{Z.init(e,t),R(e._zod,"optin",()=>t.innerType._zod.optin),R(e._zod,"optout",()=>t.innerType._zod.optout),R(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(o=>(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Se(s,n,Te()))},input:r.value}),r.issues=[]),r)):(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(o=>Se(o,n,Te()))},input:r.value}),r.issues=[]),r)}}),Ec=h("$ZodPipe",(e,t)=>{Z.init(e,t),R(e._zod,"values",()=>t.in._zod.values),R(e._zod,"optin",()=>t.in._zod.optin),R(e._zod,"optout",()=>t.out._zod.optout),R(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{const a=t.in._zod.run(r,n);return a instanceof Promise?a.then(o=>xn(o,t,n)):xn(a,t,n)}});function xn(e,t,r){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Ic=h("$ZodReadonly",(e,t)=>{Z.init(e,t),R(e._zod,"propValues",()=>t.innerType._zod.propValues),R(e._zod,"values",()=>t.innerType._zod.values),R(e._zod,"optin",()=>t.innerType._zod.optin),R(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(An):An(a)}});function An(e){return e.value=Object.freeze(e.value),e}const xc=h("$ZodLazy",(e,t)=>{Z.init(e,t),R(e._zod,"innerType",()=>t.getter()),R(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),R(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),R(e._zod,"optin",()=>e._zod.innerType._zod.optin??void 0),R(e._zod,"optout",()=>e._zod.innerType._zod.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Ac=h("$ZodCustom",(e,t)=>{ee.init(e,t),Z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,a=t.fn(n);if(a instanceof Promise)return a.then(o=>kn(o,r,n,e));kn(a,r,n,e)}});function kn(e,t,r,n){if(!e){const a={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(a.params=n._zod.def.params),t.issues.push(dt(a))}}class _o{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};delete n.id;const a={...n,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function kc(){return new _o}const ot=kc();function Oc(e,t){return new e({type:"string",...E(t)})}function Nc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...E(t)})}function On(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...E(t)})}function Cc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...E(t)})}function Rc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(t)})}function Pc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(t)})}function $c(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(t)})}function Mc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...E(t)})}function zc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...E(t)})}function Zc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(t)})}function Dc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...E(t)})}function Uc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(t)})}function jc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...E(t)})}function Lc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...E(t)})}function Fc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(t)})}function Vc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(t)})}function Bc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(t)})}function Gc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(t)})}function qc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(t)})}function bo(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...E(t)})}function Jc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...E(t)})}function Hc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...E(t)})}function Yc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...E(t)})}function Wc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(t)})}function Kc(e,t){return new e({type:"string",format:"date",check:"string_format",...E(t)})}function Xc(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...E(t)})}function Qc(e,t){return new e({type:"string",format:"duration",check:"string_format",...E(t)})}function el(e,t){return new e({type:"number",checks:[],...E(t)})}function tl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...E(t)})}function rl(e,t){return new e({type:"boolean",...E(t)})}function nl(e,t){return new e({type:"null",...E(t)})}function al(e){return new e({type:"any"})}function ol(e){return new e({type:"unknown"})}function sl(e,t){return new e({type:"never",...E(t)})}function Nn(e,t){return new mo({check:"less_than",...E(t),value:e,inclusive:!1})}function cr(e,t){return new mo({check:"less_than",...E(t),value:e,inclusive:!0})}function Cn(e,t){return new ho({check:"greater_than",...E(t),value:e,inclusive:!1})}function lr(e,t){return new ho({check:"greater_than",...E(t),value:e,inclusive:!0})}function Rn(e,t){return new _u({check:"multiple_of",...E(t),value:e})}function wo(e,t){return new wu({check:"max_length",...E(t),maximum:e})}function Mt(e,t){return new Tu({check:"min_length",...E(t),minimum:e})}function To(e,t){return new Su({check:"length_equals",...E(t),length:e})}function il(e,t){return new Eu({check:"string_format",format:"regex",...E(t),pattern:e})}function ul(e){return new Iu({check:"string_format",format:"lowercase",...E(e)})}function cl(e){return new xu({check:"string_format",format:"uppercase",...E(e)})}function ll(e,t){return new Au({check:"string_format",format:"includes",...E(t),includes:e})}function dl(e,t){return new ku({check:"string_format",format:"starts_with",...E(t),prefix:e})}function pl(e,t){return new Ou({check:"string_format",format:"ends_with",...E(t),suffix:e})}function bt(e){return new Nu({check:"overwrite",tx:e})}function fl(e){return bt(t=>t.normalize(e))}function ml(){return bt(e=>e.trim())}function hl(){return bt(e=>e.toLowerCase())}function gl(){return bt(e=>e.toUpperCase())}function vl(e,t,r){return new e({type:"array",element:t,...E(r)})}function yl(e,t,r){const n=E(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function _l(e,t,r){return new e({type:"custom",check:"custom",fn:t,...E(r)})}function bl(e){const t=wl(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(dt(n,r.value,t._zod.def));else{const a=n;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!t._zod.def.abort),r.issues.push(dt(a))}},e(r.value,r)));return t}function wl(e,t){const r=new ee({check:"custom",...E(t)});return r._zod.check=e,r}class Pn{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??ot,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var _,b,p;var n;const a=t._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const u=(b=(_=t._zod).toJSONSchema)==null?void 0:b.call(_);if(u)i.schema=u;else{const f={...r,schemaPath:[...r.schemaPath,t],path:r.path},w=t._zod.parent;if(w)i.ref=w,this.process(w,f),this.seen.get(w).isParent=!0;else{const v=i.schema;switch(a.type){case"string":{const l=v;l.type="string";const{minimum:g,maximum:y,format:d,patterns:S,contentEncoding:I}=t._zod.bag;if(typeof g=="number"&&(l.minLength=g),typeof y=="number"&&(l.maxLength=y),d&&(l.format=o[d]??d,l.format===""&&delete l.format),I&&(l.contentEncoding=I),S&&S.size>0){const x=[...S];x.length===1?l.pattern=x[0].source:x.length>1&&(i.schema.allOf=[...x.map(M=>({...this.target==="draft-7"||this.target==="draft-4"?{type:"string"}:{},pattern:M.source}))])}break}case"number":{const l=v,{minimum:g,maximum:y,format:d,multipleOf:S,exclusiveMaximum:I,exclusiveMinimum:x}=t._zod.bag;typeof d=="string"&&d.includes("int")?l.type="integer":l.type="number",typeof x=="number"&&(this.target==="draft-4"?(l.minimum=x,l.exclusiveMinimum=!0):l.exclusiveMinimum=x),typeof g=="number"&&(l.minimum=g,typeof x=="number"&&this.target!=="draft-4"&&(x>=g?delete l.minimum:delete l.exclusiveMinimum)),typeof I=="number"&&(this.target==="draft-4"?(l.maximum=I,l.exclusiveMaximum=!0):l.exclusiveMaximum=I),typeof y=="number"&&(l.maximum=y,typeof I=="number"&&this.target!=="draft-4"&&(I<=y?delete l.maximum:delete l.exclusiveMaximum)),typeof S=="number"&&(l.multipleOf=S);break}case"boolean":{const l=v;l.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{v.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{v.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const l=v,{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(l.minItems=g),typeof y=="number"&&(l.maxItems=y),l.type="array",l.items=this.process(a.element,{...f,path:[...f.path,"items"]});break}case"object":{const l=v;l.type="object",l.properties={};const g=a.shape;for(const S in g)l.properties[S]=this.process(g[S],{...f,path:[...f.path,"properties",S]});const y=new Set(Object.keys(g)),d=new Set([...y].filter(S=>{const I=a.shape[S]._zod;return this.io==="input"?I.optin===void 0:I.optout===void 0}));d.size>0&&(l.required=Array.from(d)),((p=a.catchall)==null?void 0:p._zod.def.type)==="never"?l.additionalProperties=!1:a.catchall?a.catchall&&(l.additionalProperties=this.process(a.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(l.additionalProperties=!1);break}case"union":{const l=v;l.anyOf=a.options.map((g,y)=>this.process(g,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const l=v,g=this.process(a.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(a.right,{...f,path:[...f.path,"allOf",1]}),d=I=>"allOf"in I&&Object.keys(I).length===1,S=[...d(g)?g.allOf:[g],...d(y)?y.allOf:[y]];l.allOf=S;break}case"tuple":{const l=v;l.type="array";const g=a.items.map((S,I)=>this.process(S,{...f,path:[...f.path,"prefixItems",I]}));if(this.target==="draft-2020-12"?l.prefixItems=g:l.items=g,a.rest){const S=this.process(a.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?l.items=S:l.additionalItems=S}a.rest&&(l.items=this.process(a.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:d}=t._zod.bag;typeof y=="number"&&(l.minItems=y),typeof d=="number"&&(l.maxItems=d);break}case"record":{const l=v;l.type="object",this.target!=="draft-4"&&(l.propertyNames=this.process(a.keyType,{...f,path:[...f.path,"propertyNames"]})),l.additionalProperties=this.process(a.valueType,{...f,path:[...f.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const l=v,g=eo(a.entries);g.every(y=>typeof y=="number")&&(l.type="number"),g.every(y=>typeof y=="string")&&(l.type="string"),l.enum=g;break}case"literal":{const l=v,g=[];for(const y of a.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(y))}else g.push(y);if(g.length!==0)if(g.length===1){const y=g[0];l.type=y===null?"null":typeof y,this.target==="draft-4"?l.enum=[y]:l.const=y}else g.every(y=>typeof y=="number")&&(l.type="number"),g.every(y=>typeof y=="string")&&(l.type="string"),g.every(y=>typeof y=="boolean")&&(l.type="string"),g.every(y=>y===null)&&(l.type="null"),l.enum=g;break}case"file":{const l=v,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:d,mime:S}=t._zod.bag;y!==void 0&&(g.minLength=y),d!==void 0&&(g.maxLength=d),S?S.length===1?(g.contentMediaType=S[0],Object.assign(l,g)):l.anyOf=S.map(I=>({...g,contentMediaType:I})):Object.assign(l,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const l=this.process(a.innerType,f);v.anyOf=[l,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,f),i.ref=a.innerType;break}case"success":{const l=v;l.type="boolean";break}case"default":{this.process(a.innerType,f),i.ref=a.innerType,v.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,f),i.ref=a.innerType,this.io==="input"&&(v._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,f),i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}v.default=l;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const l=v,g=t._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");l.type="string",l.pattern=g.source;break}case"pipe":{const l=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(l,f),i.ref=l;break}case"readonly":{this.process(a.innerType,f),i.ref=a.innerType,v.readOnly=!0;break}case"promise":{this.process(a.innerType,f),i.ref=a.innerType;break}case"optional":{this.process(a.innerType,f),i.ref=a.innerType;break}case"lazy":{const l=t._zod.innerType;this.process(l,f),i.ref=l;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&G(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){var m,_,b,p,f,w;const n={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},a=this.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=v=>{var S;const l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const I=(S=n.external.registry.get(v[0]))==null?void 0:S.id,x=n.external.uri??(J=>J);if(I)return{ref:x(I)};const M=v[1].defId??v[1].schema.id??`schema${this.counter++}`;return v[1].defId=M,{defId:M,ref:`${x("__shared")}#/${l}/${M}`}}if(v[1]===a)return{ref:"#"};const y=`#/${l}/`,d=v[1].schema.id??`__schema${this.counter++}`;return{defId:d,ref:y+d}},s=v=>{if(v[1].schema.$ref)return;const l=v[1],{ref:g,defId:y}=o(v);l.def={...l.schema},y&&(l.defId=y);const d=l.schema;for(const S in d)delete d[S];d.$ref=g};if(n.cycles==="throw")for(const v of this.seen.entries()){const l=v[1];if(l.cycle)throw new Error(`Cycle detected: #/${(m=l.cycle)==null?void 0:m.join("/")}/<root>
|
|
214
|
+
|
|
215
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const v of this.seen.entries()){const l=v[1];if(t===v[0]){s(v);continue}if(n.external){const y=(_=n.external.registry.get(v[0]))==null?void 0:_.id;if(t!==v[0]&&y){s(v);continue}}if((b=this.metadataRegistry.get(v[0]))==null?void 0:b.id){s(v);continue}if(l.cycle){s(v);continue}if(l.count>1&&n.reused==="ref"){s(v);continue}}const i=(v,l)=>{const g=this.seen.get(v),y=g.def??g.schema,d={...y};if(g.ref===null)return;const S=g.ref;if(g.ref=null,S){i(S,l);const I=this.seen.get(S).schema;I.$ref&&(l.target==="draft-7"||l.target==="draft-4")?(y.allOf=y.allOf??[],y.allOf.push(I)):(Object.assign(y,I),Object.assign(y,d))}g.isParent||this.override({zodSchema:v,jsonSchema:y,path:g.path??[]})};for(const v of[...this.seen.entries()].reverse())i(v[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?u.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),(p=n.external)!=null&&p.uri){const v=(f=n.external.registry.get(t))==null?void 0:f.id;if(!v)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(v)}Object.assign(u,a.def);const c=((w=n.external)==null?void 0:w.defs)??{};for(const v of this.seen.entries()){const l=v[1];l.def&&l.defId&&(c[l.defId]=l.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function Tl(e,t){if(e instanceof _o){const n=new Pn(t),a={};for(const i of e._idmap.entries()){const[u,c]=i;n.process(c)}const o={},s={registry:e,uri:t==null?void 0:t.uri,defs:a};for(const i of e._idmap.entries()){const[u,c]=i;o[u]=n.emit(c,{...t,external:s})}if(Object.keys(a).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:a}}return{schemas:o}}const r=new Pn(t);return r.process(e),r.emit(e,t)}function G(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const a=e._zod.def;switch(a.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return G(a.element,r);case"object":{for(const o in a.shape)if(G(a.shape[o],r))return!0;return!1}case"union":{for(const o of a.options)if(G(o,r))return!0;return!1}case"intersection":return G(a.left,r)||G(a.right,r);case"tuple":{for(const o of a.items)if(G(o,r))return!0;return!!(a.rest&&G(a.rest,r))}case"record":return G(a.keyType,r)||G(a.valueType,r);case"map":return G(a.keyType,r)||G(a.valueType,r);case"set":return G(a.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return G(a.innerType,r);case"lazy":return G(a.getter(),r);case"default":return G(a.innerType,r);case"prefault":return G(a.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return G(a.in,r)||G(a.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${a.type}`)}const Sl=h("ZodISODateTime",(e,t)=>{Bu.init(e,t),L.init(e,t)});function El(e){return Wc(Sl,e)}const Il=h("ZodISODate",(e,t)=>{Gu.init(e,t),L.init(e,t)});function xl(e){return Kc(Il,e)}const Al=h("ZodISOTime",(e,t)=>{qu.init(e,t),L.init(e,t)});function kl(e){return Xc(Al,e)}const Ol=h("ZodISODuration",(e,t)=>{Ju.init(e,t),L.init(e,t)});function Nl(e){return Qc(Ol,e)}const Cl=(e,t)=>{oo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ji(e,r)},flatten:{value:r=>Ui(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Ir,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Ir,2)}},isEmpty:{get(){return e.issues.length===0}}})},Vt=h("ZodError",Cl,{Parent:Error}),Rl=Li(Vt),Pl=Fi(Vt),$l=io(Vt),So=uo(Vt),D=h("ZodType",(e,t)=>(Z.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>$e(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Rl(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>$l(e,r,n),e.parseAsync=async(r,n)=>Pl(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>So(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Od(r,n)),e.superRefine=r=>e.check(Nd(r)),e.overwrite=r=>e.check(bt(r)),e.optional=()=>B(e),e.nullable=()=>zn(e),e.nullish=()=>B(zn(e)),e.nonoptional=r=>bd(e,r),e.array=()=>ie(e),e.or=r=>q([e,r]),e.and=r=>ld(e,r),e.transform=r=>Zn(e,md(r)),e.default=r=>vd(e,r),e.prefault=r=>_d(e,r),e.catch=r=>Td(e,r),e.pipe=r=>Zn(e,r),e.readonly=()=>Id(e),e.describe=r=>{const n=e.clone();return ot.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){var r;return(r=ot.get(e))==null?void 0:r.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ot.get(e);const n=e.clone();return ot.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Eo=h("_ZodString",(e,t)=>{Fr.init(e,t),D.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(il(...n)),e.includes=(...n)=>e.check(ll(...n)),e.startsWith=(...n)=>e.check(dl(...n)),e.endsWith=(...n)=>e.check(pl(...n)),e.min=(...n)=>e.check(Mt(...n)),e.max=(...n)=>e.check(wo(...n)),e.length=(...n)=>e.check(To(...n)),e.nonempty=(...n)=>e.check(Mt(1,...n)),e.lowercase=n=>e.check(ul(n)),e.uppercase=n=>e.check(cl(n)),e.trim=()=>e.check(ml()),e.normalize=(...n)=>e.check(fl(...n)),e.toLowerCase=()=>e.check(hl()),e.toUpperCase=()=>e.check(gl())}),Ml=h("ZodString",(e,t)=>{Fr.init(e,t),Eo.init(e,t),e.email=r=>e.check(Nc(zl,r)),e.url=r=>e.check(Mc(Zl,r)),e.jwt=r=>e.check(Yc(Kl,r)),e.emoji=r=>e.check(zc(Dl,r)),e.guid=r=>e.check(On($n,r)),e.uuid=r=>e.check(Cc(At,r)),e.uuidv4=r=>e.check(Rc(At,r)),e.uuidv6=r=>e.check(Pc(At,r)),e.uuidv7=r=>e.check($c(At,r)),e.nanoid=r=>e.check(Zc(Ul,r)),e.guid=r=>e.check(On($n,r)),e.cuid=r=>e.check(Dc(jl,r)),e.cuid2=r=>e.check(Uc(Ll,r)),e.ulid=r=>e.check(jc(Fl,r)),e.base64=r=>e.check(bo(Io,r)),e.base64url=r=>e.check(Jc(Yl,r)),e.xid=r=>e.check(Lc(Vl,r)),e.ksuid=r=>e.check(Fc(Bl,r)),e.ipv4=r=>e.check(Vc(Gl,r)),e.ipv6=r=>e.check(Bc(ql,r)),e.cidrv4=r=>e.check(Gc(Jl,r)),e.cidrv6=r=>e.check(qc(Hl,r)),e.e164=r=>e.check(Hc(Wl,r)),e.datetime=r=>e.check(El(r)),e.date=r=>e.check(xl(r)),e.time=r=>e.check(kl(r)),e.duration=r=>e.check(Nl(r))});function A(e){return Oc(Ml,e)}const L=h("ZodStringFormat",(e,t)=>{U.init(e,t),Eo.init(e,t)}),zl=h("ZodEmail",(e,t)=>{Mu.init(e,t),L.init(e,t)}),$n=h("ZodGUID",(e,t)=>{Pu.init(e,t),L.init(e,t)}),At=h("ZodUUID",(e,t)=>{$u.init(e,t),L.init(e,t)}),Zl=h("ZodURL",(e,t)=>{zu.init(e,t),L.init(e,t)}),Dl=h("ZodEmoji",(e,t)=>{Zu.init(e,t),L.init(e,t)}),Ul=h("ZodNanoID",(e,t)=>{Du.init(e,t),L.init(e,t)}),jl=h("ZodCUID",(e,t)=>{Uu.init(e,t),L.init(e,t)}),Ll=h("ZodCUID2",(e,t)=>{ju.init(e,t),L.init(e,t)}),Fl=h("ZodULID",(e,t)=>{Lu.init(e,t),L.init(e,t)}),Vl=h("ZodXID",(e,t)=>{Fu.init(e,t),L.init(e,t)}),Bl=h("ZodKSUID",(e,t)=>{Vu.init(e,t),L.init(e,t)}),Gl=h("ZodIPv4",(e,t)=>{Hu.init(e,t),L.init(e,t)}),ql=h("ZodIPv6",(e,t)=>{Yu.init(e,t),L.init(e,t)}),Jl=h("ZodCIDRv4",(e,t)=>{Wu.init(e,t),L.init(e,t)}),Hl=h("ZodCIDRv6",(e,t)=>{Ku.init(e,t),L.init(e,t)}),Io=h("ZodBase64",(e,t)=>{Xu.init(e,t),L.init(e,t)});function xo(e){return bo(Io,e)}const Yl=h("ZodBase64URL",(e,t)=>{ec.init(e,t),L.init(e,t)}),Wl=h("ZodE164",(e,t)=>{tc.init(e,t),L.init(e,t)}),Kl=h("ZodJWT",(e,t)=>{nc.init(e,t),L.init(e,t)}),Ao=h("ZodNumber",(e,t)=>{vo.init(e,t),D.init(e,t),e.gt=(n,a)=>e.check(Cn(n,a)),e.gte=(n,a)=>e.check(lr(n,a)),e.min=(n,a)=>e.check(lr(n,a)),e.lt=(n,a)=>e.check(Nn(n,a)),e.lte=(n,a)=>e.check(cr(n,a)),e.max=(n,a)=>e.check(cr(n,a)),e.int=n=>e.check(Mn(n)),e.safe=n=>e.check(Mn(n)),e.positive=n=>e.check(Cn(0,n)),e.nonnegative=n=>e.check(lr(0,n)),e.negative=n=>e.check(Nn(0,n)),e.nonpositive=n=>e.check(cr(0,n)),e.multipleOf=(n,a)=>e.check(Rn(n,a)),e.step=(n,a)=>e.check(Rn(n,a)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Ee(e){return el(Ao,e)}const Xl=h("ZodNumberFormat",(e,t)=>{ac.init(e,t),Ao.init(e,t)});function Mn(e){return tl(Xl,e)}const Ql=h("ZodBoolean",(e,t)=>{oc.init(e,t),D.init(e,t)});function ke(e){return rl(Ql,e)}const ed=h("ZodNull",(e,t)=>{sc.init(e,t),D.init(e,t)});function td(e){return nl(ed,e)}const rd=h("ZodAny",(e,t)=>{ic.init(e,t),D.init(e,t)});function Oe(){return al(rd)}const nd=h("ZodUnknown",(e,t)=>{uc.init(e,t),D.init(e,t)});function Ie(){return ol(nd)}const ad=h("ZodNever",(e,t)=>{cc.init(e,t),D.init(e,t)});function od(e){return sl(ad,e)}const sd=h("ZodArray",(e,t)=>{lc.init(e,t),D.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Mt(r,n)),e.nonempty=r=>e.check(Mt(1,r)),e.max=(r,n)=>e.check(wo(r,n)),e.length=(r,n)=>e.check(To(r,n)),e.unwrap=()=>e.element});function ie(e,t){return vl(sd,e,t)}const ko=h("ZodObject",(e,t)=>{dc.init(e,t),D.init(e,t),R(e,"shape",()=>t.shape),e.keyof=()=>No(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:od()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Mi(e,r),e.merge=r=>zi(e,r),e.pick=r=>Pi(e,r),e.omit=r=>$i(e,r),e.partial=(...r)=>Zi(Co,e,r[0]),e.required=(...r)=>Di(Ro,e,r[0])});function O(e,t){const r={type:"object",get shape(){return Ae(this,"shape",e?to(e):{}),this.shape},...E(t)};return new ko(r)}function Ve(e,t){return new ko({type:"object",get shape(){return Ae(this,"shape",to(e)),this.shape},catchall:Ie(),...E(t)})}const Oo=h("ZodUnion",(e,t)=>{yo.init(e,t),D.init(e,t),e.options=t.options});function q(e,t){return new Oo({type:"union",options:e,...E(t)})}const id=h("ZodDiscriminatedUnion",(e,t)=>{Oo.init(e,t),pc.init(e,t)});function ud(e,t,r){return new id({type:"union",options:t,discriminator:e,...E(r)})}const cd=h("ZodIntersection",(e,t)=>{fc.init(e,t),D.init(e,t)});function ld(e,t){return new cd({type:"intersection",left:e,right:t})}const dd=h("ZodRecord",(e,t)=>{mc.init(e,t),D.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function pt(e,t,r){return new dd({type:"record",keyType:e,valueType:t,...E(r)})}const Ar=h("ZodEnum",(e,t)=>{hc.init(e,t),D.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,a)=>{const o={};for(const s of n)if(r.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ar({...t,checks:[],...E(a),entries:o})},e.exclude=(n,a)=>{const o={...t.entries};for(const s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Ar({...t,checks:[],...E(a),entries:o})}});function No(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ar({type:"enum",entries:r,...E(t)})}const pd=h("ZodLiteral",(e,t)=>{gc.init(e,t),D.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new pd({type:"literal",values:Array.isArray(e)?e:[e],...E(t)})}const fd=h("ZodTransform",(e,t)=>{vc.init(e,t),D.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(dt(o,r.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(dt(s))}};const a=t.transform(r.value,r);return a instanceof Promise?a.then(o=>(r.value=o,r)):(r.value=a,r)}});function md(e){return new fd({type:"transform",transform:e})}const Co=h("ZodOptional",(e,t)=>{yc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType});function B(e){return new Co({type:"optional",innerType:e})}const hd=h("ZodNullable",(e,t)=>{_c.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType});function zn(e){return new hd({type:"nullable",innerType:e})}const gd=h("ZodDefault",(e,t)=>{bc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function vd(e,t){return new gd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():no(t)}})}const yd=h("ZodPrefault",(e,t)=>{wc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _d(e,t){return new yd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():no(t)}})}const Ro=h("ZodNonOptional",(e,t)=>{Tc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType});function bd(e,t){return new Ro({type:"nonoptional",innerType:e,...E(t)})}const wd=h("ZodCatch",(e,t)=>{Sc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Td(e,t){return new wd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Sd=h("ZodPipe",(e,t)=>{Ec.init(e,t),D.init(e,t),e.in=t.in,e.out=t.out});function Zn(e,t){return new Sd({type:"pipe",in:e,out:t})}const Ed=h("ZodReadonly",(e,t)=>{Ic.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Id(e){return new Ed({type:"readonly",innerType:e})}const xd=h("ZodLazy",(e,t)=>{xc.init(e,t),D.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ad(e){return new xd({type:"lazy",getter:e})}const Vr=h("ZodCustom",(e,t)=>{Ac.init(e,t),D.init(e,t)});function kd(e,t){return yl(Vr,e,t)}function Od(e,t={}){return _l(Vr,e,t)}function Nd(e){return bl(e)}function zt(e,t={error:`Input not instance of ${e.name}`}){const r=new Vr({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...E(t)});return r._zod.bag.Class=e,r}var N;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(N||(N={}));function kr(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function Cd(e,t){if(e==null)return Promise.resolve();const r=t==null?void 0:t.abortSignal;return new Promise((n,a)=>{if(r!=null&&r.aborted){a(Dn());return}const o=setTimeout(()=>{s(),n()},e),s=()=>{clearTimeout(o),r==null||r.removeEventListener("abort",i)},i=()=>{s(),a(Dn())};r==null||r.addEventListener("abort",i)})}function Dn(){return new DOMException("Delay was aborted","AbortError")}function wt(e){return Object.fromEntries([...e.headers])}var Tt=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const a=()=>{const o=r.length,s=new Array(t);for(let i=0;i<t;i++)s[i]=r[Math.random()*o|0];return s.join("")};if(e==null)return a;if(r.includes(n))throw new yi({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${a()}`},Rd=Tt();function Po(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Ce(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Pd=["fetch failed","failed to fetch"];function $o({error:e,url:t,requestBodyValues:r}){if(Ce(e))return e;if(e instanceof TypeError&&Pd.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Q({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function Br(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function $d(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r!=null))}function Bt(e,...t){const r=$d(e??{}),n=new Headers(r),a=n.get("user-agent")||"";return n.set("user-agent",[a,...t].filter(Boolean).join(" ")),Object.fromEntries(n)}var Mo="3.0.12",Md=()=>globalThis.fetch,Un=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:a,fetch:o=Md()})=>{try{const s=await o(e,{method:"GET",headers:Bt(t,`ai-sdk/provider-utils/${Mo}`,Br()),signal:a}),i=wt(s);if(!s.ok){let u;try{u=await n({response:s,url:e,requestBodyValues:{}})}catch(c){throw Ce(c)||Q.isInstance(c)?c:new Q({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw u.value}try{return await r({response:s,url:e,requestBodyValues:{}})}catch(u){throw u instanceof Error&&(Ce(u)||Q.isInstance(u))?u:new Q({message:"Failed to process successful response",cause:u,statusCode:s.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(s){throw $o({error:s,url:e,requestBodyValues:{}})}};function zd({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,a])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:a}:{mediaTypePrefix:o.replace(/\*/,""),regexes:a}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function Ct({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var Zd=/"__proto__"\s*:/,Dd=/"constructor"\s*:/;function Ud(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Zd.test(e)===!1&&Dd.test(e)===!1?t:jd(t)}function jd(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const a in n){const o=n[a];o&&typeof o=="object"&&t.push(o)}}}return e}function zo(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ud(e)}finally{Error.stackTraceLimit=t}}var Zt=Symbol.for("vercel.ai.validator");function Ld(e){return{[Zt]:!0,validate:e}}function Fd(e){return typeof e=="object"&&e!==null&&Zt in e&&e[Zt]===!0&&"validate"in e}function He(e){let t;return()=>(t==null&&(t=e()),t)}function Vd(e){return Fd(e)?e:typeof e=="function"?e():Bd(e)}function Bd(e){return Ld(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ut({value:t,cause:r.issues})}})}async function Or({value:e,schema:t}){const r=await xe({value:e,schema:t});if(!r.success)throw ut.wrap({value:e,cause:r.error});return r.value}async function xe({value:e,schema:t}){const r=Vd(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:ut.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ut.wrap({value:e,cause:n}),rawValue:e}}}async function Gd({text:e,schema:t}){try{const r=zo(e);return t==null?r:Or({value:r,schema:t})}catch(r){throw Pt.isInstance(r)||ut.isInstance(r)?r:new Pt({text:e,cause:r})}}async function Re({text:e,schema:t}){try{const r=zo(e);return t==null?{success:!0,value:r,rawValue:r}:await xe({value:r,schema:t})}catch(r){return{success:!1,error:Pt.isInstance(r)?r:new Pt({text:e,cause:r}),rawValue:void 0}}}function qd({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ai).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Re({text:r,schema:t}))}}))}var Jd=()=>globalThis.fetch,Nr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:s})=>Hd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:a,abortSignal:o,fetch:s}),Hd=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:a,abortSignal:o,fetch:s=Jd()})=>{try{const i=await s(e,{method:"POST",headers:Bt(t,`ai-sdk/provider-utils/${Mo}`,Br()),body:r.content,signal:o}),u=wt(i);if(!i.ok){let c;try{c=await a({response:i,url:e,requestBodyValues:r.values})}catch(m){throw Ce(m)||Q.isInstance(m)?m:new Q({message:"Failed to process error response",cause:m,statusCode:i.status,url:e,responseHeaders:u,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Ce(c)||Q.isInstance(c))?c:new Q({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:u,requestBodyValues:r.values})}}catch(i){throw $o({error:i,url:e,requestBodyValues:r.values})}};async function we(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var ft=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:a,requestBodyValues:o})=>{const s=await n.text(),i=wt(n);if(s.trim()==="")return{responseHeaders:i,value:new Q({message:n.statusText,url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r==null?void 0:r(n)})};try{const u=await Gd({text:s,schema:e});return{responseHeaders:i,value:new Q({message:t(u),url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:s,data:u,isRetryable:r==null?void 0:r(n,u)})}}catch{return{responseHeaders:i,value:new Q({message:n.statusText,url:a,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:s,isRetryable:r==null?void 0:r(n)})}}},Yd=e=>async({response:t})=>{const r=wt(t);if(t.body==null)throw new gi({});return{responseHeaders:r,value:qd({stream:t.body,schema:e})}},Dt=e=>async({response:t,url:r,requestBodyValues:n})=>{const a=await t.text(),o=await Re({text:a,schema:e}),s=wt(t);if(!o.success)throw new Q({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:n});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Wd=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Kd=Symbol("Let zodToJsonSchema decide on which parser to use"),jn={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"},Xd=e=>typeof e=="string"?{...jn,name:e}:{...jn,...e};function re(){return{}}function Qd(e,t){var r,n,a;const o={type:"array"};return(r=e.type)!=null&&r._def&&((a=(n=e.type)==null?void 0:n._def)==null?void 0:a.typeName)!==N.ZodAny&&(o.items=$(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function ep(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function tp(){return{type:"boolean"}}function Zo(e,t){return $(e.type._def,t)}var rp=(e,t)=>$(e.innerType._def,t);function Do(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((a,o)=>Do(e,t,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return np(e)}}var np=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function ap(e,t){return{...$(e.innerType._def,t),default:e.defaultValue()}}function op(e,t){return t.effectStrategy==="input"?$(e.schema._def,t):re()}function sp(e){return{type:"string",enum:Array.from(e.values)}}var ip=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function up(e,t){const r=[$(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),$(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(a=>!!a),n=[];return r.forEach(a=>{if(ip(a))n.push(...a.allOf);else{let o=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:s,...i}=a;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function cp(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var dr=void 0,le={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:()=>(dr===void 0&&(dr=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dr),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 Uo(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":de(r,"email",n.message,t);break;case"format:idn-email":de(r,"idn-email",n.message,t);break;case"pattern:zod":X(r,le.email,n.message,t);break}break;case"url":de(r,"uri",n.message,t);break;case"uuid":de(r,"uuid",n.message,t);break;case"regex":X(r,n.regex,n.message,t);break;case"cuid":X(r,le.cuid,n.message,t);break;case"cuid2":X(r,le.cuid2,n.message,t);break;case"startsWith":X(r,RegExp(`^${pr(n.value,t)}`),n.message,t);break;case"endsWith":X(r,RegExp(`${pr(n.value,t)}$`),n.message,t);break;case"datetime":de(r,"date-time",n.message,t);break;case"date":de(r,"date",n.message,t);break;case"time":de(r,"time",n.message,t);break;case"duration":de(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{X(r,RegExp(pr(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&de(r,"ipv4",n.message,t),n.version!=="v4"&&de(r,"ipv6",n.message,t);break}case"base64url":X(r,le.base64url,n.message,t);break;case"jwt":X(r,le.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&X(r,le.ipv4Cidr,n.message,t),n.version!=="v4"&&X(r,le.ipv6Cidr,n.message,t);break}case"emoji":X(r,le.emoji(),n.message,t);break;case"ulid":{X(r,le.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{de(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{X(r,le.base64,n.message,t);break}}break}case"nanoid":X(r,le.nanoid,n.message,t)}return r}function pr(e,t){return t.patternStrategy==="escape"?dp(e):e}var lp=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function dp(e){let t="";for(let r=0;r<e.length;r++)lp.has(e[r])||(t+="\\"),t+=e[r];return t}function de(e,t,r,n){var a;e.format||(a=e.anyOf)!=null&&a.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function X(e,t,r,n){var a;e.pattern||(a=e.allOf)!=null&&a.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Ln(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Ln(t,n)}function Ln(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=n.i?e.source.toLowerCase():e.source;let o="",s=!1,i=!1,u=!1;for(let c=0;c<a.length;c++){if(s){o+=a[c],s=!1;continue}if(n.i){if(i){if(a[c].match(/[a-z]/)){u?(o+=a[c],o+=`${a[c-2]}-${a[c]}`.toUpperCase(),u=!1):a[c+1]==="-"&&((r=a[c+2])!=null&&r.match(/[a-z]/))?(o+=a[c],u=!0):o+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){o+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(n.m){if(a[c]==="^"){o+=`(^|(?<=[\r
|
|
216
|
+
]))`;continue}else if(a[c]==="$"){o+=`($|(?=[\r
|
|
217
|
+
]))`;continue}}if(n.s&&a[c]==="."){o+=i?`${a[c]}\r
|
|
218
|
+
`:`[${a[c]}\r
|
|
219
|
+
]`;continue}o+=a[c],a[c]==="\\"?s=!0:i&&a[c]==="]"?i=!1:!i&&a[c]==="["&&(i=!0)}try{new RegExp(o)}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 o}function jo(e,t){var r,n,a,o,s,i;const u={type:"object",additionalProperties:(r=$(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===N.ZodString&&((a=e.keyType._def.checks)!=null&&a.length)){const{type:c,...m}=Uo(e.keyType._def,t);return{...u,propertyNames:m}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===N.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if(((s=e.keyType)==null?void 0:s._def.typeName)===N.ZodBranded&&e.keyType._def.type._def.typeName===N.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...m}=Zo(e.keyType._def,t);return{...u,propertyNames:m}}}return u}function pp(e,t){if(t.mapStrategy==="record")return jo(e,t);const r=$(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||re(),n=$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||re();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function fp(e){const t=e.values,n=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),a=Array.from(new Set(n.map(o=>typeof o)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function mp(){return{not:re()}}function hp(){return{type:"null"}}var Cr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gp(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Cr&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,o)=>{const s=Cr[o._def.typeName];return s&&!a.includes(s)?[...a,s]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((a,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...a,s];case"bigint":return[...a,"integer"];case"object":if(o._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===r.length){const a=n.filter((o,s,i)=>i.indexOf(o)===s);return{type:a.length>1?a:a[0],enum:r.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(o=>!n.includes(o))],[])};return vp(e,t)}var vp=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,a)=>$(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function yp(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Cr[e.innerType._def.typeName],"null"]};const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function _p(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function bp(e,t){const r={type:"object",properties:{}},n=[],a=e.shape();for(const s in a){let i=a[s];if(i===void 0||i._def===void 0)continue;const u=Tp(i),c=$(i._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});c!==void 0&&(r.properties[s]=c,u||n.push(s))}n.length&&(r.required=n);const o=wp(e,t);return o!==void 0&&(r.additionalProperties=o),r}function wp(e,t){if(e.catchall._def.typeName!=="ZodNever")return $(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 Tp(e){try{return e.isOptional()}catch{return!0}}var Sp=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return $(e.innerType._def,t);const n=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:re()},n]}:re()},Ep=(e,t)=>{if(t.pipeStrategy==="input")return $(e.in._def,t);if(t.pipeStrategy==="output")return $(e.out._def,t);const r=$(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=$(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function Ip(e,t){return $(e.type._def,t)}function xp(e,t){const n={type:"array",uniqueItems:!0,items:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Ap(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>$(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:$(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>$(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function kp(){return{not:re()}}function Op(){return re()}var Np=(e,t)=>$(e.innerType._def,t),Cp=(e,t,r)=>{switch(t){case N.ZodString:return Uo(e,r);case N.ZodNumber:return _p(e);case N.ZodObject:return bp(e,r);case N.ZodBigInt:return ep(e);case N.ZodBoolean:return tp();case N.ZodDate:return Do(e,r);case N.ZodUndefined:return kp();case N.ZodNull:return hp();case N.ZodArray:return Qd(e,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return gp(e,r);case N.ZodIntersection:return up(e,r);case N.ZodTuple:return Ap(e,r);case N.ZodRecord:return jo(e,r);case N.ZodLiteral:return cp(e);case N.ZodEnum:return sp(e);case N.ZodNativeEnum:return fp(e);case N.ZodNullable:return yp(e,r);case N.ZodOptional:return Sp(e,r);case N.ZodMap:return pp(e,r);case N.ZodSet:return xp(e,r);case N.ZodLazy:return()=>e.getter()._def;case N.ZodPromise:return Ip(e,r);case N.ZodNaN:case N.ZodNever:return mp();case N.ZodEffects:return op(e,r);case N.ZodAny:return re();case N.ZodUnknown:return Op();case N.ZodDefault:return ap(e,r);case N.ZodBranded:return Zo(e,r);case N.ZodReadonly:return Np(e,r);case N.ZodCatch:return rp(e,r);case N.ZodPipeline:return Ep(e,r);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(n=>{})()}};function $(e,t,r=!1){var n;const a=t.seen.get(e);if(t.override){const u=(n=t.override)==null?void 0:n.call(t,e,t,a,r);if(u!==Kd)return u}if(a&&!r){const u=Rp(a,t);if(u!==void 0)return u}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=Cp(e,e.typeName,t),i=typeof s=="function"?$(s(),t):s;if(i&&Pp(e,t,i),t.postProcess){const u=t.postProcess(i,e,t);return o.jsonSchema=i,u}return o.jsonSchema=i,i}var Rp=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Wd(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),re()):t.$refStrategy==="seen"?re():void 0}},Pp=(e,t,r)=>(e.description&&(r.description=e.description),r),$p=e=>{const t=Xd(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},Mp=(e,t)=>{var r;const n=$p(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[m,_])=>{var b;return{...c,[m]:(b=$(_._def,{...n,currentPath:[...n.basePath,n.definitionPath,m]},!0))!=null?b:re()}},{}):void 0;const o=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,s=(r=$(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:re(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(s.title=i);const u=o===void 0?a?{...s,[n.definitionPath]:a}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...a,[o]:s}};return u.$schema="http://json-schema.org/draft-07/schema#",u},zp=Mp;function Zp(e,t){var r;const n=(r=void 0)!=null?r:!1;return Gr(()=>zp(e,{$refStrategy:n?"root":"none"}),{validate:async a=>{const o=await e.safeParseAsync(a);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Dp(e,t){var r;const n=(r=void 0)!=null?r:!1;return Gr(()=>Tl(e,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async a=>{const o=await So(e,a);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function Up(e){return"_zod"in e}function Me(e,t){return Up(e)?Dp(e):Zp(e)}var Rr=Symbol.for("vercel.ai.schema");function Gr(e,{validate:t}={}){return{[Rr]:!0,_type:void 0,[Zt]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function jp(e){return typeof e=="object"&&e!==null&&Rr in e&&e[Rr]===!0&&"jsonSchema"in e&&"validate"in e}function Gt(e){return e==null?Gr({properties:{},additionalProperties:!1}):jp(e)?e:typeof e=="function"?e():Me(e)}var{btoa:Lp,atob:Fp}=globalThis;function qr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=Fp(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Pr(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Lp(t)}function Vp(e){return e==null?void 0:e.replace(/\/$/,"")}function Bp(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Gp({execute:e,input:t,options:r}){const n=e(t,r);if(Bp(n)){let a;for await(const o of n)a=o,yield{type:"preliminary",output:o};yield{type:"final",output:a}}else yield{type:"final",output:await n}}var fr,Fn;function qp(){if(Fn)return fr;Fn=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a=(m,_)=>{for(var b in _)e(m,b,{get:_[b],enumerable:!0})},o=(m,_,b,p)=>{if(typeof _=="object"||typeof _=="function")for(let f of r(_))!n.call(m,f)&&f!==b&&e(m,f,{get:()=>_[f],enumerable:!(p=t(_,f))||p.enumerable});return m},s=m=>o(e({},"__esModule",{value:!0}),m),i={};a(i,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>c}),fr=s(i);const u=Symbol.for("@vercel/request-context");function c(){var _,b;return((b=(_=globalThis[u])==null?void 0:_.get)==null?void 0:b.call(_))??{}}return fr}var mr,Vn;function Jp(){if(Vn)return mr;Vn=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a=(_,b)=>{for(var p in b)e(_,p,{get:b[p],enumerable:!0})},o=(_,b,p,f)=>{if(typeof b=="object"||typeof b=="function")for(let w of r(b))!n.call(_,w)&&w!==p&&e(_,w,{get:()=>b[w],enumerable:!(f=t(b,w))||f.enumerable});return _},s=_=>o(e({},"__esModule",{value:!0}),_),i={};a(i,{getContext:()=>u.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>m}),mr=s(i);var u=qp();async function c(){return""}function m(){return""}return mr}var Lo=Jp(),Hp="vercel.ai.gateway.error",hr=Symbol.for(Hp),Bn,Gn,ne=class Fo extends(Gn=Error,Bn=hr,Gn){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[Bn]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return Fo.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&hr in t&&t[hr]===!0}},Vo="GatewayAuthenticationError",Yp=`vercel.ai.gateway.error.${Vo}`,qn=Symbol.for(Yp),Jn,Hn,Jr=class Bo extends(Hn=ne,Jn=qn,Hn){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[Jn]=!0,this.name=Vo,this.type="authentication_error"}static isInstance(t){return ne.hasMarker(t)&&qn in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:a=401,cause:o}){let s;return t?s=`AI Gateway authentication failed: Invalid API key.
|
|
220
|
+
|
|
221
|
+
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
222
|
+
|
|
223
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?s=`AI Gateway authentication failed: Invalid OIDC token.
|
|
224
|
+
|
|
225
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
226
|
+
|
|
227
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:s=`AI Gateway authentication failed: No authentication provided.
|
|
228
|
+
|
|
229
|
+
Option 1 - API key:
|
|
230
|
+
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
231
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
232
|
+
|
|
233
|
+
Option 2 - OIDC token:
|
|
234
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Bo({message:s,statusCode:a,cause:o})}},Go="GatewayInvalidRequestError",Wp=`vercel.ai.gateway.error.${Go}`,Yn=Symbol.for(Wp),Wn,Kn,Kp=class extends(Kn=ne,Wn=Yn,Kn){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Wn]=!0,this.name=Go,this.type="invalid_request_error"}static isInstance(e){return ne.hasMarker(e)&&Yn in e}},qo="GatewayRateLimitError",Xp=`vercel.ai.gateway.error.${qo}`,Xn=Symbol.for(Xp),Qn,ea,Qp=class extends(ea=ne,Qn=Xn,ea){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Qn]=!0,this.name=qo,this.type="rate_limit_exceeded"}static isInstance(e){return ne.hasMarker(e)&&Xn in e}},Jo="GatewayModelNotFoundError",ef=`vercel.ai.gateway.error.${Jo}`,ta=Symbol.for(ef),tf=He(()=>Me(O({modelId:A()}))),ra,na,Ho=class extends(na=ne,ra=ta,na){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[ra]=!0,this.name=Jo,this.type="model_not_found",this.modelId=r}static isInstance(e){return ne.hasMarker(e)&&ta in e}},Yo="GatewayInternalServerError",rf=`vercel.ai.gateway.error.${Yo}`,aa=Symbol.for(rf),oa,sa,ia=class extends(sa=ne,oa=aa,sa){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[oa]=!0,this.name=Yo,this.type="internal_server_error"}static isInstance(e){return ne.hasMarker(e)&&aa in e}},Wo="GatewayResponseError",nf=`vercel.ai.gateway.error.${Wo}`,ua=Symbol.for(nf),ca,la,af=class extends(la=ne,ca=ua,la){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:a}={}){super({message:e,statusCode:t,cause:a}),this[ca]=!0,this.name=Wo,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return ne.hasMarker(e)&&ua in e}};async function da({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:a}){const o=await xe({value:e,schema:of});if(!o.success)return new af({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:o.error,cause:n});const s=o.value,i=s.error.type,u=s.error.message;switch(i){case"authentication_error":return Jr.createContextualError({apiKeyProvided:a==="api-key",oidcTokenProvided:a==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new Kp({message:u,statusCode:t,cause:n});case"rate_limit_exceeded":return new Qp({message:u,statusCode:t,cause:n});case"model_not_found":{const c=await xe({value:s.error.param,schema:tf});return new Ho({message:u,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new ia({message:u,statusCode:t,cause:n});default:return new ia({message:u,statusCode:t,cause:n})}}var of=He(()=>Me(O({error:O({message:A(),type:A().nullish(),param:Ie().nullish(),code:q([A(),Ee()]).nullish()})})));function Pe(e,t){var r;return ne.isInstance(e)?e:Q.isInstance(e)?da({response:sf(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):da({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function sf(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 Ko="ai-gateway-auth-method";async function mt(e){const t=await xe({value:e[Ko],schema:uf});return t.success?t.value:void 0}var uf=He(()=>Me(q([z("api-key"),z("oidc")]))),pa=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Un({url:`${this.config.baseURL}/config`,headers:await we(this.config.headers()),successfulResponseHandler:Dt(cf),failedResponseHandler:ft({errorSchema:Oe(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Pe(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Un({url:`${e.origin}/v1/credits`,headers:await we(this.config.headers()),successfulResponseHandler:Dt(lf),failedResponseHandler:ft({errorSchema:Oe(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Pe(e)}}},cf=He(()=>Me(O({models:ie(O({id:A(),name:A(),description:A().nullish(),pricing:O({input:A(),output:A(),input_cache_read:A().nullish(),input_cache_write:A().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:O({specificationVersion:z("v2"),provider:A(),modelId:A()}),modelType:No(["language","embedding","image"]).nullish()}))}))),lf=He(()=>Me(O({balance:A(),total_used:A()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),df=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,a=await we(this.config.headers());try{const{responseHeaders:o,value:s,rawValue:i}=await Nr({url:this.getUrl(),headers:kr(a,e.headers,this.getModelConfigHeaders(this.modelId,!1),await we(this.config.o11yHeaders)),body:t,successfulResponseHandler:Dt(Oe()),failedResponseHandler:ft({errorSchema:Oe(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...s,request:{body:t},response:{headers:o,body:i},warnings:r}}catch(o){throw await Pe(o,await mt(a))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,a=await we(this.config.headers());try{const{value:o,responseHeaders:s}=await Nr({url:this.getUrl(),headers:kr(a,e.headers,this.getModelConfigHeaders(this.modelId,!0),await we(this.config.o11yHeaders)),body:t,successfulResponseHandler:Yd(Oe()),failedResponseHandler:ft({errorSchema:Oe(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,u){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),u.enqueue(c)}else u.error(i.error)}})),request:{body:t},response:{headers:s}}}catch(o){throw await Pe(o,await mt(a))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const a=Uint8Array.from(n.data),o=Buffer.from(a).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}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)}}},pf=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:r,providerOptions:n}){var a;const o=await we(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:u}=await Nr({url:this.getUrl(),headers:kr(o,t??{},this.getModelConfigHeaders(),await we(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Dt(ff),failedResponseHandler:ft({errorSchema:Oe(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(a=i.usage)!=null?a:void 0,providerMetadata:i.providerMetadata,response:{headers:s,body:u}}}catch(s){throw await Pe(s,await mt(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},ff=He(()=>Me(O({embeddings:ie(ie(Ee())),usage:O({tokens:Ee()}).nullish(),providerMetadata:pt(A(),pt(A(),Ie())).optional()})));async function mf(){var e;return(e=Lo.getContext().headers)==null?void 0:e["x-vercel-id"]}var hf="2.0.0",gf="0.0.1";function vf(e={}){var t,r;let n=null,a=null;const o=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let s=0;const i=(r=Vp(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",u=async()=>{const f=await _f(e);if(f)return Bt({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":gf,[Ko]:f.authMethod,...e.headers},`ai-sdk/gateway/${hf}`);throw Jr.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const f=Ct({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=Ct({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),v=Ct({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const l=await mf();return{...f&&{"ai-o11y-deployment-id":f},...w&&{"ai-o11y-environment":w},...v&&{"ai-o11y-region":v},...l&&{"ai-o11y-request-id":l}}}},m=f=>new df(f,{provider:"gateway",baseURL:i,headers:u,fetch:e.fetch,o11yHeaders:c()}),_=async()=>{var f,w,v;const l=(v=(w=(f=e._internal)==null?void 0:f.currentDate)==null?void 0:w.call(f).getTime())!=null?v:Date.now();return(!n||l-s>o)&&(s=l,n=new pa({baseURL:i,headers:u,fetch:e.fetch}).getAvailableModels().then(g=>(a=g,g)).catch(async g=>{throw await Pe(g,await mt(await u()))})),a?Promise.resolve(a):n},b=async()=>new pa({baseURL:i,headers:u,fetch:e.fetch}).getCredits().catch(async f=>{throw await Pe(f,await mt(await u()))}),p=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return m(f)};return p.getAvailableModels=_,p.getCredits=b,p.imageModel=f=>{throw new Ti({modelId:f,modelType:"imageModel"})},p.languageModel=m,p.textEmbeddingModel=f=>new pf(f,{provider:"gateway",baseURL:i,headers:u,fetch:e.fetch,o11yHeaders:c()}),p}var yf=vf();async function _f(e){const t=Ct({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Lo.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var bf=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ne="1.9.0",fa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function wf(e){var t=new Set([e]),r=new Set,n=e.match(fa);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(u){return u===e};function o(i){return r.add(i),!1}function s(i){return t.add(i),!0}return function(u){if(t.has(u))return!0;if(r.has(u))return!1;var c=u.match(fa);if(!c)return o(u);var m={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return m.prerelease!=null||a.major!==m.major?o(u):a.major===0?a.minor===m.minor&&a.patch<=m.patch?s(u):o(u):a.minor<=m.minor?s(u):o(u)}}var Tf=wf(Ne),Sf=Ne.split(".")[0],ht=Symbol.for("opentelemetry.js.api."+Sf),gt=bf;function Hr(e,t,r,n){var a;n===void 0&&(n=!1);var o=gt[ht]=(a=gt[ht])!==null&&a!==void 0?a:{version:Ne};if(!n&&o[e]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(s.stack||s.message),!1}if(o.version!==Ne){var s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+Ne);return r.error(s.stack||s.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ne+"."),!0}function vt(e){var t,r,n=(t=gt[ht])===null||t===void 0?void 0:t.version;if(!(!n||!Tf(n)))return(r=gt[ht])===null||r===void 0?void 0:r[e]}function Yr(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ne+".");var r=gt[ht];r&&delete r[e]}var Ef=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),a,o=[],s;try{for(;(t===void 0||t-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(i){s={error:i}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},If=function(e,t,r){if(r||arguments.length===2)for(var n=0,a=t.length,o;n<a;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},xf=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return nt("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return nt("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return nt("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return nt("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return nt("verbose",this._namespace,t)},e}();function nt(e,t,r){var n=vt("diag");if(n)return r.unshift(t),n[e].apply(n,If([],Ef(r),!1))}var te;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(te||(te={}));function Af(e,t){e<te.NONE?e=te.NONE:e>te.ALL&&(e=te.ALL),t=t||{};function r(n,a){var o=t[n];return typeof o=="function"&&e>=a?o.bind(t):function(){}}return{error:r("error",te.ERROR),warn:r("warn",te.WARN),info:r("info",te.INFO),debug:r("debug",te.DEBUG),verbose:r("verbose",te.VERBOSE)}}var kf=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),a,o=[],s;try{for(;(t===void 0||t-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(i){s={error:i}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},Of=function(e,t,r){if(r||arguments.length===2)for(var n=0,a=t.length,o;n<a;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Nf="diag",Ut=function(){function e(){function t(a){return function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var i=vt("diag");if(i)return i[a].apply(i,Of([],kf(o),!1))}}var r=this,n=function(a,o){var s,i,u;if(o===void 0&&(o={logLevel:te.INFO}),a===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((s=c.stack)!==null&&s!==void 0?s:c.message),!1}typeof o=="number"&&(o={logLevel:o});var m=vt("diag"),_=Af((i=o.logLevel)!==null&&i!==void 0?i:te.INFO,a);if(m&&!o.suppressOverrideMessage){var b=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";m.warn("Current logger will be overwritten from "+b),_.warn("Current logger will overwrite one already registered from "+b)}return Hr("diag",_,r,!0)};r.setLogger=n,r.disable=function(){Yr(Nf,r)},r.createComponentLogger=function(a){return new xf(a)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}();function Cf(e){return Symbol.for(e)}var Rf=function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,a){var o=new e(r._currentContext);return o._currentContext.set(n,a),o},r.deleteValue=function(n){var a=new e(r._currentContext);return a._currentContext.delete(n),a}}return e}(),Pf=new Rf,$f=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),a,o=[],s;try{for(;(t===void 0||t-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(i){s={error:i}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},Mf=function(e,t,r){if(r||arguments.length===2)for(var n=0,a=t.length,o;n<a;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},zf=function(){function e(){}return e.prototype.active=function(){return Pf},e.prototype.with=function(t,r,n){for(var a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return r.call.apply(r,Mf([n],$f(a),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),Zf=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),a,o=[],s;try{for(;(t===void 0||t-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(i){s={error:i}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o},Df=function(e,t,r){if(r||arguments.length===2)for(var n=0,a=t.length,o;n<a;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},gr="context",Uf=new zf,Xo=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Hr(gr,t,Ut.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var a,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return(a=this._getContextManager()).with.apply(a,Df([t,r,n],Zf(o),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return vt(gr)||Uf},e.prototype.disable=function(){this._getContextManager().disable(),Yr(gr,Ut.instance())},e}(),$r;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})($r||($r={}));var Qo="0000000000000000",es="00000000000000000000000000000000",jf={traceId:es,spanId:Qo,traceFlags:$r.NONE},it=function(){function e(t){t===void 0&&(t=jf),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e}(),Wr=Cf("OpenTelemetry Context Key SPAN");function Kr(e){return e.getValue(Wr)||void 0}function Lf(){return Kr(Xo.getInstance().active())}function Xr(e,t){return e.setValue(Wr,t)}function Ff(e){return e.deleteValue(Wr)}function Vf(e,t){return Xr(e,new it(t))}function ts(e){var t;return(t=Kr(e))===null||t===void 0?void 0:t.spanContext()}var Bf=/^([0-9a-f]{32})$/i,Gf=/^[0-9a-f]{16}$/i;function qf(e){return Bf.test(e)&&e!==es}function Jf(e){return Gf.test(e)&&e!==Qo}function rs(e){return qf(e.traceId)&&Jf(e.spanId)}function Hf(e){return new it(e)}var vr=Xo.getInstance(),ns=function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=vr.active());var a=!!(r!=null&&r.root);if(a)return new it;var o=n&&ts(n);return Yf(o)&&rs(o)?new it(o):new it},e.prototype.startActiveSpan=function(t,r,n,a){var o,s,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,s=n,i=a);var u=s??vr.active(),c=this.startSpan(t,o,u),m=Xr(u,c);return vr.with(m,i,void 0,c)}},e}();function Yf(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var Wf=new ns,Kf=function(){function e(t,r,n,a){this._provider=t,this.name=r,this.version=n,this.options=a}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,a){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):Wf},e}(),Xf=function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new ns},e}(),Qf=new Xf,ma=function(){function e(){}return e.prototype.getTracer=function(t,r,n){var a;return(a=this.getDelegateTracer(t,r,n))!==null&&a!==void 0?a:new Kf(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Qf},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(t,r,n)},e}(),jt;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(jt||(jt={}));var yr="trace",em=function(){function e(){this._proxyTracerProvider=new ma,this.wrapSpanContext=Hf,this.isSpanContextValid=rs,this.deleteSpan=Ff,this.getSpan=Kr,this.getActiveSpan=Lf,this.getSpanContext=ts,this.setSpan=Xr,this.setSpanContext=Vf}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Hr(yr,this._proxyTracerProvider,Ut.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return vt(yr)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Yr(yr,Ut.instance()),this._proxyTracerProvider=new ma},e}(),tm=em.getInstance(),rm=Object.defineProperty,nm=(e,t)=>{for(var r in t)rm(e,r,{get:t[r],enumerable:!0})},as="AI_NoOutputSpecifiedError",os=`vercel.ai.error.${as}`,am=Symbol.for(os),ss,om=class extends C{constructor({message:e="No output specified."}={}){super({name:as,message:e}),this[ss]=!0}static isInstance(e){return C.hasMarker(e,os)}};ss=am;function sm(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let n=`${t} The tool "${r}" is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var im="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",ha=!1,um=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}ha||(ha=!0,console.info(im));for(const r of e)console.warn(sm(r))}},is="AI_InvalidArgumentError",us=`vercel.ai.error.${is}`,cm=Symbol.for(us),cs,me=class extends C{constructor({parameter:e,value:t,message:r}){super({name:is,message:`Invalid argument for parameter ${e}: ${r}`}),this[cs]=!0,this.parameter=e,this.value=t}static isInstance(e){return C.hasMarker(e,us)}};cs=cm;var ls="AI_InvalidToolInputError",ds=`vercel.ai.error.${ls}`,lm=Symbol.for(ds),ps,fs=class extends C{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${qe(r)}`}){super({name:ls,message:n,cause:r}),this[ps]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return C.hasMarker(e,ds)}};ps=lm;var ms="AI_NoObjectGeneratedError",hs=`vercel.ai.error.${ms}`,dm=Symbol.for(hs),gs,ga=class extends C{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:a,finishReason:o}){super({name:ms,message:e,cause:t}),this[gs]=!0,this.text=r,this.response=n,this.usage=a,this.finishReason=o}static isInstance(e){return C.hasMarker(e,hs)}};gs=dm;var vs="AI_NoOutputGeneratedError",ys=`vercel.ai.error.${vs}`,pm=Symbol.for(ys),_s,fm=class extends C{constructor({message:e="No output generated.",cause:t}={}){super({name:vs,message:e,cause:t}),this[_s]=!0}static isInstance(e){return C.hasMarker(e,ys)}};_s=pm;var bs="AI_NoSuchToolError",ws=`vercel.ai.error.${bs}`,mm=Symbol.for(ws),Ts,Mr=class extends C{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:bs,message:r}),this[Ts]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return C.hasMarker(e,ws)}};Ts=mm;var Ss="AI_ToolCallRepairError",Es=`vercel.ai.error.${Ss}`,hm=Symbol.for(Es),Is,gm=class extends C{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${qe(e)}`}){super({name:Ss,message:r,cause:e}),this[Is]=!0,this.originalError=t}static isInstance(e){return C.hasMarker(e,Es)}};Is=hm;var vm=class extends C{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}},xs="AI_InvalidMessageRoleError",As=`vercel.ai.error.${xs}`,ym=Symbol.for(As),ks,_m=class extends C{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:xs,message:t}),this[ks]=!0,this.role=e}static isInstance(e){return C.hasMarker(e,As)}};ks=ym;var Os="AI_DownloadError",Ns=`vercel.ai.error.${Os}`,bm=Symbol.for(Ns),Cs,_r=class extends C{constructor({url:e,statusCode:t,statusText:r,cause:n,message:a=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Os,message:a,cause:n}),this[Cs]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return C.hasMarker(e,Ns)}};Cs=bm;var Rs="AI_RetryError",Ps=`vercel.ai.error.${Rs}`,wm=Symbol.for(Ps),$s,va=class extends C{constructor({message:e,reason:t,errors:r}){super({name:Rs,message:e}),this[$s]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return C.hasMarker(e,Ps)}};$s=wm;function Ms(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new vm({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Tm().languageModel(e)}function Tm(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:yf}var Sm=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],Em=e=>{const t=typeof e=="string"?qr(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function Im(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Em(e):e}function xm({data:e,signatures:t}){const r=Im(e),n=typeof r=="string"?qr(r.substring(0,Math.min(r.length,24))):r;for(const a of t)if(n.length>=a.bytesPrefix.length&&a.bytesPrefix.every((o,s)=>o===null||n[s]===o))return a.mediaType}var Am="5.0.76",km=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:Bt({},`ai-sdk/${Am}`,Br())});if(!n.ok)throw new _r({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(t=n.headers.get("content-type"))!=null?t:void 0}}catch(n){throw _r.isInstance(n)?n:new _r({url:r,cause:n})}},Om=(e=km)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Nm(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var zs=q([A(),zt(Uint8Array),zt(ArrayBuffer),kd(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function Zs(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=Nm(e.toString());if(t==null||r==null)throw new C({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function Cm(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Pr(new Uint8Array(e)):Pr(e)}async function Rm({prompt:e,supportedUrls:t,download:r=Om()}){const n=await $m(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(a=>Pm({message:a,downloadedAssets:n}))]}function Pm({message:e,downloadedAssets:t}){const r=e.role;switch(r){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(n=>Mm(n,t)).filter(n=>n.type!=="text"||n.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(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const a=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:s}=Zs(n.data);return{type:"file",data:o,filename:n.filename,mediaType:s??n.mediaType,providerOptions:a}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:a};case"text":return{type:"text",text:n.text,providerOptions:a};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:a};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:a}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:e.providerOptions};default:{const n=r;throw new _m({role:n})}}}async function $m(e,t,r){const n=e.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var s;const i=(s=o.mediaType)!=null?s:o.type==="image"?"image/*":void 0;let u=o.type==="image"?o.image:o.data;if(typeof u=="string")try{u=new URL(u)}catch{}return{mediaType:i,data:u}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&zd({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),a=await t(n);return Object.fromEntries(a.map((o,s)=>o==null?null:[n[s].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function Mm(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const a=e.type;switch(a){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${a}`)}const{data:o,mediaType:s}=Zs(n);let i=s??e.mediaType,u=o;if(u instanceof URL){const c=t[u.toString()];c&&(u=c.data,i??(i=c.mediaType))}switch(a){case"image":return(u instanceof Uint8Array||typeof u=="string")&&(i=(r=xm({data:u,signatures:Sm}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:u,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:u,providerOptions:e.providerOptions}}}}function zm({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:a,frequencyPenalty:o,seed:s,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new me({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new me({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new me({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new me({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new me({parameter:"topK",value:n,message:"topK must be a number"});if(a!=null&&typeof a!="number")throw new me({parameter:"presencePenalty",value:a,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new me({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(s!=null&&!Number.isInteger(s))throw new me({parameter:"seed",value:s,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:a,frequencyPenalty:o,stopSequences:i,seed:s}}function Zm(e){return e!=null&&Object.keys(e).length>0}function Dm({tools:e,toolChoice:t,activeTools:r}){return Zm(e)?{tools:(r!=null?Object.entries(e).filter(([a])=>r.includes(a)):Object.entries(e)).map(([a,o])=>{const s=o.type;switch(s){case void 0:case"dynamic":case"function":return{type:"function",name:a,description:o.description,inputSchema:Gt(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:a,id:o.id,args:o.args};default:{const i=s;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var yt=Ad(()=>q([td(),A(),Ee(),ke(),pt(A(),yt),ie(yt)])),he=pt(A(),pt(A(),yt)),Ds=O({type:z("text"),text:A(),providerOptions:he.optional()}),Um=O({type:z("image"),image:q([zs,zt(URL)]),mediaType:A().optional(),providerOptions:he.optional()}),Us=O({type:z("file"),data:q([zs,zt(URL)]),filename:A().optional(),mediaType:A(),providerOptions:he.optional()}),jm=O({type:z("reasoning"),text:A(),providerOptions:he.optional()}),Lm=O({type:z("tool-call"),toolCallId:A(),toolName:A(),input:Ie(),providerOptions:he.optional(),providerExecuted:ke().optional()}),Fm=ud("type",[O({type:z("text"),value:A()}),O({type:z("json"),value:yt}),O({type:z("error-text"),value:A()}),O({type:z("error-json"),value:yt}),O({type:z("content"),value:ie(q([O({type:z("text"),text:A()}),O({type:z("media"),data:A(),mediaType:A()})]))})]),js=O({type:z("tool-result"),toolCallId:A(),toolName:A(),output:Fm,providerOptions:he.optional()}),Vm=O({role:z("system"),content:A(),providerOptions:he.optional()}),Bm=O({role:z("user"),content:q([A(),ie(q([Ds,Um,Us]))]),providerOptions:he.optional()}),Gm=O({role:z("assistant"),content:q([A(),ie(q([Ds,Us,jm,Lm,js]))]),providerOptions:he.optional()}),qm=O({role:z("tool"),content:ie(js),providerOptions:he.optional()}),Jm=q([Vm,Bm,Gm,qm]);async function Hm(e){if(e.prompt==null&&e.messages==null)throw new Le({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Le({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Le({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 Le({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Le({prompt:e,message:"messages must not be empty"});const r=await xe({value:t,schema:ie(Jm)});if(!r.success)throw new Le({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function Ym(e){return Jr.isInstance(e)||Ho.isInstance(e)?new C({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 zr({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Wm({model:e,settings:t,telemetry:r,headers:n}){var a;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((o,[s,i])=>(o[`ai.settings.${s}`]=i,o),{}),...Object.entries((a=r==null?void 0:r.metadata)!=null?a:{}).reduce((o,[s,i])=>(o[`ai.telemetry.metadata.${s}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[s,i])=>(i!==void 0&&(o[`ai.request.headers.${s}`]=i),o),{})}}var Km={startSpan(){return kt},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(kt);if(typeof r=="function")return r(kt);if(typeof n=="function")return n(kt)}},kt={spanContext(){return Xm},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}},Xm={traceId:"",spanId:"",traceFlags:0};function Qm({isEnabled:e=!1,tracer:t}={}){return e?t||tm.getTracer("ai"):Km}function Zr({name:e,tracer:t,attributes:r,fn:n,endWhenDone:a=!0}){return t.startActiveSpan(e,{attributes:r},async o=>{try{const s=await n(o);return a&&o.end(),s}catch(s){try{Ls(o,s)}finally{o.end()}throw s}})}function Ls(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:jt.ERROR,message:t.message})):e.setStatus({code:jt.ERROR})}function Be({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((r,[n,a])=>{if(a==null)return r;if(typeof a=="object"&&"input"in a&&typeof a.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return r;const o=a.input();return o==null?r:{...r,[n]:o}}if(typeof a=="object"&&"output"in a&&typeof a.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return r;const o=a.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:a}},{})}function eh(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?Cm(r.data):r.data}:r)})))}function th(e,t){return{inputTokens:at(e.inputTokens,t.inputTokens),outputTokens:at(e.outputTokens,t.outputTokens),totalTokens:at(e.totalTokens,t.totalTokens),reasoningTokens:at(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:at(e.cachedInputTokens,t.cachedInputTokens)}}function at(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ya(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function rh({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const a=r["retry-after-ms"];if(a){const s=parseFloat(a);Number.isNaN(s)||(n=s)}const o=r["retry-after"];if(o&&n===void 0){const s=parseFloat(o);Number.isNaN(s)?n=Date.parse(o)-Date.now():n=s*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var nh=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async a=>Fs(a,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Fs(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:a},o=[]){try{return await e()}catch(s){if(Ce(s)||t===0)throw s;const i=Po(s),u=[...o,s],c=u.length;if(c>t)throw new va({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:u});if(s instanceof Error&&Q.isInstance(s)&&s.isRetryable===!0&&c<=t)return await Cd(rh({error:s,exponentialBackoffDelay:r}),{abortSignal:a}),Fs(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:a},u);throw c===1?s:new va({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:u})}}function ah({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new me({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new me({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:nh({maxRetries:r,abortSignal:t})}}var oh=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Pr(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=qr(this.base64Data)),this.uint8ArrayData}},sh=class extends oh{constructor(e){super(e),this.type="file"}};async function ih({toolCall:e,tools:t,repairToolCall:r,system:n,messages:a}){try{if(t==null)throw new Mr({toolName:e.toolName});try{return await _a({toolCall:e,tools:t})}catch(o){if(r==null||!(Mr.isInstance(o)||fs.isInstance(o)))throw o;let s=null;try{s=await r({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:u}=t[i];return Gt(u).jsonSchema},system:n,messages:a,error:o})}catch(i){throw new gm({cause:i,originalError:o})}if(s==null)throw o;return await _a({toolCall:s,tools:t})}}catch(o){const s=await Re({text:e.input}),i=s.success?s.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:o}}}async function _a({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new Mr({toolName:e.toolName,availableTools:Object.keys(t)});const a=Gt(n.inputSchema),o=e.input.trim()===""?await xe({value:{},schema:a}):await Re({text:e.input,schema:a});if(o.success===!1)throw new fs({toolName:r,toolInput:e.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var uh=class{constructor({content:e,finishReason:t,usage:r,warnings:n,request:a,response:o,providerMetadata:s}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=n,this.request=a,this.response=o,this.providerMetadata=s}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!==!0)}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!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function ch(e){return({steps:t})=>t.length===e}async function lh({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function br({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:qe(e)}:r==="json"?{type:"error-json",value:ba(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:ba(e)}}function ba(e){return e===void 0?null:e}function wa({content:e,tools:t}){const r=[],n=e.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:br({tool:t==null?void 0:t[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:br({tool:t==null?void 0:t[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const a=e.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:br({tool:t==null?void 0:t[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"})}));return a.length>0&&r.push({role:"tool",content:a}),r}Tt({prefix:"aitxt",size:24});function qt(e,t){const r=new Headers(e??{});for(const[n,a]of Object.entries(t))r.has(n)||r.set(n,a);return r}function dh({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:qt(r,{"content-type":"text/plain; charset=utf-8"})})}function Vs({response:e,status:t,statusText:r,headers:n,stream:a}){e.writeHead(t??200,r,n);const o=a.getReader();(async()=>{try{for(;;){const{done:i,value:u}=await o.read();if(i)break;e.write(u)||await new Promise(m=>{e.once("drain",m)})}}catch(i){throw i}finally{e.end()}})()}function ph({response:e,status:t,statusText:r,headers:n,textStream:a}){Vs({response:e,status:t,statusText:r,headers:Object.fromEntries(qt(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:a.pipeThrough(new TextEncoderStream)})}var Bs=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
235
|
+
|
|
236
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
237
|
+
|
|
238
|
+
`)}})}},Gs={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function fh({status:e,statusText:t,headers:r,stream:n,consumeSseStream:a}){let o=n.pipeThrough(new Bs);if(a){const[s,i]=o.tee();o=s,a({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:qt(r,Gs)})}function mh({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof t=="function"?t():t}function hh(e){return e.type.startsWith("data-")}function qs(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];if(a===void 0)continue;const o=n in e?e[n]:void 0,s=a!==null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);s&&i?r[n]=qs(o,a):r[n]=a}return r}function gh(e){const t=["ROOT"];let r=-1,n=null;function a(u,c,m){switch(u){case'"':{r=c,t.pop(),t.push(m),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(m),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(m),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":{r=c,t.pop(),t.push(m),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(m),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(m),t.push("INSIDE_ARRAY_START");break}}}function o(u,c){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function s(u,c){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let u=0;u<e.length;u++){const c=e[u];switch(t[t.length-1]){case"ROOT":a(c,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{a(c,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(c,u);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=u}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=u,t.pop();break}default:{r=u,a(c,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}default:{r=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{a(c,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=u;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":{r=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(c,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(c,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const _=e.substring(n,u+1);!"false".startsWith(_)&&!"true".startsWith(_)&&!"null".startsWith(_)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(c,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(c,u)):r=u;break}}}let i=e.slice(0,r+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{i+='"';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":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const m=e.substring(n,e.length);"true".startsWith(m)?i+="true".slice(m.length):"false".startsWith(m)?i+="false".slice(m.length):"null".startsWith(m)&&(i+="null".slice(m.length))}}return i}async function Js(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Re({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Re({text:gh(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function wr(e){return e.type.startsWith("tool-")}function Ta(e){return e.type.split("-").slice(1).join("-")}function vh({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function yh({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:a,onToolCall:o,onData:s}){return e.pipeThrough(new TransformStream({async transform(i,u){await n(async({state:c,write:m})=>{var _,b,p,f;function w(d){const I=c.message.parts.filter(wr).find(x=>x.toolCallId===d);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function v(d){const I=c.message.parts.filter(x=>x.type==="dynamic-tool").find(x=>x.toolCallId===d);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function l(d){var S;const I=c.message.parts.find(J=>wr(J)&&J.toolCallId===d.toolCallId),x=d,M=I;I!=null?(I.state=d.state,M.input=x.input,M.output=x.output,M.errorText=x.errorText,M.rawInput=x.rawInput,M.preliminary=x.preliminary,M.providerExecuted=(S=x.providerExecuted)!=null?S:I.providerExecuted,x.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=x.providerMetadata)):c.message.parts.push({type:`tool-${d.toolName}`,toolCallId:d.toolCallId,state:d.state,input:x.input,output:x.output,rawInput:x.rawInput,errorText:x.errorText,providerExecuted:x.providerExecuted,preliminary:x.preliminary,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}function g(d){var S;const I=c.message.parts.find(J=>J.type==="dynamic-tool"&&J.toolCallId===d.toolCallId),x=d,M=I;I!=null?(I.state=d.state,M.toolName=d.toolName,M.input=x.input,M.output=x.output,M.errorText=x.errorText,M.rawInput=(S=x.rawInput)!=null?S:M.rawInput,M.preliminary=x.preliminary,x.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=x.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:d.toolName,toolCallId:d.toolCallId,state:d.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function y(d){if(d!=null){const S=c.message.metadata!=null?qs(c.message.metadata,d):d;t!=null&&await Or({value:S,schema:t}),c.message.metadata=S}}switch(i.type){case"text-start":{const d={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=d,c.message.parts.push(d),m();break}case"text-delta":{const d=c.activeTextParts[i.id];d.text+=i.delta,d.providerMetadata=(_=i.providerMetadata)!=null?_:d.providerMetadata,m();break}case"text-end":{const d=c.activeTextParts[i.id];d.state="done",d.providerMetadata=(b=i.providerMetadata)!=null?b:d.providerMetadata,delete c.activeTextParts[i.id],m();break}case"reasoning-start":{const d={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=d,c.message.parts.push(d),m();break}case"reasoning-delta":{const d=c.activeReasoningParts[i.id];d.text+=i.delta,d.providerMetadata=(p=i.providerMetadata)!=null?p:d.providerMetadata,m();break}case"reasoning-end":{const d=c.activeReasoningParts[i.id];d.providerMetadata=(f=i.providerMetadata)!=null?f:d.providerMetadata,d.state="done",delete c.activeReasoningParts[i.id],m();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),m();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),m();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),m();break}case"tool-input-start":{const d=c.message.parts.filter(wr);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:d.length,dynamic:i.dynamic},i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):l({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),m();break}case"tool-input-delta":{const d=c.partialToolCalls[i.toolCallId];d.text+=i.inputTextDelta;const{value:S}=await Js(d.text);d.dynamic?g({toolCallId:i.toolCallId,toolName:d.toolName,state:"input-streaming",input:S}):l({toolCallId:i.toolCallId,toolName:d.toolName,state:"input-streaming",input:S}),m();break}case"tool-input-available":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):l({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),m(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?g({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):l({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),m();break}case"tool-output-available":{if(i.dynamic){const d=v(i.toolCallId);g({toolCallId:i.toolCallId,toolName:d.toolName,state:"output-available",input:d.input,output:i.output,preliminary:i.preliminary})}else{const d=w(i.toolCallId);l({toolCallId:i.toolCallId,toolName:Ta(d),state:"output-available",input:d.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}m();break}case"tool-output-error":{if(i.dynamic){const d=v(i.toolCallId);g({toolCallId:i.toolCallId,toolName:d.toolName,state:"output-error",input:d.input,errorText:i.errorText})}else{const d=w(i.toolCallId);l({toolCallId:i.toolCallId,toolName:Ta(d),state:"output-error",input:d.input,rawInput:d.rawInput,errorText:i.errorText})}m();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await y(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&m();break}case"finish":{await y(i.messageMetadata),i.messageMetadata!=null&&m();break}case"message-metadata":{await y(i.messageMetadata),i.messageMetadata!=null&&m();break}case"error":{a==null||a(new Error(i.errorText));break}default:if(hh(i)){(r==null?void 0:r[i.type])!=null&&await Or({value:i.data,schema:r[i.type]});const d=i;if(d.transient){s==null||s(d);break}const S=d.id!=null?c.message.parts.find(I=>d.type===I.type&&d.id===I.id):void 0;S!=null?S.data=d.data:c.message.parts.push(d),s==null||s(d),m()}}u.enqueue(i)})}}))}function _h({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:a}){let o=t==null?void 0:t[t.length-1];(o==null?void 0:o.role)!=="assistant"?o=void 0:e=o.id;let s=!1;const i=a.pipeThrough(new TransformStream({transform(b,p){if(b.type==="start"){const f=b;f.messageId==null&&e!=null&&(f.messageId=e)}b.type==="abort"&&(s=!0),p.enqueue(b)}}));if(r==null)return i;const u=vh({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),c=async b=>{await b({state:u,write:()=>{}})};let m=!1;const _=async()=>{if(m||!r)return;m=!0;const b=u.message.id===(o==null?void 0:o.id);await r({isAborted:s,isContinuation:b,responseMessage:u.message,messages:[...b?t.slice(0,-1):t,u.message]})};return yh({stream:i,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(b,p){p.enqueue(b)},async cancel(){await _()},async flush(){await _()}}))}function bh({response:e,status:t,statusText:r,headers:n,stream:a,consumeSseStream:o}){let s=a.pipeThrough(new Bs);if(o){const[i,u]=s.tee();s=i,o({stream:u})}Vs({response:e,status:t,statusText:r,headers:Object.fromEntries(qt(n,Gs).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function Ot(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function a(o){var s;n=!0;try{o&&await((s=r.cancel)==null?void 0:s.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:s}=await r.read();return o?(await a(!0),{done:!0,value:void 0}):{done:!1,value:s}},async return(){return await a(!0),{done:!0,value:void 0}},async throw(o){throw await a(!0),o}}},t}async function wh({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t==null||t(n)}finally{r.releaseLock()}}function Sa(){let e,t;return{promise:new Promise((n,a)=>{e=n,t=a}),resolve:e,reject:t}}function Th(){let e=[],t=null,r=!1,n=Sa();const a=()=>{r=!0,n.resolve(),e.forEach(s=>s.cancel()),e=[],t==null||t.close()},o=async()=>{if(r&&e.length===0){t==null||t.close();return}if(e.length===0)return n=Sa(),await n.promise,o();try{const{value:s,done:i}=await e[0].read();i?(e.shift(),e.length>0?await o():r&&(t==null||t.close())):t==null||t.enqueue(s)}catch(s){t==null||t.error(s),e.shift(),a()}};return{stream:new ReadableStream({start(s){t=s},pull:o,async cancel(){for(const s of e)await s.cancel();e=[],r=!0}}),addStream:s=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(s.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&(t==null||t.close())},terminate:a}}var Nt=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(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 Sh(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function Eh({tools:e,generatorStream:t,tracer:r,telemetry:n,system:a,messages:o,abortSignal:s,repairToolCall:i,experimental_context:u}){let c=null;const m=new ReadableStream({start(l){c=l}}),_=new Set,b=new Map;let p=!1,f;function w(){p&&_.size===0&&(f!=null&&c.enqueue(f),c.close())}const v=new TransformStream({async transform(l,g){const y=l.type;switch(y){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":{g.enqueue(l);break}case"file":{g.enqueue({type:"file",file:new sh({data:l.data,mediaType:l.mediaType})});break}case"finish":{f={type:"finish",finishReason:l.finishReason,usage:l.usage,providerMetadata:l.providerMetadata};break}case"tool-call":{try{const d=await ih({toolCall:l,tools:e,repairToolCall:i,system:a,messages:o});if(g.enqueue(d),d.invalid){c.enqueue({type:"tool-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,error:Po(d.error),dynamic:!0});break}const S=e[d.toolName];if(b.set(d.toolCallId,d.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:d.input,toolCallId:d.toolCallId,messages:o,abortSignal:s,experimental_context:u}),S.execute!=null&&d.providerExecuted!==!0){const I=Rd();_.add(I),Zr({name:"ai.toolCall",attributes:Be({telemetry:n,attributes:{...zr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":d.toolName,"ai.toolCall.id":d.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(d.input)}}}),tracer:r,fn:async x=>{let M;try{const J=Gp({execute:S.execute.bind(S),input:d.input,options:{toolCallId:d.toolCallId,messages:o,abortSignal:s,experimental_context:u}});for await(const ge of J)c.enqueue({...d,type:"tool-result",output:ge.output,...ge.type==="preliminary"&&{preliminary:!0}}),ge.type==="final"&&(M=ge.output)}catch(J){Ls(x,J),c.enqueue({...d,type:"tool-error",error:J}),_.delete(I),w();return}_.delete(I),w();try{x.setAttributes(Be({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(M)}}}))}catch{}}})}}catch(d){c.enqueue({type:"error",error:d})}break}case"tool-result":{const d=l.toolName;l.isError?c.enqueue({type:"tool-error",toolCallId:l.toolCallId,toolName:d,input:b.get(l.toolCallId),providerExecuted:l.providerExecuted,error:l.result}):g.enqueue({type:"tool-result",toolCallId:l.toolCallId,toolName:d,input:b.get(l.toolCallId),output:l.result,providerExecuted:l.providerExecuted});break}default:{const d=y;throw new Error(`Unhandled chunk type: ${d}`)}}},flush(){p=!0,w()}});return new ReadableStream({async start(l){return Promise.all([t.pipeThrough(v).pipeTo(new WritableStream({write(g){l.enqueue(g)},close(){}})),m.pipeTo(new WritableStream({write(g){l.enqueue(g)},close(){l.close()}}))])}})}var Ih=Tt({prefix:"aitxt",size:24});function xh({model:e,tools:t,toolChoice:r,system:n,prompt:a,messages:o,maxRetries:s,abortSignal:i,headers:u,stopWhen:c=ch(1),experimental_output:m,experimental_telemetry:_,prepareStep:b,providerOptions:p,experimental_activeTools:f,activeTools:w=f,experimental_repairToolCall:v,experimental_transform:l,experimental_download:g,includeRawChunks:y=!1,onChunk:d,onError:S=({error:ae})=>{console.error(ae)},onFinish:I,onAbort:x,onStepFinish:M,experimental_context:J,_internal:{now:ge=Sh,generateId:Ye=Ih,currentDate:Ht=()=>new Date}={},...We}){return new kh({model:Ms(e),telemetry:_,headers:u,settings:We,maxRetries:s,abortSignal:i,system:n,prompt:a,messages:o,tools:t,toolChoice:r,transforms:ya(l),activeTools:w,repairToolCall:v,stopConditions:ya(c),output:m,providerOptions:p,prepareStep:b,includeRawChunks:y,onChunk:d,onError:S,onFinish:I,onAbort:x,onStepFinish:M,now:ge,currentDate:Ht,generateId:Ye,experimental_context:J,download:g})}function Ah(e){if(!e)return new TransformStream({transform(s,i){i.enqueue({part:s,partialOutput:void 0})}});let t,r="",n="",a="";function o({controller:s,partialOutput:i=void 0}){s.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(s,i){if(s.type==="finish-step"&&n.length>0&&o({controller:i}),s.type!=="text-delta"&&s.type!=="text-start"&&s.type!=="text-end"){i.enqueue({part:s,partialOutput:void 0});return}if(t==null)t=s.id;else if(s.id!==t){i.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-start"){i.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:s,partialOutput:void 0});return}r+=s.text,n+=s.text;const u=await e.parsePartial({text:r});if(u!=null){const c=JSON.stringify(u.partial);c!==a&&(o({controller:i,partialOutput:u.partial}),a=c)}}})}var kh=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:a,abortSignal:o,system:s,prompt:i,messages:u,tools:c,toolChoice:m,transforms:_,activeTools:b,repairToolCall:p,stopConditions:f,output:w,providerOptions:v,prepareStep:l,includeRawChunks:g,now:y,currentDate:d,generateId:S,onChunk:I,onError:x,onFinish:M,onAbort:J,onStepFinish:ge,experimental_context:Ye,download:Ht}){this._totalUsage=new Nt,this._finishReason=new Nt,this._steps=new Nt,this.output=w,this.includeRawChunks=g,this.tools=c;let We,ae=[];const en=[];let Yt,Wt,tn={},Kt=[];const oe=[];let Xt,ze={},Ze={};const Xs=new TransformStream({async transform(F,V){var H,P,ue,Xe;V.enqueue(F);const{part:T}=F;if((T.type==="text-delta"||T.type==="reasoning-delta"||T.type==="source"||T.type==="tool-call"||T.type==="tool-result"||T.type==="tool-input-start"||T.type==="tool-input-delta"||T.type==="raw")&&await(I==null?void 0:I({chunk:T})),T.type==="error"&&await x({error:Ym(T.error)}),T.type==="text-start"&&(ze[T.id]={type:"text",text:"",providerMetadata:T.providerMetadata},ae.push(ze[T.id])),T.type==="text-delta"){const j=ze[T.id];if(j==null){V.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}j.text+=T.text,j.providerMetadata=(H=T.providerMetadata)!=null?H:j.providerMetadata}if(T.type==="text-end"){const j=ze[T.id];if(j==null){V.enqueue({part:{type:"error",error:`text part ${T.id} not found`},partialOutput:void 0});return}j.providerMetadata=(P=T.providerMetadata)!=null?P:j.providerMetadata,delete ze[T.id]}if(T.type==="reasoning-start"&&(Ze[T.id]={type:"reasoning",text:"",providerMetadata:T.providerMetadata},ae.push(Ze[T.id])),T.type==="reasoning-delta"){const j=Ze[T.id];if(j==null){V.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}j.text+=T.text,j.providerMetadata=(ue=T.providerMetadata)!=null?ue:j.providerMetadata}if(T.type==="reasoning-end"){const j=Ze[T.id];if(j==null){V.enqueue({part:{type:"error",error:`reasoning part ${T.id} not found`},partialOutput:void 0});return}j.providerMetadata=(Xe=T.providerMetadata)!=null?Xe:j.providerMetadata,delete Ze[T.id]}if(T.type==="file"&&ae.push({type:"file",file:T.file}),T.type==="source"&&ae.push(T),T.type==="tool-call"&&ae.push(T),T.type==="tool-result"&&!T.preliminary&&ae.push(T),T.type==="tool-error"&&ae.push(T),T.type==="start-step"&&(tn=T.request,Kt=T.warnings),T.type==="finish-step"){const j=wa({content:ae,tools:c}),Qe=new uh({content:ae,finishReason:T.finishReason,usage:T.usage,warnings:Kt,request:tn,response:{...T.response,messages:[...en,...j]},providerMetadata:T.providerMetadata});await(ge==null?void 0:ge(Qe)),um(Kt),oe.push(Qe),ae=[],Ze={},ze={},en.push(...j),We.resolve()}T.type==="finish"&&(Wt=T.totalUsage,Yt=T.finishReason)},async flush(F){try{if(oe.length===0){const ue=new fm({message:"No output generated. Check the stream for errors."});se._finishReason.reject(ue),se._totalUsage.reject(ue),se._steps.reject(ue);return}const V=Yt??"unknown",H=Wt??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};se._finishReason.resolve(V),se._totalUsage.resolve(H),se._steps.resolve(oe);const P=oe[oe.length-1];await(M==null?void 0:M({finishReason:V,totalUsage:H,usage:P.usage,content:P.content,text:P.text,reasoningText:P.reasoningText,reasoning:P.reasoning,files:P.files,sources:P.sources,toolCalls:P.toolCalls,staticToolCalls:P.staticToolCalls,dynamicToolCalls:P.dynamicToolCalls,toolResults:P.toolResults,staticToolResults:P.staticToolResults,dynamicToolResults:P.dynamicToolResults,request:P.request,response:P.response,warnings:P.warnings,providerMetadata:P.providerMetadata,steps:oe})),Xt.setAttributes(Be({telemetry:t,attributes:{"ai.response.finishReason":V,"ai.response.text":{output:()=>P.text},"ai.response.toolCalls":{output:()=>{var ue;return(ue=P.toolCalls)!=null&&ue.length?JSON.stringify(P.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(P.providerMetadata),"ai.usage.inputTokens":H.inputTokens,"ai.usage.outputTokens":H.outputTokens,"ai.usage.totalTokens":H.totalTokens,"ai.usage.reasoningTokens":H.reasoningTokens,"ai.usage.cachedInputTokens":H.cachedInputTokens}}))}catch(V){F.error(V)}finally{Xt.end()}}}),Ke=Th();this.addStream=Ke.addStream,this.closeStream=Ke.close;const Qs=Ke.stream.getReader();let Qt=new ReadableStream({async start(F){F.enqueue({type:"start"})},async pull(F){function V(){J==null||J({steps:oe}),F.enqueue({type:"abort"}),F.close()}try{const{done:H,value:P}=await Qs.read();if(H){F.close();return}if(o!=null&&o.aborted){V();return}F.enqueue(P)}catch(H){Ce(H)&&(o!=null&&o.aborted)?V():F.error(H)}},cancel(F){return Ke.stream.cancel(F)}});for(const F of _)Qt=Qt.pipeThrough(F({tools:c,stopStream(){Ke.terminate()}}));this.baseStream=Qt.pipeThrough(Ah(w)).pipeThrough(Xs);const{maxRetries:ei,retry:ti}=ah({maxRetries:a,abortSignal:o}),er=Qm(t),ve=zm(n),rn=Wm({model:e,telemetry:t,headers:r,settings:{...ve,maxRetries:ei}}),se=this;Zr({name:"ai.streamText",attributes:Be({telemetry:t,attributes:{...zr({operationId:"ai.streamText",telemetry:t}),...rn,"ai.prompt":{input:()=>JSON.stringify({system:s,prompt:i,messages:u})}}}),tracer:er,endWhenDone:!1,fn:async F=>{Xt=F;async function V({currentStep:H,responseMessages:P,usage:ue}){var Xe,T,j,Qe,nn;const an=se.includeRawChunks;We=new Nt;const on=await Hm({system:s,prompt:i,messages:u}),et=[...on.messages,...P],pe=await(l==null?void 0:l({model:e,steps:oe,stepNumber:oe.length,messages:et})),De=Ms((Xe=pe==null?void 0:pe.model)!=null?Xe:e),sn=await Rm({prompt:{system:(T=pe==null?void 0:pe.system)!=null?T:on.system,messages:(j=pe==null?void 0:pe.messages)!=null?j:et},supportedUrls:await De.supportedUrls,download:Ht}),{toolChoice:tr,tools:rr}=Dm({tools:c,toolChoice:(Qe=pe==null?void 0:pe.toolChoice)!=null?Qe:m,activeTools:(nn=pe==null?void 0:pe.activeTools)!=null?nn:b}),{result:{stream:ri,response:un,request:cn},doStreamSpan:Ue,startTimestampMs:ln}=await ti(()=>Zr({name:"ai.streamText.doStream",attributes:Be({telemetry:t,attributes:{...zr({operationId:"ai.streamText.doStream",telemetry:t}),...rn,"ai.model.provider":De.provider,"ai.model.id":De.modelId,"ai.prompt.messages":{input:()=>eh(sn)},"ai.prompt.tools":{input:()=>rr==null?void 0:rr.map(k=>JSON.stringify(k))},"ai.prompt.toolChoice":{input:()=>tr!=null?JSON.stringify(tr):void 0},"gen_ai.system":De.provider,"gen_ai.request.model":De.modelId,"gen_ai.request.frequency_penalty":ve.frequencyPenalty,"gen_ai.request.max_tokens":ve.maxOutputTokens,"gen_ai.request.presence_penalty":ve.presencePenalty,"gen_ai.request.stop_sequences":ve.stopSequences,"gen_ai.request.temperature":ve.temperature,"gen_ai.request.top_k":ve.topK,"gen_ai.request.top_p":ve.topP}}),tracer:er,endWhenDone:!1,fn:async k=>({startTimestampMs:y(),doStreamSpan:k,result:await De.doStream({...ve,tools:rr,toolChoice:tr,responseFormat:w==null?void 0:w.responseFormat,prompt:sn,providerOptions:v,abortSignal:o,headers:r,includeRawChunks:an})})})),ni=Eh({tools:c,generatorStream:ri,tracer:er,telemetry:t,system:s,messages:et,repairToolCall:p,abortSignal:o,experimental_context:Ye}),ai=cn??{},St=[],nr=[];let ar;const or={};let je="unknown",ce={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},sr,dn=!0,fe={id:S(),timestamp:d(),modelId:e.modelId},pn="";se.addStream(ni.pipeThrough(new TransformStream({async transform(k,Y){var tt,rt,Et,ye;if(k.type==="stream-start"){ar=k.warnings;return}if(dn){const K=y()-ln;dn=!1,Ue.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":K}),Ue.setAttributes({"ai.response.msToFirstChunk":K}),Y.enqueue({type:"start-step",request:ai,warnings:ar??[]})}const fn=k.type;switch(fn){case"text-start":case"text-end":{Y.enqueue(k);break}case"text-delta":{k.delta.length>0&&(Y.enqueue({type:"text-delta",id:k.id,text:k.delta,providerMetadata:k.providerMetadata}),pn+=k.delta);break}case"reasoning-start":case"reasoning-end":{Y.enqueue(k);break}case"reasoning-delta":{Y.enqueue({type:"reasoning-delta",id:k.id,text:k.delta,providerMetadata:k.providerMetadata});break}case"tool-call":{Y.enqueue(k),St.push(k);break}case"tool-result":{Y.enqueue(k),k.preliminary||nr.push(k);break}case"tool-error":{Y.enqueue(k),nr.push(k);break}case"response-metadata":{fe={id:(tt=k.id)!=null?tt:fe.id,timestamp:(rt=k.timestamp)!=null?rt:fe.timestamp,modelId:(Et=k.modelId)!=null?Et:fe.modelId};break}case"finish":{ce=k.usage,je=k.finishReason,sr=k.providerMetadata;const K=y()-ln;Ue.addEvent("ai.stream.finish"),Ue.setAttributes({"ai.response.msToFinish":K,"ai.response.avgOutputTokensPerSecond":1e3*((ye=ce.outputTokens)!=null?ye:0)/K});break}case"file":{Y.enqueue(k);break}case"source":{Y.enqueue(k);break}case"tool-input-start":{or[k.id]=k.toolName;const K=c==null?void 0:c[k.toolName];(K==null?void 0:K.onInputStart)!=null&&await K.onInputStart({toolCallId:k.id,messages:et,abortSignal:o,experimental_context:Ye}),Y.enqueue({...k,dynamic:(K==null?void 0:K.type)==="dynamic"});break}case"tool-input-end":{delete or[k.id],Y.enqueue(k);break}case"tool-input-delta":{const K=or[k.id],ir=c==null?void 0:c[K];(ir==null?void 0:ir.onInputDelta)!=null&&await ir.onInputDelta({inputTextDelta:k.delta,toolCallId:k.id,messages:et,abortSignal:o,experimental_context:Ye}),Y.enqueue(k);break}case"error":{Y.enqueue(k),je="error";break}case"raw":{an&&Y.enqueue(k);break}default:{const K=fn;throw new Error(`Unknown chunk type: ${K}`)}}},async flush(k){const Y=St.length>0?JSON.stringify(St):void 0;try{Ue.setAttributes(Be({telemetry:t,attributes:{"ai.response.finishReason":je,"ai.response.text":{output:()=>pn},"ai.response.toolCalls":{output:()=>Y},"ai.response.id":fe.id,"ai.response.model":fe.modelId,"ai.response.timestamp":fe.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(sr),"ai.usage.inputTokens":ce.inputTokens,"ai.usage.outputTokens":ce.outputTokens,"ai.usage.totalTokens":ce.totalTokens,"ai.usage.reasoningTokens":ce.reasoningTokens,"ai.usage.cachedInputTokens":ce.cachedInputTokens,"gen_ai.response.finish_reasons":[je],"gen_ai.response.id":fe.id,"gen_ai.response.model":fe.modelId,"gen_ai.usage.input_tokens":ce.inputTokens,"gen_ai.usage.output_tokens":ce.outputTokens}}))}catch{}finally{Ue.end()}k.enqueue({type:"finish-step",finishReason:je,usage:ce,providerMetadata:sr,response:{...fe,headers:un==null?void 0:un.headers}});const tt=th(ue,ce);await We.promise;const rt=St.filter(ye=>ye.providerExecuted!==!0),Et=nr.filter(ye=>ye.providerExecuted!==!0);if(rt.length>0&&Et.length===rt.length&&!await lh({stopConditions:f,steps:oe})){P.push(...wa({content:oe[oe.length-1].content,tools:c}));try{await V({currentStep:H+1,responseMessages:P,usage:tt})}catch(ye){k.enqueue({type:"error",error:ye}),se.closeStream()}}else k.enqueue({type:"finish",finishReason:je,totalUsage:tt}),se.closeStream()}})))}await V({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(F=>{se.addStream(new ReadableStream({start(V){V.enqueue({type:"error",error:F}),V.close()}})),se.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(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ot(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ot(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await wh({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(r){(t=e==null?void 0:e.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new om;return Ot(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:a=!0,sendSources:o=!1,sendStart:s=!0,sendFinish:i=!0,onError:u=qe}={}){const c=t!=null?mh({originalMessages:e,responseMessageId:t}):void 0,m={},_=p=>{var f,w;const v=m[p];return((w=(f=this.tools)==null?void 0:f[v])==null?void 0:w.type)==="dynamic"?!0:void 0},b=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const w=n==null?void 0:n({part:p}),v=p.type;switch(v){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{a&&f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{o&&p.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),o&&p.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{m[p.id]=p.toolName;const l=_(p.id);f.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...l!=null?{dynamic:l}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{m[p.toolCallId]=p.toolName;const l=_(p.toolCallId);p.invalid?f.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...l!=null?{dynamic:l}:{},errorText:u(p.error)}):f.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...l!=null?{dynamic:l}:{}});break}case"tool-result":{const l=_(p.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...l!=null?{dynamic:l}:{}});break}case"tool-error":{const l=_(p.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:u(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...l!=null?{dynamic:l}:{}});break}case"error":{f.enqueue({type:"error",errorText:u(p.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{s&&f.enqueue({type:"start",...w!=null?{messageMetadata:w}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",...w!=null?{messageMetadata:w}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const l=v;throw new Error(`Unknown chunk type: ${l}`)}}w!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:w})}}));return Ot(_h({stream:b,messageId:c??(t==null?void 0:t()),originalMessages:e,onFinish:r,onError:u}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:a,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:u,onError:c,...m}={}){bh({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:a,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:u,onError:c}),...m})}pipeTextStreamToResponse(e,t){ph({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:i,onError:u,...c}={}){return fh({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:i,onError:u}),...c})}toTextStreamResponse(e){return dh({textStream:this.textStream,...e})}};Tt({prefix:"aiobj",size:24});Tt({prefix:"aiobj",size:24});var Oh={};nm(Oh,{object:()=>Ch,text:()=>Nh});var Nh=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Ch=({schema:e})=>{const t=Gt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await Js(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const a=n.state;throw new Error(`Unsupported parse state: ${a}`)}}},async parseOutput({text:r},n){const a=await Re({text:r});if(!a.success)throw new ga({message:"No object generated: could not parse the response.",cause:a.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await xe({value:a.value,schema:t});if(!o.success)throw new ga({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},Rh=Ve({name:A(),version:A()}),Qr=Ve({_meta:B(O({}).loose())}),_t=Qr,Ph=O({method:A(),params:B(Qr)}),$h=Ve({experimental:B(O({}).loose()),logging:B(O({}).loose()),prompts:B(Ve({listChanged:B(ke())})),resources:B(Ve({subscribe:B(ke()),listChanged:B(ke())})),tools:B(Ve({listChanged:B(ke())}))});_t.extend({protocolVersion:A(),capabilities:$h,serverInfo:Rh,instructions:B(A())});var Mh=_t.extend({nextCursor:B(A())}),zh=O({name:A(),description:B(A()),inputSchema:O({type:z("object"),properties:B(O({}).loose())}).loose()}).loose();Mh.extend({tools:ie(zh)});var Zh=O({type:z("text"),text:A()}).loose(),Dh=O({type:z("image"),data:xo(),mimeType:A()}).loose(),Hs=O({uri:A(),mimeType:B(A())}).loose(),Uh=Hs.extend({text:A()}),jh=Hs.extend({blob:xo()}),Lh=O({type:z("resource"),resource:q([Uh,jh])}).loose();_t.extend({content:ie(q([Zh,Dh,Lh])),isError:ke().default(!1).optional()}).or(_t.extend({toolResult:Ie()}));var Jt="2.0",Fh=O({jsonrpc:z(Jt),id:q([A(),Ee().int()])}).merge(Ph).strict(),Vh=O({jsonrpc:z(Jt),id:q([A(),Ee().int()]),result:_t}).strict(),Bh=O({jsonrpc:z(Jt),id:q([A(),Ee().int()]),error:O({code:Ee().int(),message:A(),data:B(Ie())})}).strict(),Gh=O({jsonrpc:z(Jt)}).merge(O({method:A(),params:B(Qr)})).strict();q([Fh,Gh,Vh,Bh]);class Ys{constructor(t){_e(this,"model","google/gemini-2.5-flash");_e(this,"temperature",.7);this.options=t,this.model=(t==null?void 0:t.model)??this.model}async handleRequest(t,r){var m,_;const{messages:n,image:a,initiator:o=null}=t,s=n.filter(b=>b.role!=="system"),i=s[s.length-1],u=a?[...s.slice(0,-1),{role:"user",content:[{type:"text",text:i.content},{type:"image",image:a}]}]:n;xh({model:this.model,system:Ea(o),messages:u,temperature:this.temperature,onFinish:((m=this.options)==null?void 0:m.onFinish)??W.noop,onError:((_=this.options)==null?void 0:_.onError)??W.noop}).pipeTextStreamToResponse(r)}isConfigured(){return!0}}class qh{constructor(t){this.backend=t}async upload({file:t,folderId:r,name:n},a){var s,i;return await((i=(s=this.backend).handleAssetsAction)==null?void 0:i.call(s,{action:"UPLOAD_ASSET",data:{name:n,file:t,folderId:r}},a))}async getAsset({id:t},r){var n,a;return(a=(n=this.backend).handleAssetsAction)==null?void 0:a.call(n,{action:"GET_ASSET",data:{id:t}},r)}async getAssets(t,r){var n,a;return(a=(n=this.backend).handleAssetsAction)==null?void 0:a.call(n,{action:"GET_ASSETS",data:t},r)}async deleteAsset({id:t},r){var n,a;return(a=(n=this.backend).handleAssetsAction)==null?void 0:a.call(n,{action:"DELETE_ASSET",data:{id:t}},r)}async updateAsset({id:t,file:r,description:n},a){var o,s;return(s=(o=this.backend).handleAssetsAction)==null?void 0:s.call(o,{action:"UPDATE_ASSET",data:{id:t,file:r,description:n}},a)}}class Ws{constructor(t){this.backend=t}async refreshToken(t){var n,a;const r=await((a=(n=this.backend).handleUsersAction)==null?void 0:a.call(n,{action:"REFRESH_TOKEN",data:t}));return r.error?{error:r.error}:r}async login({email:t,password:r}){var a,o;const n=await((o=(a=this.backend).handleUsersAction)==null?void 0:o.call(a,{action:"LOGIN",data:{email:t,password:r}}));return n.error?{error:n.error}:n}async logout(){var t,r;await((r=(t=this.backend).handleUsersAction)==null?void 0:r.call(t,{action:"LOGOUT"}))}async isUserActive(t){var n,a;return(await((a=(n=this.backend).handleUsersAction)==null?void 0:a.call(n,{action:"CHECK_USER_STATUS"},t))).success}async getUserRoleAndPermissions(t){var n,a;return await((a=(n=this.backend).handleUsersAction)==null?void 0:a.call(n,{action:"GET_ROLE_AND_PERMISSIONS"},t))}async getUserInfo(t,r){var a,o;return await((o=(a=this.backend).handleUsersAction)==null?void 0:o.call(a,{action:"GET_CHAI_USER",data:r},t))}}class Jh{constructor(t){_e(this,"fallbackLang","");_e(this,"draftMode",!1);_e(this,"backend");_e(this,"chaiUsers");_e(this,"chaiAssets");_e(this,"chaiAI");this.backend=t.backend,this._registerDefaultPageTypes(),this.chaiUsers=t.users??new Ws(this.backend),this.chaiAssets=t.assets??new qh(this.backend),this.chaiAI=t.ai??new Ys}_registerDefaultPageTypes(){xa("page",{name:"Static Page",icon:'<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M5 8V20H19V8H5ZM5 6H19V4H5V6ZM20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22ZM7 10H11V14H7V10ZM7 16H17V18H7V16ZM13 11H17V13H13V11Z"></path></svg>'}),Aa("global",{name:"Global Block",helpText:"A global block can be reused in multiple pages.",icon:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-hash-icon lucide-hash"><line x1="4" x2="20" y1="9" y2="9"/><line x1="4" x2="20" y1="15" y2="15"/><line x1="10" x2="8" y1="3" y2="21"/><line x1="16" x2="14" y1="3" y2="21"/></svg>'})}setFallbackLang(t){if(W.isEmpty(t))throw new Error("Fallback language cannot be empty");this.fallbackLang=t}getFallbackLang(){return this.fallbackLang}setDraftMode(t){this.draftMode=t}isDraftMode(){return this.draftMode}async handle(t,r,n){var o,s,i,u,c,m,_,b,p,f,w,v;switch(t.action){case"UPLOAD_ASSET":return(o=this.chaiAssets)==null?void 0:o.upload({file:t.data.file,name:t.data.name,folderId:t.data.folderId??null,optimize:t.data.optimize??!0},r);case"GET_ASSET":return(s=this.chaiAssets)==null?void 0:s.getAsset(t.data,r);case"GET_ASSETS":return(i=this.chaiAssets)==null?void 0:i.getAssets(t.data,r);case"DELETE_ASSET":return(u=this.chaiAssets)==null?void 0:u.deleteAsset(t.data,r);case"UPDATE_ASSET":return(c=this.chaiAssets)==null?void 0:c.updateAsset(t.data,r);case"REFRESH_TOKEN":return(m=this.chaiUsers)==null?void 0:m.refreshToken(t.data);case"LOGIN":return(_=this.chaiUsers)==null?void 0:_.login(t.data);case"LOGOUT":return(b=this.chaiUsers)==null?void 0:b.logout();case"CHECK_USER_STATUS":return(p=this.chaiUsers)==null?void 0:p.isUserActive(r);case"GET_ROLE_AND_PERMISSIONS":return(f=this.chaiUsers)==null?void 0:f.getUserRoleAndPermissions(r);case"GET_CHAI_USER":return(w=this.chaiUsers)==null?void 0:w.getUserInfo(r,t.data);case"ASK_AI":return(v=this.chaiAI)==null?void 0:v.handleRequest(t.data,n)}if(t.action==="GET_BUILDER_PAGE_DATA"){const l=await hn({lang:t.data.lang,draft:!0,inBuilder:!0}),g=be(t.data.pageType);return g?{...g.dataProvider?await g.dataProvider({lang:t.data.lang,draft:!0,inBuilder:!0,pageProps:t.data.pageProps??{}}):{},global:l}:{global:l}}if(t.action==="GET_PAGE_TYPES")return Promise.all(Tr().map(async l=>({key:l.key,helpText:l.helpText??"",icon:l.icon??"",dynamicSegments:l.dynamicSegments??"",dynamicSlug:l.dynamicSlug??"",hasSlug:l.hasSlug??!0,name:typeof l.name=="function"?await l.name():l.name,...W.isFunction(l.defaultTrackingInfo)?{trackingDefault:l.defaultTrackingInfo()}:{},...W.isFunction(l.defaultSeo)?{defaultSeo:l.defaultSeo()}:{},...W.isFunction(l.defaultJSONLD)?{defaultJSONLD:l.defaultJSONLD()}:{}})));if(t.action==="SEARCH_PAGE_TYPE_ITEMS"){const l=be(t.data.pageType);return l?l.search?await l.search(t.data.query):this.backend.handleAction(t,r):{error:"Page type not found"}}if(t.action==="GET_DYNAMIC_PAGES"){const l=be(t.data.pageType);return l?l.getDynamicPages?await l.getDynamicPages(t.data):[]:{error:"Page type not found"}}if(t.action==="GET_COLLECTIONS")return ka().map(l=>W.omit(l,"fetch"));if(t.action==="GET_BLOCK_ASYNC_PROPS"){const l=t.data.block,g=l._type;if(g==="Repeater"&&(l!=null&&l.repeaterItems.includes("{{#"))){const y=l.repeaterItems.replace("{{#","").replace("}}",""),d=Sr(y);return d?await(d==null?void 0:d.fetch({block:l,pageProps:t.data.pageProps,lang:t.data.lang,draft:!0,inBuilder:!0}))??[]:[]}else{const y=ii.getRegisteredChaiBlock(g);return!y||!W.isFunction(y.dataProvider)?{}:await y.dataProvider({block:l,pageProps:t.data.pageProps,lang:t.data.lang,draft:!0,inBuilder:!0})??{}}}const a=await this.backend.handleAction(t,r);return this.emit(t.action,a),a}emit(t,r){var o,s,i;if(!["CREATE_PAGE","UPDATE_PAGE","DELETE_PAGE"].includes(t))return;const n=W.get(r,"page");if(!n)return;const a=be(n.pageType);if(a)switch(t){case"CREATE_PAGE":return(o=a.onCreate)==null?void 0:o.call(a,n);case"UPDATE_PAGE":return(s=a.onUpdate)==null?void 0:s.call(a,n);case"DELETE_PAGE":return(i=a.onDelete)==null?void 0:i.call(a,n)}}async resolvePageLink(t,r){if(!W.startsWith(t,"pageType:"))return t;const n=t.split(":")[1],a=t.split(":")[2],o=be(n);return o?await this.resolveLink(o.key,a,r):t}async resolveLink(t,r,n){const a=be(t);if(!a)return"/not-found";const o=this.isDraftMode();return a.resolveLink?await a.resolveLink(r,o,n):await this.backend.handleAction({action:"GET_LINK",data:{pageType:t,id:r,draft:o,lang:n===this.getFallbackLang()?"":n}})}async getPageBySlug(t){const r=this.isDraftMode(),n={};return Tr().forEach(a=>{W.has(a,"dynamicSegments")&&a.dynamicSegments&&(n[a.key]=a.dynamicSegments)}),await this.backend.handleAction({action:"GET_PAGE_META",data:{slug:t,draft:r,dynamicSegments:n}})}async getFullPage(t){const r=this.isDraftMode();return await this.backend.handleAction({action:"GET_PAGE",data:{id:t,draft:r,mergePartials:!0}})}async getRevisionPage({id:t,type:r,lang:n}){const a=this.getFallbackLang()===n?"":n;return await this.backend.handleAction({action:"GET_REVISION_PAGE",data:{id:t,type:r,...a?{lang:a}:{}}})}async getSiteSettings(){const t=this.isDraftMode();return await this.backend.handleAction({action:"GET_WEBSITE_SETTINGS",data:{draft:t}})}async getPageData({blocks:t,pageType:r,pageProps:n,lang:a}){var _;const o=this.isDraftMode(),s=be(r),i=t.filter(b=>b._type==="Repeater"&&(b==null?void 0:b.repeaterItems.includes("{{#")));let u={};if(i.length>0){const b=i.map(f=>({collectionId:f.repeaterItems.replace("{{#","").replace("}}",""),block:f}));u=(await Promise.all(b.map(async({collectionId:f,block:w})=>{const v=Sr(f);try{const l=await(v==null?void 0:v.fetch({lang:a,draft:o,inBuilder:!1,pageProps:n,block:w}));return Promise.resolve({[`#${f}/${w._id}`]:W.get(l,"items",[])??[],[`#${f}/${w._id}/totalItems`]:W.get(l,"totalItems",-1)??-1})}catch{return Promise.resolve({[`#${f}/${w._id}`]:[],[`#${f}/${w._id}/totalItems`]:-1})}}))).reduce((f,w)=>({...f,...w}),{})}const[c,m]=await Promise.all([this.getGlobalData(a),((_=s==null?void 0:s.dataProvider)==null?void 0:_.call(s,{lang:a,draft:o,inBuilder:!1,pageProps:n}))||Promise.resolve({})]);return s?{...m,global:c,...u}:{global:c,...u}}async getGlobalData(t){return await hn({lang:t,draft:this.isDraftMode(),inBuilder:!1})}async request(t){return await this.backend.handleAction(t)}getAIHandler(){return this.chaiAI}}class Hh{constructor(t="",r=Ks){this.apiKey=t,this.apiUrl=r}async handleUsersAction(t,r){const n=await fetch(`${this.apiUrl}/v1/api/users`,{method:"POST",body:JSON.stringify(t),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":r}}),a=await n.json();return W.has(a,"error")?{...a,status:n.status}:a}async handleAction(t,r){const n=await fetch(`${this.apiUrl}/v1/api/chai`,{method:"POST",body:JSON.stringify(t),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":r}}),a=await n.json();return W.has(a,"error")?{...a,status:n.status}:a}async handleAssetsAction(t,r){return await(await fetch(`${this.apiUrl}/v1/api/assets`,{method:"POST",body:JSON.stringify(t),headers:{"x-chai-api-key":this.apiKey,"x-chai-auth-token":r}})).json()}}const Yh={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},Ks="https://api.chaibuilder.com";exports.API_URL=Ks;exports.ChaiAIChatHandler=Ys;exports.ChaiBuilderPages=Jh;exports.ChaiBuilderPagesBackend=Hh;exports.ChaiBuilderPagesUserManagement=Ws;exports.LANGUAGES=Yh;exports.getAskAiSystemPrompt=Ea;exports.getChaiCollection=Sr;exports.getChaiCollections=ka;exports.getChaiPageType=be;exports.getChaiPageTypes=Tr;exports.registerChaiCollection=di;exports.registerChaiGlobalDataProvider=li;exports.registerChaiPageType=xa;exports.registerChaiPartialType=Aa;
|