@decocms/mesh 1.3.1 → 1.4.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.
Files changed (137) hide show
  1. package/dist/client/assets/{AlertCircle-DoPcYOmu.js → AlertCircle-D6b9Ralv.js} +1 -1
  2. package/dist/client/assets/{ArrowLeft-Cho91gJm.js → ArrowLeft-CmZRAub5.js} +1 -1
  3. package/dist/client/assets/{ChevronDown--_znWqhO.js → ChevronDown-xjFrqe8j.js} +1 -1
  4. package/dist/client/assets/{Clock-OrKCoBnu.js → Clock-Bqlp1mni.js} +1 -1
  5. package/dist/client/assets/{Code01-COExI_48.js → Code01-B3S249hz.js} +1 -1
  6. package/dist/client/assets/{Copy01-CdCXGmeI.js → Copy01-D0tR5TRJ.js} +1 -1
  7. package/dist/client/assets/{CpuChip02-D26L6TWX.js → CpuChip02-BJZ8c2R6.js} +1 -1
  8. package/dist/client/assets/{DotsVertical-kYh71Jmo.js → DotsVertical-0Pg6f15X.js} +1 -1
  9. package/dist/client/assets/{File06-D4-QxuCL.js → File06-BzST8Ux5.js} +1 -1
  10. package/dist/client/assets/FlipBackward-J5E6LFga.js +1 -0
  11. package/dist/client/assets/{GitBranch01-irv8ZOt4.js → GitBranch01-C9tViAi-.js} +1 -1
  12. package/dist/client/assets/Grid01-DETN8WPx.js +1 -0
  13. package/dist/client/assets/{Inbox01-CEpI9Sk9.js → Inbox01-DxqBKn7H.js} +1 -1
  14. package/dist/client/assets/{Key01-BvGYoGe8.js → Key01-B-GFSqTW.js} +1 -1
  15. package/dist/client/assets/LinkExternal01-D-pWR4LA.js +1 -0
  16. package/dist/client/assets/{Loading01-DcFBMaXj.js → Loading01-CpvGD3vr.js} +1 -1
  17. package/dist/client/assets/{Lock01-IqrEd301.js → Lock01-DbWcWM_K.js} +1 -1
  18. package/dist/client/assets/{Play-0EPVk_yg.js → Play-D0iqjftf.js} +1 -1
  19. package/dist/client/assets/{Plus-C--SWih9.js → Plus-Df5PHguC.js} +1 -1
  20. package/dist/client/assets/{SearchMd-DiJjEUCs.js → SearchMd-BSF-Glwf.js} +1 -1
  21. package/dist/client/assets/{Terminal-Fx0j4vYu.js → Terminal-Cw0wmZeh.js} +1 -1
  22. package/dist/client/assets/{Trash01-ClQp3SU7.js → Trash01-DPFHmwKr.js} +1 -1
  23. package/dist/client/assets/{X-tggfklJn.js → X-D8XIiJvQ.js} +1 -1
  24. package/dist/client/assets/{XClose-8ptd0_kG.js → XClose-B_hUkeVk.js} +1 -1
  25. package/dist/client/assets/{alert-dialog-BTnJ6w_s.js → alert-dialog-CbCWAnT3.js} +2 -2
  26. package/dist/client/assets/{auth-DaJav-_Q.js → auth-PKeXnxbM.js} +1 -1
  27. package/dist/client/assets/{auth-catchall-Bi1SQUCA.js → auth-catchall-Wppyfaii.js} +1 -1
  28. package/dist/client/assets/{avatar-CuTiSc9V.js → avatar-g2HizpCv.js} +1 -1
  29. package/dist/client/assets/{badge-pWud7F0k.js → badge-DpuZDXUE.js} +1 -1
  30. package/dist/client/assets/{button-DoEGRp1U.js → button-hWHuMvle.js} +1 -1
  31. package/dist/client/assets/{card-CJ-1atZv.js → card-Cdw91ud0.js} +1 -1
  32. package/dist/client/assets/{checkbox-Bh9rcCG9.js → checkbox-C8hkq1Ob.js} +1 -1
  33. package/dist/client/assets/collection-detail-BhlzVbA_.js +183 -0
  34. package/dist/client/assets/collection-display-button-DJTB2EUg.js +1 -0
  35. package/dist/client/assets/{collection-header-Buxr9MZE.js → collection-header-BxKOSRWd.js} +1 -1
  36. package/dist/client/assets/{collection-page-BUbDWask.js → collection-page-BDy0PpkC.js} +1 -1
  37. package/dist/client/assets/{collection-search-DivVKI30.js → collection-search-BoabZo7c.js} +1 -1
  38. package/dist/client/assets/collection-tab-y3dKzpme.js +1 -0
  39. package/dist/client/assets/collection-table-wrapper-BERroKt9.js +1 -0
  40. package/dist/client/assets/{connection-card-BQhG2Xa_.js → connection-card-si8Xv84Q.js} +1 -1
  41. package/dist/client/assets/connection-detail-D8qvOGFn.js +1 -0
  42. package/dist/client/assets/connections-D7K8Q8og.js +1 -0
  43. package/dist/client/assets/constants-CxHW24vL.js +1 -0
  44. package/dist/client/assets/{core-DL7Okp2L.js → core-BAd4uKi4.js} +1 -1
  45. package/dist/client/assets/{create-organization-dialog-Dds34l1N.js → create-organization-dialog-D4tz0eZI.js} +1 -1
  46. package/dist/client/assets/{dialog-DzOmePFm.js → dialog-HUu8pjnY.js} +1 -1
  47. package/dist/client/assets/dropdown-menu-DG5cxUDL.js +1 -0
  48. package/dist/client/assets/empty-state-m_IydCcr.js +1 -0
  49. package/dist/client/assets/{env-vars-editor-D8jKdEG-.js → env-vars-editor-kSmLn72b.js} +1 -1
  50. package/dist/client/assets/{error-boundary-BAtxRJ1Q.js → error-boundary-B-QcFATa.js} +1 -1
  51. package/dist/client/assets/extract-connection-data-CjCzbgf3.js +1 -0
  52. package/dist/client/assets/{form-9MqLiR_v.js → form-B-xqHHYa.js} +1 -1
  53. package/dist/client/assets/formatDistanceToNow-B3w53gnj.js +1 -0
  54. package/dist/client/assets/gateway-detail-Dz5K97Qu.js +1 -0
  55. package/dist/client/assets/gateways-Bfk7wW4H.js +1 -0
  56. package/dist/client/assets/{home-CKPwY7YW.js → home-B2CMLWdT.js} +1 -1
  57. package/dist/client/assets/index-7USdUZHF.js +98 -0
  58. package/dist/client/assets/{index-IkrlX4J3.js → index-B9HSZhdB.js} +13 -13
  59. package/dist/client/assets/{index-Cu-lUDuQ.js → index-BI-brnHc.js} +1 -1
  60. package/dist/client/assets/index-BcDKMyjy.css +1 -0
  61. package/dist/client/assets/{index-v-MZw8Iv.js → index-Bs52vOb7.js} +1 -1
  62. package/dist/client/assets/index-CXiBzYKD.js +25 -0
  63. package/dist/client/assets/{input-BiKrjh13.js → input-DcZE4UoL.js} +1 -1
  64. package/dist/client/assets/json-RSU7hrk4.js +1 -0
  65. package/dist/client/assets/{json-syntax-highlighter-DKWpZiaG.js → json-syntax-highlighter-Czp62O9j.js} +2 -2
  66. package/dist/client/assets/{layout-DnHkkkij.js → layout-B5ADxfcB.js} +1 -1
  67. package/dist/client/assets/{lazy-highlighter-B7M4_4X7.js → lazy-highlighter-Z2qArbl8.js} +1 -1
  68. package/dist/client/assets/localstorage-keys-DZPXAcMr.js +1 -0
  69. package/dist/client/assets/{login-CAWaGgdX.js → login-BX781KlF.js} +1 -1
  70. package/dist/client/assets/{mcp-oauth-BeIYwRKY.js → mcp-oauth-PzyAfNM8.js} +1 -1
  71. package/dist/client/assets/members-D9riafGS.js +3 -0
  72. package/dist/client/assets/monitoring-Bz-yKjJ1.js +4 -0
  73. package/dist/client/assets/{oauth-callback-CDIYayLa.js → oauth-callback-CTNcTDd4.js} +1 -1
  74. package/dist/client/assets/{page-C3RAYK9Q.js → page-DF6IrrZD.js} +2 -2
  75. package/dist/client/assets/pin-to-sidebar-button-CJEwje2A.js +1 -0
  76. package/dist/client/assets/{popover-DtVun_-z.js → popover-DOwrFuly.js} +1 -1
  77. package/dist/client/assets/prism-light-xse74Nms.js +1 -0
  78. package/dist/client/assets/resizable-C0OMnsnz.js +1 -0
  79. package/dist/client/assets/{resource-tabs-B0Wxp2Cw.js → resource-tabs-BBkx9rqd.js} +1 -1
  80. package/dist/client/assets/responsive-select-Bl1ZcUtI.js +1 -0
  81. package/dist/client/assets/{select-C6oJSPpc.js → select-l2DSo1hq.js} +1 -1
  82. package/dist/client/assets/settings-CWXxNDHw.js +1 -0
  83. package/dist/client/assets/shell-layout-CWj_6Hth.js +19 -0
  84. package/dist/client/assets/{spinner-BI2cvb0U.js → spinner-BtMKC1U7.js} +1 -1
  85. package/dist/client/assets/store-_81OANVP.js +1 -0
  86. package/dist/client/assets/store-app-detail-CuCWq6-w.js +1 -0
  87. package/dist/client/assets/{switch-CICUEk-x.js → switch-BOFMRhtg.js} +1 -1
  88. package/dist/client/assets/{textarea-DYZxZLq1.js → textarea-BoUne3Q6.js} +1 -1
  89. package/dist/client/assets/{tools-list-B1pdeGzm.js → tools-list-D5n3plgQ.js} +1 -1
  90. package/dist/client/assets/tooltip-DxQ-KPX4.js +1 -0
  91. package/dist/client/assets/{types-BwKekgcj.js → types-8dJFzoWN.js} +1 -1
  92. package/dist/client/assets/{use-binding-CQxg2gSi.js → use-binding-Ccb4SpbZ.js} +2 -2
  93. package/dist/client/assets/{use-connection-B7SaX83w.js → use-connection-BfQqOvPU.js} +1 -1
  94. package/dist/client/assets/{use-connection-resources-B6GNOl9A.js → use-connection-resources-BuPCYNbb.js} +1 -1
  95. package/dist/client/assets/{use-gateway-BlseD0Sx.js → use-gateway-BWSXRpvE.js} +1 -1
  96. package/dist/client/assets/{use-list-state-BU6IyL55.js → use-list-state-qFWsDnqD.js} +1 -1
  97. package/dist/client/assets/{use-mcp-C2f_uqzY.js → use-mcp-40LwnzhO.js} +1 -1
  98. package/dist/client/assets/{use-members-CWSu_Z-H.js → use-members-BorgQnCE.js} +1 -1
  99. package/dist/client/assets/{use-mobile-CdiMQ9En.js → use-mobile-v3aq_7jb.js} +1 -1
  100. package/dist/client/assets/{use-organization-settings-Cnjs0OiP.js → use-organization-settings-QpyD7U2T.js} +1 -1
  101. package/dist/client/assets/{use-tool-call-BpBoE-Mi.js → use-tool-call-CLKWIhEj.js} +1 -1
  102. package/dist/client/assets/useQuery-DE63pAfU.js +1 -0
  103. package/dist/client/assets/{useSuspenseInfiniteQuery-0wQdaodf.js → useSuspenseInfiniteQuery-DUZsUnhN.js} +1 -1
  104. package/dist/client/assets/{view-mode-toggle-Dq1mWwHt.js → view-mode-toggle-C9GLUxuG.js} +1 -1
  105. package/dist/client/assets/{well-known-mcp-DX3tGGx0.js → well-known-mcp-D13f-8h2.js} +1 -1
  106. package/dist/client/assets/workflow-DJAFzntg.js +1 -0
  107. package/dist/client/index.html +2 -2
  108. package/dist/server/cli.js +124 -124
  109. package/dist/server/server.js +4 -4
  110. package/package.json +1 -1
  111. package/dist/client/assets/InfoCircle-BH6ukjrt.js +0 -1
  112. package/dist/client/assets/LinkExternal01-C8zs3bR9.js +0 -1
  113. package/dist/client/assets/Upload01-qHdORxg4.js +0 -1
  114. package/dist/client/assets/collection-detail-7RgcpBz4.js +0 -183
  115. package/dist/client/assets/collection-display-button-B5AAU4Bw.js +0 -1
  116. package/dist/client/assets/collection-table-wrapper-lGkt7E0b.js +0 -1
  117. package/dist/client/assets/connection-detail-DWS__uKs.js +0 -1
  118. package/dist/client/assets/connections-BASUKxPo.js +0 -1
  119. package/dist/client/assets/dropdown-menu-B9LS1Ke-.js +0 -1
  120. package/dist/client/assets/extract-connection-data-lX5EQrvR.js +0 -1
  121. package/dist/client/assets/formatDistanceToNow-D7en5Npb.js +0 -1
  122. package/dist/client/assets/gateway-detail-CxcoEeja.js +0 -1
  123. package/dist/client/assets/gateways-Z3eqRHG3.js +0 -1
  124. package/dist/client/assets/index-Bp5sMtgd.js +0 -25
  125. package/dist/client/assets/index-BtfNSYYi.css +0 -1
  126. package/dist/client/assets/json-C3gxFz3i.js +0 -1
  127. package/dist/client/assets/localstorage-keys-C9gCmhF_.js +0 -1
  128. package/dist/client/assets/members-DuEm4VkF.js +0 -3
  129. package/dist/client/assets/monitoring-m_4t86_p.js +0 -4
  130. package/dist/client/assets/prism-light-BDjQ_TVh.js +0 -1
  131. package/dist/client/assets/resizable-ADGi5uO6.js +0 -98
  132. package/dist/client/assets/settings-DpVdsR8r.js +0 -1
  133. package/dist/client/assets/shell-layout-UFhBDwon.js +0 -19
  134. package/dist/client/assets/store-RumD0h8V.js +0 -1
  135. package/dist/client/assets/store-app-detail-C0Bjj1dL.js +0 -1
  136. package/dist/client/assets/tooltip-DsFBYF2A.js +0 -1
  137. package/dist/client/assets/useQuery-9D_KMlJN.js +0 -1
@@ -258,7 +258,7 @@ Attempted to suspend at:`);this.suspended=new FY1(`(${this.suspendedCount++})`),
258
258
  ${this._constructorStack}
259
259
  Lifetime used`):new o40("Lifetime not alive")}},i$=class extends h9{constructor(Q,X){super(Q,void 0,void 0,X)}get dupable(){return!0}dup(){return this}dispose(){}},t40=class extends h9{constructor(Q,X,Y,J){super(Q,X,Y,J)}dispose(){this._alive=!1}};I5=class Q extends y7{constructor(){super(...arguments);this._disposables=new h9(new Set),this.manage=(X)=>(this._disposables.value.add(X),X)}static withScope(X){let Y=new Q,J;try{return X(Y)}catch(G){throw J=G,G}finally{a40(Y,J)}}static withScopeMaybeAsync(X,Y){return QS6(void 0,function*(J){let G=new Q,W;try{return yield*J.of(Y.call(X,J,G))}catch(Z){throw W=Z,Z}finally{a40(G,W)}})}static async withScopeAsync(X){let Y=new Q,J;try{return await X(Y)}catch(G){throw J=G,G}finally{a40(Y,J)}}get alive(){return this._disposables.alive}dispose(){let X=Array.from(this._disposables.value.values()).reverse();for(let Y of X)Y.alive&&Y.dispose();this._disposables.dispose()}};Y80=class Q extends y7{static success(X){return new OY1(X)}static fail(X,Y){return new LY1(X,Y)}static is(X){return X instanceof Q}},OY1=class extends Y80{constructor(Q){super();this.value=Q}get alive(){return Ay(this.value)?this.value.alive:!0}dispose(){Ay(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Q){return this.value}},LY1=class extends Y80{constructor(Q,X){super();this.error=Q,this.onUnwrap=X}get alive(){return Ay(this.error)?this.error.alive:!0}dispose(){Ay(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Q){return Q}},o3=Y80,wY1=class extends y7{constructor(Q){super();this.resolve=(X)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(X)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Q.context,this.owner=Q.context.runtime,this.handle=Q.promiseHandle,this.settled=new Promise((X)=>{this.onSettled=X}),this.resolveHandle=Q.resolveHandle,this.rejectHandle=Q.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},_x4=Symbol("Unstable"),J80=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});WS6=class extends y7{constructor(Q,X){super();this.handle=Q,this.context=X,this._isDone=!1,this.owner=X.runtime}[Symbol.iterator](){return this}next(Q){if(!this.alive||this._isDone)return{done:!0,value:void 0};let X=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(X,Q)}return(Q){if(!this.alive)return{done:!0,value:void 0};let X=this.context.getProp(this.handle,"return");if(X===this.context.undefined&&Q===void 0)return this.dispose(),{done:!0,value:void 0};let Y=this.callIteratorMethod(X,Q);return X.dispose(),this.dispose(),Y}throw(Q){if(!this.alive)return{done:!0,value:void 0};let X=Q instanceof h9?Q:this.context.newError(Q),Y=this.context.getProp(this.handle,"throw"),J=this.callIteratorMethod(Y,Q);return X.alive&&X.dispose(),Y.dispose(),this.dispose(),J}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Q,X){let Y=X?this.context.callFunction(Q,this.handle,X):this.context.callFunction(Q,this.handle);if(Y.error)return this.dispose(),{value:Y};let J=this.context.getProp(Y.value,"done").consume((W)=>this.context.dump(W));if(J)return Y.value.dispose(),this.dispose(),{done:J,value:void 0};let G=this.context.getProp(Y.value,"value");return Y.value.dispose(),{value:o3.success(G),done:J}}},ZS6=class extends MY1{constructor(Q){super(Q.module);this.scope=new I5,this.copyJSValue=(X)=>this.ffi.QTS_DupValuePointer(this.ctx.value,X),this.freeJSValue=(X)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,X)},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.owner=Q.owner,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=this.scope.manage(Q.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Q){return this.scope.manage(Q)}consumeJSCharPointer(Q){let X=this.module.UTF8ToString(Q);return this.ffi.QTS_FreeCString(this.ctx.value,Q),X}heapValueHandle(Q){return new h9(Q,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(Q){return this.manage(this.heapValueHandle(Q)),new i$(Q,this.owner)}},PY1=class extends y7{constructor(Q){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(X,Y,J,G,W)=>{if(X!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let Z=this.getFunction(W);if(!Z)throw Error(`QuickJSContext had no callback with id ${W}`);return I5.withScopeMaybeAsync(this,function*($,K){let H=K.manage(new t40(Y,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),F=Array(J);for(let V=0;V<J;V++){let q=this.ffi.QTS_ArgvGetJSValueConstPointer(G,V);F[V]=K.manage(new t40(q,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let V=yield*$(Z.apply(H,F));if(V){if("error"in V&&V.error)throw this.runtime.debugLog("throw error",V.error),V.error;let q=K.manage(V instanceof h9?V:V.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,q.value)}return 0}catch(V){return this.errorToHandle(V).consume((q)=>this.ffi.QTS_Throw(this.ctx.value,q.value))}})}},this.runtime=Q.runtime,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=Q.ctx,this.memory=new ZS6({...Q,owner:this.runtime}),Q.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let Q=this.ffi.QTS_GetUndefined();return this._undefined=new i$(Q)}get null(){if(this._null)return this._null;let Q=this.ffi.QTS_GetNull();return this._null=new i$(Q)}get true(){if(this._true)return this._true;let Q=this.ffi.QTS_GetTrue();return this._true=new i$(Q)}get false(){if(this._false)return this._false;let Q=this.ffi.QTS_GetFalse();return this._false=new i$(Q)}get global(){if(this._global)return this._global;let Q=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Q),this._global}newNumber(Q){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Q))}newString(Q){let X=this.memory.newHeapCharPointer(Q).consume((Y)=>this.ffi.QTS_NewString(this.ctx.value,Y.value.ptr));return this.memory.heapValueHandle(X)}newUniqueSymbol(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,0));return this.memory.heapValueHandle(Y)}newSymbolFor(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,1));return this.memory.heapValueHandle(Y)}getWellKnownSymbol(Q){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Q)}newBigInt(Q){if(!this._BigInt){let J=this.getProp(this.global,"BigInt");this.memory.manage(J),this._BigInt=new i$(J.value,this.runtime)}let X=this._BigInt,Y=String(Q);return this.newString(Y).consume((J)=>this.unwrapResult(this.callFunction(X,this.undefined,J)))}newObject(Q){Q&&this.runtime.assertOwned(Q);let X=Q?this.ffi.QTS_NewObjectProto(this.ctx.value,Q.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(X)}newArray(){let Q=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Q)}newArrayBuffer(Q){let X=new Uint8Array(Q),Y=this.memory.newHeapBufferPointer(X),J=this.ffi.QTS_NewArrayBuffer(this.ctx.value,Y.value.pointer,X.length);return this.memory.heapValueHandle(J)}newPromise(Q){let X=I5.withScope((Y)=>{let J=Y.manage(this.memory.newMutablePointerArray(2)),G=this.ffi.QTS_NewPromiseCapability(this.ctx.value,J.value.ptr),W=this.memory.heapValueHandle(G),[Z,$]=Array.from(J.value.typedArray).map((K)=>this.memory.heapValueHandle(K));return new wY1({context:this,promiseHandle:W,resolveHandle:Z,rejectHandle:$})});return Q&&typeof Q=="function"&&(Q=new Promise(Q)),Q&&Promise.resolve(Q).then(X.resolve,(Y)=>Y instanceof h9?X.reject(Y):this.newError(Y).consume(X.reject)),X}newFunction(Q,X){let Y=++this.fnNextId;return this.setFunction(Y,X),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,Y,Q))}newError(Q){let X=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Q&&typeof Q=="object"?(Q.name!==void 0&&this.newString(Q.name).consume((Y)=>this.setProp(X,"name",Y)),Q.message!==void 0&&this.newString(Q.message).consume((Y)=>this.setProp(X,"message",Y))):typeof Q=="string"?this.newString(Q).consume((Y)=>this.setProp(X,"message",Y)):Q!==void 0&&this.newString(String(Q)).consume((Y)=>this.setProp(X,"message",Y)),X}typeof(Q){return this.runtime.assertOwned(Q),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Q.value))}getNumber(Q){return this.runtime.assertOwned(Q),this.ffi.QTS_GetFloat64(this.ctx.value,Q.value)}getString(Q){return this.runtime.assertOwned(Q),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Q.value))}getSymbol(Q){this.runtime.assertOwned(Q);let X=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Q.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Q.value)?Symbol.for(X):Symbol(X)}getBigInt(Q){this.runtime.assertOwned(Q);let X=this.getString(Q);return BigInt(X)}getArrayBuffer(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Q.value),Y=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Q.value);if(!Y)throw Error("Couldn't allocate memory to get ArrayBuffer");return new h9(this.module.HEAPU8.subarray(Y,Y+X),void 0,()=>this.module._free(Y))}getPromiseState(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_PromiseState(this.ctx.value,Q.value);if(X<0)return{type:"fulfilled",value:Q,notAPromise:!0};if(X===Py.Pending)return{type:"pending",get error(){return new UY1("Cannot unwrap a pending promise")}};let Y=this.ffi.QTS_PromiseResult(this.ctx.value,Q.value),J=this.memory.heapValueHandle(Y);if(X===Py.Fulfilled)return{type:"fulfilled",value:J};if(X===Py.Rejected)return{type:"rejected",error:J};throw J.dispose(),Error(`Unknown JSPromiseStateEnum: ${X}`)}resolvePromise(Q){this.runtime.assertOwned(Q);let X=I5.withScope((Y)=>{let J=Y.manage(this.getProp(this.global,"Promise")),G=Y.manage(this.getProp(J,"resolve"));return this.callFunction(G,J,Q)});return X.error?Promise.resolve(X):new Promise((Y)=>{I5.withScope((J)=>{let G=J.manage(this.newFunction("resolve",(K)=>{Y(this.success(K&&K.dup()))})),W=J.manage(this.newFunction("reject",(K)=>{Y(this.fail(K&&K.dup()))})),Z=J.manage(X.value),$=J.manage(this.getProp(Z,"then"));this.callFunction($,Z,G,W).unwrap().dispose()})})}isEqual(Q,X,Y=$P.IsStrictlyEqual){if(Q===X)return!0;this.runtime.assertOwned(Q),this.runtime.assertOwned(X);let J=this.ffi.QTS_IsEqual(this.ctx.value,Q.value,X.value,Y);if(J===-1)throw new KY1("WASM variant does not expose equality");return!!J}eq(Q,X){return this.isEqual(Q,X,$P.IsStrictlyEqual)}sameValue(Q,X){return this.isEqual(Q,X,$P.IsSameValue)}sameValueZero(Q,X){return this.isEqual(Q,X,$P.IsSameValueZero)}getProp(Q,X){this.runtime.assertOwned(Q);let Y;return typeof X=="number"&&X>=0?Y=this.ffi.QTS_GetPropNumber(this.ctx.value,Q.value,X):Y=this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_GetProp(this.ctx.value,Q.value,J.value)),this.memory.heapValueHandle(Y)}getLength(Q){if(this.runtime.assertOwned(Q),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Q.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Q,X={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Q),Q.value;let Y=JS6(X);if(Y===0)throw new BY1("No options set, will return an empty array");return I5.withScope((J)=>{let G=J.manage(this.memory.newMutablePointerArray(1)),W=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,G.value.ptr,this.uint32Out.value.ptr,Q.value,Y);if(W)return this.fail(this.memory.heapValueHandle(W));let Z=this.uint32Out.value.typedArray[0],$=G.value.typedArray[0],K=new Uint32Array(this.module.HEAP8.buffer,$,Z),H=Array.from(K).map((F)=>this.memory.heapValueHandle(F));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,$),this.success(NY1(H))})}getIterator(Q){let X=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return I5.withScope((Y)=>{let J=Y.manage(this.getProp(Q,X)),G=this.callFunction(J,Q);return G.error?G:this.success(new WS6(G.value,this))})}setProp(Q,X,Y){this.runtime.assertOwned(Q),this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_SetProp(this.ctx.value,Q.value,J.value,Y.value))}defineProp(Q,X,Y){this.runtime.assertOwned(Q),I5.withScope((J)=>{let G=J.manage(this.borrowPropertyKey(X)),W=Y.value||this.undefined,Z=!!Y.configurable,$=!!Y.enumerable,K=!!Y.value,H=Y.get?J.manage(this.newFunction(Y.get.name,Y.get)):this.undefined,F=Y.set?J.manage(this.newFunction(Y.set.name,Y.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Q.value,G.value,W.value,H.value,F.value,Z,$,K)})}callFunction(Q,X,...Y){this.runtime.assertOwned(Q);let J,G=Y[0];G===void 0||Array.isArray(G)?J=G??[]:J=Y;let W=this.memory.toPointerArray(J).consume(($)=>this.ffi.QTS_Call(this.ctx.value,Q.value,X.value,J.length,$.value)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}callMethod(Q,X,Y=[]){return this.getProp(Q,X).consume((J)=>this.callFunction(J,Q,Y))}evalCode(Q,X="eval.js",Y){let J=Y===void 0?1:0,G=YS6(Y),W=this.memory.newHeapCharPointer(Q).consume(($)=>this.ffi.QTS_Eval(this.ctx.value,$.value.ptr,$.value.strlen,X,J,G)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}throw(Q){return this.errorToHandle(Q).consume((X)=>this.ffi.QTS_Throw(this.ctx.value,X.value))}borrowPropertyKey(Q){return typeof Q=="number"?this.newNumber(Q):typeof Q=="string"?this.newString(Q):new i$(Q.value,this.runtime)}getMemory(Q){if(Q===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Q){this.runtime.assertOwned(Q);let X=this.typeof(Q);if(X==="string")return this.getString(Q);if(X==="number")return this.getNumber(Q);if(X==="bigint")return this.getBigInt(Q);if(X==="undefined")return;if(X==="symbol")return this.getSymbol(Q);let Y=this.getPromiseState(Q);if(Y.type==="fulfilled"&&!Y.notAPromise)return Q.dispose(),{type:Y.type,value:Y.value.consume(this.dump)};if(Y.type==="pending")return Q.dispose(),{type:Y.type};if(Y.type==="rejected")return Q.dispose(),{type:Y.type,error:Y.error.consume(this.dump)};let J=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Q.value));try{return JSON.parse(J)}catch{return J}}unwrapResult(Q){if(Q.error){let X="context"in Q.error?Q.error.context:this,Y=Q.error.consume((J)=>this.dump(J));if(Y&&typeof Y=="object"&&typeof Y.message=="string"){let{message:J,name:G,stack:W,...Z}=Y,$=new r40(Y,X);typeof G=="string"&&($.name=Y.name),$.message=J;let K=$.stack;throw typeof W=="string"&&($.stack=`${G}: ${J}
260
260
  ${Y.stack}Host: ${K}`),Object.assign($,Z),$}throw new r40(Y)}return Q.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(Q){let X=Q>>8,Y=this.fnMaps.get(X);if(Y)return Y.get(Q)}setFunction(Q,X){let Y=Q>>8,J=this.fnMaps.get(Y);return J||(J=new Map,this.fnMaps.set(Y,J)),J.set(Q,X)}errorToHandle(Q){return Q instanceof h9?Q:this.newError(Q)}encodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_encode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}decodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_decode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}success(Q){return o3.success(Q)}fail(Q){return o3.fail(Q,(X)=>this.unwrapResult(X))}},TY1=class extends y7{constructor(Q){super();this.scope=new I5,this.contextMap=new Map,this._debugMode=!1,this.cToHostCallbacks={shouldInterrupt:(X)=>{if(X!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let Y=this.interruptHandler;if(!Y)throw Error("QuickJSContext had no interrupt handler");return Y(this)?1:0},loadModuleSource:GY1(this,function*(X,Y,J,G){let W=this.moduleLoader;if(!W)throw Error("Runtime has no module loader");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let Z=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let $=yield*X(W(G,Z));if(typeof $=="object"&&"error"in $&&$.error)throw this.debugLog("cToHostLoadModule: loader returned error",$.error),$.error;let K=typeof $=="string"?$:("value"in $)?$.value:$;return this.memory.newHeapCharPointer(K).value.ptr}catch($){return this.debugLog("cToHostLoadModule: caught error",$),Z.throw($),0}}),normalizeModule:GY1(this,function*(X,Y,J,G,W){let Z=this.moduleNormalizer;if(!Z)throw Error("Runtime has no module normalizer");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let $=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let K=yield*X(Z(G,W,$));if(typeof K=="object"&&"error"in K&&K.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",K.error),K.error;let H=typeof K=="string"?K:K.value;return $.getMemory(this.rt.value).newHeapCharPointer(H).value.ptr}catch(K){return this.debugLog("normalizeModule: caught error",K),$.throw(K),0}})},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.module=Q.module,this.memory=new MY1(this.module),this.ffi=Q.ffi,this.rt=Q.rt,this.callbacks=Q.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),e40&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Q={}){let X=XS6(Q.intrinsics),Y=new h9(Q.contextPointer||this.ffi.QTS_NewContext(this.rt.value,X),void 0,(G)=>{this.contextMap.delete(G),this.callbacks.deleteContext(G),this.ffi.QTS_FreeContext(G)}),J=new PY1({module:this.module,ctx:Y,ffi:this.ffi,rt:this.rt,ownedLifetimes:Q.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(Y.value,J),J}setModuleLoader(Q,X){this.moduleLoader=Q,this.moduleNormalizer=X,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(Q){let X=this.interruptHandler;this.interruptHandler=Q,X||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Q=-1){let X=this.memory.newMutablePointerArray(1),Y=this.ffi.QTS_ExecutePendingJob(this.rt.value,Q??-1,X.value.ptr),J=X.value.typedArray[0];if(X.dispose(),J===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,Y),o3.success(0);let G=this.contextMap.get(J)??this.newContext({contextPointer:J}),W=G.getMemory(this.rt.value).heapValueHandle(Y);if(G.typeof(W)==="number"){let Z=G.getNumber(W);return W.dispose(),o3.success(Z)}else{let Z=Object.assign(W,{context:G});return o3.fail(Z,($)=>G.unwrapResult($))}}setMemoryLimit(Q){if(Q<0&&Q!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Q)}computeMemoryUsage(){let Q=this.getSystemContext().getMemory(this.rt.value);return Q.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Q.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Q){if(Q<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Q)}assertOwned(Q){if(Q.owner&&Q.owner.rt!==this.rt)throw new $Y1(`Handle is not owned by this runtime: ${Q.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Q){this._debugMode=Q,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Q?1:0)}isDebugMode(){return this._debugMode}debugLog(...Q){this._debugMode&&console.log("quickjs-emscripten:",...Q)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var AY1={};K8(AY1,{applyModuleEvalRuntimeOptions:()=>Z80,applyBaseRuntimeOptions:()=>W80,QuickJSWASMModule:()=>$80,QuickJSModuleCallbacks:()=>G80});var EY1=o(()=>{K80()});var CY1={};K8(CY1,{QuickJSFFI:()=>KS6});var KS6=class{constructor(Q){this.module=Q,this.DEBUG=!1,this.QTS_Throw=this.module.cwrap("QTS_Throw","number",["number","number"]),this.QTS_NewError=this.module.cwrap("QTS_NewError","number",["number"]),this.QTS_RuntimeSetMemoryLimit=this.module.cwrap("QTS_RuntimeSetMemoryLimit",null,["number","number"]),this.QTS_RuntimeComputeMemoryUsage=this.module.cwrap("QTS_RuntimeComputeMemoryUsage","number",["number","number"]),this.QTS_RuntimeDumpMemoryUsage=this.module.cwrap("QTS_RuntimeDumpMemoryUsage","number",["number"]),this.QTS_RecoverableLeakCheck=this.module.cwrap("QTS_RecoverableLeakCheck","number",[]),this.QTS_BuildIsSanitizeLeak=this.module.cwrap("QTS_BuildIsSanitizeLeak","number",[]),this.QTS_RuntimeSetMaxStackSize=this.module.cwrap("QTS_RuntimeSetMaxStackSize",null,["number","number"]),this.QTS_GetUndefined=this.module.cwrap("QTS_GetUndefined","number",[]),this.QTS_GetNull=this.module.cwrap("QTS_GetNull","number",[]),this.QTS_GetFalse=this.module.cwrap("QTS_GetFalse","number",[]),this.QTS_GetTrue=this.module.cwrap("QTS_GetTrue","number",[]),this.QTS_NewRuntime=this.module.cwrap("QTS_NewRuntime","number",[]),this.QTS_FreeRuntime=this.module.cwrap("QTS_FreeRuntime",null,["number"]),this.QTS_NewContext=this.module.cwrap("QTS_NewContext","number",["number","number"]),this.QTS_FreeContext=this.module.cwrap("QTS_FreeContext",null,["number"]),this.QTS_FreeValuePointer=this.module.cwrap("QTS_FreeValuePointer",null,["number","number"]),this.QTS_FreeValuePointerRuntime=this.module.cwrap("QTS_FreeValuePointerRuntime",null,["number","number"]),this.QTS_FreeVoidPointer=this.module.cwrap("QTS_FreeVoidPointer",null,["number","number"]),this.QTS_FreeCString=this.module.cwrap("QTS_FreeCString",null,["number","number"]),this.QTS_DupValuePointer=this.module.cwrap("QTS_DupValuePointer","number",["number","number"]),this.QTS_NewObject=this.module.cwrap("QTS_NewObject","number",["number"]),this.QTS_NewObjectProto=this.module.cwrap("QTS_NewObjectProto","number",["number","number"]),this.QTS_NewArray=this.module.cwrap("QTS_NewArray","number",["number"]),this.QTS_NewArrayBuffer=this.module.cwrap("QTS_NewArrayBuffer","number",["number","number","number"]),this.QTS_NewFloat64=this.module.cwrap("QTS_NewFloat64","number",["number","number"]),this.QTS_GetFloat64=this.module.cwrap("QTS_GetFloat64","number",["number","number"]),this.QTS_NewString=this.module.cwrap("QTS_NewString","number",["number","number"]),this.QTS_GetString=this.module.cwrap("QTS_GetString","number",["number","number"]),this.QTS_GetArrayBuffer=this.module.cwrap("QTS_GetArrayBuffer","number",["number","number"]),this.QTS_GetArrayBufferLength=this.module.cwrap("QTS_GetArrayBufferLength","number",["number","number"]),this.QTS_NewSymbol=this.module.cwrap("QTS_NewSymbol","number",["number","number","number"]),this.QTS_GetSymbolDescriptionOrKey=this.module.cwrap("QTS_GetSymbolDescriptionOrKey","number",["number","number"]),this.QTS_IsGlobalSymbol=this.module.cwrap("QTS_IsGlobalSymbol","number",["number","number"]),this.QTS_IsJobPending=this.module.cwrap("QTS_IsJobPending","number",["number"]),this.QTS_ExecutePendingJob=this.module.cwrap("QTS_ExecutePendingJob","number",["number","number","number"]),this.QTS_GetProp=this.module.cwrap("QTS_GetProp","number",["number","number","number"]),this.QTS_GetPropNumber=this.module.cwrap("QTS_GetPropNumber","number",["number","number","number"]),this.QTS_SetProp=this.module.cwrap("QTS_SetProp",null,["number","number","number","number"]),this.QTS_DefineProp=this.module.cwrap("QTS_DefineProp",null,["number","number","number","number","number","number","boolean","boolean","boolean"]),this.QTS_GetOwnPropertyNames=this.module.cwrap("QTS_GetOwnPropertyNames","number",["number","number","number","number","number"]),this.QTS_Call=this.module.cwrap("QTS_Call","number",["number","number","number","number","number"]),this.QTS_ResolveException=this.module.cwrap("QTS_ResolveException","number",["number","number"]),this.QTS_Dump=this.module.cwrap("QTS_Dump","number",["number","number"]),this.QTS_Eval=this.module.cwrap("QTS_Eval","number",["number","number","number","string","number","number"]),this.QTS_GetModuleNamespace=this.module.cwrap("QTS_GetModuleNamespace","number",["number","number"]),this.QTS_Typeof=this.module.cwrap("QTS_Typeof","number",["number","number"]),this.QTS_GetLength=this.module.cwrap("QTS_GetLength","number",["number","number","number"]),this.QTS_IsEqual=this.module.cwrap("QTS_IsEqual","number",["number","number","number","number"]),this.QTS_GetGlobalObject=this.module.cwrap("QTS_GetGlobalObject","number",["number"]),this.QTS_NewPromiseCapability=this.module.cwrap("QTS_NewPromiseCapability","number",["number","number"]),this.QTS_PromiseState=this.module.cwrap("QTS_PromiseState","number",["number","number"]),this.QTS_PromiseResult=this.module.cwrap("QTS_PromiseResult","number",["number","number"]),this.QTS_TestStringArg=this.module.cwrap("QTS_TestStringArg",null,["string"]),this.QTS_GetDebugLogEnabled=this.module.cwrap("QTS_GetDebugLogEnabled","number",["number"]),this.QTS_SetDebugLogEnabled=this.module.cwrap("QTS_SetDebugLogEnabled",null,["number","number"]),this.QTS_BuildIsDebug=this.module.cwrap("QTS_BuildIsDebug","number",[]),this.QTS_BuildIsAsyncify=this.module.cwrap("QTS_BuildIsAsyncify","number",[]),this.QTS_NewFunction=this.module.cwrap("QTS_NewFunction","number",["number","number","string"]),this.QTS_ArgvGetJSValueConstPointer=this.module.cwrap("QTS_ArgvGetJSValueConstPointer","number",["number","number"]),this.QTS_RuntimeEnableInterruptHandler=this.module.cwrap("QTS_RuntimeEnableInterruptHandler",null,["number"]),this.QTS_RuntimeDisableInterruptHandler=this.module.cwrap("QTS_RuntimeDisableInterruptHandler",null,["number"]),this.QTS_RuntimeEnableModuleLoader=this.module.cwrap("QTS_RuntimeEnableModuleLoader",null,["number","number"]),this.QTS_RuntimeDisableModuleLoader=this.module.cwrap("QTS_RuntimeDisableModuleLoader",null,["number"]),this.QTS_bjson_encode=this.module.cwrap("QTS_bjson_encode","number",["number","number"]),this.QTS_bjson_decode=this.module.cwrap("QTS_bjson_decode","number",["number","number"])}};var IY1=()=>{};var RY1={};K8(RY1,{default:()=>FS6});var HS6,FS6;var SY1=o(()=>{HS6=(()=>{var Q=import.meta.url;return async function(X={}){var Y,J=X,G,W,Z=new Promise((w,v)=>{G=w,W=v}),$=typeof window=="object",K=typeof importScripts=="function",H=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(H){let{createRequire:w}=await import("module");var F=w(import.meta.url)}function V(w){w={log:w||function(){}};for(let v of V.Ia)v(w);return J.quickJSEmscriptenExtensions=w}V.Ia=[],J.quickjsEmscriptenInit=V,V.Ia.push((w)=>{w.getWasmMemory=function(){return R}});var q=Object.assign({},J),U="./this.program",D=(w,v)=>{throw v},B="",L,M;if(H){var C=F("fs"),E=F("path");B=F("url").fileURLToPath(new URL("./",import.meta.url)),M=(w)=>{return w=K1(w)?new URL(w):E.normalize(w),C.readFileSync(w)},L=(w)=>{return w=K1(w)?new URL(w):E.normalize(w),new Promise((v,c)=>{C.readFile(w,void 0,(s,u)=>{s?c(s):v(u.buffer)})})},!J.thisProgram&&1<process.argv.length&&(U=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),D=(w,v)=>{throw process.exitCode=w,v}}else if($||K)K?B=self.location.href:typeof document<"u"&&document.currentScript&&(B=document.currentScript.src),Q&&(B=Q),B.startsWith("blob:")?B="":B=B.substr(0,B.replace(/[?#].*/,"").lastIndexOf("/")+1),K&&(M=(w)=>{var v=new XMLHttpRequest;return v.open("GET",w,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),L=(w)=>K1(w)?new Promise((v,c)=>{var s=new XMLHttpRequest;s.open("GET",w,!0),s.responseType="arraybuffer",s.onload=()=>{s.status==200||s.status==0&&s.response?v(s.response):c(s.status)},s.onerror=c,s.send(null)}):fetch(w,{credentials:"same-origin"}).then((v)=>v.ok?v.arrayBuffer():Promise.reject(Error(v.status+" : "+v.url)));var A=J.print||console.log.bind(console),T=J.printErr||console.error.bind(console);Object.assign(J,q),q=null,J.thisProgram&&(U=J.thisProgram);var j=J.wasmBinary,R,k=!1,y,b,h,a,f;function S(){var w=R.buffer;J.HEAP8=b=new Int8Array(w),J.HEAP16=new Int16Array(w),J.HEAPU8=h=new Uint8Array(w),J.HEAPU16=new Uint16Array(w),J.HEAP32=a=new Int32Array(w),J.HEAPU32=f=new Uint32Array(w),J.HEAPF32=new Float32Array(w),J.HEAPF64=new Float64Array(w)}J.wasmMemory?R=J.wasmMemory:R=new WebAssembly.Memory({initial:(J.INITIAL_MEMORY||16777216)/65536,maximum:32768}),S();var m=[],Q0=[],r=[];function J0(){var w=J.preRun.shift();m.unshift(w)}var z0=0,Z0=null,V0=null;function T0(w){throw J.onAbort?.(w),w="Aborted("+w+")",T(w),k=!0,y=1,w=new WebAssembly.RuntimeError(w+". Build with -sASSERTIONS for more info."),W(w),w}var _0=(w)=>w.startsWith("data:application/octet-stream;base64,"),K1=(w)=>w.startsWith("file://"),N0;function G0(w){if(w==N0&&j)return new Uint8Array(j);if(M)return M(w);throw"both async and sync fetching of the wasm failed"}function R0(w){return j?Promise.resolve().then(()=>G0(w)):L(w).then((v)=>new Uint8Array(v),()=>G0(w))}function l1(w,v,c){return R0(w).then((s)=>WebAssembly.instantiate(s,v)).then(c,(s)=>{T(`failed to asynchronously prepare wasm: ${s}`),T0(s)})}function b1(w,v){var c=N0;return j||typeof WebAssembly.instantiateStreaming!="function"||_0(c)||K1(c)||H||typeof fetch!="function"?l1(c,w,v):fetch(c,{credentials:"same-origin"}).then((s)=>WebAssembly.instantiateStreaming(s,w).then(v,function(u){return T(`wasm streaming compile failed: ${u}`),T("falling back to ArrayBuffer instantiation"),l1(c,w,v)}))}function b0(w){this.name="ExitStatus",this.message=`Program terminated with exit(${w})`,this.status=w}var L0=(w)=>{for(;0<w.length;)w.shift()(J)},$0=J.noExitRuntime||!0,P0=typeof TextDecoder<"u"?new TextDecoder:void 0,H0=(w,v,c)=>{var s=v+c;for(c=v;w[c]&&!(c>=s);)++c;if(16<c-v&&w.buffer&&P0)return P0.decode(w.subarray(v,c));for(s="";v<c;){var u=w[v++];if(u&128){var M0=w[v++]&63;if((u&224)==192)s+=String.fromCharCode((u&31)<<6|M0);else{var t0=w[v++]&63;u=(u&240)==224?(u&15)<<12|M0<<6|t0:(u&7)<<18|M0<<12|t0<<6|w[v++]&63,65536>u?s+=String.fromCharCode(u):(u-=65536,s+=String.fromCharCode(55296|u>>10,56320|u&1023))}}else s+=String.fromCharCode(u)}return s},U0=[0,31,60,91,121,152,182,213,244,274,305,335],u0=[0,31,59,90,120,151,181,212,243,273,304,334],A0={},S0=0,B1=(w)=>{y=w,$0||0<S0||(J.onExit?.(w),k=!0),D(w,new b0(w))},p1=(w)=>{if(!k)try{if(w(),!($0||0<S0))try{y=w=y,B1(w)}catch(v){v instanceof b0||v=="unwind"||D(1,v)}}catch(v){v instanceof b0||v=="unwind"||D(1,v)}},T6;T6=()=>performance.now();var l0=(w,v,c)=>{var s=h;if(!(0<c))return 0;var u=v;c=v+c-1;for(var M0=0;M0<w.length;++M0){var t0=w.charCodeAt(M0);if(55296<=t0&&57343>=t0){var T1=w.charCodeAt(++M0);t0=65536+((t0&1023)<<10)|T1&1023}if(127>=t0){if(v>=c)break;s[v++]=t0}else{if(2047>=t0){if(v+1>=c)break;s[v++]=192|t0>>6}else{if(65535>=t0){if(v+2>=c)break;s[v++]=224|t0>>12}else{if(v+3>=c)break;s[v++]=240|t0>>18,s[v++]=128|t0>>12&63}s[v++]=128|t0>>6&63}s[v++]=128|t0&63}}return s[v]=0,v-u},d0={},C0=()=>{if(!Y1){var w={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:U||"./this.program"},v;for(v in d0)d0[v]===void 0?delete w[v]:w[v]=d0[v];var c=[];for(v in w)c.push(`${v}=${w[v]}`);Y1=c}return Y1},Y1,I4=[null,[],[]],u6=(w)=>{for(var v=0,c=0;c<w.length;++c){var s=w.charCodeAt(c);127>=s?v++:2047>=s?v+=2:55296<=s&&57343>=s?(v+=4,++c):v+=3}return v},o8=(w,v,c,s)=>{var u={string:(L1)=>{var R6=0;if(L1!==null&&L1!==void 0&&L1!==0){R6=u6(L1)+1;var C8=_(R6);l0(L1,C8,R6),R6=C8}return R6},array:(L1)=>{var R6=_(L1.length);return b.set(L1,R6),R6}};w=J["_"+w];var M0=[],t0=0;if(s)for(var T1=0;T1<s.length;T1++){var v0=u[c[T1]];v0?(t0===0&&(t0=e()),M0[T1]=v0(s[T1])):M0[T1]=s[T1]}return c=w(...M0),c=function(L1){return t0!==0&&O(t0),v==="string"?L1?H0(h,L1):"":v==="boolean"?!!L1:L1}(c)},A1={b:(w,v,c,s)=>{T0(`Assertion failed: ${w?H0(h,w):""}, at: `+[v?v?H0(h,v):"":"unknown filename",c,s?s?H0(h,s):"":"unknown function"])},q:()=>{T0("")},n:()=>{$0=!1,S0=0},j:function(w,v,c){w=new Date(1000*(v+2097152>>>0<4194305-!!w?(w>>>0)+4294967296*v:NaN)),a[c>>2]=w.getSeconds(),a[c+4>>2]=w.getMinutes(),a[c+8>>2]=w.getHours(),a[c+12>>2]=w.getDate(),a[c+16>>2]=w.getMonth(),a[c+20>>2]=w.getFullYear()-1900,a[c+24>>2]=w.getDay(),v=w.getFullYear(),a[c+28>>2]=(v%4!==0||v%100===0&&v%400!==0?u0:U0)[w.getMonth()]+w.getDate()-1|0,a[c+36>>2]=-(60*w.getTimezoneOffset()),v=new Date(w.getFullYear(),6,1).getTimezoneOffset();var s=new Date(w.getFullYear(),0,1).getTimezoneOffset();a[c+32>>2]=(v!=s&&w.getTimezoneOffset()==Math.min(s,v))|0},l:(w,v)=>{if(A0[w]&&(clearTimeout(A0[w].id),delete A0[w]),!v)return 0;var c=setTimeout(()=>{delete A0[w],p1(()=>R4(w,T6()))},v);return A0[w]={id:c,Na:v},0},o:(w,v,c,s)=>{var u=new Date().getFullYear(),M0=new Date(u,0,1).getTimezoneOffset();u=new Date(u,6,1).getTimezoneOffset(),f[w>>2]=60*Math.max(M0,u),a[v>>2]=Number(M0!=u),v=(t0)=>{var T1=Math.abs(t0);return`UTC${0<=t0?"-":"+"}${String(Math.floor(T1/60)).padStart(2,"0")}${String(T1%60).padStart(2,"0")}`},w=v(M0),v=v(u),u<M0?(l0(w,c,17),l0(v,s,17)):(l0(w,s,17),l0(v,c,17))},p:()=>Date.now(),m:(w)=>{var v=h.length;if(w>>>=0,2147483648<w)return!1;for(var c=1;4>=c;c*=2){var s=v*(1+0.2/c);s=Math.min(s,w+100663296);Q:{s=(Math.min(2147483648,65536*Math.ceil(Math.max(w,s)/65536))-R.buffer.byteLength+65535)/65536;try{R.grow(s),S();var u=1;break Q}catch(M0){}u=void 0}if(u)return!0}return!1},f:(w,v)=>{var c=0;return C0().forEach((s,u)=>{var M0=v+c;u=f[w+4*u>>2]=M0;for(M0=0;M0<s.length;++M0)b[u++]=s.charCodeAt(M0);b[u]=0,c+=s.length+1}),0},g:(w,v)=>{var c=C0();f[w>>2]=c.length;var s=0;return c.forEach((u)=>s+=u.length+1),f[v>>2]=s,0},e:()=>52,k:function(){return 70},d:(w,v,c,s)=>{for(var u=0,M0=0;M0<c;M0++){var t0=f[v>>2],T1=f[v+4>>2];v+=8;for(var v0=0;v0<T1;v0++){var L1=h[t0+v0],R6=I4[w];L1===0||L1===10?((w===1?A:T)(H0(R6,0)),R6.length=0):R6.push(L1)}u+=T1}return f[s>>2]=u,0},a:R,c:B1,s:function(w,v,c,s,u){return J.callbacks.callFunction(void 0,w,v,c,s,u)},r:function(w){return J.callbacks.shouldInterrupt(void 0,w)},i:function(w,v,c){return c=c?H0(h,c):"",J.callbacks.loadModuleSource(void 0,w,v,c)},h:function(w,v,c,s){return c=c?H0(h,c):"",s=s?H0(h,s):"",J.callbacks.normalizeModule(void 0,w,v,c,s)}},I0=function(){function w(c){return I0=c.exports,Q0.unshift(I0.t),z0--,J.monitorRunDependencies?.(z0),z0==0&&(Z0!==null&&(clearInterval(Z0),Z0=null),V0&&(c=V0,V0=null,c())),I0}var v={a:A1};if(z0++,J.monitorRunDependencies?.(z0),J.instantiateWasm)try{return J.instantiateWasm(v,w)}catch(c){T(`Module.instantiateWasm callback failed with error: ${c}`),W(c)}return N0||=J.locateFile?_0("emscripten-module.wasm")?"emscripten-module.wasm":J.locateFile?J.locateFile("emscripten-module.wasm",B):B+"emscripten-module.wasm":new URL("emscripten-module.wasm",import.meta.url).href,b1(v,function(c){w(c.instance)}).catch(W),{}}();J._malloc=(w)=>(J._malloc=I0.u)(w),J._QTS_Throw=(w,v)=>(J._QTS_Throw=I0.v)(w,v),J._QTS_NewError=(w)=>(J._QTS_NewError=I0.w)(w),J._QTS_RuntimeSetMemoryLimit=(w,v)=>(J._QTS_RuntimeSetMemoryLimit=I0.x)(w,v),J._QTS_RuntimeComputeMemoryUsage=(w,v)=>(J._QTS_RuntimeComputeMemoryUsage=I0.y)(w,v),J._QTS_RuntimeDumpMemoryUsage=(w)=>(J._QTS_RuntimeDumpMemoryUsage=I0.z)(w),J._QTS_RecoverableLeakCheck=()=>(J._QTS_RecoverableLeakCheck=I0.A)(),J._QTS_BuildIsSanitizeLeak=()=>(J._QTS_BuildIsSanitizeLeak=I0.B)(),J._QTS_RuntimeSetMaxStackSize=(w,v)=>(J._QTS_RuntimeSetMaxStackSize=I0.C)(w,v),J._QTS_GetUndefined=()=>(J._QTS_GetUndefined=I0.D)(),J._QTS_GetNull=()=>(J._QTS_GetNull=I0.E)(),J._QTS_GetFalse=()=>(J._QTS_GetFalse=I0.F)(),J._QTS_GetTrue=()=>(J._QTS_GetTrue=I0.G)(),J._QTS_NewRuntime=()=>(J._QTS_NewRuntime=I0.H)(),J._QTS_FreeRuntime=(w)=>(J._QTS_FreeRuntime=I0.I)(w),J._free=(w)=>(J._free=I0.J)(w),J._QTS_NewContext=(w,v)=>(J._QTS_NewContext=I0.K)(w,v),J._QTS_FreeContext=(w)=>(J._QTS_FreeContext=I0.L)(w),J._QTS_FreeValuePointer=(w,v)=>(J._QTS_FreeValuePointer=I0.M)(w,v),J._QTS_FreeValuePointerRuntime=(w,v)=>(J._QTS_FreeValuePointerRuntime=I0.N)(w,v),J._QTS_FreeVoidPointer=(w,v)=>(J._QTS_FreeVoidPointer=I0.O)(w,v),J._QTS_FreeCString=(w,v)=>(J._QTS_FreeCString=I0.P)(w,v),J._QTS_DupValuePointer=(w,v)=>(J._QTS_DupValuePointer=I0.Q)(w,v),J._QTS_NewObject=(w)=>(J._QTS_NewObject=I0.R)(w),J._QTS_NewObjectProto=(w,v)=>(J._QTS_NewObjectProto=I0.S)(w,v),J._QTS_NewArray=(w)=>(J._QTS_NewArray=I0.T)(w),J._QTS_NewArrayBuffer=(w,v,c)=>(J._QTS_NewArrayBuffer=I0.U)(w,v,c),J._QTS_NewFloat64=(w,v)=>(J._QTS_NewFloat64=I0.V)(w,v),J._QTS_GetFloat64=(w,v)=>(J._QTS_GetFloat64=I0.W)(w,v),J._QTS_NewString=(w,v)=>(J._QTS_NewString=I0.X)(w,v),J._QTS_GetString=(w,v)=>(J._QTS_GetString=I0.Y)(w,v),J._QTS_GetArrayBuffer=(w,v)=>(J._QTS_GetArrayBuffer=I0.Z)(w,v),J._QTS_GetArrayBufferLength=(w,v)=>(J._QTS_GetArrayBufferLength=I0._)(w,v),J._QTS_NewSymbol=(w,v,c)=>(J._QTS_NewSymbol=I0.$)(w,v,c),J._QTS_GetSymbolDescriptionOrKey=(w,v)=>(J._QTS_GetSymbolDescriptionOrKey=I0.aa)(w,v),J._QTS_IsGlobalSymbol=(w,v)=>(J._QTS_IsGlobalSymbol=I0.ba)(w,v),J._QTS_IsJobPending=(w)=>(J._QTS_IsJobPending=I0.ca)(w),J._QTS_ExecutePendingJob=(w,v,c)=>(J._QTS_ExecutePendingJob=I0.da)(w,v,c),J._QTS_GetProp=(w,v,c)=>(J._QTS_GetProp=I0.ea)(w,v,c),J._QTS_GetPropNumber=(w,v,c)=>(J._QTS_GetPropNumber=I0.fa)(w,v,c),J._QTS_SetProp=(w,v,c,s)=>(J._QTS_SetProp=I0.ga)(w,v,c,s),J._QTS_DefineProp=(w,v,c,s,u,M0,t0,T1,v0)=>(J._QTS_DefineProp=I0.ha)(w,v,c,s,u,M0,t0,T1,v0),J._QTS_GetOwnPropertyNames=(w,v,c,s,u)=>(J._QTS_GetOwnPropertyNames=I0.ia)(w,v,c,s,u),J._QTS_Call=(w,v,c,s,u)=>(J._QTS_Call=I0.ja)(w,v,c,s,u),J._QTS_ResolveException=(w,v)=>(J._QTS_ResolveException=I0.ka)(w,v),J._QTS_Dump=(w,v)=>(J._QTS_Dump=I0.la)(w,v),J._QTS_Eval=(w,v,c,s,u,M0)=>(J._QTS_Eval=I0.ma)(w,v,c,s,u,M0),J._QTS_GetModuleNamespace=(w,v)=>(J._QTS_GetModuleNamespace=I0.na)(w,v),J._QTS_Typeof=(w,v)=>(J._QTS_Typeof=I0.oa)(w,v),J._QTS_GetLength=(w,v,c)=>(J._QTS_GetLength=I0.pa)(w,v,c),J._QTS_IsEqual=(w,v,c,s)=>(J._QTS_IsEqual=I0.qa)(w,v,c,s),J._QTS_GetGlobalObject=(w)=>(J._QTS_GetGlobalObject=I0.ra)(w),J._QTS_NewPromiseCapability=(w,v)=>(J._QTS_NewPromiseCapability=I0.sa)(w,v),J._QTS_PromiseState=(w,v)=>(J._QTS_PromiseState=I0.ta)(w,v),J._QTS_PromiseResult=(w,v)=>(J._QTS_PromiseResult=I0.ua)(w,v),J._QTS_TestStringArg=(w)=>(J._QTS_TestStringArg=I0.va)(w),J._QTS_GetDebugLogEnabled=(w)=>(J._QTS_GetDebugLogEnabled=I0.wa)(w),J._QTS_SetDebugLogEnabled=(w,v)=>(J._QTS_SetDebugLogEnabled=I0.xa)(w,v),J._QTS_BuildIsDebug=()=>(J._QTS_BuildIsDebug=I0.ya)(),J._QTS_BuildIsAsyncify=()=>(J._QTS_BuildIsAsyncify=I0.za)(),J._QTS_NewFunction=(w,v,c)=>(J._QTS_NewFunction=I0.Aa)(w,v,c),J._QTS_ArgvGetJSValueConstPointer=(w,v)=>(J._QTS_ArgvGetJSValueConstPointer=I0.Ba)(w,v),J._QTS_RuntimeEnableInterruptHandler=(w)=>(J._QTS_RuntimeEnableInterruptHandler=I0.Ca)(w),J._QTS_RuntimeDisableInterruptHandler=(w)=>(J._QTS_RuntimeDisableInterruptHandler=I0.Da)(w),J._QTS_RuntimeEnableModuleLoader=(w,v)=>(J._QTS_RuntimeEnableModuleLoader=I0.Ea)(w,v),J._QTS_RuntimeDisableModuleLoader=(w)=>(J._QTS_RuntimeDisableModuleLoader=I0.Fa)(w),J._QTS_bjson_encode=(w,v)=>(J._QTS_bjson_encode=I0.Ga)(w,v),J._QTS_bjson_decode=(w,v)=>(J._QTS_bjson_decode=I0.Ha)(w,v);var R4=(w,v)=>(R4=I0.Ja)(w,v),O=(w)=>(O=I0.Ka)(w),_=(w)=>(_=I0.La)(w),e=()=>(e=I0.Ma)();J.cwrap=(w,v,c,s)=>{var u=!c||c.every((M0)=>M0==="number"||M0==="boolean");return v!=="string"&&u&&!s?J["_"+w]:(...M0)=>o8(w,v,c,M0)},J.UTF8ToString=(w,v)=>w?H0(h,w,v):"",J.stringToUTF8=(w,v,c)=>l0(w,v,c),J.lengthBytesUTF8=u6;var Y0;V0=function w(){Y0||z(),Y0||(V0=w)};function z(){function w(){if(!Y0&&(Y0=!0,J.calledRun=!0,!k)){if(L0(Q0),G(J),J.onRuntimeInitialized?.(),J.postRun)for(typeof J.postRun=="function"&&(J.postRun=[J.postRun]);J.postRun.length;){var v=J.postRun.shift();r.unshift(v)}L0(r)}}if(!(0<z0)){if(J.preRun)for(typeof J.preRun=="function"&&(J.preRun=[J.preRun]);J.preRun.length;)J0();L0(m),0<z0||(J.setStatus?(J.setStatus("Running..."),setTimeout(function(){setTimeout(function(){J.setStatus("")},1),w()},1)):w())}}if(J.preInit)for(typeof J.preInit=="function"&&(J.preInit=[J.preInit]);0<J.preInit.length;)J.preInit.pop()();return z(),Y=Z,Y}})(),FS6=HS6});var L80=I((uu4,w51)=>{var{defineProperty:O80,getOwnPropertyDescriptor:dk6,getOwnPropertyNames:pk6}=Object,ck6=Object.prototype.hasOwnProperty,nk6=(Q,X)=>{for(var Y in X)O80(Q,Y,{get:X[Y],enumerable:!0})},ik6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of pk6(X))if(!ck6.call(Q,G)&&G!==Y)O80(Q,G,{get:()=>X[G],enumerable:!(J=dk6(X,G))||J.enumerable})}return Q},ak6=(Q)=>ik6(O80({},"__esModule",{value:!0}),Q),O51={};nk6(O51,{SYMBOL_FOR_REQ_CONTEXT:()=>L51,getContext:()=>rk6});w51.exports=ak6(O51);var L51=Symbol.for("@vercel/request-context");function rk6(){return globalThis[L51]?.get?.()??{}}});var UP=I((mu4,T51)=>{var{defineProperty:w80,getOwnPropertyDescriptor:ok6,getOwnPropertyNames:sk6}=Object,tk6=Object.prototype.hasOwnProperty,ek6=(Q,X)=>{for(var Y in X)w80(Q,Y,{get:X[Y],enumerable:!0})},Qv6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of sk6(X))if(!tk6.call(Q,G)&&G!==Y)w80(Q,G,{get:()=>X[G],enumerable:!(J=ok6(X,G))||J.enumerable})}return Q},Xv6=(Q)=>Qv6(w80({},"__esModule",{value:!0}),Q),M51={};ek6(M51,{VercelOidcTokenError:()=>P51});T51.exports=Xv6(M51);class P51 extends Error{constructor(Q,X){super(Q);this.name="VercelOidcTokenError",this.cause=X}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C51=I((lu4,j51)=>{var{create:Yv6,defineProperty:ky,getOwnPropertyDescriptor:Jv6,getOwnPropertyNames:Gv6,getPrototypeOf:Wv6}=Object,Zv6=Object.prototype.hasOwnProperty,$v6=(Q,X)=>{for(var Y in X)ky(Q,Y,{get:X[Y],enumerable:!0})},A51=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Gv6(X))if(!Zv6.call(Q,G)&&G!==Y)ky(Q,G,{get:()=>X[G],enumerable:!(J=Jv6(X,G))||J.enumerable})}return Q},P80=(Q,X,Y)=>(Y=Q!=null?Yv6(Wv6(Q)):{},A51(X||!Q||!Q.__esModule?ky(Y,"default",{value:Q,enumerable:!0}):Y,Q)),Kv6=(Q)=>A51(ky({},"__esModule",{value:!0}),Q),E51={};$v6(E51,{findRootDir:()=>Vv6,getUserDataDir:()=>qv6});j51.exports=Kv6(E51);var BP=P80(D0("path")),Hv6=P80(D0("fs")),M80=P80(D0("os")),Fv6=UP();function Vv6(){try{let Q=process.cwd();while(Q!==BP.default.dirname(Q)){let X=BP.default.join(Q,".vercel");if(Hv6.default.existsSync(X))return Q;Q=BP.default.dirname(Q)}}catch(Q){throw new Fv6.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qv6(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(M80.default.platform()){case"darwin":return BP.default.join(M80.default.homedir(),"Library/Application Support");case"linux":return BP.default.join(M80.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var y51=I((du4,_51)=>{var{create:zv6,defineProperty:vy,getOwnPropertyDescriptor:Uv6,getOwnPropertyNames:Bv6,getPrototypeOf:Dv6}=Object,Nv6=Object.prototype.hasOwnProperty,Ov6=(Q,X)=>{for(var Y in X)vy(Q,Y,{get:X[Y],enumerable:!0})},I51=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Bv6(X))if(!Nv6.call(Q,G)&&G!==Y)vy(Q,G,{get:()=>X[G],enumerable:!(J=Uv6(X,G))||J.enumerable})}return Q},R51=(Q,X,Y)=>(Y=Q!=null?zv6(Dv6(Q)):{},I51(X||!Q||!Q.__esModule?vy(Y,"default",{value:Q,enumerable:!0}):Y,Q)),Lv6=(Q)=>I51(vy({},"__esModule",{value:!0}),Q),S51={};Ov6(S51,{isValidAccessToken:()=>Tv6,readAuthConfig:()=>Mv6,writeAuthConfig:()=>Pv6});_51.exports=Lv6(S51);var DP=R51(D0("fs")),k51=R51(D0("path")),wv6=_y();function v51(){let Q=(0,wv6.getVercelDataDir)();if(!Q)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return k51.join(Q,"auth.json")}function Mv6(){try{let Q=v51();if(!DP.existsSync(Q))return null;let X=DP.readFileSync(Q,"utf8");if(!X)return null;return JSON.parse(X)}catch(Q){return null}}function Pv6(Q){let X=v51(),Y=k51.dirname(X);if(!DP.existsSync(Y))DP.mkdirSync(Y,{mode:504,recursive:!0});DP.writeFileSync(X,JSON.stringify(Q,null,2),{mode:384})}function Tv6(Q){if(!Q.token)return!1;if(typeof Q.expiresAt!=="number")return!0;let X=Math.floor(Date.now()/1000);return Q.expiresAt>=X}});var x51=I((pu4,h51)=>{var{defineProperty:E80,getOwnPropertyDescriptor:Av6,getOwnPropertyNames:Ev6}=Object,jv6=Object.prototype.hasOwnProperty,Cv6=(Q,X)=>{for(var Y in X)E80(Q,Y,{get:X[Y],enumerable:!0})},Iv6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Ev6(X))if(!jv6.call(Q,G)&&G!==Y)E80(Q,G,{get:()=>X[G],enumerable:!(J=Av6(X,G))||J.enumerable})}return Q},Rv6=(Q)=>Iv6(E80({},"__esModule",{value:!0}),Q),b51={};Cv6(b51,{processTokenResponse:()=>yv6,refreshTokenRequest:()=>_v6});h51.exports=Rv6(b51);var T80=D0("os"),Sv6="https://vercel.com",kv6="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f51=`@vercel/oidc node-${process.version} ${(0,T80.platform)()} (${(0,T80.arch)()}) ${(0,T80.hostname)()}`,A80=null;async function vv6(){if(A80)return A80;let Q=`${Sv6}/.well-known/openid-configuration`,X=await fetch(Q,{headers:{"user-agent":f51}});if(!X.ok)throw Error("Failed to discover OAuth endpoints");let Y=await X.json();if(!Y||typeof Y.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Y.token_endpoint;return A80=J,J}async function _v6(Q){let X=await vv6();return await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f51},body:new URLSearchParams({client_id:kv6,grant_type:"refresh_token",...Q})})}async function yv6(Q){let X=await Q.json();if(!Q.ok){let Y=typeof X==="object"&&X&&"error"in X?String(X.error):"Token refresh failed";return[Error(Y)]}if(typeof X!=="object"||X===null)return[Error("Invalid token response")];if(typeof X.access_token!=="string")return[Error("Missing access_token in response")];if(X.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof X.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,X]}});var _y=I((cu4,d51)=>{var{create:bv6,defineProperty:yy,getOwnPropertyDescriptor:fv6,getOwnPropertyNames:hv6,getPrototypeOf:xv6}=Object,gv6=Object.prototype.hasOwnProperty,uv6=(Q,X)=>{for(var Y in X)yy(Q,Y,{get:X[Y],enumerable:!0})},u51=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of hv6(X))if(!gv6.call(Q,G)&&G!==Y)yy(Q,G,{get:()=>X[G],enumerable:!(J=fv6(X,G))||J.enumerable})}return Q},m51=(Q,X,Y)=>(Y=Q!=null?bv6(xv6(Q)):{},u51(X||!Q||!Q.__esModule?yy(Y,"default",{value:Q,enumerable:!0}):Y,Q)),mv6=(Q)=>u51(yy({},"__esModule",{value:!0}),Q),l51={};uv6(l51,{assertVercelOidcTokenResponse:()=>j80,findProjectInfo:()=>cv6,getTokenPayload:()=>av6,getVercelCliToken:()=>dv6,getVercelDataDir:()=>lv6,getVercelOidcToken:()=>pv6,isExpired:()=>rv6,loadToken:()=>iv6,saveToken:()=>nv6});d51.exports=mv6(l51);var NP=m51(D0("path")),JF=m51(D0("fs")),vU=UP(),by=C51(),kU=y51(),g51=x51();function lv6(){let X=(0,by.getUserDataDir)();if(!X)return null;return NP.join(X,"com.vercel.cli")}async function dv6(){let Q=(0,kU.readAuthConfig)();if(!Q)return null;if((0,kU.isValidAccessToken)(Q))return Q.token||null;if(!Q.refreshToken)return(0,kU.writeAuthConfig)({}),null;try{let X=await(0,g51.refreshTokenRequest)({refresh_token:Q.refreshToken}),[Y,J]=await(0,g51.processTokenResponse)(X);if(Y||!J)return(0,kU.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,kU.writeAuthConfig)(G),G.token??null}catch(X){return(0,kU.writeAuthConfig)({}),null}}async function pv6(Q,X,Y){let J=`https://api.vercel.com/v1/projects/${X}/token?source=vercel-oidc-refresh${Y?`&teamId=${Y}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`}});if(!G.ok)throw new vU.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let W=await G.json();return j80(W),W}function j80(Q){if(!Q||typeof Q!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in Q)||typeof Q.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function cv6(){let Q=(0,by.findRootDir)();if(!Q)throw new vU.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let X=NP.join(Q,".vercel","project.json");if(!JF.existsSync(X))throw new vU.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Y=JSON.parse(JF.readFileSync(X,"utf8"));if(typeof Y.projectId!=="string"&&typeof Y.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Y.projectId,teamId:Y.orgId}}function nv6(Q,X){let Y=(0,by.getUserDataDir)();if(!Y)throw new vU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=NP.join(Y,"com.vercel.token",`${X}.json`),G=JSON.stringify(Q);JF.mkdirSync(NP.dirname(J),{mode:504,recursive:!0}),JF.writeFileSync(J,G),JF.chmodSync(J,432);return}function iv6(Q){let X=(0,by.getUserDataDir)();if(!X)throw new vU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Y=NP.join(X,"com.vercel.token",`${Q}.json`);if(!JF.existsSync(Y))return null;let J=JSON.parse(JF.readFileSync(Y,"utf8"));return j80(J),J}function av6(Q){let X=Q.split(".");if(X.length!==3)throw new vU.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Y=X[1].replace(/-/g,"+").replace(/_/g,"/"),J=Y.padEnd(Y.length+(4-Y.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function rv6(Q){return Q.exp*1000<Date.now()}});var n51=I((nu4,c51)=>{var{defineProperty:I80,getOwnPropertyDescriptor:ov6,getOwnPropertyNames:sv6}=Object,tv6=Object.prototype.hasOwnProperty,ev6=(Q,X)=>{for(var Y in X)I80(Q,Y,{get:X[Y],enumerable:!0})},Q_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of sv6(X))if(!tv6.call(Q,G)&&G!==Y)I80(Q,G,{get:()=>X[G],enumerable:!(J=ov6(X,G))||J.enumerable})}return Q},X_6=(Q)=>Q_6(I80({},"__esModule",{value:!0}),Q),p51={};ev6(p51,{refreshToken:()=>Y_6});c51.exports=X_6(p51);var C80=UP(),GF=_y();async function Y_6(){let{projectId:Q,teamId:X}=(0,GF.findProjectInfo)(),Y=(0,GF.loadToken)(Q);if(!Y||(0,GF.isExpired)((0,GF.getTokenPayload)(Y.token))){let J=await(0,GF.getVercelCliToken)();if(!J)throw new C80.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!Q)throw new C80.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Y=await(0,GF.getVercelOidcToken)(J,Q,X),!Y)throw new C80.VercelOidcTokenError("Failed to refresh OIDC token");(0,GF.saveToken)(Y,Q)}process.env.VERCEL_OIDC_TOKEN=Y.token;return}});var r51=I((iu4,a51)=>{var{defineProperty:S80,getOwnPropertyDescriptor:J_6,getOwnPropertyNames:G_6}=Object,W_6=Object.prototype.hasOwnProperty,Z_6=(Q,X)=>{for(var Y in X)S80(Q,Y,{get:X[Y],enumerable:!0})},$_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of G_6(X))if(!W_6.call(Q,G)&&G!==Y)S80(Q,G,{get:()=>X[G],enumerable:!(J=J_6(X,G))||J.enumerable})}return Q},K_6=(Q)=>$_6(S80({},"__esModule",{value:!0}),Q),i51={};Z_6(i51,{getVercelOidcToken:()=>V_6,getVercelOidcTokenSync:()=>R80});a51.exports=K_6(i51);var H_6=L80(),F_6=UP();async function V_6(){let Q="",X;try{Q=R80()}catch(Y){X=Y}try{let[{getTokenPayload:Y,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => m6(_y())),await Promise.resolve().then(() => m6(n51()))]);if(!Q||J(Y(Q)))await G(),Q=R80()}catch(Y){let J=X instanceof Error?X.message:"";if(Y instanceof Error)J=`${J}
261
- ${Y.message}`;if(J)throw new F_6.VercelOidcTokenError(J);throw Y}return Q}function R80(){let Q=(0,H_6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!Q)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return Q}});var v80=I((au4,t51)=>{var{defineProperty:k80,getOwnPropertyDescriptor:q_6,getOwnPropertyNames:z_6}=Object,U_6=Object.prototype.hasOwnProperty,B_6=(Q,X)=>{for(var Y in X)k80(Q,Y,{get:X[Y],enumerable:!0})},D_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of z_6(X))if(!U_6.call(Q,G)&&G!==Y)k80(Q,G,{get:()=>X[G],enumerable:!(J=q_6(X,G))||J.enumerable})}return Q},N_6=(Q)=>D_6(k80({},"__esModule",{value:!0}),Q),s51={};B_6(s51,{getContext:()=>O_6.getContext,getVercelOidcToken:()=>o51.getVercelOidcToken,getVercelOidcTokenSync:()=>o51.getVercelOidcTokenSync});t51.exports=N_6(s51);var o51=r51(),O_6=L80()});var SE=m6($1(),1),ek0=m6(pk0(),1),Qv0=m6(Ql(),1),Xv0=m6(Im(),1),Xl=new Qv0.PrometheusExporter({preventServerStart:!0}),an1=new ek0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Xv0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:Xl});an1.start();var jD=SE.trace.getTracer("mcp-mesh","1.0.0"),Yv0=SE.metrics.getMeter("mcp-mesh","1.0.0");var Yl=class extends Error{res;status;constructor(Q=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Q}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var Jv0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],rn1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,on1=(Q,X)=>{if(!Q)return{};let Y=new Headers(Q.headers);if(X){let J=Y.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!rn1.test(Z));if(W.length>0)throw new Yl(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Y.delete(Z)})}}return Jv0.forEach((J)=>{Y.delete(J)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:Y,signal:Q.signal}},sn1=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let X=new Headers;for(let[Y,J]of Object.entries(Q.headers))if(J==null)X.delete(Y);else X.set(Y,J);return Q.headers=X,Q},Gv0=async(Q,X)=>{let{raw:Y,customFetch:J,strictConnectionProcessing:G=!1,...W}=X instanceof Request?{raw:X}:X??{},Z=new Request(Q,{...on1(Y,G),...sn1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(Jv0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Wv0=(Q)=>(X)=>{let Y=new URL(X.req.raw.url),J=new URL(Q);return J.pathname=Y.pathname,J.search=Y.search,Gv0(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};import{resolve as CD,dirname as tn1}from"path";var en1="http://localhost:4000",Qi1="./dist/client";function Xi1(Q,X){let Y=CD(X),J=CD(Q);return J===Y||J.startsWith(Y+"/")}function Yi1({requestPath:Q,clientDir:X}){let Y=Q.startsWith("/")?Q.slice(1):Q,J=CD(X,Y);if(!Xi1(J,X))return null;return J}function Zv0(Q,X="../client"){let Y=new URL(Q),J=tn1(Y.pathname);return CD(J,X)}function $v0(Q={}){let{env:X="production",devServerUrl:Y=en1,clientDir:J=Qi1,isServerPath:G=()=>!1}=Q;if(X==="development"){let W=Wv0(Y);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=Yi1({requestPath:K,clientDir:J});if(!H)return null;let F=CD(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var iW1=m6(Ql(),1);var Jl=(Q,X,Y)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(Q[$])F=Q[$][0][0],J.req.routeIndex=$;else F=$===Q.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&X)J.error=V,K=await X(V,J),H=!0;else throw V}else if(J.finalized===!1&&Y)K=await Y(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var Kv0=Symbol();var Hv0=async(Q,X=Object.create(null))=>{let{all:Y=!1,dot:J=!1}=X,W=(Q instanceof kE?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Ji1(Q,{all:Y,dot:J});return{}};async function Ji1(Q,X){let Y=await Q.formData();if(Y)return Gi1(Y,X);return{}}function Gi1(Q,X){let Y=Object.create(null);if(Q.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Y[G]=J;else Wi1(Y,G,J)}),X.dot)Object.entries(Y).forEach(([J,G])=>{if(J.includes("."))Zi1(Y,J,G),delete Y[J]});return Y}var Wi1=(Q,X,Y)=>{if(Q[X]!==void 0)if(Array.isArray(Q[X]))Q[X].push(Y);else Q[X]=[Q[X],Y];else if(!X.endsWith("[]"))Q[X]=Y;else Q[X]=[Y]},Zi1=(Q,X,Y)=>{let J=Q,G=X.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Y;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var Wl=(Q)=>{let X=Q.split("/");if(X[0]==="")X.shift();return X},Fv0=(Q)=>{let{groups:X,path:Y}=$i1(Q),J=Wl(Y);return Ki1(J,X)},$i1=(Q)=>{let X=[];return Q=Q.replace(/\{[^}]+\}/g,(Y,J)=>{let G=`@${J}`;return X.push([G,Y]),G}),{groups:X,path:Q}},Ki1=(Q,X)=>{for(let Y=X.length-1;Y>=0;Y--){let[J]=X[Y];for(let G=Q.length-1;G>=0;G--)if(Q[G].includes(J)){Q[G]=Q[G].replace(J,X[Y][1]);break}}return Q},vE={},Vv0=(Q,X)=>{if(Q==="*")return"*";let Y=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let J=`${Q}#${X}`;if(!vE[J])if(Y[2])vE[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Y[1],new RegExp(`^${Y[2]}(?=/${X})`)]:[Q,Y[1],new RegExp(`^${Y[2]}$`)];else vE[J]=[Q,Y[1],!0];return vE[J]}return null},_E=(Q,X)=>{try{return X(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return X(Y)}catch{return Y}})}},Hi1=(Q)=>_E(Q,decodeURI),Zl=(Q)=>{let X=Q.url,Y=X.indexOf("/",X.indexOf(":")+4),J=Y;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let W=X.indexOf("?",J),Z=X.slice(Y,W===-1?void 0:W);return Hi1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return X.slice(Y,J)};var qv0=(Q)=>{let X=Zl(Q);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},aK=(Q,X,...Y)=>{if(Y.length)X=aK(X,...Y);return`${Q?.[0]==="/"?"":"/"}${Q}${X==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},yE=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let X=Q.split("/"),Y=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Y.length===0&&J==="")Y.push("/");else Y.push(J);let W=G.replace("?","");J+="/"+W,Y.push(J)}else J+="/"+G}),Y.filter((G,W,Z)=>Z.indexOf(G)===W)},Gl=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?_E(Q,$l):Q},zv0=(Q,X,Y)=>{let J;if(!Y&&X&&!/[%+]/.test(X)){let Z=Q.indexOf("?",8);if(Z===-1)return;if(!Q.startsWith(X,Z+1))Z=Q.indexOf(`&${X}`,Z+1);while(Z!==-1){let $=Q.charCodeAt(Z+X.length+1);if($===61){let K=Z+X.length+2,H=Q.indexOf("&",K);return Gl(Q.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=Q.indexOf(`&${X}`,Z+1)}if(J=/[%+]/.test(Q),!J)return}let G={};J??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let Z=Q.indexOf("&",W+1),$=Q.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=Q.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=Gl(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=Q.slice($+1,Z===-1?void 0:Z),J)H=Gl(H);if(Y){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return X?G[X]:G},Uv0=zv0,Bv0=(Q,X)=>{return zv0(Q,X,!0)},$l=decodeURIComponent;var Dv0=(Q)=>_E(Q,$l),kE=class{raw;#Q;#X;routeIndex=0;path;bodyCache={};constructor(Q,X="/",Y=[[]]){this.raw=Q,this.path=X,this.#X=Y,this.#Q={}}param(Q){return Q?this.#Y(Q):this.#J()}#Y(Q){let X=this.#X[0][this.routeIndex][1][Q],Y=this.#W(X);return Y&&/\%/.test(Y)?Dv0(Y):Y}#J(){let Q={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Y of X){let J=this.#W(this.#X[0][this.routeIndex][1][Y]);if(J!==void 0)Q[Y]=/\%/.test(J)?Dv0(J):J}return Q}#W(Q){return this.#X[1]?this.#X[1][Q]:Q}query(Q){return Uv0(this.url,Q)}queries(Q){return Bv0(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let X={};return this.raw.headers.forEach((Y,J)=>{X[J]=Y}),X}async parseBody(Q){return this.bodyCache.parsedBody??=await Hv0(this,Q)}#G=(Q)=>{let{bodyCache:X,raw:Y}=this,J=X[Q];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return X[Q]=Y[Q]()};json(){return this.#G("text").then((Q)=>JSON.parse(Q))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Q,X){this.#Q[Q]=X}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[Kv0](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Q]])=>Q)}get routePath(){return this.#X[0].map(([[,Q]])=>Q)[this.routeIndex].path}};var Nv0={Stringify:1,BeforeStream:2,Stream:3},Fi1=(Q,X)=>{let Y=new String(Q);return Y.isEscaped=!0,Y.callbacks=X,Y};var Kl=async(Q,X,Y,J,G)=>{if(typeof Q==="object"&&!(Q instanceof String)){if(!(Q instanceof Promise))Q=Q.toString();if(Q instanceof Promise)Q=await Q}let W=Q.callbacks;if(!W?.length)return Promise.resolve(Q);if(G)G[0]+=Q;else G=[Q];let Z=Promise.all(W.map(($)=>$({phase:X,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>Kl(K,X,!1,J,G))).then(()=>G[0]));if(Y)return Fi1(await Z,W);else return Z};var Vi1="text/plain; charset=UTF-8",Hl=(Q,X)=>{return{"Content-Type":Q,...X}},Ov0=class{#Q;#X;env={};#Y;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(Q,X){if(this.#Q=Q,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#q=X.path,this.#V=X.matchResult}get req(){return this.#X??=new kE(this.#Q,this.#q,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[X,Y]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let G of J)Q.headers.append("set-cookie",G)}else Q.headers.set(X,Y)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Q)};setLayout=(Q)=>this.#$=Q;getLayout=()=>this.#$;setRenderer=(Q)=>{this.#Z=Q};header=(Q,X,Y)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(X===void 0)J.delete(Q);else if(Y?.append)J.append(Q,X);else J.set(Q,X)};status=(Q)=>{this.#J=Q};set=(Q,X)=>{this.#Y??=new Map,this.#Y.set(Q,X)};get=(Q)=>{return this.#Y?this.#Y.get(Q):void 0};get var(){if(!this.#Y)return{};return Object.fromEntries(this.#Y)}#F(Q,X,Y){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof X==="object"&&"headers"in X){let W=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Y)for(let[W,Z]of Object.entries(Y))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Q,{status:G,headers:J})}newResponse=(...Q)=>this.#F(...Q);body=(Q,X,Y)=>this.#F(Q,X,Y);text=(Q,X,Y)=>{return!this.#K&&!this.#J&&!X&&!Y&&!this.finalized?new Response(Q):this.#F(Q,X,Hl(Vi1,Y))};json=(Q,X,Y)=>{return this.#F(JSON.stringify(Q),X,Hl("application/json",Y))};html=(Q,X,Y)=>{let J=(G)=>this.#F(G,X,Hl("text/html; charset=UTF-8",Y));return typeof Q==="object"?Kl(Q,Nv0.Stringify,!1,{}).then(J):J(Q)};redirect=(Q,X)=>{let Y=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(Y)?Y:encodeURI(Y)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var p4="ALL",Lv0="all",wv0=["get","post","put","delete","options","patch"],bE="Can not add a route since the matcher is already built.",fE=class extends Error{};var Mv0="__COMPOSED_HANDLER";var qi1=(Q)=>{return Q.text("404 Not Found",404)},Pv0=(Q,X)=>{if("getResponse"in Q){let Y=Q.getResponse();return X.newResponse(Y.body,Y)}return console.error(Q),X.text("Internal Server Error",500)},Tv0=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(X={}){[...wv0,Lv0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#Q=Z;else this.#J(W,this.#Q,Z);return $.forEach((K)=>{this.#J(W,this.#Q,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#Q=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#Q,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(p4,this.#Q,$)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??Zl:qv0}#X(){let X=new Q({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Y=this.#Y,X.routes=this.routes,X}#Y=qi1;errorHandler=Pv0;route(X,Y){let J=this.basePath(X);return Y.routes.map((G)=>{let W;if(Y.errorHandler===Pv0)W=G.handler;else W=async(Z,$)=>(await Jl([],Y.errorHandler)(Z,()=>G.handler(Z,$))).res,W[Mv0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(X){let Y=this.#X();return Y._basePath=aK(this._basePath,X),Y}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Y=X,this};mount(X,Y,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=aK(this._basePath,X),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Y(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(p4,aK(X,"*"),$),this}#J(X,Y,J){X=X.toUpperCase(),Y=aK(this._basePath,Y);let G={basePath:this._basePath,path:Y,method:X,handler:J};this.router.add(X,Y,[J,G]),this.routes.push(G)}#W(X,Y){if(X instanceof Error)return this.errorHandler(X,Y);throw X}#G(X,Y,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Y,J,"GET")))();let W=this.getPath(X,{env:J}),Z=this.router.match(G,W),$=new Ov0(X,{path:W,matchResult:Z,env:J,executionCtx:Y,notFoundHandler:this.#Y});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Y($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Y($))).catch((F)=>this.#W(F,$)):H??this.#Y($)}let K=Jl(Z[0],this.errorHandler,this.#Y);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(X,...Y)=>{return this.#G(X,Y[1],Y[0],X.method)};request=(X,Y,J,G)=>{if(X instanceof Request)return this.fetch(Y?new Request(X,Y):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${aK("/",X)}`,Y),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var ID=[];function hE(Q,X){let Y=this.buildAllMatchers(),J=(G,W)=>{let Z=Y[G]||Y[p4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],ID];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(Q,X)}var xE="[^/]+",RD=".*",SD="(?:|/.*)",rK=Symbol(),zi1=new Set(".\\+*[^]$()");function Ui1(Q,X){if(Q.length===1)return X.length===1?Q<X?-1:1:-1;if(X.length===1)return 1;if(Q===RD||Q===SD)return 1;else if(X===RD||X===SD)return-1;if(Q===xE)return 1;else if(X===xE)return-1;return Q.length===X.length?Q<X?-1:1:X.length-Q.length}var Av0=class Q{#Q;#X;#Y=Object.create(null);insert(X,Y,J,G,W){if(X.length===0){if(this.#Q!==void 0)throw rK;if(W)return;this.#Q=Y;return}let[Z,...$]=X,K=Z==="*"?$.length===0?["","",RD]:["","",xE]:Z==="/*"?["","",SD]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||xE;if(F&&K[2]){if(V===".*")throw rK;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw rK}if(H=this.#Y[V],!H){if(Object.keys(this.#Y).some((q)=>q!==RD&&q!==SD))throw rK;if(W)return;if(H=this.#Y[V]=new Q,F!=="")H.#X=G.varIndex++}if(!W&&F!=="")J.push([F,H.#X])}else if(H=this.#Y[Z],!H){if(Object.keys(this.#Y).some((F)=>F.length>1&&F!==RD&&F!==SD))throw rK;if(W)return;H=this.#Y[Z]=new Q}H.insert($,Y,J,G,W)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(Ui1).map((J)=>{let G=this.#Y[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:zi1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Q==="number")Y.unshift(`#${this.#Q}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var Ev0=class{#Q={varIndex:0};#X=new Av0;insert(Q,X,Y){let J=[],G=[];for(let Z=0;;){let $=!1;if(Q=Q.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#X.insert(W,X,J,this.#Q,Y),J}buildRegExp(){let Q=this.#X.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let X=0,Y=[],J=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Y[++X]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++X,"";return""}),[new RegExp(`^${Q}`),Y,J]}};var Bi1=[/^$/,[],Object.create(null)],jv0=Object.create(null);function Cv0(Q){return jv0[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function Di1(){jv0=Object.create(null)}function Ni1(Q){let X=new Ev0,Y=[];if(Q.length===0)return Bi1;let J=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,U,D]=J[H];if(q)G[U]=[D.map(([L])=>[L,Object.create(null)]),ID];else F++;let B;try{B=X.insert(U,F,q)}catch(L){throw L===rK?new fE(U):L}if(q)continue;Y[F]=D.map(([L,M])=>{let C=Object.create(null);M-=1;for(;M>=0;M--){let[E,A]=B[M];C[E]=A}return[L,C]})}let[W,Z,$]=X.buildRegExp();for(let H=0,F=Y.length;H<F;H++)for(let V=0,q=Y[H].length;V<q;V++){let U=Y[H][V]?.[1];if(!U)continue;let D=Object.keys(U);for(let B=0,L=D.length;B<L;B++)U[D[B]]=$[U[D[B]]]}let K=[];for(let H in Z)K[H]=Y[Z[H]];return[W,K,G]}function UV(Q,X){if(!Q)return;for(let Y of Object.keys(Q).sort((J,G)=>G.length-J.length))if(Cv0(Y).test(X))return[...Q[Y]];return}var gE=class{name="RegExpRouter";#Q;#X;constructor(){this.#Q={[p4]:Object.create(null)},this.#X={[p4]:Object.create(null)}}add(Q,X,Y){let J=this.#Q,G=this.#X;if(!J||!G)throw Error(bE);if(!J[Q])[J,G].forEach(($)=>{$[Q]=Object.create(null),Object.keys($[p4]).forEach((K)=>{$[Q][K]=[...$[p4][K]]})});if(X==="/*")X="*";let W=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let $=Cv0(X);if(Q===p4)Object.keys(J).forEach((K)=>{J[K][X]||=UV(J[K],X)||UV(J[p4],X)||[]});else J[Q][X]||=UV(J[Q],X)||UV(J[p4],X)||[];Object.keys(J).forEach((K)=>{if(Q===p4||Q===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Y,W])})}),Object.keys(G).forEach((K)=>{if(Q===p4||Q===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Y,W]))});return}let Z=yE(X)||[X];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(Q===p4||Q===F)G[F][H]||=[...UV(J[F],H)||UV(J[p4],H)||[]],G[F][H].push([Y,W-K+$+1])})}}match=hE;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Q)).forEach((X)=>{Q[X]||=this.#Y(X)}),this.#Q=this.#X=void 0,Di1(),Q}#Y(Q){let X=[],Y=Q===p4;if([this.#Q,this.#X].forEach((J)=>{let G=J[Q]?Object.keys(J[Q]).map((W)=>[W,J[Q][W]]):[];if(G.length!==0)Y||=!0,X.push(...G);else if(Q!==p4)X.push(...Object.keys(J[p4]).map((W)=>[W,J[p4][W]]))}),!Y)return null;else return Ni1(X)}};var Oi1=class{name="PreparedRegExpRouter";#Q;#X;constructor(Q,X){this.#Q=Q,this.#X=X}#Y(Q,X){let Y=this.#Q[Q];Y[1].forEach((J)=>J&&J.push(X)),Object.values(Y[2]).forEach((J)=>J[0].push(X))}#J(Q,X,Y,J,G){let W=this.#Q[Q];if(!G)W[2][X][0].push([Y,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Y,G]);else W[2][Z||X][0].push([Y,G])})}add(Q,X,Y){if(!this.#Q[Q]){let G=this.#Q[p4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),ID];this.#Q[Q]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(X==="/*"||X==="*"){let G=[Y,{}];if(Q===p4)for(let W in this.#Q)this.#Y(W,G);else this.#Y(Q,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,W]of J)if(Q===p4)for(let Z in this.#Q)this.#J(Z,X,Y,G,W);else this.#J(Q,X,Y,G,W)}buildAllMatchers(){return this.#Q}match=hE};var Fl=class{name="SmartRouter";#Q=[];#X=[];constructor(Q){this.#Q=Q.routers}add(Q,X,Y){if(!this.#X)throw Error(bE);this.#X.push([Q,X,Y])}match(Q,X){if(!this.#X)throw Error("Fatal error");let Y=this.#Q,J=this.#X,G=Y.length,W=0,Z;for(;W<G;W++){let $=Y[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(Q,X)}catch(K){if(K instanceof fE)continue;throw K}this.match=$.match.bind($),this.#Q=[$],this.#X=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#X||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var kD=Object.create(null),Iv0=class Q{#Q;#X;#Y;#J=0;#W=kD;constructor(X,Y,J){if(this.#X=J||Object.create(null),this.#Q=[],X&&Y){let G=Object.create(null);G[X]={handler:Y,possibleKeys:[],score:0},this.#Q=[G]}this.#Y=[]}insert(X,Y,J){this.#J=++this.#J;let G=this,W=Fv0(Y),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Vv0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#X){if(G=G.#X[q],V)Z.push(V[1]);continue}if(G.#X[q]=new Q,V)G.#Y.push(V),Z.push(V[1]);G=G.#X[q]}return G.#Q.push({[X]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(X,Y,J,G){let W=[];for(let Z=0,$=X.#Q.length;Z<$;Z++){let K=X.#Q[Z],H=K[Y]||K[p4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==kD||G&&G!==kD)for(let V=0,q=H.possibleKeys.length;V<q;V++){let U=H.possibleKeys[V],D=F[H.score];H.params[U]=G?.[U]&&!D?G[U]:J[U]??G?.[U],F[H.score]=!0}}}return W}search(X,Y){let J=[];this.#W=kD;let W=[this],Z=Wl(Y),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let U=0,D=W.length;U<D;U++){let B=W[U],L=B.#X[F];if(L)if(L.#W=B.#W,V){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,B.#W));J.push(...this.#G(L,X,B.#W))}else q.push(L);for(let M=0,C=B.#Y.length;M<C;M++){let E=B.#Y[M],A=B.#W===kD?{}:{...B.#W};if(E==="*"){let b=B.#X["*"];if(b)J.push(...this.#G(b,X,B.#W)),b.#W=A,q.push(b);continue}let[T,j,R]=E;if(!F&&!(R instanceof RegExp))continue;let k=B.#X[T],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(A[j]=b[0],J.push(...this.#G(k,X,B.#W,A)),Object.keys(k.#X).length){k.#W=A;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(A[j]=F,V){if(J.push(...this.#G(k,X,A,B.#W)),k.#X["*"])J.push(...this.#G(k.#X["*"],X,A,B.#W))}else k.#W=A,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var Vl=class{name="TrieRouter";#Q;constructor(){this.#Q=new Iv0}add(Q,X,Y){let J=yE(X);if(J){for(let G=0,W=J.length;G<W;G++)this.#Q.insert(Q,J[G],Y);return}this.#Q.insert(Q,X,Y)}match(Q,X){return this.#Q.search(Q,X)}};var d9=class extends Tv0{constructor(Q={}){super(Q);this.router=Q.router??new Fl({routers:[new gE,new Vl]})}};var Rv0=(Q)=>{let Y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Y.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Y.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Y.credentials)K("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)K("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Y.origin!=="*")K("Vary","Origin");if(Y.maxAge!=null)K("Access-Control-Max-Age",Y.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Y.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Y.origin!=="*")Z.header("Vary","Origin",{append:!0})}};function Li1(){let{process:Q,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function Sv0(){let{navigator:Q}=globalThis,X="cloudflare:workers";return!(Q!==void 0&&Q.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!Li1())}var wi1=(Q)=>{let[X,Y]=[",","."];return Q.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Y)},Mi1=(Q)=>{let X=Date.now()-Q;return wi1([X<1000?X+"ms":Math.round(X/1000)+"s"])},Pi1=async(Q)=>{if(await Sv0())switch(Q/100|0){case 5:return`\x1B[31m${Q}\x1B[0m`;case 4:return`\x1B[33m${Q}\x1B[0m`;case 3:return`\x1B[36m${Q}\x1B[0m`;case 2:return`\x1B[32m${Q}\x1B[0m`}return`${Q}`};async function kv0(Q,X,Y,J,G=0,W){let Z=X==="<--"?`${X} ${Y} ${J}`:`${X} ${Y} ${J} ${await Pi1(G)} ${W}`;Q(Z)}var vv0=(Q=console.log)=>{return async function(Y,J){let{method:G,url:W}=Y.req,Z=W.slice(W.indexOf("/",8));await kv0(Q,"<--",G,Z);let $=Date.now();await J(),await kv0(Q,"-->",G,Z,Y.res.status,Mi1($))}};var ql=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_GATEWAY_CREATE",description:"Create gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_LIST",description:"List gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_GET",description:"View gateway details",category:"Gateways"},{name:"COLLECTION_GATEWAY_UPDATE",description:"Update gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_DELETE",description:"Delete gateways",category:"Gateways",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"}];function vD(){let Q={Organizations:[],Connections:[],Gateways:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[]};for(let X of ql)Q[X.category]?.push(X);return Q}var Ti1=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Ai1="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+Ti1+"]*",Ei1=new RegExp("^"+Ai1+"$");function _v0(Q,X){let Y=[],J=X.exec(Q);while(J){let G=[];G.startIndex=X.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Y.push(G),J=X.exec(Q)}return Y}var zl=function(Q){let X=Ei1.exec(Q);return!(X===null||typeof X>"u")};var ji1={allowBooleanAttributes:!1,unpairedTags:[]};function xv0(Q,X){X=Object.assign({},ji1,X);let Y=[],J=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let W=0;W<Q.length;W++)if(Q[W]==="<"&&Q[W+1]==="?"){if(W+=2,W=bv0(Q,W),W.err)return W}else if(Q[W]==="<"){let Z=W;if(W++,Q[W]==="!"){W=fv0(Q,W);continue}else{let $=!1;if(Q[W]==="/")$=!0,W++;let K="";for(;W<Q.length&&Q[W]!==">"&&Q[W]!==" "&&Q[W]!=="\t"&&Q[W]!==`
261
+ ${Y.message}`;if(J)throw new F_6.VercelOidcTokenError(J);throw Y}return Q}function R80(){let Q=(0,H_6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!Q)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return Q}});var v80=I((au4,t51)=>{var{defineProperty:k80,getOwnPropertyDescriptor:q_6,getOwnPropertyNames:z_6}=Object,U_6=Object.prototype.hasOwnProperty,B_6=(Q,X)=>{for(var Y in X)k80(Q,Y,{get:X[Y],enumerable:!0})},D_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of z_6(X))if(!U_6.call(Q,G)&&G!==Y)k80(Q,G,{get:()=>X[G],enumerable:!(J=q_6(X,G))||J.enumerable})}return Q},N_6=(Q)=>D_6(k80({},"__esModule",{value:!0}),Q),s51={};B_6(s51,{getContext:()=>O_6.getContext,getVercelOidcToken:()=>o51.getVercelOidcToken,getVercelOidcTokenSync:()=>o51.getVercelOidcTokenSync});t51.exports=N_6(s51);var o51=r51(),O_6=L80()});var SE=m6($1(),1),ek0=m6(pk0(),1),Qv0=m6(Ql(),1),Xv0=m6(Im(),1),Xl=new Qv0.PrometheusExporter({preventServerStart:!0}),an1=new ek0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Xv0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:Xl});an1.start();var jD=SE.trace.getTracer("mcp-mesh","1.0.0"),Yv0=SE.metrics.getMeter("mcp-mesh","1.0.0");var Yl=class extends Error{res;status;constructor(Q=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Q}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var Jv0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],rn1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,on1=(Q,X)=>{if(!Q)return{};let Y=new Headers(Q.headers);if(X){let J=Y.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!rn1.test(Z));if(W.length>0)throw new Yl(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Y.delete(Z)})}}return Jv0.forEach((J)=>{Y.delete(J)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:Y,signal:Q.signal}},sn1=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let X=new Headers;for(let[Y,J]of Object.entries(Q.headers))if(J==null)X.delete(Y);else X.set(Y,J);return Q.headers=X,Q},Gv0=async(Q,X)=>{let{raw:Y,customFetch:J,strictConnectionProcessing:G=!1,...W}=X instanceof Request?{raw:X}:X??{},Z=new Request(Q,{...on1(Y,G),...sn1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(Jv0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Wv0=(Q)=>(X)=>{let Y=new URL(X.req.raw.url),J=new URL(Q);return J.pathname=Y.pathname,J.search=Y.search,Gv0(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};import{resolve as CD,dirname as tn1}from"path";var en1="http://localhost:4000",Qi1="./dist/client";function Xi1(Q,X){let Y=CD(X),J=CD(Q);return J===Y||J.startsWith(Y+"/")}function Yi1({requestPath:Q,clientDir:X}){let Y=Q.startsWith("/")?Q.slice(1):Q,J=CD(X,Y);if(!Xi1(J,X))return null;return J}function Zv0(Q,X="../client"){let Y=new URL(Q),J=tn1(Y.pathname);return CD(J,X)}function $v0(Q={}){let{env:X="production",devServerUrl:Y=en1,clientDir:J=Qi1,isServerPath:G=()=>!1}=Q;if(X==="development"){let W=Wv0(Y);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=Yi1({requestPath:K,clientDir:J});if(!H)return null;let F=CD(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var iW1=m6(Ql(),1);var Jl=(Q,X,Y)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(Q[$])F=Q[$][0][0],J.req.routeIndex=$;else F=$===Q.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&X)J.error=V,K=await X(V,J),H=!0;else throw V}else if(J.finalized===!1&&Y)K=await Y(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var Kv0=Symbol();var Hv0=async(Q,X=Object.create(null))=>{let{all:Y=!1,dot:J=!1}=X,W=(Q instanceof kE?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Ji1(Q,{all:Y,dot:J});return{}};async function Ji1(Q,X){let Y=await Q.formData();if(Y)return Gi1(Y,X);return{}}function Gi1(Q,X){let Y=Object.create(null);if(Q.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Y[G]=J;else Wi1(Y,G,J)}),X.dot)Object.entries(Y).forEach(([J,G])=>{if(J.includes("."))Zi1(Y,J,G),delete Y[J]});return Y}var Wi1=(Q,X,Y)=>{if(Q[X]!==void 0)if(Array.isArray(Q[X]))Q[X].push(Y);else Q[X]=[Q[X],Y];else if(!X.endsWith("[]"))Q[X]=Y;else Q[X]=[Y]},Zi1=(Q,X,Y)=>{let J=Q,G=X.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Y;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var Wl=(Q)=>{let X=Q.split("/");if(X[0]==="")X.shift();return X},Fv0=(Q)=>{let{groups:X,path:Y}=$i1(Q),J=Wl(Y);return Ki1(J,X)},$i1=(Q)=>{let X=[];return Q=Q.replace(/\{[^}]+\}/g,(Y,J)=>{let G=`@${J}`;return X.push([G,Y]),G}),{groups:X,path:Q}},Ki1=(Q,X)=>{for(let Y=X.length-1;Y>=0;Y--){let[J]=X[Y];for(let G=Q.length-1;G>=0;G--)if(Q[G].includes(J)){Q[G]=Q[G].replace(J,X[Y][1]);break}}return Q},vE={},Vv0=(Q,X)=>{if(Q==="*")return"*";let Y=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let J=`${Q}#${X}`;if(!vE[J])if(Y[2])vE[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Y[1],new RegExp(`^${Y[2]}(?=/${X})`)]:[Q,Y[1],new RegExp(`^${Y[2]}$`)];else vE[J]=[Q,Y[1],!0];return vE[J]}return null},_E=(Q,X)=>{try{return X(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return X(Y)}catch{return Y}})}},Hi1=(Q)=>_E(Q,decodeURI),Zl=(Q)=>{let X=Q.url,Y=X.indexOf("/",X.indexOf(":")+4),J=Y;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let W=X.indexOf("?",J),Z=X.slice(Y,W===-1?void 0:W);return Hi1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return X.slice(Y,J)};var qv0=(Q)=>{let X=Zl(Q);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},aK=(Q,X,...Y)=>{if(Y.length)X=aK(X,...Y);return`${Q?.[0]==="/"?"":"/"}${Q}${X==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},yE=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let X=Q.split("/"),Y=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Y.length===0&&J==="")Y.push("/");else Y.push(J);let W=G.replace("?","");J+="/"+W,Y.push(J)}else J+="/"+G}),Y.filter((G,W,Z)=>Z.indexOf(G)===W)},Gl=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?_E(Q,$l):Q},zv0=(Q,X,Y)=>{let J;if(!Y&&X&&!/[%+]/.test(X)){let Z=Q.indexOf("?",8);if(Z===-1)return;if(!Q.startsWith(X,Z+1))Z=Q.indexOf(`&${X}`,Z+1);while(Z!==-1){let $=Q.charCodeAt(Z+X.length+1);if($===61){let K=Z+X.length+2,H=Q.indexOf("&",K);return Gl(Q.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=Q.indexOf(`&${X}`,Z+1)}if(J=/[%+]/.test(Q),!J)return}let G={};J??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let Z=Q.indexOf("&",W+1),$=Q.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=Q.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=Gl(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=Q.slice($+1,Z===-1?void 0:Z),J)H=Gl(H);if(Y){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return X?G[X]:G},Uv0=zv0,Bv0=(Q,X)=>{return zv0(Q,X,!0)},$l=decodeURIComponent;var Dv0=(Q)=>_E(Q,$l),kE=class{raw;#Q;#X;routeIndex=0;path;bodyCache={};constructor(Q,X="/",Y=[[]]){this.raw=Q,this.path=X,this.#X=Y,this.#Q={}}param(Q){return Q?this.#Y(Q):this.#J()}#Y(Q){let X=this.#X[0][this.routeIndex][1][Q],Y=this.#W(X);return Y&&/\%/.test(Y)?Dv0(Y):Y}#J(){let Q={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Y of X){let J=this.#W(this.#X[0][this.routeIndex][1][Y]);if(J!==void 0)Q[Y]=/\%/.test(J)?Dv0(J):J}return Q}#W(Q){return this.#X[1]?this.#X[1][Q]:Q}query(Q){return Uv0(this.url,Q)}queries(Q){return Bv0(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let X={};return this.raw.headers.forEach((Y,J)=>{X[J]=Y}),X}async parseBody(Q){return this.bodyCache.parsedBody??=await Hv0(this,Q)}#G=(Q)=>{let{bodyCache:X,raw:Y}=this,J=X[Q];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return X[Q]=Y[Q]()};json(){return this.#G("text").then((Q)=>JSON.parse(Q))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Q,X){this.#Q[Q]=X}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[Kv0](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Q]])=>Q)}get routePath(){return this.#X[0].map(([[,Q]])=>Q)[this.routeIndex].path}};var Nv0={Stringify:1,BeforeStream:2,Stream:3},Fi1=(Q,X)=>{let Y=new String(Q);return Y.isEscaped=!0,Y.callbacks=X,Y};var Kl=async(Q,X,Y,J,G)=>{if(typeof Q==="object"&&!(Q instanceof String)){if(!(Q instanceof Promise))Q=Q.toString();if(Q instanceof Promise)Q=await Q}let W=Q.callbacks;if(!W?.length)return Promise.resolve(Q);if(G)G[0]+=Q;else G=[Q];let Z=Promise.all(W.map(($)=>$({phase:X,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>Kl(K,X,!1,J,G))).then(()=>G[0]));if(Y)return Fi1(await Z,W);else return Z};var Vi1="text/plain; charset=UTF-8",Hl=(Q,X)=>{return{"Content-Type":Q,...X}},Ov0=class{#Q;#X;env={};#Y;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(Q,X){if(this.#Q=Q,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#q=X.path,this.#V=X.matchResult}get req(){return this.#X??=new kE(this.#Q,this.#q,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[X,Y]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let G of J)Q.headers.append("set-cookie",G)}else Q.headers.set(X,Y)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Q)};setLayout=(Q)=>this.#$=Q;getLayout=()=>this.#$;setRenderer=(Q)=>{this.#Z=Q};header=(Q,X,Y)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(X===void 0)J.delete(Q);else if(Y?.append)J.append(Q,X);else J.set(Q,X)};status=(Q)=>{this.#J=Q};set=(Q,X)=>{this.#Y??=new Map,this.#Y.set(Q,X)};get=(Q)=>{return this.#Y?this.#Y.get(Q):void 0};get var(){if(!this.#Y)return{};return Object.fromEntries(this.#Y)}#F(Q,X,Y){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof X==="object"&&"headers"in X){let W=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Y)for(let[W,Z]of Object.entries(Y))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Q,{status:G,headers:J})}newResponse=(...Q)=>this.#F(...Q);body=(Q,X,Y)=>this.#F(Q,X,Y);text=(Q,X,Y)=>{return!this.#K&&!this.#J&&!X&&!Y&&!this.finalized?new Response(Q):this.#F(Q,X,Hl(Vi1,Y))};json=(Q,X,Y)=>{return this.#F(JSON.stringify(Q),X,Hl("application/json",Y))};html=(Q,X,Y)=>{let J=(G)=>this.#F(G,X,Hl("text/html; charset=UTF-8",Y));return typeof Q==="object"?Kl(Q,Nv0.Stringify,!1,{}).then(J):J(Q)};redirect=(Q,X)=>{let Y=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(Y)?Y:encodeURI(Y)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var p4="ALL",Lv0="all",wv0=["get","post","put","delete","options","patch"],bE="Can not add a route since the matcher is already built.",fE=class extends Error{};var Mv0="__COMPOSED_HANDLER";var qi1=(Q)=>{return Q.text("404 Not Found",404)},Pv0=(Q,X)=>{if("getResponse"in Q){let Y=Q.getResponse();return X.newResponse(Y.body,Y)}return console.error(Q),X.text("Internal Server Error",500)},Tv0=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(X={}){[...wv0,Lv0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#Q=Z;else this.#J(W,this.#Q,Z);return $.forEach((K)=>{this.#J(W,this.#Q,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#Q=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#Q,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(p4,this.#Q,$)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??Zl:qv0}#X(){let X=new Q({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Y=this.#Y,X.routes=this.routes,X}#Y=qi1;errorHandler=Pv0;route(X,Y){let J=this.basePath(X);return Y.routes.map((G)=>{let W;if(Y.errorHandler===Pv0)W=G.handler;else W=async(Z,$)=>(await Jl([],Y.errorHandler)(Z,()=>G.handler(Z,$))).res,W[Mv0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(X){let Y=this.#X();return Y._basePath=aK(this._basePath,X),Y}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Y=X,this};mount(X,Y,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=aK(this._basePath,X),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Y(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(p4,aK(X,"*"),$),this}#J(X,Y,J){X=X.toUpperCase(),Y=aK(this._basePath,Y);let G={basePath:this._basePath,path:Y,method:X,handler:J};this.router.add(X,Y,[J,G]),this.routes.push(G)}#W(X,Y){if(X instanceof Error)return this.errorHandler(X,Y);throw X}#G(X,Y,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Y,J,"GET")))();let W=this.getPath(X,{env:J}),Z=this.router.match(G,W),$=new Ov0(X,{path:W,matchResult:Z,env:J,executionCtx:Y,notFoundHandler:this.#Y});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Y($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Y($))).catch((F)=>this.#W(F,$)):H??this.#Y($)}let K=Jl(Z[0],this.errorHandler,this.#Y);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(X,...Y)=>{return this.#G(X,Y[1],Y[0],X.method)};request=(X,Y,J,G)=>{if(X instanceof Request)return this.fetch(Y?new Request(X,Y):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${aK("/",X)}`,Y),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var ID=[];function hE(Q,X){let Y=this.buildAllMatchers(),J=(G,W)=>{let Z=Y[G]||Y[p4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],ID];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(Q,X)}var xE="[^/]+",RD=".*",SD="(?:|/.*)",rK=Symbol(),zi1=new Set(".\\+*[^]$()");function Ui1(Q,X){if(Q.length===1)return X.length===1?Q<X?-1:1:-1;if(X.length===1)return 1;if(Q===RD||Q===SD)return 1;else if(X===RD||X===SD)return-1;if(Q===xE)return 1;else if(X===xE)return-1;return Q.length===X.length?Q<X?-1:1:X.length-Q.length}var Av0=class Q{#Q;#X;#Y=Object.create(null);insert(X,Y,J,G,W){if(X.length===0){if(this.#Q!==void 0)throw rK;if(W)return;this.#Q=Y;return}let[Z,...$]=X,K=Z==="*"?$.length===0?["","",RD]:["","",xE]:Z==="/*"?["","",SD]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||xE;if(F&&K[2]){if(V===".*")throw rK;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw rK}if(H=this.#Y[V],!H){if(Object.keys(this.#Y).some((q)=>q!==RD&&q!==SD))throw rK;if(W)return;if(H=this.#Y[V]=new Q,F!=="")H.#X=G.varIndex++}if(!W&&F!=="")J.push([F,H.#X])}else if(H=this.#Y[Z],!H){if(Object.keys(this.#Y).some((F)=>F.length>1&&F!==RD&&F!==SD))throw rK;if(W)return;H=this.#Y[Z]=new Q}H.insert($,Y,J,G,W)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(Ui1).map((J)=>{let G=this.#Y[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:zi1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Q==="number")Y.unshift(`#${this.#Q}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var Ev0=class{#Q={varIndex:0};#X=new Av0;insert(Q,X,Y){let J=[],G=[];for(let Z=0;;){let $=!1;if(Q=Q.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#X.insert(W,X,J,this.#Q,Y),J}buildRegExp(){let Q=this.#X.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let X=0,Y=[],J=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Y[++X]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++X,"";return""}),[new RegExp(`^${Q}`),Y,J]}};var Bi1=[/^$/,[],Object.create(null)],jv0=Object.create(null);function Cv0(Q){return jv0[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function Di1(){jv0=Object.create(null)}function Ni1(Q){let X=new Ev0,Y=[];if(Q.length===0)return Bi1;let J=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,U,D]=J[H];if(q)G[U]=[D.map(([L])=>[L,Object.create(null)]),ID];else F++;let B;try{B=X.insert(U,F,q)}catch(L){throw L===rK?new fE(U):L}if(q)continue;Y[F]=D.map(([L,M])=>{let C=Object.create(null);M-=1;for(;M>=0;M--){let[E,A]=B[M];C[E]=A}return[L,C]})}let[W,Z,$]=X.buildRegExp();for(let H=0,F=Y.length;H<F;H++)for(let V=0,q=Y[H].length;V<q;V++){let U=Y[H][V]?.[1];if(!U)continue;let D=Object.keys(U);for(let B=0,L=D.length;B<L;B++)U[D[B]]=$[U[D[B]]]}let K=[];for(let H in Z)K[H]=Y[Z[H]];return[W,K,G]}function UV(Q,X){if(!Q)return;for(let Y of Object.keys(Q).sort((J,G)=>G.length-J.length))if(Cv0(Y).test(X))return[...Q[Y]];return}var gE=class{name="RegExpRouter";#Q;#X;constructor(){this.#Q={[p4]:Object.create(null)},this.#X={[p4]:Object.create(null)}}add(Q,X,Y){let J=this.#Q,G=this.#X;if(!J||!G)throw Error(bE);if(!J[Q])[J,G].forEach(($)=>{$[Q]=Object.create(null),Object.keys($[p4]).forEach((K)=>{$[Q][K]=[...$[p4][K]]})});if(X==="/*")X="*";let W=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let $=Cv0(X);if(Q===p4)Object.keys(J).forEach((K)=>{J[K][X]||=UV(J[K],X)||UV(J[p4],X)||[]});else J[Q][X]||=UV(J[Q],X)||UV(J[p4],X)||[];Object.keys(J).forEach((K)=>{if(Q===p4||Q===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Y,W])})}),Object.keys(G).forEach((K)=>{if(Q===p4||Q===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Y,W]))});return}let Z=yE(X)||[X];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(Q===p4||Q===F)G[F][H]||=[...UV(J[F],H)||UV(J[p4],H)||[]],G[F][H].push([Y,W-K+$+1])})}}match=hE;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Q)).forEach((X)=>{Q[X]||=this.#Y(X)}),this.#Q=this.#X=void 0,Di1(),Q}#Y(Q){let X=[],Y=Q===p4;if([this.#Q,this.#X].forEach((J)=>{let G=J[Q]?Object.keys(J[Q]).map((W)=>[W,J[Q][W]]):[];if(G.length!==0)Y||=!0,X.push(...G);else if(Q!==p4)X.push(...Object.keys(J[p4]).map((W)=>[W,J[p4][W]]))}),!Y)return null;else return Ni1(X)}};var Oi1=class{name="PreparedRegExpRouter";#Q;#X;constructor(Q,X){this.#Q=Q,this.#X=X}#Y(Q,X){let Y=this.#Q[Q];Y[1].forEach((J)=>J&&J.push(X)),Object.values(Y[2]).forEach((J)=>J[0].push(X))}#J(Q,X,Y,J,G){let W=this.#Q[Q];if(!G)W[2][X][0].push([Y,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Y,G]);else W[2][Z||X][0].push([Y,G])})}add(Q,X,Y){if(!this.#Q[Q]){let G=this.#Q[p4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),ID];this.#Q[Q]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(X==="/*"||X==="*"){let G=[Y,{}];if(Q===p4)for(let W in this.#Q)this.#Y(W,G);else this.#Y(Q,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,W]of J)if(Q===p4)for(let Z in this.#Q)this.#J(Z,X,Y,G,W);else this.#J(Q,X,Y,G,W)}buildAllMatchers(){return this.#Q}match=hE};var Fl=class{name="SmartRouter";#Q=[];#X=[];constructor(Q){this.#Q=Q.routers}add(Q,X,Y){if(!this.#X)throw Error(bE);this.#X.push([Q,X,Y])}match(Q,X){if(!this.#X)throw Error("Fatal error");let Y=this.#Q,J=this.#X,G=Y.length,W=0,Z;for(;W<G;W++){let $=Y[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(Q,X)}catch(K){if(K instanceof fE)continue;throw K}this.match=$.match.bind($),this.#Q=[$],this.#X=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#X||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var kD=Object.create(null),Iv0=class Q{#Q;#X;#Y;#J=0;#W=kD;constructor(X,Y,J){if(this.#X=J||Object.create(null),this.#Q=[],X&&Y){let G=Object.create(null);G[X]={handler:Y,possibleKeys:[],score:0},this.#Q=[G]}this.#Y=[]}insert(X,Y,J){this.#J=++this.#J;let G=this,W=Fv0(Y),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Vv0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#X){if(G=G.#X[q],V)Z.push(V[1]);continue}if(G.#X[q]=new Q,V)G.#Y.push(V),Z.push(V[1]);G=G.#X[q]}return G.#Q.push({[X]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(X,Y,J,G){let W=[];for(let Z=0,$=X.#Q.length;Z<$;Z++){let K=X.#Q[Z],H=K[Y]||K[p4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==kD||G&&G!==kD)for(let V=0,q=H.possibleKeys.length;V<q;V++){let U=H.possibleKeys[V],D=F[H.score];H.params[U]=G?.[U]&&!D?G[U]:J[U]??G?.[U],F[H.score]=!0}}}return W}search(X,Y){let J=[];this.#W=kD;let W=[this],Z=Wl(Y),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let U=0,D=W.length;U<D;U++){let B=W[U],L=B.#X[F];if(L)if(L.#W=B.#W,V){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,B.#W));J.push(...this.#G(L,X,B.#W))}else q.push(L);for(let M=0,C=B.#Y.length;M<C;M++){let E=B.#Y[M],A=B.#W===kD?{}:{...B.#W};if(E==="*"){let b=B.#X["*"];if(b)J.push(...this.#G(b,X,B.#W)),b.#W=A,q.push(b);continue}let[T,j,R]=E;if(!F&&!(R instanceof RegExp))continue;let k=B.#X[T],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(A[j]=b[0],J.push(...this.#G(k,X,B.#W,A)),Object.keys(k.#X).length){k.#W=A;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(A[j]=F,V){if(J.push(...this.#G(k,X,A,B.#W)),k.#X["*"])J.push(...this.#G(k.#X["*"],X,A,B.#W))}else k.#W=A,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var Vl=class{name="TrieRouter";#Q;constructor(){this.#Q=new Iv0}add(Q,X,Y){let J=yE(X);if(J){for(let G=0,W=J.length;G<W;G++)this.#Q.insert(Q,J[G],Y);return}this.#Q.insert(Q,X,Y)}match(Q,X){return this.#Q.search(Q,X)}};var d9=class extends Tv0{constructor(Q={}){super(Q);this.router=Q.router??new Fl({routers:[new gE,new Vl]})}};function Li1(){let{process:Q,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function Rv0(){let{navigator:Q}=globalThis,X="cloudflare:workers";return!(Q!==void 0&&Q.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!Li1())}var wi1=(Q)=>{let[X,Y]=[",","."];return Q.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Y)},Mi1=(Q)=>{let X=Date.now()-Q;return wi1([X<1000?X+"ms":Math.round(X/1000)+"s"])},Pi1=async(Q)=>{if(await Rv0())switch(Q/100|0){case 5:return`\x1B[31m${Q}\x1B[0m`;case 4:return`\x1B[33m${Q}\x1B[0m`;case 3:return`\x1B[36m${Q}\x1B[0m`;case 2:return`\x1B[32m${Q}\x1B[0m`}return`${Q}`};async function Sv0(Q,X,Y,J,G=0,W){let Z=X==="<--"?`${X} ${Y} ${J}`:`${X} ${Y} ${J} ${await Pi1(G)} ${W}`;Q(Z)}var kv0=(Q=console.log)=>{return async function(Y,J){let{method:G,url:W}=Y.req,Z=W.slice(W.indexOf("/",8));await Sv0(Q,"<--",G,Z);let $=Date.now();await J(),await Sv0(Q,"-->",G,Z,Y.res.status,Mi1($))}};var vv0=(Q)=>{let Y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Y.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Y.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Y.credentials)K("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)K("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Y.origin!=="*")K("Vary","Origin");if(Y.maxAge!=null)K("Access-Control-Max-Age",Y.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Y.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Y.origin!=="*")Z.header("Vary","Origin",{append:!0})}};var ql=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_GATEWAY_CREATE",description:"Create gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_LIST",description:"List gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_GET",description:"View gateway details",category:"Gateways"},{name:"COLLECTION_GATEWAY_UPDATE",description:"Update gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_DELETE",description:"Delete gateways",category:"Gateways",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"}];function vD(){let Q={Organizations:[],Connections:[],Gateways:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[]};for(let X of ql)Q[X.category]?.push(X);return Q}var Ti1=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Ai1="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+Ti1+"]*",Ei1=new RegExp("^"+Ai1+"$");function _v0(Q,X){let Y=[],J=X.exec(Q);while(J){let G=[];G.startIndex=X.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Y.push(G),J=X.exec(Q)}return Y}var zl=function(Q){let X=Ei1.exec(Q);return!(X===null||typeof X>"u")};var ji1={allowBooleanAttributes:!1,unpairedTags:[]};function xv0(Q,X){X=Object.assign({},ji1,X);let Y=[],J=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let W=0;W<Q.length;W++)if(Q[W]==="<"&&Q[W+1]==="?"){if(W+=2,W=bv0(Q,W),W.err)return W}else if(Q[W]==="<"){let Z=W;if(W++,Q[W]==="!"){W=fv0(Q,W);continue}else{let $=!1;if(Q[W]==="/")$=!0,W++;let K="";for(;W<Q.length&&Q[W]!==">"&&Q[W]!==" "&&Q[W]!=="\t"&&Q[W]!==`
262
262
  `&&Q[W]!=="\r";W++)K+=Q[W];if(K=K.trim(),K[K.length-1]==="/")K=K.substring(0,K.length-1),W--;if(!yi1(K)){let V;if(K.trim().length===0)V="Invalid space after '<'.";else V="Tag '"+K+"' is an invalid name.";return u8("InvalidTag",V,p9(Q,W))}let H=Ri1(Q,W);if(H===!1)return u8("InvalidAttr","Attributes for '"+K+"' have open quote.",p9(Q,W));let F=H.value;if(W=H.index,F[F.length-1]==="/"){let V=W-F.length;F=F.substring(0,F.length-1);let q=hv0(F,X);if(q===!0)J=!0;else return u8(q.err.code,q.err.msg,p9(Q,V+q.err.line))}else if($)if(!H.tagClosed)return u8("InvalidTag","Closing tag '"+K+"' doesn't have proper closing.",p9(Q,W));else if(F.trim().length>0)return u8("InvalidTag","Closing tag '"+K+"' can't have attributes or invalid starting.",p9(Q,Z));else if(Y.length===0)return u8("InvalidTag","Closing tag '"+K+"' has not been opened.",p9(Q,Z));else{let V=Y.pop();if(K!==V.tagName){let q=p9(Q,V.tagStartPos);return u8("InvalidTag","Expected closing tag '"+V.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+K+"'.",p9(Q,Z))}if(Y.length==0)G=!0}else{let V=hv0(F,X);if(V!==!0)return u8(V.err.code,V.err.msg,p9(Q,W-F.length+V.err.line));if(G===!0)return u8("InvalidXml","Multiple possible root nodes found.",p9(Q,W));else if(X.unpairedTags.indexOf(K)!==-1);else Y.push({tagName:K,tagStartPos:Z});J=!0}for(W++;W<Q.length;W++)if(Q[W]==="<")if(Q[W+1]==="!"){W++,W=fv0(Q,W);continue}else if(Q[W+1]==="?"){if(W=bv0(Q,++W),W.err)return W}else break;else if(Q[W]==="&"){let V=vi1(Q,W);if(V==-1)return u8("InvalidChar","char '&' is not expected.",p9(Q,W));W=V}else if(G===!0&&!yv0(Q[W]))return u8("InvalidXml","Extra text at the end",p9(Q,W));if(Q[W]==="<")W--}}else{if(yv0(Q[W]))continue;return u8("InvalidChar","char '"+Q[W]+"' is not expected.",p9(Q,W))}if(!J)return u8("InvalidXml","Start tag expected.",1);else if(Y.length==1)return u8("InvalidTag","Unclosed tag '"+Y[0].tagName+"'.",p9(Q,Y[0].tagStartPos));else if(Y.length>0)return u8("InvalidXml","Invalid '"+JSON.stringify(Y.map((W)=>W.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function yv0(Q){return Q===" "||Q==="\t"||Q===`
263
263
  `||Q==="\r"}function bv0(Q,X){let Y=X;for(;X<Q.length;X++)if(Q[X]=="?"||Q[X]==" "){let J=Q.substr(Y,X-Y);if(X>5&&J==="xml")return u8("InvalidXml","XML declaration allowed only at the start of the document.",p9(Q,X));else if(Q[X]=="?"&&Q[X+1]==">"){X++;break}else continue}return X}function fv0(Q,X){if(Q.length>X+5&&Q[X+1]==="-"&&Q[X+2]==="-"){for(X+=3;X<Q.length;X++)if(Q[X]==="-"&&Q[X+1]==="-"&&Q[X+2]===">"){X+=2;break}}else if(Q.length>X+8&&Q[X+1]==="D"&&Q[X+2]==="O"&&Q[X+3]==="C"&&Q[X+4]==="T"&&Q[X+5]==="Y"&&Q[X+6]==="P"&&Q[X+7]==="E"){let Y=1;for(X+=8;X<Q.length;X++)if(Q[X]==="<")Y++;else if(Q[X]===">"){if(Y--,Y===0)break}}else if(Q.length>X+9&&Q[X+1]==="["&&Q[X+2]==="C"&&Q[X+3]==="D"&&Q[X+4]==="A"&&Q[X+5]==="T"&&Q[X+6]==="A"&&Q[X+7]==="["){for(X+=8;X<Q.length;X++)if(Q[X]==="]"&&Q[X+1]==="]"&&Q[X+2]===">"){X+=2;break}}return X}var Ci1='"',Ii1="'";function Ri1(Q,X){let Y="",J="",G=!1;for(;X<Q.length;X++){if(Q[X]===Ci1||Q[X]===Ii1)if(J==="")J=Q[X];else if(J!==Q[X]);else J="";else if(Q[X]===">"){if(J===""){G=!0;break}}Y+=Q[X]}if(J!=="")return!1;return{value:Y,index:X,tagClosed:G}}var Si1=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function hv0(Q,X){let Y=_v0(Q,Si1),J={};for(let G=0;G<Y.length;G++){if(Y[G][1].length===0)return u8("InvalidAttr","Attribute '"+Y[G][2]+"' has no space in starting.",_D(Y[G]));else if(Y[G][3]!==void 0&&Y[G][4]===void 0)return u8("InvalidAttr","Attribute '"+Y[G][2]+"' is without value.",_D(Y[G]));else if(Y[G][3]===void 0&&!X.allowBooleanAttributes)return u8("InvalidAttr","boolean attribute '"+Y[G][2]+"' is not allowed.",_D(Y[G]));let W=Y[G][2];if(!_i1(W))return u8("InvalidAttr","Attribute '"+W+"' is an invalid name.",_D(Y[G]));if(!J.hasOwnProperty(W))J[W]=1;else return u8("InvalidAttr","Attribute '"+W+"' is repeated.",_D(Y[G]))}return!0}function ki1(Q,X){let Y=/\d/;if(Q[X]==="x")X++,Y=/[\da-fA-F]/;for(;X<Q.length;X++){if(Q[X]===";")return X;if(!Q[X].match(Y))break}return-1}function vi1(Q,X){if(X++,Q[X]===";")return-1;if(Q[X]==="#")return X++,ki1(Q,X);let Y=0;for(;X<Q.length;X++,Y++){if(Q[X].match(/\w/)&&Y<20)continue;if(Q[X]===";")break;return-1}return X}function u8(Q,X,Y){return{err:{code:Q,msg:X,line:Y.line||Y,col:Y.col}}}function _i1(Q){return zl(Q)}function yi1(Q){return zl(Q)}function p9(Q,X){let Y=Q.substring(0,X).split(/\r?\n/);return{line:Y.length,col:Y[Y.length-1].length+1}}function _D(Q){return Q.startIndex+Q[1].length}var gv0={validate:xv0};var R9=m6(gm0(),1);hZ();H5();hZ();H5();KX();fQ();var T8=(Q,X="ms")=>{return new Date(Date.now()+(X==="sec"?Q*1000:Q))},lS=new WeakMap;function Bn0(Q,X){let Y=X.fields,J={};for(let G in Q){let W=Y[G];if(!W){J[G]=Q[G];continue}if(W.returned===!1)continue;J[G]=Q[G]}return J}function dS(Q,X){if(!lS.has(Q))lS.set(Q,new Map);let Y=lS.get(Q);if(Y.has(X))return Y.get(X);let J={...X==="user"?Q.user?.additionalFields:{},...X==="session"?Q.session?.additionalFields:{}};for(let G of Q.plugins||[])if(G.schema&&G.schema[X])J={...J,...G.schema[X].fields};return lS.get(Q).set(X,J),J}function W9(Q,X){return{...Bn0(X,{fields:dS(Q,"user")}),id:X.id}}function X7(Q,X){return Bn0(X,{fields:dS(Q,"session")})}function Dn0(Q,X){let Y=X.action||"create",J=X.fields,G=Object.assign(Object.create(null),null);for(let W in J){if(W in Q){if(J[W].input===!1){if(J[W].defaultValue!==void 0){if(Y!=="update"){G[W]=J[W].defaultValue;continue}}if(Q[W])throw new n("BAD_REQUEST",{message:`${W} is not allowed to be set`});continue}if(J[W].validator?.input&&Q[W]!==void 0){G[W]=J[W].validator.input["~standard"].validate(Q[W]);continue}if(J[W].transform?.input&&Q[W]!==void 0){G[W]=J[W].transform?.input(Q[W]);continue}G[W]=Q[W];continue}if(J[W].defaultValue!==void 0&&Y==="create"){if(typeof J[W].defaultValue==="function"){G[W]=J[W].defaultValue();continue}G[W]=J[W].defaultValue;continue}if(J[W].required&&Y==="create")throw new n("BAD_REQUEST",{message:`${W} is required`})}return G}function oo(Q,X={},Y){return Dn0(X,{fields:dS(Q,"user"),action:Y})}function Nn0(Q,X){return Dn0(X,{fields:dS(Q,"session")})}function cX(Q,X){if(!X)return Q;for(let Y in X){let J=X[Y]?.modelName;if(J)Q[Y].modelName=J;for(let G in Q[Y].fields){let W=X[Y]?.fields?.[G];if(!W)continue;Q[Y].fields[G].fieldName=W}}return Q}nX();W1();var u76="127.0.0.1";function q$(Q,X){if(X.advanced?.ipAddress?.disableIpTracking)return null;if(J7()||qz())return u76;let Y="headers"in Q?Q.headers:Q,J=X.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let W="get"in Y?Y.get(G):Y[G];if(typeof W==="string"){let Z=W.split(",")[0].trim();if(m76(Z))return Z}}return null}function m76(Q){if(J3().safeParse(Q).success)return!0;if(G3().safeParse(Q).success)return!0;return!1}HX();CG();nX();d8();import{sql as _G}from"kysely";async function i76(Q,X){let Y;if(!Q.database){let J=UJ(Q),G=Object.keys(J).reduce((Z,$)=>{return Z[$]=[],Z},{}),{memoryAdapter:W}=await Promise.resolve().then(() => (Mn0(),wn0));Y=W(G)(Q)}else if(typeof Q.database==="function")Y=Q.database(Q);else Y=await X(Q);if(!Y.transaction)m1.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Y.transaction=async(J)=>{return J(Y)};return Y}async function Pn0(Q){return i76(Q,async(X)=>{let{createKyselyAdapter:Y}=await Promise.resolve().then(() => (Xs(),Qs)),{kysely:J,databaseType:G,transaction:W}=await Y(X);if(!J)throw new k1("Failed to initialize database adapter");let{kyselyAdapter:Z}=await Promise.resolve().then(() => (Xs(),Qs));return Z(J,{type:G||"sqlite",debugLogs:X.database&&"debugLogs"in X.database?X.database.debugLogs:!1,transaction:W})(X)})}function a76(Q,X){let Y=X.hooks;async function J(K,H,F){let V=await wY(),q=K;for(let B of Y||[]){let L=B[H]?.create?.before;if(L){let M=await L(q,V);if(M===!1)return null;if(typeof M==="object"&&"data"in M)q={...q,...M.data}}}let U=F?await F.fn(q):null,D=!F||F.executeMainFn?await(await D4(Q)).create({model:H,data:q,forceAllowId:!0}):U;for(let B of Y||[]){let L=B[H]?.create?.after;if(L)await L(D,V)}return D}async function G(K,H,F,V){let q=await wY(),U=K;for(let L of Y||[]){let M=L[F]?.update?.before;if(M){let C=await M(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)U={...U,...C.data}}}let D=V?await V.fn(U):null,B=!V||V.executeMainFn?await(await D4(Q)).update({model:F,update:U,where:H}):D;for(let L of Y||[]){let M=L[F]?.update?.after;if(M)await M(B,q)}return B}async function W(K,H,F,V){let q=await wY(),U=K;for(let L of Y||[]){let M=L[F]?.update?.before;if(M){let C=await M(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)U={...U,...C.data}}}let D=V?await V.fn(U):null,B=!V||V.executeMainFn?await(await D4(Q)).updateMany({model:F,update:U,where:H}):D;for(let L of Y||[]){let M=L[F]?.update?.after;if(M)await M(B,q)}return B}async function Z(K,H,F){let V=await wY(),q=null;try{q=(await(await D4(Q)).findMany({model:H,where:K,limit:1}))[0]||null}catch(B){}if(q)for(let B of Y||[]){let L=B[H]?.delete?.before;if(L){if(await L(q,V)===!1)return null}}let U=F?await F.fn(K):null,D=!F||F.executeMainFn?await(await D4(Q)).delete({model:H,where:K}):U;if(q)for(let B of Y||[]){let L=B[H]?.delete?.after;if(L)await L(q,V)}return D}async function $(K,H,F){let V=await wY(),q=[];try{q=await(await D4(Q)).findMany({model:H,where:K})}catch(B){}for(let B of q)for(let L of Y||[]){let M=L[H]?.delete?.before;if(M){if(await M(B,V)===!1)return null}}let U=F?await F.fn(K):null,D=!F||F.executeMainFn?await(await D4(Q)).deleteMany({model:H,where:K}):U;for(let B of q)for(let L of Y||[]){let M=L[H]?.delete?.after;if(M)await M(B,V)}return D}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:W,deleteWithHooks:Z,deleteManyWithHooks:$}}var Ys=(Q,X)=>{let{logger:Y,options:J}=X,G=J.secondaryStorage,W=J.session?.expiresIn||604800,{createWithHooks:Z,updateWithHooks:$,updateManyWithHooks:K,deleteWithHooks:H,deleteManyWithHooks:F}=a76(Q,X);async function V(q){if(!G)return;let U=await G.get(`active-sessions-${q.id}`);if(!U)return;let D=Date.now(),B=(A4(U)||[]).filter((L)=>L.expiresAt>D);await Promise.all(B.map(async({token:L})=>{let M=await G.get(L);if(!M)return;let C=A4(M);if(!C)return;let E=Math.max(Math.floor(new Date(C.session.expiresAt).getTime()-D)/1000,0);await G.set(L,JSON.stringify({session:C.session,user:q}),Math.floor(E))}))}return{createOAuthUser:async(q,U)=>{return HO(Q,async()=>{let D=await Z({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:D,account:await Z({...U,userId:D.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let U=await G.get(`active-sessions-${q}`);if(!U)return[];let D=A4(U)||[],B=Date.now(),L=D.filter((C)=>C.expiresAt>B),M=[];for(let C of L){let E=await G.get(C.token);if(E){let A=A4(E);if(!A)return[];let T=X7(X.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});M.push(T)}}return M}return await(await D4(Q)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,U,D,B)=>{return await(await D4(Q)).findMany({model:"user",limit:q,offset:U,sortBy:D,where:B})},countTotalUsers:async(q)=>{let U=await(await D4(Q)).count({model:"user",where:q});if(typeof U==="string")return parseInt(U);return U},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,U,D,B)=>{let L=await wY().catch(()=>null),M=L?.headers||L?.request?.headers,{id:C,...E}=D||{},A=Nn0(L?.context.options??J,{}),T={ipAddress:L?.request||L?.headers?q$(L?.request||L?.headers,L?.context.options)||"":"",userAgent:M?.get("user-agent")||"",...E,expiresAt:U?T8(86400,"sec"):T8(W,"sec"),userId:q,token:XQ(32),createdAt:new Date,updatedAt:new Date,...A,...B?E:{}};return await Z(T,"session",G?{fn:async(j)=>{let R=await G.get(`active-sessions-${q}`),k=[],y=Date.now();if(R)k=A4(R)||[],k=k.filter((m)=>m.expiresAt>y);let b=k.sort((m,Q0)=>m.expiresAt-Q0.expiresAt),h=b.at(-1)?.expiresAt;if(b.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!h||h<T.expiresAt.getTime())h=T.expiresAt.getTime();let a=Math.max(Math.floor((h-y)/1000),0);if(a>0)await G.set(`active-sessions-${q}`,JSON.stringify(b),a);let f=await Q.findOne({model:"user",where:[{field:"id",value:q}]}),S=Math.max(Math.floor((T.expiresAt.getTime()-y)/1000),0);if(S>0)await G.set(T.token,JSON.stringify({session:j,user:f}),S);return j},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let L=await G.get(q);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let M=A4(L);if(!M)return null;return{session:X7(X.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:W9(X.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let U=await(await D4(Q)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!U)return null;let{user:D,...B}=U;if(!D)return null;return{session:X7(X.options,B),user:W9(X.options,D)}},findSessions:async(q)=>{if(G){let D=[];for(let B of q){let L=await G.get(B);if(L){let M=A4(L);if(!M)return[];let C={session:{...M.session,expiresAt:new Date(M.session.expiresAt)},user:{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)}};D.push(C)}}return D}let U=await(await D4(Q)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!U.length)return[];if(U.some((D)=>!D.user))return[];return U.map((D)=>{let{user:B,...L}=D;return{session:L,user:B}})},updateSession:async(q,U)=>{return await $(U,[{field:"token",value:q}],"session",G?{async fn(D){let B=await G.get(q),L=null;if(B){let M=A4(B);if(!M)return null;return L={...M.session,...D},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let U=await G.get(q);if(U){let{session:D}=A4(U)??{};if(!D){Y.error("Session not found in secondary storage");return}let B=D.userId,L=await G.get(`active-sessions-${B}`);if(L){let M=A4(L)||[],C=Date.now(),E=M.filter((T)=>T.expiresAt>C&&T.token!==q),A=E.sort((T,j)=>T.expiresAt-j.expiresAt).at(-1)?.expiresAt;if(E.length>0&&A&&A>Date.now())await G.set(`active-sessions-${B}`,JSON.stringify(E),Math.floor((A-C)/1000));else await G.delete(`active-sessions-${B}`)}else Y.error("Active sessions list not found in secondary storage")}if(await G.delete(q),!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await(await D4(Q)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let U=await G.get(`active-sessions-${q}`),D=U?A4(U):[];if(!D)return;for(let B of D)await G.delete(B.token)}else for(let U of q)if(await G.get(U))await G.delete(U);if(!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,U,D)=>{let B=await(await D4(Q)).findMany({model:"account",where:[{value:U,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((M)=>M.providerId===D)});if(B)if(B.user)return{user:B.user,accounts:[B]};else{let L=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[B]};return null}else{let L=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await D4(Q)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,U)=>{let D=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...U?.includeAccounts?{account:!0}:{}}});if(!D)return null;let{account:B,...L}=D;return{user:L,accounts:B??[]}},findUserById:async(q)=>{if(!q)return null;return await(await D4(Q)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,U)=>{let D=await $(U,[{field:"id",value:q}],"user",void 0);return await V(D),await V(D),D},updateUserByEmail:async(q,U)=>{let D=await $(U,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(D),await V(D),D},updatePassword:async(q,U)=>{await K({password:U},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await D4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await D4(Q)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,U)=>{return await(await D4(Q)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:U}]})},findAccountByUserId:async(q)=>{return await(await D4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,U)=>{return await $(U,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let U=await(await D4(Q)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await D4(Q)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return U[0]},deleteVerificationValue:async(q)=>{await(await D4(Q)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await D4(Q)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,U)=>{return await $(U,[{field:"id",value:q}],"verification",void 0)}}};function r76(Q){let X=UJ(Q),Y={};for(let J in X){let G=X[J],W=G.fields,Z={};if(Object.entries(W).forEach(([$,K])=>{if(Z[K.fieldName||$]=K,K.references){let H=X[K.references.model];if(H)Z[K.fieldName||$].references={...K.references,model:H.modelName,field:K.references.field}}}),Y[G.modelName]){Y[G.modelName].fields={...Y[G.modelName].fields,...Z};continue}Y[G.modelName]={fields:Z,order:G.order||1/0}}return Y}var o76={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function s76(Q,X,Y){function J(W){return W.toLowerCase().split("(")[0].trim()}if(X==="string[]"||X==="number[]")return Q.toLowerCase().includes("json");let G=o76[Y];return(Array.isArray(X)?G.string.map((W)=>W.toLowerCase()):G[X].map((W)=>W.toLowerCase())).includes(J(Q))}async function t76(Q){try{let X=await _G`SHOW search_path`.execute(Q);if(X.rows[0]?.search_path)return X.rows[0].search_path.split(",").map((Y)=>Y.trim()).map((Y)=>Y.replace(/^["']|["']$/g,"")).filter((Y)=>!Y.startsWith("$"))[0]||"public"}catch(X){}return"public"}async function Tn0(Q){let X=r76(Q),Y=Uz(Q.logger),{kysely:J,databaseType:G}=await p2(Q);if(!G)Y.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Y.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let W="public";if(G==="postgres"){W=await t76(J),Y.debug(`PostgreSQL migration: Using schema '${W}' (from search_path)`);try{if(!(await _G`
264
264
  SELECT schema_name
@@ -1062,7 +1062,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
1062
1062
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
1063
1063
 
1064
1064
  Option 2 - OIDC token:
1065
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:Z,statusCode:G,cause:W})}},AG1="GatewayInvalidRequestError",M_6=`vercel.ai.gateway.error.${AG1}`,GG1=Symbol.for(M_6),WG1,ZG1,P_6=class extends(ZG1=yY,WG1=GG1,ZG1){constructor({message:Q="Invalid request",statusCode:X=400,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[WG1]=!0,this.name=AG1,this.type="invalid_request_error"}static isInstance(Q){return yY.hasMarker(Q)&&GG1 in Q}},EG1="GatewayRateLimitError",T_6=`vercel.ai.gateway.error.${EG1}`,$G1=Symbol.for(T_6),KG1,HG1,A_6=class extends(HG1=yY,KG1=$G1,HG1){constructor({message:Q="Rate limit exceeded",statusCode:X=429,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[KG1]=!0,this.name=EG1,this.type="rate_limit_exceeded"}static isInstance(Q){return yY.hasMarker(Q)&&$G1 in Q}},jG1="GatewayModelNotFoundError",E_6=`vercel.ai.gateway.error.${jG1}`,FG1=Symbol.for(E_6),j_6=OX(()=>z9(N.object({modelId:N.string()}))),VG1,qG1,C_6=class extends(qG1=yY,VG1=FG1,qG1){constructor({message:Q="Model not found",statusCode:X=404,modelId:Y,cause:J}={}){super({message:Q,statusCode:X,cause:J});this[VG1]=!0,this.name=jG1,this.type="model_not_found",this.modelId=Y}static isInstance(Q){return yY.hasMarker(Q)&&FG1 in Q}},CG1="GatewayInternalServerError",I_6=`vercel.ai.gateway.error.${CG1}`,zG1=Symbol.for(I_6),UG1,BG1,DG1=class extends(BG1=yY,UG1=zG1,BG1){constructor({message:Q="Internal server error",statusCode:X=500,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[UG1]=!0,this.name=CG1,this.type="internal_server_error"}static isInstance(Q){return yY.hasMarker(Q)&&zG1 in Q}},IG1="GatewayResponseError",R_6=`vercel.ai.gateway.error.${IG1}`,NG1=Symbol.for(R_6),OG1,LG1,S_6=class extends(LG1=yY,OG1=NG1,LG1){constructor({message:Q="Invalid response from Gateway",statusCode:X=502,response:Y,validationError:J,cause:G}={}){super({message:Q,statusCode:X,cause:G});this[OG1]=!0,this.name=IG1,this.type="response_error",this.response=Y,this.validationError=J}static isInstance(Q){return yY.hasMarker(Q)&&NG1 in Q}};async function wG1({response:Q,statusCode:X,defaultMessage:Y="Gateway request failed",cause:J,authMethod:G}){let W=await LX({value:Q,schema:k_6});if(!W.success)return new S_6({message:`Invalid error response format: ${Y}`,statusCode:X,response:Q,validationError:W.error,cause:J});let Z=W.value,$=Z.error.type,K=Z.error.message;switch($){case"authentication_error":return fy.createContextualError({apiKeyProvided:G==="api-key",oidcTokenProvided:G==="oidc",statusCode:X,cause:J});case"invalid_request_error":return new P_6({message:K,statusCode:X,cause:J});case"rate_limit_exceeded":return new A_6({message:K,statusCode:X,cause:J});case"model_not_found":{let H=await LX({value:Z.error.param,schema:j_6});return new C_6({message:K,statusCode:X,modelId:H.success?H.value.modelId:void 0,cause:J})}case"internal_server_error":return new DG1({message:K,statusCode:X,cause:J});default:return new DG1({message:K,statusCode:X,cause:J})}}var k_6=OX(()=>z9(N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.unknown().nullish(),code:N.union([N.string(),N.number()]).nullish()})})));function o$(Q,X){var Y;if(yY.isInstance(Q))return Q;if(r8.isInstance(Q))return wG1({response:v_6(Q),statusCode:(Y=Q.statusCode)!=null?Y:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:X});return wG1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:X})}function v_6(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(X){return Q.responseBody}return{}}var RG1="ai-gateway-auth-method";async function _U(Q){let X=await LX({value:Q[RG1],schema:__6});return X.success?X.value:void 0}var __6=OX(()=>z9(N.union([N.literal("api-key"),N.literal("oidc")]))),MG1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await D80({url:`${this.config.baseURL}/config`,headers:await U9(this.config.headers()),successfulResponseHandler:f7(y_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return Q}catch(Q){throw await o$(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:X}=await D80({url:`${Q.origin}/v1/credits`,headers:await U9(this.config.headers()),successfulResponseHandler:f7(b_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(Y)=>Y}),fetch:this.config.fetch});return X}catch(Q){throw await o$(Q)}}},y_6=OX(()=>z9(N.object({models:N.array(N.object({id:N.string(),name:N.string(),description:N.string().nullish(),pricing:N.object({input:N.string(),output:N.string(),input_cache_read:N.string().nullish(),input_cache_write:N.string().nullish()}).transform(({input:Q,output:X,input_cache_read:Y,input_cache_write:J})=>({input:Q,output:X,...Y?{cachedInputTokens:Y}:{},...J?{cacheCreationInputTokens:J}:{}})).nullish(),specification:N.object({specificationVersion:N.literal("v3"),provider:N.string(),modelId:N.string()}),modelType:N.enum(["language","embedding","image"]).nullish()}))}))),b_6=OX(()=>z9(N.object({balance:N.string(),total_used:N.string()}).transform(({balance:Q,total_used:X})=>({balance:Q,totalUsed:X})))),f_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:X,...Y}=Q;return{args:this.maybeEncodeFileParts(Y),warnings:[]}}async doGenerate(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await U9(this.config.headers());try{let{responseHeaders:W,value:Z,rawValue:$}=await YF({url:this.getUrl(),headers:e3(G,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await U9(this.config.o11yHeaders)),body:X,successfulResponseHandler:f7(N.any()),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(K)=>K}),...J&&{abortSignal:J},fetch:this.config.fetch});return{...Z,request:{body:X},response:{headers:W,body:$},warnings:Y}}catch(W){throw await o$(W,await _U(G))}}async doStream(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await U9(this.config.headers());try{let{value:W,responseHeaders:Z}=await YF({url:this.getUrl(),headers:e3(G,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await U9(this.config.o11yHeaders)),body:X,successfulResponseHandler:B51(N.any()),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:($)=>$}),...J&&{abortSignal:J},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start($){if(Y.length>0)$.enqueue({type:"stream-start",warnings:Y})},transform($,K){if($.success){let H=$.value;if(H.type==="raw"&&!Q.includeRawChunks)return;if(H.type==="response-metadata"&&H.timestamp&&typeof H.timestamp==="string")H.timestamp=new Date(H.timestamp);K.enqueue(H)}else K.error($.error)}})),request:{body:X},response:{headers:Z}}}catch(W){throw await o$(W,await _U(G))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let X of Q.prompt)for(let Y of X.content)if(this.isFilePart(Y)){let J=Y;if(J.data instanceof Uint8Array){let G=Uint8Array.from(J.data),W=Buffer.from(G).toString("base64");J.data=new URL(`data:${J.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,X){return{"ai-language-model-specification-version":"3","ai-language-model-id":Q,"ai-language-model-streaming":String(X)}}},h_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:X,abortSignal:Y,providerOptions:J}){var G;let W=await U9(this.config.headers());try{let{responseHeaders:Z,value:$,rawValue:K}=await YF({url:this.getUrl(),headers:e3(W,X!=null?X:{},this.getModelConfigHeaders(),await U9(this.config.o11yHeaders)),body:{values:Q,...J?{providerOptions:J}:{}},successfulResponseHandler:f7(x_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(H)=>H}),...Y&&{abortSignal:Y},fetch:this.config.fetch});return{embeddings:$.embeddings,usage:(G=$.usage)!=null?G:void 0,providerMetadata:$.providerMetadata,response:{headers:Z,body:K},warnings:[]}}catch(Z){throw await o$(Z,await _U(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},x_6=OX(()=>z9(N.object({embeddings:N.array(N.array(N.number())),usage:N.object({tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.unknown())).optional()}))),g_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:X,size:Y,aspectRatio:J,seed:G,files:W,mask:Z,providerOptions:$,headers:K,abortSignal:H}){var F;let V=await U9(this.config.headers());try{let{responseHeaders:q,value:U,rawValue:D}=await YF({url:this.getUrl(),headers:e3(V,K!=null?K:{},this.getModelConfigHeaders(),await U9(this.config.o11yHeaders)),body:{prompt:Q,n:X,...Y&&{size:Y},...J&&{aspectRatio:J},...G&&{seed:G},...$&&{providerOptions:$},...W&&{files:W.map((B)=>PG1(B))},...Z&&{mask:PG1(Z)}},successfulResponseHandler:f7(m_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(B)=>B}),...H&&{abortSignal:H},fetch:this.config.fetch});return{images:U.images,warnings:(F=U.warnings)!=null?F:[],providerMetadata:U.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw o$(q,await _U(V))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function PG1(Q){if(Q.type==="file"&&Q.data instanceof Uint8Array)return{...Q,data:XF(Q.data)};return Q}var u_6=N.object({images:N.array(N.unknown()).optional()}).catchall(N.unknown()),m_6=N.object({images:N.array(N.string()),warnings:N.array(N.object({type:N.literal("other"),message:N.string()})).optional(),providerMetadata:N.record(N.string(),u_6).optional()});async function l_6(){var Q;return(Q=SG1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var d_6="3.0.9",p_6="0.0.1";function c_6(Q={}){var X,Y;let J=null,G=null,W=(X=Q.metadataCacheRefreshMillis)!=null?X:300000,Z=0,$=(Y=D51(Q.baseURL))!=null?Y:"https://ai-gateway.vercel.sh/v3/ai",K=async()=>{try{let B=await n_6(Q);return a$({Authorization:`Bearer ${B.token}`,"ai-gateway-protocol-version":p_6,[RG1]:B.authMethod,...Q.headers},`ai-sdk/gateway/${d_6}`)}catch(B){throw fy.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:B})}},H=()=>{let B=qP({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),L=qP({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),M=qP({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let C=await l_6();return{...B&&{"ai-o11y-deployment-id":B},...L&&{"ai-o11y-environment":L},...M&&{"ai-o11y-region":M},...C&&{"ai-o11y-request-id":C}}}},F=(B)=>{return new f_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},V=async()=>{var B,L,M;let C=(M=(L=(B=Q._internal)==null?void 0:B.currentDate)==null?void 0:L.call(B).getTime())!=null?M:Date.now();if(!J||C-Z>W)Z=C,J=new MG1({baseURL:$,headers:K,fetch:Q.fetch}).getAvailableModels().then((E)=>{return G=E,E}).catch(async(E)=>{throw await o$(E,await _U(await K()))});return G?Promise.resolve(G):J},q=async()=>{return new MG1({baseURL:$,headers:K,fetch:Q.fetch}).getCredits().catch(async(B)=>{throw await o$(B,await _U(await K()))})},U=function(B){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return F(B)};U.specificationVersion="v3",U.getAvailableModels=V,U.getCredits=q,U.imageModel=(B)=>{return new g_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},U.languageModel=F;let D=(B)=>{return new h_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})};return U.embeddingModel=D,U.textEmbeddingModel=D,U}var vG1=c_6();async function n_6(Q){let X=qP({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(X)return{token:X,authMethod:"api-key"};return{token:await kG1.getVercelOidcToken(),authMethod:"oidc"}}r6();r6();r6();r6();r6();r6();var kW1=m6($1(),1),m80=m6($1(),1);r6();r6();var i_6=Object.defineProperty,a_6=(Q,X)=>{for(var Y in X)i_6(Q,Y,{get:X[Y],enumerable:!0})},mG1="AI_InvalidArgumentError",lG1=`vercel.ai.error.${mG1}`,r_6=Symbol.for(lG1),dG1,GW=class extends P1{constructor({parameter:Q,value:X,message:Y}){super({name:mG1,message:`Invalid argument for parameter ${Q}: ${Y}`});this[dG1]=!0,this.parameter=Q,this.value=X}static isInstance(Q){return P1.hasMarker(Q,lG1)}};dG1=r_6;var o_6="AI_InvalidStreamPartError",s_6=`vercel.ai.error.${o_6}`,t_6=Symbol.for(s_6),e_6;e_6=t_6;var pG1="AI_InvalidToolApprovalError",cG1=`vercel.ai.error.${pG1}`,Qy6=Symbol.for(cG1),nG1,Xy6=class extends P1{constructor({approvalId:Q}){super({name:pG1,message:`Tool approval response references unknown approvalId: "${Q}". No matching tool-approval-request found in message history.`});this[nG1]=!0,this.approvalId=Q}static isInstance(Q){return P1.hasMarker(Q,cG1)}};nG1=Qy6;var iG1="AI_InvalidToolInputError",aG1=`vercel.ai.error.${iG1}`,Yy6=Symbol.for(aG1),rG1,n80=class extends P1{constructor({toolInput:Q,toolName:X,cause:Y,message:J=`Invalid input for tool ${X}: ${R5(Y)}`}){super({name:iG1,message:J,cause:Y});this[rG1]=!0,this.toolInput=Q,this.toolName=X}static isInstance(Q){return P1.hasMarker(Q,aG1)}};rG1=Yy6;var oG1="AI_ToolCallNotFoundForApprovalError",sG1=`vercel.ai.error.${oG1}`,Jy6=Symbol.for(sG1),tG1,eG1=class extends P1{constructor({toolCallId:Q,approvalId:X}){super({name:oG1,message:`Tool call "${Q}" not found for approval request "${X}".`});this[tG1]=!0,this.toolCallId=Q,this.approvalId=X}static isInstance(Q){return P1.hasMarker(Q,sG1)}};tG1=Jy6;var Gy6="AI_NoImageGeneratedError",Wy6=`vercel.ai.error.${Gy6}`,Zy6=Symbol.for(Wy6),$y6;$y6=Zy6;var QW1="AI_NoObjectGeneratedError",XW1=`vercel.ai.error.${QW1}`,Ky6=Symbol.for(XW1),YW1,s$=class extends P1{constructor({message:Q="No object generated.",cause:X,text:Y,response:J,usage:G,finishReason:W}){super({name:QW1,message:Q,cause:X});this[YW1]=!0,this.text=Y,this.response=J,this.usage=G,this.finishReason=W}static isInstance(Q){return P1.hasMarker(Q,XW1)}};YW1=Ky6;var JW1="AI_NoOutputGeneratedError",GW1=`vercel.ai.error.${JW1}`,Hy6=Symbol.for(GW1),WW1,Fy6=class extends P1{constructor({message:Q="No output generated.",cause:X}={}){super({name:JW1,message:Q,cause:X});this[WW1]=!0}static isInstance(Q){return P1.hasMarker(Q,GW1)}};WW1=Hy6;var ZW1="AI_NoSuchToolError",$W1=`vercel.ai.error.${ZW1}`,Vy6=Symbol.for($W1),KW1,g80=class extends P1{constructor({toolName:Q,availableTools:X=void 0,message:Y=`Model tried to call unavailable tool '${Q}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:ZW1,message:Y});this[KW1]=!0,this.toolName=Q,this.availableTools=X}static isInstance(Q){return P1.hasMarker(Q,$W1)}};KW1=Vy6;var HW1="AI_ToolCallRepairError",FW1=`vercel.ai.error.${HW1}`,qy6=Symbol.for(FW1),VW1,zy6=class extends P1{constructor({cause:Q,originalError:X,message:Y=`Error repairing tool call: ${R5(Q)}`}){super({name:HW1,message:Y,cause:Q});this[VW1]=!0,this.originalError=X}static isInstance(Q){return P1.hasMarker(Q,FW1)}};VW1=qy6;var Uy6=class extends P1{constructor(Q){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${Q.version} for provider "${Q.provider}" and model "${Q.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=Q.version,this.provider=Q.provider,this.modelId=Q.modelId}},By6="AI_InvalidDataContentError",Dy6=`vercel.ai.error.${By6}`,Ny6=Symbol.for(Dy6),Oy6;Oy6=Ny6;var qW1="AI_InvalidMessageRoleError",zW1=`vercel.ai.error.${qW1}`,Ly6=Symbol.for(zW1),UW1,wy6=class extends P1{constructor({role:Q,message:X=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:qW1,message:X});this[UW1]=!0,this.role=Q}static isInstance(Q){return P1.hasMarker(Q,zW1)}};UW1=Ly6;var BW1="AI_MessageConversionError",DW1=`vercel.ai.error.${BW1}`,My6=Symbol.for(DW1),NW1,Py6=class extends P1{constructor({originalMessage:Q,message:X}){super({name:BW1,message:X});this[NW1]=!0,this.originalMessage=Q}static isInstance(Q){return P1.hasMarker(Q,DW1)}};NW1=My6;var OW1="AI_RetryError",LW1=`vercel.ai.error.${OW1}`,Ty6=Symbol.for(LW1),wW1,_G1=class extends P1{constructor({message:Q,reason:X,errors:Y}){super({name:OW1,message:Q});this[wW1]=!0,this.reason=X,this.errors=Y,this.lastError=Y[Y.length-1]}static isInstance(Q){return P1.hasMarker(Q,LW1)}};wW1=Ty6;function Ay6({warning:Q,provider:X,model:Y}){let J=`AI SDK Warning (${X} / ${Y}):`;switch(Q.type){case"unsupported":{let G=`${J} The feature "${Q.feature}" is not supported.`;if(Q.details)G+=` ${Q.details}`;return G}case"compatibility":{let G=`${J} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)G+=` ${Q.details}`;return G}case"other":return`${J} ${Q.message}`;default:return`${J} ${JSON.stringify(Q,null,2)}`}}var Ey6="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",yG1=!1,MW1=(Q)=>{if(Q.warnings.length===0)return;let X=globalThis.AI_SDK_LOG_WARNINGS;if(X===!1)return;if(typeof X==="function"){X(Q);return}if(!yG1)yG1=!0,console.info(Ey6);for(let Y of Q.warnings)console.warn(Ay6({warning:Y,provider:Q.provider,model:Q.model}))};function jy6({provider:Q,modelId:X}){MW1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:X})}function Cy6(Q){if(Q.specificationVersion==="v3")return Q;return jy6({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(X,Y){switch(Y){case"specificationVersion":return"v3";case"doGenerate":return async(...J)=>{let G=await X.doGenerate(...J);return{...G,finishReason:PW1(G.finishReason),usage:TW1(G.usage)}};case"doStream":return async(...J)=>{let G=await X.doStream(...J);return{...G,stream:Iy6(G.stream)}};default:return X[Y]}}})}function Iy6(Q){return Q.pipeThrough(new TransformStream({transform(X,Y){switch(X.type){case"finish":Y.enqueue({...X,finishReason:PW1(X.finishReason),usage:TW1(X.usage)});break;default:Y.enqueue(X);break}}}))}function PW1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function TW1(Q){return{inputTokens:{total:Q.inputTokens,noCache:void 0,cacheRead:Q.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:Q.outputTokens,text:void 0,reasoning:Q.reasoningTokens}}}function AW1(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let X=Q;throw new Uy6({version:X.specificationVersion,provider:X.provider,modelId:X.modelId})}return Cy6(Q)}return Ry6().languageModel(Q)}function Ry6(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:vG1}function EW1(Q){if(Q==null)return;if(typeof Q==="number")return Q;return Q.totalMs}var Sy6=[{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]}];var ky6=(Q)=>{let X=typeof Q==="string"?SU(Q):Q,Y=(X[6]&127)<<21|(X[7]&127)<<14|(X[8]&127)<<7|X[9]&127;return X.slice(Y+10)};function vy6(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?ky6(Q):Q}function _y6({data:Q,signatures:X}){let Y=vy6(Q),J=typeof Y==="string"?SU(Y.substring(0,Math.min(Y.length,24))):Y;for(let G of X)if(J.length>=G.bytesPrefix.length&&G.bytesPrefix.every((W,Z)=>W===null||J[Z]===W))return G.mediaType;return}var yy6="6.0.16",by6=async({url:Q})=>{var X;let Y=Q.toString();try{let J=await fetch(Y,{headers:a$({},`ai-sdk/${yy6}`,Sy())});if(!J.ok)throw new Ry({url:Y,statusCode:J.status,statusText:J.statusText});return{data:new Uint8Array(await J.arrayBuffer()),mediaType:(X=J.headers.get("content-type"))!=null?X:void 0}}catch(J){if(Ry.isInstance(J))throw J;throw new Ry({url:Y,cause:J})}},fy6=(Q=by6)=>(X)=>Promise.all(X.map(async(Y)=>Y.isUrlSupportedByModel?null:Q(Y)));function hy6(Q){try{let[X,Y]=Q.split(",");return{mediaType:X.split(";")[0].split(":")[1],base64Content:Y}}catch(X){return{mediaType:void 0,base64Content:void 0}}}var jW1=N.union([N.string(),N.instanceof(Uint8Array),N.instanceof(ArrayBuffer),N.custom((Q)=>{var X,Y;return(Y=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Q))!=null?Y:!1},{message:"Must be a Buffer"})]);function CW1(Q){if(Q instanceof Uint8Array)return{data:Q,mediaType:void 0};if(Q instanceof ArrayBuffer)return{data:new Uint8Array(Q),mediaType:void 0};if(typeof Q==="string")try{Q=new URL(Q)}catch(X){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:X,base64Content:Y}=hy6(Q.toString());if(X==null||Y==null)throw new P1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:Y,mediaType:X}}return{data:Q,mediaType:void 0}}function xy6(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return XF(new Uint8Array(Q));return XF(Q)}function gy(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function gy6({prompt:Q,supportedUrls:X,download:Y=fy6()}){let J=await my6(Q.messages,Y,X),G=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:gy(Q.system).map((Z)=>({role:"system",content:Z.content,providerOptions:Z.providerOptions})):[],...Q.messages.map((Z)=>uy6({message:Z,downloadedAssets:J}))],W=[];for(let Z of G){if(Z.role!=="tool"){W.push(Z);continue}let $=W.at(-1);if(($==null?void 0:$.role)==="tool")$.content.push(...Z.content);else W.push(Z)}return W}function uy6({message:Q,downloadedAssets:X}){let Y=Q.role;switch(Y){case"system":return{role:"system",content:Q.content,providerOptions:Q.providerOptions};case"user":{if(typeof Q.content==="string")return{role:"user",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"user",content:Q.content.map((J)=>ly6(J,X)).filter((J)=>J.type!=="text"||J.text!==""),providerOptions:Q.providerOptions}}case"assistant":{if(typeof Q.content==="string")return{role:"assistant",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"assistant",content:Q.content.filter((J)=>J.type!=="text"||J.text!==""||J.providerOptions!=null).filter((J)=>J.type!=="tool-approval-request").map((J)=>{let G=J.providerOptions;switch(J.type){case"file":{let{data:W,mediaType:Z}=CW1(J.data);return{type:"file",data:W,filename:J.filename,mediaType:Z!=null?Z:J.mediaType,providerOptions:G}}case"reasoning":return{type:"reasoning",text:J.text,providerOptions:G};case"text":return{type:"text",text:J.text,providerOptions:G};case"tool-call":return{type:"tool-call",toolCallId:J.toolCallId,toolName:J.toolName,input:J.input,providerExecuted:J.providerExecuted,providerOptions:G};case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:bG1(J.output),providerOptions:G}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((J)=>J.type!=="tool-approval-response"||J.providerExecuted).map((J)=>{switch(J.type){case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:bG1(J.output),providerOptions:J.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:J.approvalId,approved:J.approved,reason:J.reason}}}),providerOptions:Q.providerOptions};default:throw new wy6({role:Y})}}async function my6(Q,X,Y){let J=Q.filter((W)=>W.role==="user").map((W)=>W.content).filter((W)=>Array.isArray(W)).flat().filter((W)=>W.type==="image"||W.type==="file").map((W)=>{var Z;let $=(Z=W.mediaType)!=null?Z:W.type==="image"?"image/*":void 0,K=W.type==="image"?W.image:W.data;if(typeof K==="string")try{K=new URL(K)}catch(H){}return{mediaType:$,data:K}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&$51({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:Y})})),G=await X(J);return Object.fromEntries(G.map((W,Z)=>W==null?null:[J[Z].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function ly6(Q,X){var Y;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let J,G=Q.type;switch(G){case"image":J=Q.image;break;case"file":J=Q.data;break;default:throw Error(`Unsupported part type: ${G}`)}let{data:W,mediaType:Z}=CW1(J),$=Z!=null?Z:Q.mediaType,K=W;if(K instanceof URL){let H=X[K.toString()];if(H)K=H.data,$!=null||($=H.mediaType)}switch(G){case"image":{if(K instanceof Uint8Array||typeof K==="string")$=(Y=_y6({data:K,signatures:Sy6}))!=null?Y:$;return{type:"file",mediaType:$!=null?$:"image/*",filename:void 0,data:K,providerOptions:Q.providerOptions}}case"file":{if($==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:$,filename:Q.filename,data:K,providerOptions:Q.providerOptions}}}}function bG1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((X)=>{if(X.type!=="media")return X;if(X.mediaType.startsWith("image/"))return{type:"image-data",data:X.data,mediaType:X.mediaType};return{type:"file-data",data:X.data,mediaType:X.mediaType}})}}async function bU({toolCallId:Q,input:X,output:Y,tool:J,errorMode:G}){if(G==="text")return{type:"error-text",value:R5(Y)};else if(G==="json")return{type:"error-json",value:fG1(Y)};if(J==null?void 0:J.toModelOutput)return await J.toModelOutput({toolCallId:Q,input:X,output:Y});return typeof Y==="string"?{type:"text",value:Y}:{type:"json",value:fG1(Y)}}function fG1(Q){return Q===void 0?null:Q}function dy6({maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,seed:Z,stopSequences:$}){if(Q!=null){if(!Number.isInteger(Q))throw new GW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new GW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(X!=null){if(typeof X!=="number")throw new GW({parameter:"temperature",value:X,message:"temperature must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new GW({parameter:"topP",value:Y,message:"topP must be a number"})}if(J!=null){if(typeof J!=="number")throw new GW({parameter:"topK",value:J,message:"topK must be a number"})}if(G!=null){if(typeof G!=="number")throw new GW({parameter:"presencePenalty",value:G,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new GW({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if(Z!=null){if(!Number.isInteger(Z))throw new GW({parameter:"seed",value:Z,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,stopSequences:$,seed:Z}}function py6(Q){return Q!=null&&Object.keys(Q).length>0}async function cy6({tools:Q,toolChoice:X,activeTools:Y}){if(!py6(Q))return{tools:void 0,toolChoice:void 0};let J=Y!=null?Object.entries(Q).filter(([W])=>Y.includes(W)):Object.entries(Q),G=[];for(let[W,Z]of J){let $=Z.type;switch($){case void 0:case"dynamic":case"function":G.push({type:"function",name:W,description:Z.description,inputSchema:await YW(Z.inputSchema).jsonSchema,...Z.inputExamples!=null?{inputExamples:Z.inputExamples}:{},providerOptions:Z.providerOptions,...Z.strict!=null?{strict:Z.strict}:{}});break;case"provider":G.push({type:"provider",name:W,id:Z.id,args:Z.args});break;default:throw Error(`Unsupported tool type: ${$}`)}}return{tools:G,toolChoice:X==null?{type:"auto"}:typeof X==="string"?{type:X}:{type:"tool",toolName:X.toolName}}}var LP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),LP.optional()),N.array(LP)])),i1=N.record(N.string(),N.record(N.string(),LP.optional())),IW1=N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),ny6=N.object({type:N.literal("image"),image:N.union([jW1,N.instanceof(URL)]),mediaType:N.string().optional(),providerOptions:i1.optional()}),RW1=N.object({type:N.literal("file"),data:N.union([jW1,N.instanceof(URL)]),filename:N.string().optional(),mediaType:N.string(),providerOptions:i1.optional()}),iy6=N.object({type:N.literal("reasoning"),text:N.string(),providerOptions:i1.optional()}),ay6=N.object({type:N.literal("tool-call"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerOptions:i1.optional(),providerExecuted:N.boolean().optional()}),ry6=N.discriminatedUnion("type",[N.object({type:N.literal("text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("json"),value:LP,providerOptions:i1.optional()}),N.object({type:N.literal("execution-denied"),reason:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("error-text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("error-json"),value:LP,providerOptions:i1.optional()}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("media"),data:N.string(),mediaType:N.string()}),N.object({type:N.literal("file-data"),data:N.string(),mediaType:N.string(),filename:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("file-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("image-data"),data:N.string(),mediaType:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("custom"),providerOptions:i1.optional()})]))})]),SW1=N.object({type:N.literal("tool-result"),toolCallId:N.string(),toolName:N.string(),output:ry6,providerOptions:i1.optional()}),oy6=N.object({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),sy6=N.object({type:N.literal("tool-approval-response"),approvalId:N.string(),approved:N.boolean(),reason:N.string().optional()}),ty6=N.object({role:N.literal("system"),content:N.string(),providerOptions:i1.optional()}),ey6=N.object({role:N.literal("user"),content:N.union([N.string(),N.array(N.union([IW1,ny6,RW1]))]),providerOptions:i1.optional()}),Qb6=N.object({role:N.literal("assistant"),content:N.union([N.string(),N.array(N.union([IW1,RW1,iy6,ay6,SW1,oy6]))]),providerOptions:i1.optional()}),Xb6=N.object({role:N.literal("tool"),content:N.array(N.union([SW1,sy6])),providerOptions:i1.optional()}),Yb6=N.union([ty6,ey6,Qb6,Xb6]);async function Jb6(Q){if(Q.prompt==null&&Q.messages==null)throw new s3({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new s3({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!gy(Q.system).every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&J.role==="system"))throw new s3({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let X;if(Q.prompt!=null&&typeof Q.prompt==="string")X=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))X=Q.prompt;else if(Q.messages!=null)X=Q.messages;else throw new s3({prompt:Q,message:"prompt or messages must be defined"});if(X.length===0)throw new s3({prompt:Q,message:"messages must not be empty"});let Y=await LX({value:X,schema:N.array(Yb6)});if(!Y.success)throw new s3({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:Y.error});return{messages:X,system:Q.system}}function Gb6(Q){if(!fy.isInstance(Q))return Q;let X=(process==null?void 0:"production")==="production",Y="https://ai-sdk.dev/unauthenticated-ai-gateway";if(X)return new P1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${Y}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
1065
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:Z,statusCode:G,cause:W})}},AG1="GatewayInvalidRequestError",M_6=`vercel.ai.gateway.error.${AG1}`,GG1=Symbol.for(M_6),WG1,ZG1,P_6=class extends(ZG1=yY,WG1=GG1,ZG1){constructor({message:Q="Invalid request",statusCode:X=400,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[WG1]=!0,this.name=AG1,this.type="invalid_request_error"}static isInstance(Q){return yY.hasMarker(Q)&&GG1 in Q}},EG1="GatewayRateLimitError",T_6=`vercel.ai.gateway.error.${EG1}`,$G1=Symbol.for(T_6),KG1,HG1,A_6=class extends(HG1=yY,KG1=$G1,HG1){constructor({message:Q="Rate limit exceeded",statusCode:X=429,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[KG1]=!0,this.name=EG1,this.type="rate_limit_exceeded"}static isInstance(Q){return yY.hasMarker(Q)&&$G1 in Q}},jG1="GatewayModelNotFoundError",E_6=`vercel.ai.gateway.error.${jG1}`,FG1=Symbol.for(E_6),j_6=OX(()=>z9(N.object({modelId:N.string()}))),VG1,qG1,C_6=class extends(qG1=yY,VG1=FG1,qG1){constructor({message:Q="Model not found",statusCode:X=404,modelId:Y,cause:J}={}){super({message:Q,statusCode:X,cause:J});this[VG1]=!0,this.name=jG1,this.type="model_not_found",this.modelId=Y}static isInstance(Q){return yY.hasMarker(Q)&&FG1 in Q}},CG1="GatewayInternalServerError",I_6=`vercel.ai.gateway.error.${CG1}`,zG1=Symbol.for(I_6),UG1,BG1,DG1=class extends(BG1=yY,UG1=zG1,BG1){constructor({message:Q="Internal server error",statusCode:X=500,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[UG1]=!0,this.name=CG1,this.type="internal_server_error"}static isInstance(Q){return yY.hasMarker(Q)&&zG1 in Q}},IG1="GatewayResponseError",R_6=`vercel.ai.gateway.error.${IG1}`,NG1=Symbol.for(R_6),OG1,LG1,S_6=class extends(LG1=yY,OG1=NG1,LG1){constructor({message:Q="Invalid response from Gateway",statusCode:X=502,response:Y,validationError:J,cause:G}={}){super({message:Q,statusCode:X,cause:G});this[OG1]=!0,this.name=IG1,this.type="response_error",this.response=Y,this.validationError=J}static isInstance(Q){return yY.hasMarker(Q)&&NG1 in Q}};async function wG1({response:Q,statusCode:X,defaultMessage:Y="Gateway request failed",cause:J,authMethod:G}){let W=await LX({value:Q,schema:k_6});if(!W.success)return new S_6({message:`Invalid error response format: ${Y}`,statusCode:X,response:Q,validationError:W.error,cause:J});let Z=W.value,$=Z.error.type,K=Z.error.message;switch($){case"authentication_error":return fy.createContextualError({apiKeyProvided:G==="api-key",oidcTokenProvided:G==="oidc",statusCode:X,cause:J});case"invalid_request_error":return new P_6({message:K,statusCode:X,cause:J});case"rate_limit_exceeded":return new A_6({message:K,statusCode:X,cause:J});case"model_not_found":{let H=await LX({value:Z.error.param,schema:j_6});return new C_6({message:K,statusCode:X,modelId:H.success?H.value.modelId:void 0,cause:J})}case"internal_server_error":return new DG1({message:K,statusCode:X,cause:J});default:return new DG1({message:K,statusCode:X,cause:J})}}var k_6=OX(()=>z9(N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.unknown().nullish(),code:N.union([N.string(),N.number()]).nullish()})})));function o$(Q,X){var Y;if(yY.isInstance(Q))return Q;if(r8.isInstance(Q))return wG1({response:v_6(Q),statusCode:(Y=Q.statusCode)!=null?Y:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:X});return wG1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:X})}function v_6(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(X){return Q.responseBody}return{}}var RG1="ai-gateway-auth-method";async function _U(Q){let X=await LX({value:Q[RG1],schema:__6});return X.success?X.value:void 0}var __6=OX(()=>z9(N.union([N.literal("api-key"),N.literal("oidc")]))),MG1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await D80({url:`${this.config.baseURL}/config`,headers:await U9(this.config.headers()),successfulResponseHandler:f7(y_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return Q}catch(Q){throw await o$(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:X}=await D80({url:`${Q.origin}/v1/credits`,headers:await U9(this.config.headers()),successfulResponseHandler:f7(b_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(Y)=>Y}),fetch:this.config.fetch});return X}catch(Q){throw await o$(Q)}}},y_6=OX(()=>z9(N.object({models:N.array(N.object({id:N.string(),name:N.string(),description:N.string().nullish(),pricing:N.object({input:N.string(),output:N.string(),input_cache_read:N.string().nullish(),input_cache_write:N.string().nullish()}).transform(({input:Q,output:X,input_cache_read:Y,input_cache_write:J})=>({input:Q,output:X,...Y?{cachedInputTokens:Y}:{},...J?{cacheCreationInputTokens:J}:{}})).nullish(),specification:N.object({specificationVersion:N.literal("v3"),provider:N.string(),modelId:N.string()}),modelType:N.enum(["language","embedding","image"]).nullish()}))}))),b_6=OX(()=>z9(N.object({balance:N.string(),total_used:N.string()}).transform(({balance:Q,total_used:X})=>({balance:Q,totalUsed:X})))),f_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:X,...Y}=Q;return{args:this.maybeEncodeFileParts(Y),warnings:[]}}async doGenerate(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await U9(this.config.headers());try{let{responseHeaders:W,value:Z,rawValue:$}=await YF({url:this.getUrl(),headers:e3(G,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await U9(this.config.o11yHeaders)),body:X,successfulResponseHandler:f7(N.any()),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(K)=>K}),...J&&{abortSignal:J},fetch:this.config.fetch});return{...Z,request:{body:X},response:{headers:W,body:$},warnings:Y}}catch(W){throw await o$(W,await _U(G))}}async doStream(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await U9(this.config.headers());try{let{value:W,responseHeaders:Z}=await YF({url:this.getUrl(),headers:e3(G,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await U9(this.config.o11yHeaders)),body:X,successfulResponseHandler:B51(N.any()),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:($)=>$}),...J&&{abortSignal:J},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start($){if(Y.length>0)$.enqueue({type:"stream-start",warnings:Y})},transform($,K){if($.success){let H=$.value;if(H.type==="raw"&&!Q.includeRawChunks)return;if(H.type==="response-metadata"&&H.timestamp&&typeof H.timestamp==="string")H.timestamp=new Date(H.timestamp);K.enqueue(H)}else K.error($.error)}})),request:{body:X},response:{headers:Z}}}catch(W){throw await o$(W,await _U(G))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let X of Q.prompt)for(let Y of X.content)if(this.isFilePart(Y)){let J=Y;if(J.data instanceof Uint8Array){let G=Uint8Array.from(J.data),W=Buffer.from(G).toString("base64");J.data=new URL(`data:${J.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,X){return{"ai-language-model-specification-version":"3","ai-language-model-id":Q,"ai-language-model-streaming":String(X)}}},h_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:X,abortSignal:Y,providerOptions:J}){var G;let W=await U9(this.config.headers());try{let{responseHeaders:Z,value:$,rawValue:K}=await YF({url:this.getUrl(),headers:e3(W,X!=null?X:{},this.getModelConfigHeaders(),await U9(this.config.o11yHeaders)),body:{values:Q,...J?{providerOptions:J}:{}},successfulResponseHandler:f7(x_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(H)=>H}),...Y&&{abortSignal:Y},fetch:this.config.fetch});return{embeddings:$.embeddings,usage:(G=$.usage)!=null?G:void 0,providerMetadata:$.providerMetadata,response:{headers:Z,body:K},warnings:[]}}catch(Z){throw await o$(Z,await _U(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},x_6=OX(()=>z9(N.object({embeddings:N.array(N.array(N.number())),usage:N.object({tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.unknown())).optional()}))),g_6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:X,size:Y,aspectRatio:J,seed:G,files:W,mask:Z,providerOptions:$,headers:K,abortSignal:H}){var F;let V=await U9(this.config.headers());try{let{responseHeaders:q,value:U,rawValue:D}=await YF({url:this.getUrl(),headers:e3(V,K!=null?K:{},this.getModelConfigHeaders(),await U9(this.config.o11yHeaders)),body:{prompt:Q,n:X,...Y&&{size:Y},...J&&{aspectRatio:J},...G&&{seed:G},...$&&{providerOptions:$},...W&&{files:W.map((B)=>PG1(B))},...Z&&{mask:PG1(Z)}},successfulResponseHandler:f7(m_6),failedResponseHandler:JW({errorSchema:N.any(),errorToMessage:(B)=>B}),...H&&{abortSignal:H},fetch:this.config.fetch});return{images:U.images,warnings:(F=U.warnings)!=null?F:[],providerMetadata:U.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw o$(q,await _U(V))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function PG1(Q){if(Q.type==="file"&&Q.data instanceof Uint8Array)return{...Q,data:XF(Q.data)};return Q}var u_6=N.object({images:N.array(N.unknown()).optional()}).catchall(N.unknown()),m_6=N.object({images:N.array(N.string()),warnings:N.array(N.object({type:N.literal("other"),message:N.string()})).optional(),providerMetadata:N.record(N.string(),u_6).optional()});async function l_6(){var Q;return(Q=SG1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var d_6="3.0.9",p_6="0.0.1";function c_6(Q={}){var X,Y;let J=null,G=null,W=(X=Q.metadataCacheRefreshMillis)!=null?X:300000,Z=0,$=(Y=D51(Q.baseURL))!=null?Y:"https://ai-gateway.vercel.sh/v3/ai",K=async()=>{try{let B=await n_6(Q);return a$({Authorization:`Bearer ${B.token}`,"ai-gateway-protocol-version":p_6,[RG1]:B.authMethod,...Q.headers},`ai-sdk/gateway/${d_6}`)}catch(B){throw fy.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:B})}},H=()=>{let B=qP({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),L=qP({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),M=qP({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let C=await l_6();return{...B&&{"ai-o11y-deployment-id":B},...L&&{"ai-o11y-environment":L},...M&&{"ai-o11y-region":M},...C&&{"ai-o11y-request-id":C}}}},F=(B)=>{return new f_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},V=async()=>{var B,L,M;let C=(M=(L=(B=Q._internal)==null?void 0:B.currentDate)==null?void 0:L.call(B).getTime())!=null?M:Date.now();if(!J||C-Z>W)Z=C,J=new MG1({baseURL:$,headers:K,fetch:Q.fetch}).getAvailableModels().then((E)=>{return G=E,E}).catch(async(E)=>{throw await o$(E,await _U(await K()))});return G?Promise.resolve(G):J},q=async()=>{return new MG1({baseURL:$,headers:K,fetch:Q.fetch}).getCredits().catch(async(B)=>{throw await o$(B,await _U(await K()))})},U=function(B){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return F(B)};U.specificationVersion="v3",U.getAvailableModels=V,U.getCredits=q,U.imageModel=(B)=>{return new g_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},U.languageModel=F;let D=(B)=>{return new h_6(B,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})};return U.embeddingModel=D,U.textEmbeddingModel=D,U}var vG1=c_6();async function n_6(Q){let X=qP({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(X)return{token:X,authMethod:"api-key"};return{token:await kG1.getVercelOidcToken(),authMethod:"oidc"}}r6();r6();r6();r6();r6();r6();var kW1=m6($1(),1),m80=m6($1(),1);r6();r6();var i_6=Object.defineProperty,a_6=(Q,X)=>{for(var Y in X)i_6(Q,Y,{get:X[Y],enumerable:!0})},mG1="AI_InvalidArgumentError",lG1=`vercel.ai.error.${mG1}`,r_6=Symbol.for(lG1),dG1,GW=class extends P1{constructor({parameter:Q,value:X,message:Y}){super({name:mG1,message:`Invalid argument for parameter ${Q}: ${Y}`});this[dG1]=!0,this.parameter=Q,this.value=X}static isInstance(Q){return P1.hasMarker(Q,lG1)}};dG1=r_6;var o_6="AI_InvalidStreamPartError",s_6=`vercel.ai.error.${o_6}`,t_6=Symbol.for(s_6),e_6;e_6=t_6;var pG1="AI_InvalidToolApprovalError",cG1=`vercel.ai.error.${pG1}`,Qy6=Symbol.for(cG1),nG1,Xy6=class extends P1{constructor({approvalId:Q}){super({name:pG1,message:`Tool approval response references unknown approvalId: "${Q}". No matching tool-approval-request found in message history.`});this[nG1]=!0,this.approvalId=Q}static isInstance(Q){return P1.hasMarker(Q,cG1)}};nG1=Qy6;var iG1="AI_InvalidToolInputError",aG1=`vercel.ai.error.${iG1}`,Yy6=Symbol.for(aG1),rG1,n80=class extends P1{constructor({toolInput:Q,toolName:X,cause:Y,message:J=`Invalid input for tool ${X}: ${R5(Y)}`}){super({name:iG1,message:J,cause:Y});this[rG1]=!0,this.toolInput=Q,this.toolName=X}static isInstance(Q){return P1.hasMarker(Q,aG1)}};rG1=Yy6;var oG1="AI_ToolCallNotFoundForApprovalError",sG1=`vercel.ai.error.${oG1}`,Jy6=Symbol.for(sG1),tG1,eG1=class extends P1{constructor({toolCallId:Q,approvalId:X}){super({name:oG1,message:`Tool call "${Q}" not found for approval request "${X}".`});this[tG1]=!0,this.toolCallId=Q,this.approvalId=X}static isInstance(Q){return P1.hasMarker(Q,sG1)}};tG1=Jy6;var Gy6="AI_NoImageGeneratedError",Wy6=`vercel.ai.error.${Gy6}`,Zy6=Symbol.for(Wy6),$y6;$y6=Zy6;var QW1="AI_NoObjectGeneratedError",XW1=`vercel.ai.error.${QW1}`,Ky6=Symbol.for(XW1),YW1,s$=class extends P1{constructor({message:Q="No object generated.",cause:X,text:Y,response:J,usage:G,finishReason:W}){super({name:QW1,message:Q,cause:X});this[YW1]=!0,this.text=Y,this.response=J,this.usage=G,this.finishReason=W}static isInstance(Q){return P1.hasMarker(Q,XW1)}};YW1=Ky6;var JW1="AI_NoOutputGeneratedError",GW1=`vercel.ai.error.${JW1}`,Hy6=Symbol.for(GW1),WW1,Fy6=class extends P1{constructor({message:Q="No output generated.",cause:X}={}){super({name:JW1,message:Q,cause:X});this[WW1]=!0}static isInstance(Q){return P1.hasMarker(Q,GW1)}};WW1=Hy6;var ZW1="AI_NoSuchToolError",$W1=`vercel.ai.error.${ZW1}`,Vy6=Symbol.for($W1),KW1,g80=class extends P1{constructor({toolName:Q,availableTools:X=void 0,message:Y=`Model tried to call unavailable tool '${Q}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:ZW1,message:Y});this[KW1]=!0,this.toolName=Q,this.availableTools=X}static isInstance(Q){return P1.hasMarker(Q,$W1)}};KW1=Vy6;var HW1="AI_ToolCallRepairError",FW1=`vercel.ai.error.${HW1}`,qy6=Symbol.for(FW1),VW1,zy6=class extends P1{constructor({cause:Q,originalError:X,message:Y=`Error repairing tool call: ${R5(Q)}`}){super({name:HW1,message:Y,cause:Q});this[VW1]=!0,this.originalError=X}static isInstance(Q){return P1.hasMarker(Q,FW1)}};VW1=qy6;var Uy6=class extends P1{constructor(Q){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${Q.version} for provider "${Q.provider}" and model "${Q.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=Q.version,this.provider=Q.provider,this.modelId=Q.modelId}},By6="AI_InvalidDataContentError",Dy6=`vercel.ai.error.${By6}`,Ny6=Symbol.for(Dy6),Oy6;Oy6=Ny6;var qW1="AI_InvalidMessageRoleError",zW1=`vercel.ai.error.${qW1}`,Ly6=Symbol.for(zW1),UW1,wy6=class extends P1{constructor({role:Q,message:X=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:qW1,message:X});this[UW1]=!0,this.role=Q}static isInstance(Q){return P1.hasMarker(Q,zW1)}};UW1=Ly6;var BW1="AI_MessageConversionError",DW1=`vercel.ai.error.${BW1}`,My6=Symbol.for(DW1),NW1,Py6=class extends P1{constructor({originalMessage:Q,message:X}){super({name:BW1,message:X});this[NW1]=!0,this.originalMessage=Q}static isInstance(Q){return P1.hasMarker(Q,DW1)}};NW1=My6;var OW1="AI_RetryError",LW1=`vercel.ai.error.${OW1}`,Ty6=Symbol.for(LW1),wW1,_G1=class extends P1{constructor({message:Q,reason:X,errors:Y}){super({name:OW1,message:Q});this[wW1]=!0,this.reason=X,this.errors=Y,this.lastError=Y[Y.length-1]}static isInstance(Q){return P1.hasMarker(Q,LW1)}};wW1=Ty6;function Ay6({warning:Q,provider:X,model:Y}){let J=`AI SDK Warning (${X} / ${Y}):`;switch(Q.type){case"unsupported":{let G=`${J} The feature "${Q.feature}" is not supported.`;if(Q.details)G+=` ${Q.details}`;return G}case"compatibility":{let G=`${J} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)G+=` ${Q.details}`;return G}case"other":return`${J} ${Q.message}`;default:return`${J} ${JSON.stringify(Q,null,2)}`}}var Ey6="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",yG1=!1,MW1=(Q)=>{if(Q.warnings.length===0)return;let X=globalThis.AI_SDK_LOG_WARNINGS;if(X===!1)return;if(typeof X==="function"){X(Q);return}if(!yG1)yG1=!0,console.info(Ey6);for(let Y of Q.warnings)console.warn(Ay6({warning:Y,provider:Q.provider,model:Q.model}))};function jy6({provider:Q,modelId:X}){MW1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:X})}function Cy6(Q){if(Q.specificationVersion==="v3")return Q;return jy6({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(X,Y){switch(Y){case"specificationVersion":return"v3";case"doGenerate":return async(...J)=>{let G=await X.doGenerate(...J);return{...G,finishReason:PW1(G.finishReason),usage:TW1(G.usage)}};case"doStream":return async(...J)=>{let G=await X.doStream(...J);return{...G,stream:Iy6(G.stream)}};default:return X[Y]}}})}function Iy6(Q){return Q.pipeThrough(new TransformStream({transform(X,Y){switch(X.type){case"finish":Y.enqueue({...X,finishReason:PW1(X.finishReason),usage:TW1(X.usage)});break;default:Y.enqueue(X);break}}}))}function PW1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function TW1(Q){return{inputTokens:{total:Q.inputTokens,noCache:void 0,cacheRead:Q.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:Q.outputTokens,text:void 0,reasoning:Q.reasoningTokens}}}function AW1(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let X=Q;throw new Uy6({version:X.specificationVersion,provider:X.provider,modelId:X.modelId})}return Cy6(Q)}return Ry6().languageModel(Q)}function Ry6(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:vG1}function EW1(Q){if(Q==null)return;if(typeof Q==="number")return Q;return Q.totalMs}var Sy6=[{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]}];var ky6=(Q)=>{let X=typeof Q==="string"?SU(Q):Q,Y=(X[6]&127)<<21|(X[7]&127)<<14|(X[8]&127)<<7|X[9]&127;return X.slice(Y+10)};function vy6(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?ky6(Q):Q}function _y6({data:Q,signatures:X}){let Y=vy6(Q),J=typeof Y==="string"?SU(Y.substring(0,Math.min(Y.length,24))):Y;for(let G of X)if(J.length>=G.bytesPrefix.length&&G.bytesPrefix.every((W,Z)=>W===null||J[Z]===W))return G.mediaType;return}var yy6="6.0.17",by6=async({url:Q})=>{var X;let Y=Q.toString();try{let J=await fetch(Y,{headers:a$({},`ai-sdk/${yy6}`,Sy())});if(!J.ok)throw new Ry({url:Y,statusCode:J.status,statusText:J.statusText});return{data:new Uint8Array(await J.arrayBuffer()),mediaType:(X=J.headers.get("content-type"))!=null?X:void 0}}catch(J){if(Ry.isInstance(J))throw J;throw new Ry({url:Y,cause:J})}},fy6=(Q=by6)=>(X)=>Promise.all(X.map(async(Y)=>Y.isUrlSupportedByModel?null:Q(Y)));function hy6(Q){try{let[X,Y]=Q.split(",");return{mediaType:X.split(";")[0].split(":")[1],base64Content:Y}}catch(X){return{mediaType:void 0,base64Content:void 0}}}var jW1=N.union([N.string(),N.instanceof(Uint8Array),N.instanceof(ArrayBuffer),N.custom((Q)=>{var X,Y;return(Y=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Q))!=null?Y:!1},{message:"Must be a Buffer"})]);function CW1(Q){if(Q instanceof Uint8Array)return{data:Q,mediaType:void 0};if(Q instanceof ArrayBuffer)return{data:new Uint8Array(Q),mediaType:void 0};if(typeof Q==="string")try{Q=new URL(Q)}catch(X){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:X,base64Content:Y}=hy6(Q.toString());if(X==null||Y==null)throw new P1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:Y,mediaType:X}}return{data:Q,mediaType:void 0}}function xy6(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return XF(new Uint8Array(Q));return XF(Q)}function gy(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function gy6({prompt:Q,supportedUrls:X,download:Y=fy6()}){let J=await my6(Q.messages,Y,X),G=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:gy(Q.system).map((Z)=>({role:"system",content:Z.content,providerOptions:Z.providerOptions})):[],...Q.messages.map((Z)=>uy6({message:Z,downloadedAssets:J}))],W=[];for(let Z of G){if(Z.role!=="tool"){W.push(Z);continue}let $=W.at(-1);if(($==null?void 0:$.role)==="tool")$.content.push(...Z.content);else W.push(Z)}return W}function uy6({message:Q,downloadedAssets:X}){let Y=Q.role;switch(Y){case"system":return{role:"system",content:Q.content,providerOptions:Q.providerOptions};case"user":{if(typeof Q.content==="string")return{role:"user",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"user",content:Q.content.map((J)=>ly6(J,X)).filter((J)=>J.type!=="text"||J.text!==""),providerOptions:Q.providerOptions}}case"assistant":{if(typeof Q.content==="string")return{role:"assistant",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"assistant",content:Q.content.filter((J)=>J.type!=="text"||J.text!==""||J.providerOptions!=null).filter((J)=>J.type!=="tool-approval-request").map((J)=>{let G=J.providerOptions;switch(J.type){case"file":{let{data:W,mediaType:Z}=CW1(J.data);return{type:"file",data:W,filename:J.filename,mediaType:Z!=null?Z:J.mediaType,providerOptions:G}}case"reasoning":return{type:"reasoning",text:J.text,providerOptions:G};case"text":return{type:"text",text:J.text,providerOptions:G};case"tool-call":return{type:"tool-call",toolCallId:J.toolCallId,toolName:J.toolName,input:J.input,providerExecuted:J.providerExecuted,providerOptions:G};case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:bG1(J.output),providerOptions:G}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((J)=>J.type!=="tool-approval-response"||J.providerExecuted).map((J)=>{switch(J.type){case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:bG1(J.output),providerOptions:J.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:J.approvalId,approved:J.approved,reason:J.reason}}}),providerOptions:Q.providerOptions};default:throw new wy6({role:Y})}}async function my6(Q,X,Y){let J=Q.filter((W)=>W.role==="user").map((W)=>W.content).filter((W)=>Array.isArray(W)).flat().filter((W)=>W.type==="image"||W.type==="file").map((W)=>{var Z;let $=(Z=W.mediaType)!=null?Z:W.type==="image"?"image/*":void 0,K=W.type==="image"?W.image:W.data;if(typeof K==="string")try{K=new URL(K)}catch(H){}return{mediaType:$,data:K}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&$51({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:Y})})),G=await X(J);return Object.fromEntries(G.map((W,Z)=>W==null?null:[J[Z].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function ly6(Q,X){var Y;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let J,G=Q.type;switch(G){case"image":J=Q.image;break;case"file":J=Q.data;break;default:throw Error(`Unsupported part type: ${G}`)}let{data:W,mediaType:Z}=CW1(J),$=Z!=null?Z:Q.mediaType,K=W;if(K instanceof URL){let H=X[K.toString()];if(H)K=H.data,$!=null||($=H.mediaType)}switch(G){case"image":{if(K instanceof Uint8Array||typeof K==="string")$=(Y=_y6({data:K,signatures:Sy6}))!=null?Y:$;return{type:"file",mediaType:$!=null?$:"image/*",filename:void 0,data:K,providerOptions:Q.providerOptions}}case"file":{if($==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:$,filename:Q.filename,data:K,providerOptions:Q.providerOptions}}}}function bG1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((X)=>{if(X.type!=="media")return X;if(X.mediaType.startsWith("image/"))return{type:"image-data",data:X.data,mediaType:X.mediaType};return{type:"file-data",data:X.data,mediaType:X.mediaType}})}}async function bU({toolCallId:Q,input:X,output:Y,tool:J,errorMode:G}){if(G==="text")return{type:"error-text",value:R5(Y)};else if(G==="json")return{type:"error-json",value:fG1(Y)};if(J==null?void 0:J.toModelOutput)return await J.toModelOutput({toolCallId:Q,input:X,output:Y});return typeof Y==="string"?{type:"text",value:Y}:{type:"json",value:fG1(Y)}}function fG1(Q){return Q===void 0?null:Q}function dy6({maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,seed:Z,stopSequences:$}){if(Q!=null){if(!Number.isInteger(Q))throw new GW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new GW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(X!=null){if(typeof X!=="number")throw new GW({parameter:"temperature",value:X,message:"temperature must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new GW({parameter:"topP",value:Y,message:"topP must be a number"})}if(J!=null){if(typeof J!=="number")throw new GW({parameter:"topK",value:J,message:"topK must be a number"})}if(G!=null){if(typeof G!=="number")throw new GW({parameter:"presencePenalty",value:G,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new GW({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if(Z!=null){if(!Number.isInteger(Z))throw new GW({parameter:"seed",value:Z,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,stopSequences:$,seed:Z}}function py6(Q){return Q!=null&&Object.keys(Q).length>0}async function cy6({tools:Q,toolChoice:X,activeTools:Y}){if(!py6(Q))return{tools:void 0,toolChoice:void 0};let J=Y!=null?Object.entries(Q).filter(([W])=>Y.includes(W)):Object.entries(Q),G=[];for(let[W,Z]of J){let $=Z.type;switch($){case void 0:case"dynamic":case"function":G.push({type:"function",name:W,description:Z.description,inputSchema:await YW(Z.inputSchema).jsonSchema,...Z.inputExamples!=null?{inputExamples:Z.inputExamples}:{},providerOptions:Z.providerOptions,...Z.strict!=null?{strict:Z.strict}:{}});break;case"provider":G.push({type:"provider",name:W,id:Z.id,args:Z.args});break;default:throw Error(`Unsupported tool type: ${$}`)}}return{tools:G,toolChoice:X==null?{type:"auto"}:typeof X==="string"?{type:X}:{type:"tool",toolName:X.toolName}}}var LP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),LP.optional()),N.array(LP)])),i1=N.record(N.string(),N.record(N.string(),LP.optional())),IW1=N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),ny6=N.object({type:N.literal("image"),image:N.union([jW1,N.instanceof(URL)]),mediaType:N.string().optional(),providerOptions:i1.optional()}),RW1=N.object({type:N.literal("file"),data:N.union([jW1,N.instanceof(URL)]),filename:N.string().optional(),mediaType:N.string(),providerOptions:i1.optional()}),iy6=N.object({type:N.literal("reasoning"),text:N.string(),providerOptions:i1.optional()}),ay6=N.object({type:N.literal("tool-call"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerOptions:i1.optional(),providerExecuted:N.boolean().optional()}),ry6=N.discriminatedUnion("type",[N.object({type:N.literal("text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("json"),value:LP,providerOptions:i1.optional()}),N.object({type:N.literal("execution-denied"),reason:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("error-text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("error-json"),value:LP,providerOptions:i1.optional()}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("media"),data:N.string(),mediaType:N.string()}),N.object({type:N.literal("file-data"),data:N.string(),mediaType:N.string(),filename:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("file-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("image-data"),data:N.string(),mediaType:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("custom"),providerOptions:i1.optional()})]))})]),SW1=N.object({type:N.literal("tool-result"),toolCallId:N.string(),toolName:N.string(),output:ry6,providerOptions:i1.optional()}),oy6=N.object({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),sy6=N.object({type:N.literal("tool-approval-response"),approvalId:N.string(),approved:N.boolean(),reason:N.string().optional()}),ty6=N.object({role:N.literal("system"),content:N.string(),providerOptions:i1.optional()}),ey6=N.object({role:N.literal("user"),content:N.union([N.string(),N.array(N.union([IW1,ny6,RW1]))]),providerOptions:i1.optional()}),Qb6=N.object({role:N.literal("assistant"),content:N.union([N.string(),N.array(N.union([IW1,RW1,iy6,ay6,SW1,oy6]))]),providerOptions:i1.optional()}),Xb6=N.object({role:N.literal("tool"),content:N.array(N.union([SW1,sy6])),providerOptions:i1.optional()}),Yb6=N.union([ty6,ey6,Qb6,Xb6]);async function Jb6(Q){if(Q.prompt==null&&Q.messages==null)throw new s3({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new s3({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!gy(Q.system).every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&J.role==="system"))throw new s3({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let X;if(Q.prompt!=null&&typeof Q.prompt==="string")X=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))X=Q.prompt;else if(Q.messages!=null)X=Q.messages;else throw new s3({prompt:Q,message:"prompt or messages must be defined"});if(X.length===0)throw new s3({prompt:Q,message:"messages must not be empty"});let Y=await LX({value:X,schema:N.array(Yb6)});if(!Y.success)throw new s3({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:Y.error});return{messages:X,system:Q.system}}function Gb6(Q){if(!fy.isInstance(Q))return Q;let X=(process==null?void 0:"production")==="production",Y="https://ai-sdk.dev/unauthenticated-ai-gateway";if(X)return new P1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${Y}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
1066
1066
 
1067
1067
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
1068
1068
 
@@ -1074,7 +1074,7 @@ Learn more: \x1B[34m${Y}\x1B[0m
1074
1074
 
1075
1075
  `)},flush(Q){Q.enqueue(`data: [DONE]
1076
1076
 
1077
- `)}})}},xW1={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function kb6({status:Q,statusText:X,headers:Y,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new hW1);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:Q,statusText:X,headers:uy(Y,xW1)})}function vb6({originalMessages:Q,responseMessageId:X}){if(Q==null)return;let Y=Q[Q.length-1];return(Y==null?void 0:Y.role)==="assistant"?Y.id:typeof X==="function"?X():X}var Dl4=OX(()=>z9(N.union([N.strictObject({type:N.literal("text-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("error"),errorText:N.string()}),N.strictObject({type:N.literal("tool-input-start"),toolCallId:N.string(),toolName:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-delta"),toolCallId:N.string(),inputTextDelta:N.string()}),N.strictObject({type:N.literal("tool-input-available"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-error"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),errorText:N.string(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),N.strictObject({type:N.literal("tool-output-available"),toolCallId:N.string(),output:N.unknown(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),preliminary:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-error"),toolCallId:N.string(),errorText:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-denied"),toolCallId:N.string()}),N.strictObject({type:N.literal("reasoning-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("file"),url:N.string(),mediaType:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.custom((Q)=>typeof Q==="string"&&Q.startsWith("data-"),{message:'Type must start with "data-"'}),id:N.string().optional(),data:N.unknown(),transient:N.boolean().optional()}),N.strictObject({type:N.literal("start-step")}),N.strictObject({type:N.literal("finish-step")}),N.strictObject({type:N.literal("start"),messageId:N.string().optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("finish"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("abort"),reason:N.string().optional()}),N.strictObject({type:N.literal("message-metadata"),messageMetadata:N.unknown()})])));function _b6(Q){return Q.type.startsWith("data-")}function b80(Q){return Q.type.startsWith("data-")}function f80(Q){return Q.type==="text"}function h80(Q){return Q.type==="file"}function gG1(Q){return Q.type==="reasoning"}function p80(Q){return Q.type.startsWith("tool-")}function gW1(Q){return Q.type==="dynamic-tool"}function OP(Q){return p80(Q)||gW1(Q)}function c80(Q){return Q.type.split("-").slice(1).join("-")}function x80(Q){return gW1(Q)?Q.toolName:c80(Q)}function yb6({lastMessage:Q,messageId:X}){return{message:(Q==null?void 0:Q.role)==="assistant"?Q:{id:X,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function bb6({stream:Q,messageMetadataSchema:X,dataPartSchemas:Y,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return Q.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,U,D;function B(E){let T=H.message.parts.filter(OP).find((j)=>j.toolCallId===E);if(T==null)throw Error(`no tool invocation found for tool call ${E}`);return T}function L(E){var A;let T=H.message.parts.find((k)=>p80(k)&&k.toolCallId===E.toolCallId),j=E,R=T;if(T!=null){if(T.state=E.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,E.title!==void 0)R.title=E.title;if(R.providerExecuted=(A=j.providerExecuted)!=null?A:T.providerExecuted,j.providerMetadata!=null&&T.state==="input-available")T.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${E.toolName}`,toolCallId:E.toolCallId,state:E.state,title:E.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function M(E){var A,T;let j=H.message.parts.find((y)=>y.type==="dynamic-tool"&&y.toolCallId===E.toolCallId),R=E,k=j;if(j!=null){if(j.state=E.state,k.toolName=E.toolName,k.input=R.input,k.output=R.output,k.errorText=R.errorText,k.rawInput=(A=R.rawInput)!=null?A:k.rawInput,k.preliminary=R.preliminary,E.title!==void 0)k.title=E.title;if(k.providerExecuted=(T=R.providerExecuted)!=null?T:j.providerExecuted,R.providerMetadata!=null&&j.state==="input-available")j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:E.toolName,toolCallId:E.toolCallId,state:E.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:E.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(E){if(E!=null){let A=H.message.metadata!=null?i80(H.message.metadata,E):E;if(X!=null)await zP({value:A,schema:X});H.message.metadata=A}}switch($.type){case"text-start":{let E={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=E,H.message.parts.push(E),F();break}case"text-delta":{let E=H.activeTextParts[$.id];E.text+=$.delta,E.providerMetadata=(V=$.providerMetadata)!=null?V:E.providerMetadata,F();break}case"text-end":{let E=H.activeTextParts[$.id];E.state="done",E.providerMetadata=(q=$.providerMetadata)!=null?q:E.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let E={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=E,H.message.parts.push(E),F();break}case"reasoning-delta":{let E=H.activeReasoningParts[$.id];E.text+=$.delta,E.providerMetadata=(U=$.providerMetadata)!=null?U:E.providerMetadata,F();break}case"reasoning-end":{let E=H.activeReasoningParts[$.id];E.providerMetadata=(D=$.providerMetadata)!=null?D:E.providerMetadata,E.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let E=H.message.parts.filter(p80);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:E.length,dynamic:$.dynamic,title:$.title},$.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});F();break}case"tool-input-delta":{let E=H.partialToolCalls[$.toolCallId];E.text+=$.inputTextDelta;let{value:A}=await wP(E.text);if(E.dynamic)M({toolCallId:$.toolCallId,toolName:E.toolName,state:"input-streaming",input:A,title:E.title});else L({toolCallId:$.toolCallId,toolName:E.toolName,state:"input-streaming",input:A,title:E.title});F();break}case"tool-input-available":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let E=B($.toolCallId);E.state="approval-requested",E.approval={id:$.approvalId},F();break}case"tool-output-denied":{let E=B($.toolCallId);E.state="output-denied",F();break}case"tool-output-available":{let E=B($.toolCallId);if(E.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:E.toolName,state:"output-available",input:E.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:E.title});else L({toolCallId:$.toolCallId,toolName:c80(E),state:"output-available",input:E.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:E.title});F();break}case"tool-output-error":{let E=B($.toolCallId);if(E.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:E.toolName,state:"output-error",input:E.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:E.title});else L({toolCallId:$.toolCallId,toolName:c80(E),state:"output-error",input:E.input,rawInput:E.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:E.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(_b6($)){if((Y==null?void 0:Y[$.type])!=null)await zP({value:$.data,schema:Y[$.type]});let E=$;if(E.transient){Z==null||Z(E);break}let A=E.id!=null?H.message.parts.find((T)=>E.type===T.type&&E.id===T.id):void 0;if(A!=null)A.data=E.data;else H.message.parts.push(E);Z==null||Z(E),F()}}K.enqueue($)})}}))}function fb6({messageId:Q,originalMessages:X=[],onFinish:Y,onError:J,stream:G}){let W=X==null?void 0:X[X.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else Q=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,U){if(q.type==="start"){let D=q;if(D.messageId==null&&Q!=null)D.messageId=Q}if(q.type==="abort")Z=!0;U.enqueue(q)}}));if(Y==null)return $;let K=yb6({lastMessage:W?structuredClone(W):void 0,messageId:Q!=null?Q:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Y)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Y({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?X.slice(0,-1):X,K.message],finishReason:K.finishReason})};return bb6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,U){U.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function hb6({response:Q,status:X,statusText:Y,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new hW1);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}fW1({response:Q,status:X,statusText:Y,headers:Object.fromEntries(uy(J,xW1).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function xy(Q){let X=Q.pipeThrough(new TransformStream);return X[Symbol.asyncIterator]=function(){let Y=this.getReader(),J=!1;async function G(W){var Z;J=!0;try{if(W)await((Z=Y.cancel)==null?void 0:Z.call(Y))}finally{try{Y.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Y.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},X}async function xb6({stream:Q,onError:X}){let Y=Q.getReader();try{while(!0){let{done:J}=await Y.read();if(J)break}}catch(J){X==null||X(J)}finally{Y.releaseLock()}}function uG1(){let Q,X;return{promise:new Promise((J,G)=>{Q=J,X=G}),resolve:Q,reject:X}}function gb6(){let Q=[],X=null,Y=!1,J=uG1(),G=()=>{Y=!0,J.resolve(),Q.forEach((Z)=>Z.cancel()),Q=[],X==null||X.close()},W=async()=>{if(Y&&Q.length===0){X==null||X.close();return}if(Q.length===0)return J=uG1(),await J.promise,W();try{let{value:Z,done:$}=await Q[0].read();if($)if(Q.shift(),Q.length===0&&Y)X==null||X.close();else await W();else X==null||X.enqueue(Z)}catch(Z){X==null||X.error(Z),Q.shift(),G()}};return{stream:new ReadableStream({start(Z){X=Z},pull:W,async cancel(){for(let Z of Q)await Z.cancel();Q=[],Y=!0}}),addStream:(Z)=>{if(Y)throw Error("Cannot add inner stream: outer stream is closed");Q.push(Z.getReader()),J.resolve()},close:()=>{if(Y=!0,J.resolve(),Q.length===0)X==null||X.close()},terminate:G}}function ub6(){var Q,X;return(X=(Q=globalThis==null?void 0:globalThis.performance)==null?void 0:Q.now())!=null?X:Date.now()}function mb6({tools:Q,generatorStream:X,tracer:Y,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(E){F=E}}),q=new Set,U=new Map,D=new Map,B=!1,L=void 0;function M(){if(B&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(E,A){let T=E.type;switch(T){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":{A.enqueue(E);break}case"file":{A.enqueue({type:"file",file:new Nb6({data:E.data,mediaType:E.mediaType})});break}case"finish":{L={type:"finish",finishReason:E.finishReason.unified,rawFinishReason:E.finishReason.raw,usage:Fb6(E.usage),providerMetadata:E.providerMetadata};break}case"tool-approval-request":{let j=D.get(E.toolCallId);if(j==null){F.enqueue({type:"error",error:new eG1({toolCallId:E.toolCallId,approvalId:E.approvalId})});break}A.enqueue({type:"tool-approval-request",approvalId:E.approvalId,toolCall:j});break}case"tool-call":{try{let j=await Eb6({toolCall:E,tools:Q,repairToolCall:$,system:G,messages:W});if(D.set(j.toolCallId,j),A.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:VP(j.error),dynamic:!0,title:j.title});break}let R=Q==null?void 0:Q[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await Ob6({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(U.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let k=H();q.add(k),yW1({toolCall:j,tools:Q,tracer:Y,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(y)=>{F.enqueue(y)}}).then((y)=>{F.enqueue(y)}).catch((y)=>{F.enqueue({type:"error",error:y})}).finally(()=>{q.delete(k),M()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=E.toolName;if(E.isError)F.enqueue({type:"tool-error",toolCallId:E.toolCallId,toolName:j,input:U.get(E.toolCallId),providerExecuted:!0,error:E.result,dynamic:E.dynamic});else A.enqueue({type:"tool-result",toolCallId:E.toolCallId,toolName:j,input:U.get(E.toolCallId),output:E.result,providerExecuted:!0,dynamic:E.dynamic});break}default:throw Error(`Unhandled chunk type: ${T}`)}},flush(){B=!0,M()}});return new ReadableStream({async start(E){return Promise.all([X.pipeThrough(C).pipeTo(new WritableStream({write(A){E.enqueue(A)},close(){}})),V.pipeTo(new WritableStream({write(A){E.enqueue(A)},close(){E.close()}}))])}})}var lb6=XW({prefix:"aitxt",size:24});function uW1({model:Q,tools:X,toolChoice:Y,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=a80(1),experimental_output:V,output:q=V,experimental_telemetry:U,prepareStep:D,providerOptions:B,experimental_activeTools:L,activeTools:M=L,experimental_repairToolCall:C,experimental_transform:E,experimental_download:A,includeRawChunks:T=!1,onChunk:j,onError:R=({error:Q0})=>{console.error(Q0)},onFinish:k,onAbort:y,onStepFinish:b,experimental_context:h,_internal:{now:a=ub6,generateId:f=lb6,currentDate:S=()=>new Date}={},...m}){let Q0=EW1(K);return new pb6({model:AW1(Q),telemetry:U,headers:H,settings:m,maxRetries:Z,abortSignal:Ib6($,Q0!=null?AbortSignal.timeout(Q0):void 0),system:J,prompt:G,messages:W,tools:X,toolChoice:Y,transforms:gy(E),activeTools:M,repairToolCall:C,stopConditions:gy(F),output:q,providerOptions:B,prepareStep:D,includeRawChunks:T,onChunk:j,onError:R,onFinish:k,onAbort:y,onStepFinish:b,now:a,currentDate:S,generateId:f,experimental_context:h,download:A})}function db6(Q){let X=void 0,Y="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:X,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(X==null)X=$.id;else if($.id!==X){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Y+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await Q.parsePartialOutput({text:Y});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var pb6=class{constructor({model:Q,telemetry:X,headers:Y,settings:J,maxRetries:G,abortSignal:W,system:Z,prompt:$,messages:K,tools:H,toolChoice:F,transforms:V,activeTools:q,repairToolCall:U,stopConditions:D,output:B,providerOptions:L,prepareStep:M,includeRawChunks:C,now:E,currentDate:A,generateId:T,onChunk:j,onError:R,onFinish:k,onAbort:y,onStepFinish:b,experimental_context:h,download:a}){this._totalUsage=new QF,this._finishReason=new QF,this._rawFinishReason=new QF,this._steps=new QF,this.outputSpecification=B,this.includeRawChunks=C,this.tools=H;let f,S=[],m=[],Q0=void 0,r=void 0,J0=void 0,z0={},Z0=[],V0=[],T0=new Map,_0,K1={},N0={},G0=new TransformStream({async transform(u0,A0){var S0,B1,p1,T6;A0.enqueue(u0);let{part:l0}=u0;if(l0.type==="text-delta"||l0.type==="reasoning-delta"||l0.type==="source"||l0.type==="tool-call"||l0.type==="tool-result"||l0.type==="tool-input-start"||l0.type==="tool-input-delta"||l0.type==="raw")await(j==null?void 0:j({chunk:l0}));if(l0.type==="error")await R({error:Gb6(l0.error)});if(l0.type==="text-start")K1[l0.id]={type:"text",text:"",providerMetadata:l0.providerMetadata},S.push(K1[l0.id]);if(l0.type==="text-delta"){let d0=K1[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}d0.text+=l0.text,d0.providerMetadata=(S0=l0.providerMetadata)!=null?S0:d0.providerMetadata}if(l0.type==="text-end"){let d0=K1[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}d0.providerMetadata=(B1=l0.providerMetadata)!=null?B1:d0.providerMetadata,delete K1[l0.id]}if(l0.type==="reasoning-start")N0[l0.id]={type:"reasoning",text:"",providerMetadata:l0.providerMetadata},S.push(N0[l0.id]);if(l0.type==="reasoning-delta"){let d0=N0[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}d0.text+=l0.text,d0.providerMetadata=(p1=l0.providerMetadata)!=null?p1:d0.providerMetadata}if(l0.type==="reasoning-end"){let d0=N0[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}d0.providerMetadata=(T6=l0.providerMetadata)!=null?T6:d0.providerMetadata,delete N0[l0.id]}if(l0.type==="file")S.push({type:"file",file:l0.file});if(l0.type==="source")S.push(l0);if(l0.type==="tool-call")S.push(l0);if(l0.type==="tool-result"&&!l0.preliminary)S.push(l0);if(l0.type==="tool-approval-request")S.push(l0);if(l0.type==="tool-error")S.push(l0);if(l0.type==="start-step")S=[],N0={},K1={},z0=l0.request,Z0=l0.warnings;if(l0.type==="finish-step"){let d0=await xG1({content:S,tools:H}),C0=new jb6({content:S,finishReason:l0.finishReason,rawFinishReason:l0.rawFinishReason,usage:l0.usage,warnings:Z0,request:z0,response:{...l0.response,messages:[...m,...d0]},providerMetadata:l0.providerMetadata});await(b==null?void 0:b(C0)),MW1({warnings:Z0,provider:Q.provider,model:Q.modelId}),V0.push(C0),m.push(...d0),f.resolve()}if(l0.type==="finish")J0=l0.totalUsage,Q0=l0.finishReason,r=l0.rawFinishReason},async flush(u0){try{if(V0.length===0){let p1=new Fy6({message:"No output generated. Check the stream for errors."});U0._finishReason.reject(p1),U0._rawFinishReason.reject(p1),U0._totalUsage.reject(p1),U0._steps.reject(p1);return}let A0=Q0!=null?Q0:"other",S0=J0!=null?J0:y80();U0._finishReason.resolve(A0),U0._rawFinishReason.resolve(r),U0._totalUsage.resolve(S0),U0._steps.resolve(V0);let B1=V0[V0.length-1];await(k==null?void 0:k({finishReason:B1.finishReason,rawFinishReason:B1.rawFinishReason,totalUsage:S0,usage:B1.usage,content:B1.content,text:B1.text,reasoningText:B1.reasoningText,reasoning:B1.reasoning,files:B1.files,sources:B1.sources,toolCalls:B1.toolCalls,staticToolCalls:B1.staticToolCalls,dynamicToolCalls:B1.dynamicToolCalls,toolResults:B1.toolResults,staticToolResults:B1.staticToolResults,dynamicToolResults:B1.dynamicToolResults,request:B1.request,response:B1.response,warnings:B1.warnings,providerMetadata:B1.providerMetadata,steps:V0,experimental_context:h})),_0.setAttributes(await yU({telemetry:X,attributes:{"ai.response.finishReason":A0,"ai.response.text":{output:()=>B1.text},"ai.response.toolCalls":{output:()=>{var p1;return((p1=B1.toolCalls)==null?void 0:p1.length)?JSON.stringify(B1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(B1.providerMetadata),"ai.usage.inputTokens":S0.inputTokens,"ai.usage.outputTokens":S0.outputTokens,"ai.usage.totalTokens":S0.totalTokens,"ai.usage.reasoningTokens":S0.reasoningTokens,"ai.usage.cachedInputTokens":S0.cachedInputTokens}}))}catch(A0){u0.error(A0)}finally{_0.end()}}}),R0=gb6();this.addStream=R0.addStream,this.closeStream=R0.close;let l1=R0.stream.getReader(),b1=new ReadableStream({async start(u0){u0.enqueue({type:"start"})},async pull(u0){function A0(){y==null||y({steps:V0}),u0.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:R5(W.reason)}:{}}),u0.close()}try{let{done:S0,value:B1}=await l1.read();if(S0){u0.close();return}if(W==null?void 0:W.aborted){A0();return}u0.enqueue(B1)}catch(S0){if(b7(S0)&&(W==null?void 0:W.aborted))A0();else u0.error(S0)}},cancel(u0){return R0.stream.cancel(u0)}});for(let u0 of V)b1=b1.pipeThrough(u0({tools:H,stopStream(){R0.terminate()}}));this.baseStream=b1.pipeThrough(db6(B!=null?B:d80())).pipeThrough(G0);let{maxRetries:b0,retry:L0}=Ub6({maxRetries:G,abortSignal:W}),$0=Kb6(X),P0=dy6(J),H0=Wb6({model:Q,telemetry:X,headers:Y,settings:{...P0,maxRetries:b0}}),U0=this;l80({name:"ai.streamText",attributes:yU({telemetry:X,attributes:{...u80({operationId:"ai.streamText",telemetry:X}),...H0,"ai.prompt":{input:()=>JSON.stringify({system:Z,prompt:$,messages:K})}}}),tracer:$0,endWhenDone:!1,fn:async(u0)=>{_0=u0;let A0=await Jb6({system:Z,prompt:$,messages:K}),S0=A0.messages,B1=[],{approvedToolApprovals:p1,deniedToolApprovals:T6}=Bb6({messages:S0});if(T6.length>0||p1.length>0){let d0=[...p1,...T6].filter((A1)=>A1.toolCall.providerExecuted),C0=p1.filter((A1)=>!A1.toolCall.providerExecuted),Y1=T6.filter((A1)=>!A1.toolCall.providerExecuted),I4=T6.filter((A1)=>A1.toolCall.providerExecuted),u6,o8=new ReadableStream({start(A1){u6=A1}});U0.addStream(o8);try{for(let I0 of[...Y1,...I4])u6==null||u6.enqueue({type:"tool-output-denied",toolCallId:I0.toolCall.toolCallId,toolName:I0.toolCall.toolName});let A1=[];if(await Promise.all(C0.map(async(I0)=>{let R4=await yW1({toolCall:I0.toolCall,tools:H,tracer:$0,telemetry:X,messages:S0,abortSignal:W,experimental_context:h,onPreliminaryToolResult:(O)=>{u6==null||u6.enqueue(O)}});if(R4!=null)u6==null||u6.enqueue(R4),A1.push(R4)})),d0.length>0)B1.push({role:"tool",content:d0.map((I0)=>({type:"tool-approval-response",approvalId:I0.approvalResponse.approvalId,approved:I0.approvalResponse.approved,reason:I0.approvalResponse.reason,providerExecuted:!0}))});if(A1.length>0||Y1.length>0){let I0=[];for(let R4 of A1)I0.push({type:"tool-result",toolCallId:R4.toolCallId,toolName:R4.toolName,output:await bU({toolCallId:R4.toolCallId,input:R4.input,tool:H==null?void 0:H[R4.toolName],output:R4.type==="tool-result"?R4.output:R4.error,errorMode:R4.type==="tool-error"?"json":"none"})});for(let R4 of Y1)I0.push({type:"tool-result",toolCallId:R4.toolCall.toolCallId,toolName:R4.toolCall.toolName,output:{type:"execution-denied",reason:R4.approvalResponse.reason}});B1.push({role:"tool",content:I0})}}finally{u6==null||u6.close()}}m.push(...B1);async function l0({currentStep:d0,responseMessages:C0,usage:Y1}){var I4,u6,o8,A1,I0,R4;let O=U0.includeRawChunks;f=new QF;let _=[...S0,...C0],e=await(M==null?void 0:M({model:Q,steps:V0,stepNumber:V0.length,messages:_,experimental_context:h})),Y0=AW1((I4=e==null?void 0:e.model)!=null?I4:Q),z=await gy6({prompt:{system:(u6=e==null?void 0:e.system)!=null?u6:A0.system,messages:(o8=e==null?void 0:e.messages)!=null?o8:_},supportedUrls:await Y0.supportedUrls,download:a}),{toolChoice:w,tools:v}=await cy6({tools:H,toolChoice:(A1=e==null?void 0:e.toolChoice)!=null?A1:F,activeTools:(I0=e==null?void 0:e.activeTools)!=null?I0:q});h=(R4=e==null?void 0:e.experimental_context)!=null?R4:h;let c=i80(L,e==null?void 0:e.providerOptions),{result:{stream:s,response:u,request:M0},doStreamSpan:t0,startTimestampMs:T1}=await L0(()=>l80({name:"ai.streamText.doStream",attributes:yU({telemetry:X,attributes:{...u80({operationId:"ai.streamText.doStream",telemetry:X}),...H0,"ai.model.provider":Y0.provider,"ai.model.id":Y0.modelId,"ai.prompt.messages":{input:()=>Hb6(z)},"ai.prompt.tools":{input:()=>v==null?void 0:v.map((J1)=>JSON.stringify(J1))},"ai.prompt.toolChoice":{input:()=>w!=null?JSON.stringify(w):void 0},"gen_ai.system":Y0.provider,"gen_ai.request.model":Y0.modelId,"gen_ai.request.frequency_penalty":P0.frequencyPenalty,"gen_ai.request.max_tokens":P0.maxOutputTokens,"gen_ai.request.presence_penalty":P0.presencePenalty,"gen_ai.request.stop_sequences":P0.stopSequences,"gen_ai.request.temperature":P0.temperature,"gen_ai.request.top_k":P0.topK,"gen_ai.request.top_p":P0.topP}}),tracer:$0,endWhenDone:!1,fn:async(J1)=>({startTimestampMs:E(),doStreamSpan:J1,result:await Y0.doStream({...P0,tools:v,toolChoice:w,responseFormat:await(B==null?void 0:B.responseFormat),prompt:z,providerOptions:c,abortSignal:W,headers:Y,includeRawChunks:O})})})),v0=mb6({tools:H,generatorStream:s,tracer:$0,telemetry:X,system:Z,messages:_,repairToolCall:U,abortSignal:W,experimental_context:h,generateId:T}),L1=M0!=null?M0:{},R6=[],C8=[],_6,wX={},y5="other",h7=void 0,p0=y80(),U6,GQ=!0,y8={id:T(),timestamp:A(),modelId:Q.modelId},X1="";U0.addStream(v0.pipeThrough(new TransformStream({async transform(J1,H4){var MX,t$,MP,DQ,WF;if(J1.type==="stream-start"){_6=J1.warnings;return}if(GQ){let WQ=E()-T1;GQ=!1,t0.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":WQ}),t0.setAttributes({"ai.response.msToFirstChunk":WQ}),H4.enqueue({type:"start-step",request:L1,warnings:_6!=null?_6:[]})}let dy=J1.type;switch(dy){case"tool-approval-request":case"text-start":case"text-end":{H4.enqueue(J1);break}case"text-delta":{if(J1.delta.length>0)H4.enqueue({type:"text-delta",id:J1.id,text:J1.delta,providerMetadata:J1.providerMetadata}),X1+=J1.delta;break}case"reasoning-start":case"reasoning-end":{H4.enqueue(J1);break}case"reasoning-delta":{H4.enqueue({type:"reasoning-delta",id:J1.id,text:J1.delta,providerMetadata:J1.providerMetadata});break}case"tool-call":{H4.enqueue(J1),R6.push(J1);break}case"tool-result":{if(H4.enqueue(J1),!J1.preliminary)C8.push(J1);break}case"tool-error":{H4.enqueue(J1),C8.push(J1);break}case"response-metadata":{y8={id:(MX=J1.id)!=null?MX:y8.id,timestamp:(t$=J1.timestamp)!=null?t$:y8.timestamp,modelId:(MP=J1.modelId)!=null?MP:y8.modelId};break}case"finish":{p0=J1.usage,y5=J1.finishReason,h7=J1.rawFinishReason,U6=J1.providerMetadata;let WQ=E()-T1;t0.addEvent("ai.stream.finish"),t0.setAttributes({"ai.response.msToFinish":WQ,"ai.response.avgOutputTokensPerSecond":1000*((DQ=p0.outputTokens)!=null?DQ:0)/WQ});break}case"file":{H4.enqueue(J1);break}case"source":{H4.enqueue(J1);break}case"tool-input-start":{wX[J1.id]=J1.toolName;let WQ=H==null?void 0:H[J1.toolName];if((WQ==null?void 0:WQ.onInputStart)!=null)await WQ.onInputStart({toolCallId:J1.id,messages:_,abortSignal:W,experimental_context:h});H4.enqueue({...J1,dynamic:(WF=J1.dynamic)!=null?WF:(WQ==null?void 0:WQ.type)==="dynamic",title:WQ==null?void 0:WQ.title});break}case"tool-input-end":{delete wX[J1.id],H4.enqueue(J1);break}case"tool-input-delta":{let WQ=wX[J1.id],py=H==null?void 0:H[WQ];if((py==null?void 0:py.onInputDelta)!=null)await py.onInputDelta({inputTextDelta:J1.delta,toolCallId:J1.id,messages:_,abortSignal:W,experimental_context:h});H4.enqueue(J1);break}case"error":{H4.enqueue(J1),y5="error";break}case"raw":{if(O)H4.enqueue(J1);break}default:throw Error(`Unknown chunk type: ${dy}`)}},async flush(J1){let H4=R6.length>0?JSON.stringify(R6):void 0;try{t0.setAttributes(await yU({telemetry:X,attributes:{"ai.response.finishReason":y5,"ai.response.text":{output:()=>X1},"ai.response.toolCalls":{output:()=>H4},"ai.response.id":y8.id,"ai.response.model":y8.modelId,"ai.response.timestamp":y8.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(U6),"ai.usage.inputTokens":p0.inputTokens,"ai.usage.outputTokens":p0.outputTokens,"ai.usage.totalTokens":p0.totalTokens,"ai.usage.reasoningTokens":p0.reasoningTokens,"ai.usage.cachedInputTokens":p0.cachedInputTokens,"gen_ai.response.finish_reasons":[y5],"gen_ai.response.id":y8.id,"gen_ai.response.model":y8.modelId,"gen_ai.usage.input_tokens":p0.inputTokens,"gen_ai.usage.output_tokens":p0.outputTokens}}))}catch(DQ){}finally{t0.end()}J1.enqueue({type:"finish-step",finishReason:y5,rawFinishReason:h7,usage:p0,providerMetadata:U6,response:{...y8,headers:u==null?void 0:u.headers}});let MX=Vb6(Y1,p0);await f.promise;let t$=R6.filter((DQ)=>DQ.providerExecuted!==!0),MP=C8.filter((DQ)=>DQ.providerExecuted!==!0);for(let DQ of R6){if(DQ.providerExecuted!==!0)continue;let WF=H==null?void 0:H[DQ.toolName];if((WF==null?void 0:WF.type)==="provider"&&WF.supportsDeferredResults){if(!C8.some((WQ)=>WQ.type==="tool-result"&&WQ.toolCallId===DQ.toolCallId))T0.set(DQ.toolCallId,{toolName:DQ.toolName})}}for(let DQ of C8)if(DQ.type==="tool-result")T0.delete(DQ.toolCallId);if((t$.length>0&&MP.length===t$.length||T0.size>0)&&!await Cb6({stopConditions:D,steps:V0})){C0.push(...await xG1({content:V0[V0.length-1].content,tools:H}));try{await l0({currentStep:d0+1,responseMessages:C0,usage:MX})}catch(DQ){J1.enqueue({type:"error",error:DQ}),U0.closeStream()}}else J1.enqueue({type:"finish",finishReason:y5,rawFinishReason:h7,totalUsage:MX}),U0.closeStream()}})))}await l0({currentStep:0,responseMessages:B1,usage:y80()})}}).catch((u0)=>{U0.addStream(new ReadableStream({start(A0){A0.enqueue({type:"error",error:u0}),A0.close()}})),U0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((Q)=>Q[Q.length-1])}get content(){return this.finalStep.then((Q)=>Q.content)}get warnings(){return this.finalStep.then((Q)=>Q.warnings)}get providerMetadata(){return this.finalStep.then((Q)=>Q.providerMetadata)}get text(){return this.finalStep.then((Q)=>Q.text)}get reasoningText(){return this.finalStep.then((Q)=>Q.reasoningText)}get reasoning(){return this.finalStep.then((Q)=>Q.reasoning)}get sources(){return this.finalStep.then((Q)=>Q.sources)}get files(){return this.finalStep.then((Q)=>Q.files)}get toolCalls(){return this.finalStep.then((Q)=>Q.toolCalls)}get staticToolCalls(){return this.finalStep.then((Q)=>Q.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((Q)=>Q.dynamicToolCalls)}get toolResults(){return this.finalStep.then((Q)=>Q.toolResults)}get staticToolResults(){return this.finalStep.then((Q)=>Q.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((Q)=>Q.dynamicToolResults)}get usage(){return this.finalStep.then((Q)=>Q.usage)}get request(){return this.finalStep.then((Q)=>Q.request)}get response(){return this.finalStep.then((Q)=>Q.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[Q,X]=this.baseStream.tee();return this.baseStream=X,Q}get textStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){if(Q.type==="text-delta")X.enqueue(Q.text)}})))}get fullStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){X.enqueue(Q)}})))}async consumeStream(Q){var X;try{await xb6({stream:this.fullStream,onError:Q==null?void 0:Q.onError})}catch(Y){(X=Q==null?void 0:Q.onError)==null||X.call(Q,Y)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:Q},X){if(Q!=null)X.enqueue(Q)}})))}get output(){return this.finalStep.then((Q)=>{var X;return((X=this.outputSpecification)!=null?X:d80()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})})}toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=R5}={}){let H=X!=null?vb6({originalMessages:Q,responseMessageId:X}):void 0,F=(q)=>{var U;let D=(U=this.tools)==null?void 0:U[q.toolName];if(D==null)return q.dynamic;return(D==null?void 0:D.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,U)=>{let D=J==null?void 0:J({part:q}),B=q.type;switch(B){case"text-start":{U.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{U.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{U.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{U.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)U.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{U.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{U.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")U.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")U.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);U.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{U.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)U.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else U.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{U.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);U.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);U.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{U.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{U.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{U.enqueue({type:"start-step"});break}case"finish-step":{U.enqueue({type:"finish-step"});break}case"start":{if(Z)U.enqueue({type:"start",...D!=null?{messageMetadata:D}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)U.enqueue({type:"finish",finishReason:q.finishReason,...D!=null?{messageMetadata:D}:{}});break}case"abort":{U.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${B}`)}if(D!=null&&B!=="start"&&B!=="finish")U.enqueue({type:"message-metadata",messageMetadata:D})}}));return xy(fb6({stream:V,messageId:H!=null?H:X==null?void 0:X(),originalMessages:Q,onFinish:Y,onError:K}))}pipeUIMessageStreamToResponse(Q,{originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){hb6({response:Q,stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(Q,X){Sb6({response:Q,textStream:this.textStream,...X})}toUIMessageStreamResponse({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return kb6({stream:this.toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(Q){return Rb6({textStream:this.textStream,...Q})}};async function mW1(Q,X){let Y=[];if(X==null?void 0:X.ignoreIncompleteToolCalls)Q=Q.map((J)=>({...J,parts:J.parts.filter((G)=>!OP(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of Q)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Y.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Y.push({role:"user",content:J.parts.map((G)=>{var W;if(f80(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(h80(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(b80(G))return(W=X==null?void 0:X.convertDataPart)==null?void 0:W.call(X,G)}).filter(Z51)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let D of G)if(f80(D))q.push({type:"text",text:D.text,...D.providerMetadata!=null?{providerOptions:D.providerMetadata}:{}});else if(h80(D))q.push({type:"file",mediaType:D.mediaType,filename:D.filename,data:D.url});else if(gG1(D))q.push({type:"reasoning",text:D.text,providerOptions:D.providerMetadata});else if(OP(D)){let B=x80(D);if(D.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:D.toolCallId,toolName:B,input:D.state==="output-error"?(Z=D.input)!=null?Z:("rawInput"in D)?D.rawInput:void 0:D.input,providerExecuted:D.providerExecuted,...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}}),D.approval!=null)q.push({type:"tool-approval-request",approvalId:D.approval.id,toolCallId:D.toolCallId});if(D.providerExecuted===!0&&D.state!=="approval-responded"&&(D.state==="output-available"||D.state==="output-error"))q.push({type:"tool-result",toolCallId:D.toolCallId,toolName:B,output:await bU({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:($=X==null?void 0:X.tools)==null?void 0:$[B],errorMode:D.state==="output-error"?"json":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}})}}else if(b80(D)){let B=(K=X==null?void 0:X.convertDataPart)==null?void 0:K.call(X,D);if(B!=null)q.push(B)}else throw Error(`Unsupported part: ${D}`);Y.push({role:"assistant",content:q});let U=G.filter((D)=>{var B;return OP(D)&&(D.providerExecuted!==!0||((B=D.approval)==null?void 0:B.approved)!=null)});if(U.length>0){let D=[];for(let B of U){if(((H=B.approval)==null?void 0:H.approved)!=null)D.push({type:"tool-approval-response",approvalId:B.approval.id,approved:B.approval.approved,reason:B.approval.reason,providerExecuted:B.providerExecuted});if(B.providerExecuted===!0)continue;switch(B.state){case"output-denied":{D.push({type:"tool-result",toolCallId:B.toolCallId,toolName:x80(B),output:{type:"error-text",value:(F=B.approval.reason)!=null?F:"Tool execution denied."},...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=x80(B);D.push({type:"tool-result",toolCallId:B.toolCallId,toolName:L,output:await bU({toolCallId:B.toolCallId,input:B.input,output:B.state==="output-error"?B.errorText:B.output,tool:(V=X==null?void 0:X.tools)==null?void 0:V[L],errorMode:B.state==="output-error"?"text":"none"}),...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}});break}}}if(D.length>0)Y.push({role:"tool",content:D})}G=[]}for(let Z of J.parts)if(f80(Z)||gG1(Z)||h80(Z)||OP(Z)||b80(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new Py6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Y}var Ml4=OX(()=>z9(N.array(N.object({id:N.string(),role:N.enum(["system","user","assistant"]),metadata:N.unknown().optional(),parts:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("reasoning"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("file"),mediaType:N.string(),filename:N.string().optional(),url:N.string(),providerMetadata:i1.optional()}),N.object({type:N.literal("step-start")}),N.object({type:N.string().startsWith("data-"),id:N.string().optional(),data:N.unknown()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-streaming"),input:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-error"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-denied"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-streaming"),providerExecuted:N.boolean().optional(),input:N.unknown().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-error"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-denied"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var Tl4=XW({prefix:"aiobj",size:24});var El4=XW({prefix:"aiobj",size:24});function lW1({messages:Q,reasoning:X="none",toolCalls:Y=[],emptyMessages:J="remove"}){if(X==="all"||X==="before-last-message")Q=Q.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||X==="before-last-message"&&W===Q.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Y==="none")Y=[];else if(Y==="all")Y=[{type:"all"}];else if(Y==="before-last-message")Y=[{type:"before-last-message"}];else if(typeof Y==="string")Y=[{type:Y}];for(let G of Y){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of Q.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}Q=Q.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=Q.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")Q=Q.filter((G)=>G.content.length>0);return Q}var cb6="AI_NoSuchProviderError",nb6=`vercel.ai.error.${cb6}`,ib6=Symbol.for(nb6),ab6;ab6=ib6;W1();function dW1(Q){let X=Q.trim();if(!X)return null;if(X.startsWith("event:"))return null;if(X.startsWith("id:"))return null;if(X.startsWith("retry:"))return null;let Y=X;if(Y.startsWith("data:")){if(Y=Y.slice(5).trim(),!Y)return null;if(Y==="[DONE]")return null}try{return JSON.parse(Y)}catch(J){return console.warn("[llm-provider] Failed to parse stream line as JSON. Skipping line.",{line:Y.slice(0,200)},J),null}}function rb6(Q){if(!Q.body)throw Error("Response body is null");let X="";return Q.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(Y,J){X+=Y;let G=X.split(`
1077
+ `)}})}},xW1={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function kb6({status:Q,statusText:X,headers:Y,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new hW1);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:Q,statusText:X,headers:uy(Y,xW1)})}function vb6({originalMessages:Q,responseMessageId:X}){if(Q==null)return;let Y=Q[Q.length-1];return(Y==null?void 0:Y.role)==="assistant"?Y.id:typeof X==="function"?X():X}var Dl4=OX(()=>z9(N.union([N.strictObject({type:N.literal("text-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("error"),errorText:N.string()}),N.strictObject({type:N.literal("tool-input-start"),toolCallId:N.string(),toolName:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-delta"),toolCallId:N.string(),inputTextDelta:N.string()}),N.strictObject({type:N.literal("tool-input-available"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-error"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),errorText:N.string(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),N.strictObject({type:N.literal("tool-output-available"),toolCallId:N.string(),output:N.unknown(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),preliminary:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-error"),toolCallId:N.string(),errorText:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-denied"),toolCallId:N.string()}),N.strictObject({type:N.literal("reasoning-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("file"),url:N.string(),mediaType:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.custom((Q)=>typeof Q==="string"&&Q.startsWith("data-"),{message:'Type must start with "data-"'}),id:N.string().optional(),data:N.unknown(),transient:N.boolean().optional()}),N.strictObject({type:N.literal("start-step")}),N.strictObject({type:N.literal("finish-step")}),N.strictObject({type:N.literal("start"),messageId:N.string().optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("finish"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("abort"),reason:N.string().optional()}),N.strictObject({type:N.literal("message-metadata"),messageMetadata:N.unknown()})])));function _b6(Q){return Q.type.startsWith("data-")}function b80(Q){return Q.type.startsWith("data-")}function f80(Q){return Q.type==="text"}function h80(Q){return Q.type==="file"}function gG1(Q){return Q.type==="reasoning"}function p80(Q){return Q.type.startsWith("tool-")}function gW1(Q){return Q.type==="dynamic-tool"}function OP(Q){return p80(Q)||gW1(Q)}function c80(Q){return Q.type.split("-").slice(1).join("-")}function x80(Q){return gW1(Q)?Q.toolName:c80(Q)}function yb6({lastMessage:Q,messageId:X}){return{message:(Q==null?void 0:Q.role)==="assistant"?Q:{id:X,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function bb6({stream:Q,messageMetadataSchema:X,dataPartSchemas:Y,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return Q.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,U,D;function B(E){let T=H.message.parts.filter(OP).find((j)=>j.toolCallId===E);if(T==null)throw Error(`no tool invocation found for tool call ${E}`);return T}function L(E){var A;let T=H.message.parts.find((k)=>p80(k)&&k.toolCallId===E.toolCallId),j=E,R=T;if(T!=null){if(T.state=E.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,E.title!==void 0)R.title=E.title;if(R.providerExecuted=(A=j.providerExecuted)!=null?A:T.providerExecuted,j.providerMetadata!=null&&T.state==="input-available")T.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${E.toolName}`,toolCallId:E.toolCallId,state:E.state,title:E.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function M(E){var A,T;let j=H.message.parts.find((y)=>y.type==="dynamic-tool"&&y.toolCallId===E.toolCallId),R=E,k=j;if(j!=null){if(j.state=E.state,k.toolName=E.toolName,k.input=R.input,k.output=R.output,k.errorText=R.errorText,k.rawInput=(A=R.rawInput)!=null?A:k.rawInput,k.preliminary=R.preliminary,E.title!==void 0)k.title=E.title;if(k.providerExecuted=(T=R.providerExecuted)!=null?T:j.providerExecuted,R.providerMetadata!=null&&j.state==="input-available")j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:E.toolName,toolCallId:E.toolCallId,state:E.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:E.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(E){if(E!=null){let A=H.message.metadata!=null?i80(H.message.metadata,E):E;if(X!=null)await zP({value:A,schema:X});H.message.metadata=A}}switch($.type){case"text-start":{let E={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=E,H.message.parts.push(E),F();break}case"text-delta":{let E=H.activeTextParts[$.id];E.text+=$.delta,E.providerMetadata=(V=$.providerMetadata)!=null?V:E.providerMetadata,F();break}case"text-end":{let E=H.activeTextParts[$.id];E.state="done",E.providerMetadata=(q=$.providerMetadata)!=null?q:E.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let E={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=E,H.message.parts.push(E),F();break}case"reasoning-delta":{let E=H.activeReasoningParts[$.id];E.text+=$.delta,E.providerMetadata=(U=$.providerMetadata)!=null?U:E.providerMetadata,F();break}case"reasoning-end":{let E=H.activeReasoningParts[$.id];E.providerMetadata=(D=$.providerMetadata)!=null?D:E.providerMetadata,E.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let E=H.message.parts.filter(p80);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:E.length,dynamic:$.dynamic,title:$.title},$.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});F();break}case"tool-input-delta":{let E=H.partialToolCalls[$.toolCallId];E.text+=$.inputTextDelta;let{value:A}=await wP(E.text);if(E.dynamic)M({toolCallId:$.toolCallId,toolName:E.toolName,state:"input-streaming",input:A,title:E.title});else L({toolCallId:$.toolCallId,toolName:E.toolName,state:"input-streaming",input:A,title:E.title});F();break}case"tool-input-available":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let E=B($.toolCallId);E.state="approval-requested",E.approval={id:$.approvalId},F();break}case"tool-output-denied":{let E=B($.toolCallId);E.state="output-denied",F();break}case"tool-output-available":{let E=B($.toolCallId);if(E.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:E.toolName,state:"output-available",input:E.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:E.title});else L({toolCallId:$.toolCallId,toolName:c80(E),state:"output-available",input:E.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:E.title});F();break}case"tool-output-error":{let E=B($.toolCallId);if(E.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:E.toolName,state:"output-error",input:E.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:E.title});else L({toolCallId:$.toolCallId,toolName:c80(E),state:"output-error",input:E.input,rawInput:E.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:E.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(_b6($)){if((Y==null?void 0:Y[$.type])!=null)await zP({value:$.data,schema:Y[$.type]});let E=$;if(E.transient){Z==null||Z(E);break}let A=E.id!=null?H.message.parts.find((T)=>E.type===T.type&&E.id===T.id):void 0;if(A!=null)A.data=E.data;else H.message.parts.push(E);Z==null||Z(E),F()}}K.enqueue($)})}}))}function fb6({messageId:Q,originalMessages:X=[],onFinish:Y,onError:J,stream:G}){let W=X==null?void 0:X[X.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else Q=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,U){if(q.type==="start"){let D=q;if(D.messageId==null&&Q!=null)D.messageId=Q}if(q.type==="abort")Z=!0;U.enqueue(q)}}));if(Y==null)return $;let K=yb6({lastMessage:W?structuredClone(W):void 0,messageId:Q!=null?Q:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Y)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Y({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?X.slice(0,-1):X,K.message],finishReason:K.finishReason})};return bb6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,U){U.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function hb6({response:Q,status:X,statusText:Y,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new hW1);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}fW1({response:Q,status:X,statusText:Y,headers:Object.fromEntries(uy(J,xW1).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function xy(Q){let X=Q.pipeThrough(new TransformStream);return X[Symbol.asyncIterator]=function(){let Y=this.getReader(),J=!1;async function G(W){var Z;J=!0;try{if(W)await((Z=Y.cancel)==null?void 0:Z.call(Y))}finally{try{Y.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Y.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},X}async function xb6({stream:Q,onError:X}){let Y=Q.getReader();try{while(!0){let{done:J}=await Y.read();if(J)break}}catch(J){X==null||X(J)}finally{Y.releaseLock()}}function uG1(){let Q,X;return{promise:new Promise((J,G)=>{Q=J,X=G}),resolve:Q,reject:X}}function gb6(){let Q=[],X=null,Y=!1,J=uG1(),G=()=>{Y=!0,J.resolve(),Q.forEach((Z)=>Z.cancel()),Q=[],X==null||X.close()},W=async()=>{if(Y&&Q.length===0){X==null||X.close();return}if(Q.length===0)return J=uG1(),await J.promise,W();try{let{value:Z,done:$}=await Q[0].read();if($)if(Q.shift(),Q.length===0&&Y)X==null||X.close();else await W();else X==null||X.enqueue(Z)}catch(Z){X==null||X.error(Z),Q.shift(),G()}};return{stream:new ReadableStream({start(Z){X=Z},pull:W,async cancel(){for(let Z of Q)await Z.cancel();Q=[],Y=!0}}),addStream:(Z)=>{if(Y)throw Error("Cannot add inner stream: outer stream is closed");Q.push(Z.getReader()),J.resolve()},close:()=>{if(Y=!0,J.resolve(),Q.length===0)X==null||X.close()},terminate:G}}function ub6(){var Q,X;return(X=(Q=globalThis==null?void 0:globalThis.performance)==null?void 0:Q.now())!=null?X:Date.now()}function mb6({tools:Q,generatorStream:X,tracer:Y,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(E){F=E}}),q=new Set,U=new Map,D=new Map,B=!1,L=void 0;function M(){if(B&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(E,A){let T=E.type;switch(T){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":{A.enqueue(E);break}case"file":{A.enqueue({type:"file",file:new Nb6({data:E.data,mediaType:E.mediaType})});break}case"finish":{L={type:"finish",finishReason:E.finishReason.unified,rawFinishReason:E.finishReason.raw,usage:Fb6(E.usage),providerMetadata:E.providerMetadata};break}case"tool-approval-request":{let j=D.get(E.toolCallId);if(j==null){F.enqueue({type:"error",error:new eG1({toolCallId:E.toolCallId,approvalId:E.approvalId})});break}A.enqueue({type:"tool-approval-request",approvalId:E.approvalId,toolCall:j});break}case"tool-call":{try{let j=await Eb6({toolCall:E,tools:Q,repairToolCall:$,system:G,messages:W});if(D.set(j.toolCallId,j),A.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:VP(j.error),dynamic:!0,title:j.title});break}let R=Q==null?void 0:Q[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await Ob6({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(U.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let k=H();q.add(k),yW1({toolCall:j,tools:Q,tracer:Y,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(y)=>{F.enqueue(y)}}).then((y)=>{F.enqueue(y)}).catch((y)=>{F.enqueue({type:"error",error:y})}).finally(()=>{q.delete(k),M()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=E.toolName;if(E.isError)F.enqueue({type:"tool-error",toolCallId:E.toolCallId,toolName:j,input:U.get(E.toolCallId),providerExecuted:!0,error:E.result,dynamic:E.dynamic});else A.enqueue({type:"tool-result",toolCallId:E.toolCallId,toolName:j,input:U.get(E.toolCallId),output:E.result,providerExecuted:!0,dynamic:E.dynamic});break}default:throw Error(`Unhandled chunk type: ${T}`)}},flush(){B=!0,M()}});return new ReadableStream({async start(E){return Promise.all([X.pipeThrough(C).pipeTo(new WritableStream({write(A){E.enqueue(A)},close(){}})),V.pipeTo(new WritableStream({write(A){E.enqueue(A)},close(){E.close()}}))])}})}var lb6=XW({prefix:"aitxt",size:24});function uW1({model:Q,tools:X,toolChoice:Y,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=a80(1),experimental_output:V,output:q=V,experimental_telemetry:U,prepareStep:D,providerOptions:B,experimental_activeTools:L,activeTools:M=L,experimental_repairToolCall:C,experimental_transform:E,experimental_download:A,includeRawChunks:T=!1,onChunk:j,onError:R=({error:Q0})=>{console.error(Q0)},onFinish:k,onAbort:y,onStepFinish:b,experimental_context:h,_internal:{now:a=ub6,generateId:f=lb6,currentDate:S=()=>new Date}={},...m}){let Q0=EW1(K);return new pb6({model:AW1(Q),telemetry:U,headers:H,settings:m,maxRetries:Z,abortSignal:Ib6($,Q0!=null?AbortSignal.timeout(Q0):void 0),system:J,prompt:G,messages:W,tools:X,toolChoice:Y,transforms:gy(E),activeTools:M,repairToolCall:C,stopConditions:gy(F),output:q,providerOptions:B,prepareStep:D,includeRawChunks:T,onChunk:j,onError:R,onFinish:k,onAbort:y,onStepFinish:b,now:a,currentDate:S,generateId:f,experimental_context:h,download:A})}function db6(Q){let X=void 0,Y="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:X,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(X==null)X=$.id;else if($.id!==X){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Y+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await Q.parsePartialOutput({text:Y});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var pb6=class{constructor({model:Q,telemetry:X,headers:Y,settings:J,maxRetries:G,abortSignal:W,system:Z,prompt:$,messages:K,tools:H,toolChoice:F,transforms:V,activeTools:q,repairToolCall:U,stopConditions:D,output:B,providerOptions:L,prepareStep:M,includeRawChunks:C,now:E,currentDate:A,generateId:T,onChunk:j,onError:R,onFinish:k,onAbort:y,onStepFinish:b,experimental_context:h,download:a}){this._totalUsage=new QF,this._finishReason=new QF,this._rawFinishReason=new QF,this._steps=new QF,this.outputSpecification=B,this.includeRawChunks=C,this.tools=H;let f,S=[],m=[],Q0=void 0,r=void 0,J0=void 0,z0={},Z0=[],V0=[],T0=new Map,_0,K1={},N0={},G0=new TransformStream({async transform(u0,A0){var S0,B1,p1,T6;A0.enqueue(u0);let{part:l0}=u0;if(l0.type==="text-delta"||l0.type==="reasoning-delta"||l0.type==="source"||l0.type==="tool-call"||l0.type==="tool-result"||l0.type==="tool-input-start"||l0.type==="tool-input-delta"||l0.type==="raw")await(j==null?void 0:j({chunk:l0}));if(l0.type==="error")await R({error:Gb6(l0.error)});if(l0.type==="text-start")K1[l0.id]={type:"text",text:"",providerMetadata:l0.providerMetadata},S.push(K1[l0.id]);if(l0.type==="text-delta"){let d0=K1[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}d0.text+=l0.text,d0.providerMetadata=(S0=l0.providerMetadata)!=null?S0:d0.providerMetadata}if(l0.type==="text-end"){let d0=K1[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`text part ${l0.id} not found`},partialOutput:void 0});return}d0.providerMetadata=(B1=l0.providerMetadata)!=null?B1:d0.providerMetadata,delete K1[l0.id]}if(l0.type==="reasoning-start")N0[l0.id]={type:"reasoning",text:"",providerMetadata:l0.providerMetadata},S.push(N0[l0.id]);if(l0.type==="reasoning-delta"){let d0=N0[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}d0.text+=l0.text,d0.providerMetadata=(p1=l0.providerMetadata)!=null?p1:d0.providerMetadata}if(l0.type==="reasoning-end"){let d0=N0[l0.id];if(d0==null){A0.enqueue({part:{type:"error",error:`reasoning part ${l0.id} not found`},partialOutput:void 0});return}d0.providerMetadata=(T6=l0.providerMetadata)!=null?T6:d0.providerMetadata,delete N0[l0.id]}if(l0.type==="file")S.push({type:"file",file:l0.file});if(l0.type==="source")S.push(l0);if(l0.type==="tool-call")S.push(l0);if(l0.type==="tool-result"&&!l0.preliminary)S.push(l0);if(l0.type==="tool-approval-request")S.push(l0);if(l0.type==="tool-error")S.push(l0);if(l0.type==="start-step")S=[],N0={},K1={},z0=l0.request,Z0=l0.warnings;if(l0.type==="finish-step"){let d0=await xG1({content:S,tools:H}),C0=new jb6({content:S,finishReason:l0.finishReason,rawFinishReason:l0.rawFinishReason,usage:l0.usage,warnings:Z0,request:z0,response:{...l0.response,messages:[...m,...d0]},providerMetadata:l0.providerMetadata});await(b==null?void 0:b(C0)),MW1({warnings:Z0,provider:Q.provider,model:Q.modelId}),V0.push(C0),m.push(...d0),f.resolve()}if(l0.type==="finish")J0=l0.totalUsage,Q0=l0.finishReason,r=l0.rawFinishReason},async flush(u0){try{if(V0.length===0){let p1=(W==null?void 0:W.aborted)?W.reason:new Fy6({message:"No output generated. Check the stream for errors."});U0._finishReason.reject(p1),U0._rawFinishReason.reject(p1),U0._totalUsage.reject(p1),U0._steps.reject(p1);return}let A0=Q0!=null?Q0:"other",S0=J0!=null?J0:y80();U0._finishReason.resolve(A0),U0._rawFinishReason.resolve(r),U0._totalUsage.resolve(S0),U0._steps.resolve(V0);let B1=V0[V0.length-1];await(k==null?void 0:k({finishReason:B1.finishReason,rawFinishReason:B1.rawFinishReason,totalUsage:S0,usage:B1.usage,content:B1.content,text:B1.text,reasoningText:B1.reasoningText,reasoning:B1.reasoning,files:B1.files,sources:B1.sources,toolCalls:B1.toolCalls,staticToolCalls:B1.staticToolCalls,dynamicToolCalls:B1.dynamicToolCalls,toolResults:B1.toolResults,staticToolResults:B1.staticToolResults,dynamicToolResults:B1.dynamicToolResults,request:B1.request,response:B1.response,warnings:B1.warnings,providerMetadata:B1.providerMetadata,steps:V0,experimental_context:h})),_0.setAttributes(await yU({telemetry:X,attributes:{"ai.response.finishReason":A0,"ai.response.text":{output:()=>B1.text},"ai.response.toolCalls":{output:()=>{var p1;return((p1=B1.toolCalls)==null?void 0:p1.length)?JSON.stringify(B1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(B1.providerMetadata),"ai.usage.inputTokens":S0.inputTokens,"ai.usage.outputTokens":S0.outputTokens,"ai.usage.totalTokens":S0.totalTokens,"ai.usage.reasoningTokens":S0.reasoningTokens,"ai.usage.cachedInputTokens":S0.cachedInputTokens}}))}catch(A0){u0.error(A0)}finally{_0.end()}}}),R0=gb6();this.addStream=R0.addStream,this.closeStream=R0.close;let l1=R0.stream.getReader(),b1=new ReadableStream({async start(u0){u0.enqueue({type:"start"})},async pull(u0){function A0(){y==null||y({steps:V0}),u0.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:R5(W.reason)}:{}}),u0.close()}try{let{done:S0,value:B1}=await l1.read();if(S0){u0.close();return}if(W==null?void 0:W.aborted){A0();return}u0.enqueue(B1)}catch(S0){if(b7(S0)&&(W==null?void 0:W.aborted))A0();else u0.error(S0)}},cancel(u0){return R0.stream.cancel(u0)}});for(let u0 of V)b1=b1.pipeThrough(u0({tools:H,stopStream(){R0.terminate()}}));this.baseStream=b1.pipeThrough(db6(B!=null?B:d80())).pipeThrough(G0);let{maxRetries:b0,retry:L0}=Ub6({maxRetries:G,abortSignal:W}),$0=Kb6(X),P0=dy6(J),H0=Wb6({model:Q,telemetry:X,headers:Y,settings:{...P0,maxRetries:b0}}),U0=this;l80({name:"ai.streamText",attributes:yU({telemetry:X,attributes:{...u80({operationId:"ai.streamText",telemetry:X}),...H0,"ai.prompt":{input:()=>JSON.stringify({system:Z,prompt:$,messages:K})}}}),tracer:$0,endWhenDone:!1,fn:async(u0)=>{_0=u0;let A0=await Jb6({system:Z,prompt:$,messages:K}),S0=A0.messages,B1=[],{approvedToolApprovals:p1,deniedToolApprovals:T6}=Bb6({messages:S0});if(T6.length>0||p1.length>0){let d0=[...p1,...T6].filter((A1)=>A1.toolCall.providerExecuted),C0=p1.filter((A1)=>!A1.toolCall.providerExecuted),Y1=T6.filter((A1)=>!A1.toolCall.providerExecuted),I4=T6.filter((A1)=>A1.toolCall.providerExecuted),u6,o8=new ReadableStream({start(A1){u6=A1}});U0.addStream(o8);try{for(let I0 of[...Y1,...I4])u6==null||u6.enqueue({type:"tool-output-denied",toolCallId:I0.toolCall.toolCallId,toolName:I0.toolCall.toolName});let A1=[];if(await Promise.all(C0.map(async(I0)=>{let R4=await yW1({toolCall:I0.toolCall,tools:H,tracer:$0,telemetry:X,messages:S0,abortSignal:W,experimental_context:h,onPreliminaryToolResult:(O)=>{u6==null||u6.enqueue(O)}});if(R4!=null)u6==null||u6.enqueue(R4),A1.push(R4)})),d0.length>0)B1.push({role:"tool",content:d0.map((I0)=>({type:"tool-approval-response",approvalId:I0.approvalResponse.approvalId,approved:I0.approvalResponse.approved,reason:I0.approvalResponse.reason,providerExecuted:!0}))});if(A1.length>0||Y1.length>0){let I0=[];for(let R4 of A1)I0.push({type:"tool-result",toolCallId:R4.toolCallId,toolName:R4.toolName,output:await bU({toolCallId:R4.toolCallId,input:R4.input,tool:H==null?void 0:H[R4.toolName],output:R4.type==="tool-result"?R4.output:R4.error,errorMode:R4.type==="tool-error"?"json":"none"})});for(let R4 of Y1)I0.push({type:"tool-result",toolCallId:R4.toolCall.toolCallId,toolName:R4.toolCall.toolName,output:{type:"execution-denied",reason:R4.approvalResponse.reason}});B1.push({role:"tool",content:I0})}}finally{u6==null||u6.close()}}m.push(...B1);async function l0({currentStep:d0,responseMessages:C0,usage:Y1}){var I4,u6,o8,A1,I0,R4;let O=U0.includeRawChunks;f=new QF;let _=[...S0,...C0],e=await(M==null?void 0:M({model:Q,steps:V0,stepNumber:V0.length,messages:_,experimental_context:h})),Y0=AW1((I4=e==null?void 0:e.model)!=null?I4:Q),z=await gy6({prompt:{system:(u6=e==null?void 0:e.system)!=null?u6:A0.system,messages:(o8=e==null?void 0:e.messages)!=null?o8:_},supportedUrls:await Y0.supportedUrls,download:a}),{toolChoice:w,tools:v}=await cy6({tools:H,toolChoice:(A1=e==null?void 0:e.toolChoice)!=null?A1:F,activeTools:(I0=e==null?void 0:e.activeTools)!=null?I0:q});h=(R4=e==null?void 0:e.experimental_context)!=null?R4:h;let c=i80(L,e==null?void 0:e.providerOptions),{result:{stream:s,response:u,request:M0},doStreamSpan:t0,startTimestampMs:T1}=await L0(()=>l80({name:"ai.streamText.doStream",attributes:yU({telemetry:X,attributes:{...u80({operationId:"ai.streamText.doStream",telemetry:X}),...H0,"ai.model.provider":Y0.provider,"ai.model.id":Y0.modelId,"ai.prompt.messages":{input:()=>Hb6(z)},"ai.prompt.tools":{input:()=>v==null?void 0:v.map((J1)=>JSON.stringify(J1))},"ai.prompt.toolChoice":{input:()=>w!=null?JSON.stringify(w):void 0},"gen_ai.system":Y0.provider,"gen_ai.request.model":Y0.modelId,"gen_ai.request.frequency_penalty":P0.frequencyPenalty,"gen_ai.request.max_tokens":P0.maxOutputTokens,"gen_ai.request.presence_penalty":P0.presencePenalty,"gen_ai.request.stop_sequences":P0.stopSequences,"gen_ai.request.temperature":P0.temperature,"gen_ai.request.top_k":P0.topK,"gen_ai.request.top_p":P0.topP}}),tracer:$0,endWhenDone:!1,fn:async(J1)=>({startTimestampMs:E(),doStreamSpan:J1,result:await Y0.doStream({...P0,tools:v,toolChoice:w,responseFormat:await(B==null?void 0:B.responseFormat),prompt:z,providerOptions:c,abortSignal:W,headers:Y,includeRawChunks:O})})})),v0=mb6({tools:H,generatorStream:s,tracer:$0,telemetry:X,system:Z,messages:_,repairToolCall:U,abortSignal:W,experimental_context:h,generateId:T}),L1=M0!=null?M0:{},R6=[],C8=[],_6,wX={},y5="other",h7=void 0,p0=y80(),U6,GQ=!0,y8={id:T(),timestamp:A(),modelId:Q.modelId},X1="";U0.addStream(v0.pipeThrough(new TransformStream({async transform(J1,H4){var MX,t$,MP,DQ,WF;if(J1.type==="stream-start"){_6=J1.warnings;return}if(GQ){let WQ=E()-T1;GQ=!1,t0.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":WQ}),t0.setAttributes({"ai.response.msToFirstChunk":WQ}),H4.enqueue({type:"start-step",request:L1,warnings:_6!=null?_6:[]})}let dy=J1.type;switch(dy){case"tool-approval-request":case"text-start":case"text-end":{H4.enqueue(J1);break}case"text-delta":{if(J1.delta.length>0)H4.enqueue({type:"text-delta",id:J1.id,text:J1.delta,providerMetadata:J1.providerMetadata}),X1+=J1.delta;break}case"reasoning-start":case"reasoning-end":{H4.enqueue(J1);break}case"reasoning-delta":{H4.enqueue({type:"reasoning-delta",id:J1.id,text:J1.delta,providerMetadata:J1.providerMetadata});break}case"tool-call":{H4.enqueue(J1),R6.push(J1);break}case"tool-result":{if(H4.enqueue(J1),!J1.preliminary)C8.push(J1);break}case"tool-error":{H4.enqueue(J1),C8.push(J1);break}case"response-metadata":{y8={id:(MX=J1.id)!=null?MX:y8.id,timestamp:(t$=J1.timestamp)!=null?t$:y8.timestamp,modelId:(MP=J1.modelId)!=null?MP:y8.modelId};break}case"finish":{p0=J1.usage,y5=J1.finishReason,h7=J1.rawFinishReason,U6=J1.providerMetadata;let WQ=E()-T1;t0.addEvent("ai.stream.finish"),t0.setAttributes({"ai.response.msToFinish":WQ,"ai.response.avgOutputTokensPerSecond":1000*((DQ=p0.outputTokens)!=null?DQ:0)/WQ});break}case"file":{H4.enqueue(J1);break}case"source":{H4.enqueue(J1);break}case"tool-input-start":{wX[J1.id]=J1.toolName;let WQ=H==null?void 0:H[J1.toolName];if((WQ==null?void 0:WQ.onInputStart)!=null)await WQ.onInputStart({toolCallId:J1.id,messages:_,abortSignal:W,experimental_context:h});H4.enqueue({...J1,dynamic:(WF=J1.dynamic)!=null?WF:(WQ==null?void 0:WQ.type)==="dynamic",title:WQ==null?void 0:WQ.title});break}case"tool-input-end":{delete wX[J1.id],H4.enqueue(J1);break}case"tool-input-delta":{let WQ=wX[J1.id],py=H==null?void 0:H[WQ];if((py==null?void 0:py.onInputDelta)!=null)await py.onInputDelta({inputTextDelta:J1.delta,toolCallId:J1.id,messages:_,abortSignal:W,experimental_context:h});H4.enqueue(J1);break}case"error":{H4.enqueue(J1),y5="error";break}case"raw":{if(O)H4.enqueue(J1);break}default:throw Error(`Unknown chunk type: ${dy}`)}},async flush(J1){let H4=R6.length>0?JSON.stringify(R6):void 0;try{t0.setAttributes(await yU({telemetry:X,attributes:{"ai.response.finishReason":y5,"ai.response.text":{output:()=>X1},"ai.response.toolCalls":{output:()=>H4},"ai.response.id":y8.id,"ai.response.model":y8.modelId,"ai.response.timestamp":y8.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(U6),"ai.usage.inputTokens":p0.inputTokens,"ai.usage.outputTokens":p0.outputTokens,"ai.usage.totalTokens":p0.totalTokens,"ai.usage.reasoningTokens":p0.reasoningTokens,"ai.usage.cachedInputTokens":p0.cachedInputTokens,"gen_ai.response.finish_reasons":[y5],"gen_ai.response.id":y8.id,"gen_ai.response.model":y8.modelId,"gen_ai.usage.input_tokens":p0.inputTokens,"gen_ai.usage.output_tokens":p0.outputTokens}}))}catch(DQ){}finally{t0.end()}J1.enqueue({type:"finish-step",finishReason:y5,rawFinishReason:h7,usage:p0,providerMetadata:U6,response:{...y8,headers:u==null?void 0:u.headers}});let MX=Vb6(Y1,p0);await f.promise;let t$=R6.filter((DQ)=>DQ.providerExecuted!==!0),MP=C8.filter((DQ)=>DQ.providerExecuted!==!0);for(let DQ of R6){if(DQ.providerExecuted!==!0)continue;let WF=H==null?void 0:H[DQ.toolName];if((WF==null?void 0:WF.type)==="provider"&&WF.supportsDeferredResults){if(!C8.some((WQ)=>WQ.type==="tool-result"&&WQ.toolCallId===DQ.toolCallId))T0.set(DQ.toolCallId,{toolName:DQ.toolName})}}for(let DQ of C8)if(DQ.type==="tool-result")T0.delete(DQ.toolCallId);if((t$.length>0&&MP.length===t$.length||T0.size>0)&&!await Cb6({stopConditions:D,steps:V0})){C0.push(...await xG1({content:V0[V0.length-1].content,tools:H}));try{await l0({currentStep:d0+1,responseMessages:C0,usage:MX})}catch(DQ){J1.enqueue({type:"error",error:DQ}),U0.closeStream()}}else J1.enqueue({type:"finish",finishReason:y5,rawFinishReason:h7,totalUsage:MX}),U0.closeStream()}})))}await l0({currentStep:0,responseMessages:B1,usage:y80()})}}).catch((u0)=>{U0.addStream(new ReadableStream({start(A0){A0.enqueue({type:"error",error:u0}),A0.close()}})),U0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((Q)=>Q[Q.length-1])}get content(){return this.finalStep.then((Q)=>Q.content)}get warnings(){return this.finalStep.then((Q)=>Q.warnings)}get providerMetadata(){return this.finalStep.then((Q)=>Q.providerMetadata)}get text(){return this.finalStep.then((Q)=>Q.text)}get reasoningText(){return this.finalStep.then((Q)=>Q.reasoningText)}get reasoning(){return this.finalStep.then((Q)=>Q.reasoning)}get sources(){return this.finalStep.then((Q)=>Q.sources)}get files(){return this.finalStep.then((Q)=>Q.files)}get toolCalls(){return this.finalStep.then((Q)=>Q.toolCalls)}get staticToolCalls(){return this.finalStep.then((Q)=>Q.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((Q)=>Q.dynamicToolCalls)}get toolResults(){return this.finalStep.then((Q)=>Q.toolResults)}get staticToolResults(){return this.finalStep.then((Q)=>Q.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((Q)=>Q.dynamicToolResults)}get usage(){return this.finalStep.then((Q)=>Q.usage)}get request(){return this.finalStep.then((Q)=>Q.request)}get response(){return this.finalStep.then((Q)=>Q.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[Q,X]=this.baseStream.tee();return this.baseStream=X,Q}get textStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){if(Q.type==="text-delta")X.enqueue(Q.text)}})))}get fullStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){X.enqueue(Q)}})))}async consumeStream(Q){var X;try{await xb6({stream:this.fullStream,onError:Q==null?void 0:Q.onError})}catch(Y){(X=Q==null?void 0:Q.onError)==null||X.call(Q,Y)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return xy(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:Q},X){if(Q!=null)X.enqueue(Q)}})))}get output(){return this.finalStep.then((Q)=>{var X;return((X=this.outputSpecification)!=null?X:d80()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})})}toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=R5}={}){let H=X!=null?vb6({originalMessages:Q,responseMessageId:X}):void 0,F=(q)=>{var U;let D=(U=this.tools)==null?void 0:U[q.toolName];if(D==null)return q.dynamic;return(D==null?void 0:D.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,U)=>{let D=J==null?void 0:J({part:q}),B=q.type;switch(B){case"text-start":{U.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{U.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{U.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{U.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)U.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{U.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{U.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")U.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")U.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);U.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{U.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)U.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else U.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{U.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);U.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);U.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{U.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{U.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{U.enqueue({type:"start-step"});break}case"finish-step":{U.enqueue({type:"finish-step"});break}case"start":{if(Z)U.enqueue({type:"start",...D!=null?{messageMetadata:D}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)U.enqueue({type:"finish",finishReason:q.finishReason,...D!=null?{messageMetadata:D}:{}});break}case"abort":{U.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${B}`)}if(D!=null&&B!=="start"&&B!=="finish")U.enqueue({type:"message-metadata",messageMetadata:D})}}));return xy(fb6({stream:V,messageId:H!=null?H:X==null?void 0:X(),originalMessages:Q,onFinish:Y,onError:K}))}pipeUIMessageStreamToResponse(Q,{originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){hb6({response:Q,stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(Q,X){Sb6({response:Q,textStream:this.textStream,...X})}toUIMessageStreamResponse({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return kb6({stream:this.toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(Q){return Rb6({textStream:this.textStream,...Q})}};async function mW1(Q,X){let Y=[];if(X==null?void 0:X.ignoreIncompleteToolCalls)Q=Q.map((J)=>({...J,parts:J.parts.filter((G)=>!OP(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of Q)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Y.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Y.push({role:"user",content:J.parts.map((G)=>{var W;if(f80(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(h80(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(b80(G))return(W=X==null?void 0:X.convertDataPart)==null?void 0:W.call(X,G)}).filter(Z51)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let D of G)if(f80(D))q.push({type:"text",text:D.text,...D.providerMetadata!=null?{providerOptions:D.providerMetadata}:{}});else if(h80(D))q.push({type:"file",mediaType:D.mediaType,filename:D.filename,data:D.url});else if(gG1(D))q.push({type:"reasoning",text:D.text,providerOptions:D.providerMetadata});else if(OP(D)){let B=x80(D);if(D.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:D.toolCallId,toolName:B,input:D.state==="output-error"?(Z=D.input)!=null?Z:("rawInput"in D)?D.rawInput:void 0:D.input,providerExecuted:D.providerExecuted,...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}}),D.approval!=null)q.push({type:"tool-approval-request",approvalId:D.approval.id,toolCallId:D.toolCallId});if(D.providerExecuted===!0&&D.state!=="approval-responded"&&(D.state==="output-available"||D.state==="output-error"))q.push({type:"tool-result",toolCallId:D.toolCallId,toolName:B,output:await bU({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:($=X==null?void 0:X.tools)==null?void 0:$[B],errorMode:D.state==="output-error"?"json":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}})}}else if(b80(D)){let B=(K=X==null?void 0:X.convertDataPart)==null?void 0:K.call(X,D);if(B!=null)q.push(B)}else throw Error(`Unsupported part: ${D}`);Y.push({role:"assistant",content:q});let U=G.filter((D)=>{var B;return OP(D)&&(D.providerExecuted!==!0||((B=D.approval)==null?void 0:B.approved)!=null)});if(U.length>0){let D=[];for(let B of U){if(((H=B.approval)==null?void 0:H.approved)!=null)D.push({type:"tool-approval-response",approvalId:B.approval.id,approved:B.approval.approved,reason:B.approval.reason,providerExecuted:B.providerExecuted});if(B.providerExecuted===!0)continue;switch(B.state){case"output-denied":{D.push({type:"tool-result",toolCallId:B.toolCallId,toolName:x80(B),output:{type:"error-text",value:(F=B.approval.reason)!=null?F:"Tool execution denied."},...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=x80(B);D.push({type:"tool-result",toolCallId:B.toolCallId,toolName:L,output:await bU({toolCallId:B.toolCallId,input:B.input,output:B.state==="output-error"?B.errorText:B.output,tool:(V=X==null?void 0:X.tools)==null?void 0:V[L],errorMode:B.state==="output-error"?"text":"none"}),...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}});break}}}if(D.length>0)Y.push({role:"tool",content:D})}G=[]}for(let Z of J.parts)if(f80(Z)||gG1(Z)||h80(Z)||OP(Z)||b80(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new Py6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Y}var Ml4=OX(()=>z9(N.array(N.object({id:N.string(),role:N.enum(["system","user","assistant"]),metadata:N.unknown().optional(),parts:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("reasoning"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("file"),mediaType:N.string(),filename:N.string().optional(),url:N.string(),providerMetadata:i1.optional()}),N.object({type:N.literal("step-start")}),N.object({type:N.string().startsWith("data-"),id:N.string().optional(),data:N.unknown()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-streaming"),input:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-error"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-denied"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-streaming"),providerExecuted:N.boolean().optional(),input:N.unknown().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-error"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-denied"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var Tl4=XW({prefix:"aiobj",size:24});var El4=XW({prefix:"aiobj",size:24});function lW1({messages:Q,reasoning:X="none",toolCalls:Y=[],emptyMessages:J="remove"}){if(X==="all"||X==="before-last-message")Q=Q.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||X==="before-last-message"&&W===Q.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Y==="none")Y=[];else if(Y==="all")Y=[{type:"all"}];else if(Y==="before-last-message")Y=[{type:"before-last-message"}];else if(typeof Y==="string")Y=[{type:Y}];for(let G of Y){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of Q.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}Q=Q.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=Q.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")Q=Q.filter((G)=>G.content.length>0);return Q}var cb6="AI_NoSuchProviderError",nb6=`vercel.ai.error.${cb6}`,ib6=Symbol.for(nb6),ab6;ab6=ib6;W1();function dW1(Q){let X=Q.trim();if(!X)return null;if(X.startsWith("event:"))return null;if(X.startsWith("id:"))return null;if(X.startsWith("retry:"))return null;let Y=X;if(Y.startsWith("data:")){if(Y=Y.slice(5).trim(),!Y)return null;if(Y==="[DONE]")return null}try{return JSON.parse(Y)}catch(J){return console.warn("[llm-provider] Failed to parse stream line as JSON. Skipping line.",{line:Y.slice(0,200)},J),null}}function rb6(Q){if(!Q.body)throw Error("Response body is null");let X="";return Q.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(Y,J){X+=Y;let G=X.split(`
1078
1078
  `);X=G.pop()??"";for(let W of G)if(W.trim()){let Z=dW1(W);if(Z)J.enqueue(Z)}},flush(Y){if(X.trim()){let J=dW1(X);if(J)Y.enqueue(J)}}}))}var ob6=(Q)=>{return Object.fromEntries(Object.entries(Q).map(([X,Y])=>[X,Y.map((J)=>new RegExp(J))]))},pW1=(Q)=>{return{imageModel:()=>{throw Error("Image models are not supported by this provider")},textEmbeddingModel:()=>{throw Error("Text embedding models are not supported by this provider")},listModels:async()=>{return await Q.COLLECTION_LLM_LIST({})},languageModel:(X)=>{let Y=QW(()=>Q.LLM_METADATA({modelId:X}).then((J)=>ob6(J.supportedUrls)));return{specificationVersion:"v2",provider:"llm-binding",modelId:X,supportedUrls:Y,doGenerate:async(J)=>{let G=await Q.LLM_DO_GENERATE({callOptions:J,modelId:X}),W=G.response?.timestamp?new Date(G.response.timestamp):void 0;return{...G,response:{...G.response,timestamp:W},usage:{inputTokens:G.usage.inputTokens??void 0,outputTokens:G.usage.outputTokens??void 0,totalTokens:G.usage.totalTokens??void 0,reasoningTokens:G.usage.reasoningTokens??void 0}}},doStream:async(J)=>{let G=await Q.LLM_DO_STREAM({callOptions:J,modelId:X});if(!G.ok)throw Error(`Streaming failed for model ${X} with the status code: ${G.status}
1079
1079
  ${await G.text()}`);return{stream:rb6(G),response:{headers:Object.fromEntries(G.headers?.entries()??[])}}}}}}};var sb6=32768,tb6=50,eb6=N.object({messages:N.any(),model:N.object({id:N.string(),connectionId:N.string(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),limits:N.object({contextWindow:N.number().optional(),maxOutputTokens:N.number().optional()}).optional()}).loose(),gateway:N.object({id:N.string()}).loose(),stream:N.boolean().optional(),temperature:N.number().optional(),maxWindowSize:N.number().optional(),thread_id:N.string().optional()}),cW1=new d9;function Qf6(Q,X){if(!Q.organization)throw Error("Organization context is required");if(Q.organization.slug!==X)throw Error("Organization slug mismatch");return Q.organization}async function Xf6(Q,X,Y){let J=await Q.storage.connections.findById(Y);if(!J)return null;if(J.organization_id!==X)throw Error("Connection does not belong to organization");if(J.status!=="active")throw Error(`Connection is ${J.status.toUpperCase()}, not active`);return J}var Yf6=async(Q,X)=>{let J=(await Q.listTools()).tools.map((G)=>{let{name:W,title:Z,description:$,inputSchema:K,outputSchema:H}=G;return[W,N80({title:Z??W,description:$,inputSchema:r$(K),outputSchema:H?r$(H):void 0,execute:(F,V)=>{let q=X&&Object.keys(X).length>0?{...F,_meta:{properties:X}}:F;return Q.callTool({name:G.name,arguments:q},aG,{signal:V.abortSignal})},toModelOutput:({output:F})=>{if(F.isError)return{type:"error-text",value:F.content.map((q)=>q.type==="text"?q.text:null).filter(Boolean).join(`
1080
- `)||"Unknown error"};if("structuredContent"in F)return{type:"json",value:F.structuredContent};return{type:"content",value:F.content}}})]});return Object.fromEntries(J)};function Jf6(Q,X){let Y=Ny(new URL(Q.url)),J=`${Y.protocol}//${Y.host}`,G=new Headers,W=["cookie","authorization"];for(let Z of W)if(Q.headers.has(Z))G.set(Z,Q.headers.get(Z));return new I7(new URL(`/mcp/gateway/${X}`,J),{requestInit:{headers:G}})}cW1.post("/:org/models/stream",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("org"),J=null;try{let G=Qf6(X,Y),W=await Q.req.json(),Z=eb6.safeParse(W);if(!Z.success)return Q.json({error:"Invalid request body",details:Z.error.issues},400);let $=Z.data,{model:K,gateway:H,messages:F,temperature:V,maxWindowSize:q=tb6,thread_id:U}=$,D=K.limits?.maxOutputTokens??sb6,B=Jf6(Q.req.raw,H.id),L=new _J({name:"mcp-mesh-proxy",version:"1.0.0"}),[M,C]=await Promise.all([mW1(F,{ignoreIncompleteToolCalls:!0}),Xf6(X,G.id,K.connectionId),L.connect(B)]);if(!C)return Q.json({error:`Model connection not found: ${K.connectionId}`},404);J=L;let E=M.find((f)=>f.role==="system"),A=E?.role==="system"?E.content:void 0,T=M.filter((f)=>f.role!=="system"),j=lW1({messages:T,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-q),R=U?{thread_id:U}:void 0,[k,y]=await Promise.all([X.createMCPProxy(C),Yf6(L,R)]),b=U91.forClient(k),h=pW1(b).languageModel(K.id);return uW1({model:h,system:A,messages:j,tools:y,temperature:V,maxOutputTokens:D,abortSignal:Q.req.raw.signal,stopWhen:a80(30),onError:async(f)=>{console.error("[models:stream] Error",f),await L.close().catch(console.error)},onFinish:async()=>{await L.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:f})=>{if(f.type==="start")return{gateway:H,model:K,created_at:new Date,thread_id:U};if(f.type==="finish-step")return{usage:{...f.usage,providerMetadata:f.providerMetadata}};return{}}})}catch(G){let W=G;if(await J?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:Y})),Q.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:Y,error:W.message,stack:W.stack})),Q.json({error:W.message},500)}});var nW1=cW1;R3();var my=null;async function Gf6(Q,X){let J=(await Q.storage.connections.list(X)).find((G)=>G.connection_url?.startsWith(ps0));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function Wf6(Q){let X=new URLSearchParams;if(Q){let[Y,J]=Q.split("/");if(Y)X.set("workspace_hint",Y);if(J)X.set("project_hint",J)}else X.set("auto_personal","true");return X}var Zf6=new iW1.PrometheusSerializer,$f6=()=>ht(v7),Kf6=()=>ft(v7);function aW1(Q={}){let X=Q.database??Kv();if(my&&my.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(my.stop()).catch((Z)=>{console.error("[EventBus] Error stopping previous worker:",Z)});let Y;if(Q.eventBus)Y=Q.eventBus;else Y=eX1(X);my=Y;let J=new d9;J.use("/*",Rv0({origin:(Z)=>{if(Z.includes("localhost")||Z.includes("127.0.0.1"))return Z;return Z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),J.use("*",vv0()),J.use("*",async(Z,$)=>{if(await $(),Z.res.status>=500){let H=await Z.res.clone().text();console.error(`[5xx Response] ${Z.req.method} ${Z.req.path} - ${Z.res.status}:`,H)}}),J.get(YP.HEALTH,(Z)=>{return Z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),J.get(YP.METRICS,async(Z)=>{try{let $=await Xl.collect(),K=Zf6.serialize($.resourceMetrics);return Z.text(K,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch($){return console.error("Failed to collect metrics:",$),Z.text("# Error collecting metrics",500)}}),J.route("/api/auth/custom",YY1),J.all("/api/auth/*",async(Z)=>{return await v7.handler(Z.req.raw)}),J.route("/",SX1),J.all("/oauth-proxy/:connectionId/*",async(Z)=>{let $=Z.req.param("connectionId"),K=Z.req.path.split("/").filter(Boolean),H=K[K.length-1],F=Z.get("meshContext");if(!F)F=await n$.create(Z.req.raw),Z.set("meshContext",F);let V=await F.storage.connections.findById($);if(!V?.connection_url)return Z.json({error:"Connection not found"},404);let q=await Dy(V.connection_url),U,D=new URL(V.connection_url);if(q.ok)U=(await q.json()).authorization_servers?.[0];if(!U)U=D.origin;let B=await m40(U);if(!B.ok)return Z.json({error:"Failed to get auth server metadata"},502);let L=await B.json(),M;if(H==="authorize")M=L.authorization_endpoint;else if(H==="token")M=L.token_endpoint;else if(H==="register")M=L.registration_endpoint;if(!M)return Z.json({error:`Unknown OAuth endpoint: ${H}`},404);let C=new URL(M),E=new URL(Z.req.url);if(C.search=E.search,H==="authorize"){if(C.searchParams.has("resource"))C.searchParams.set("resource",V.connection_url);if(cs0(V.connection_url))try{let h=await Gf6(F,V.organization_id),a=Wf6(h);for(let[f,S]of a)C.searchParams.set(f,S)}catch(h){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",h)}return Z.redirect(C.toString(),302)}let A={Accept:Z.req.header("Accept")||"application/json"},T=Z.req.header("Content-Type");if(T)A["Content-Type"]=T;let j=Z.req.header("Authorization");if(j)A.Authorization=j;let R;if(Z.req.method!=="GET"&&Z.req.method!=="HEAD")if(H==="token"&&T?.includes("application/x-www-form-urlencoded")){let h=await Z.req.formData();if(h.has("resource"))h.set("resource",V.connection_url);let a=new URLSearchParams;for(let[f,S]of h.entries())a.append(f,S.toString());R=a.toString()}else R=Z.req.raw.body??void 0;let k=await fetch(C.toString(),{method:Z.req.method,headers:A,body:R,duplex:"half",redirect:"manual"}),y=new Headers,b=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[h,a]of k.headers.entries())if(!b.includes(h.toLowerCase()))y.set(h,a);return new Response(k.body,{status:k.status,statusText:k.statusText,headers:y})}),J.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(Z)=>{let K=await $f6()(Z.req.raw),H=await K.json();return Response.json(H,K)});let G=async(Z)=>{let K=await Kf6()(Z.req.raw),H=await K.json();return Response.json(H,K)};J.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",G),n$.set(uX1({db:X.db,databaseType:X.type,auth:v7,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:jD,meter:Yv0},eventBus:Y})),Promise.resolve(Y.start()).then(()=>{console.log("[EventBus] Worker started")}),J.use("*",async(Z,$)=>{if(dX1(Z.req.path))return $();let K=await n$.create(Z.req.raw);return Z.set("meshContext",K),$()}),J.get("/api/tools/management",(Z)=>{return Z.json({tools:ql,grouped:vD()})});let W=async(Z,$)=>{let K=Z.var.meshContext;if(!K.auth.user?.id&&!K.auth.apiKey?.id){let H=new URL(Z.req.url);return Z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await $()};return J.use("/mcp/:connectionId?",W),J.use("/mcp/gateway/:gatewayId?",W),J.route("/mcp",dY1),J.route("/mcp",cY1),J.route("/mcp",xX1),J.route("/api",nW1),J.post("/org/:organizationId/events/:type",async(Z)=>{let $=Z.req.param("organizationId");return await Z.var.meshContext.eventBus.publish($,Ew.SELF($),{data:await Z.req.json(),type:`public:${Z.req.param("type")}`,subject:Z.req.query("subject"),deliverAt:Z.req.query("deliverAt"),cron:Z.req.query("cron")}),Z.json({success:!0})}),J.notFound((Z)=>{return Z.json({error:"Not Found",path:Z.req.path},404)}),J.onError((Z,$)=>{console.error("Server error :",Z);let K=Z instanceof Error?Z.message:"Unknown error";return $.json({error:"Internal Server Error",message:K},500)}),J}var rW1=parseInt(process.env.PORT||"3000",10),ly="\x1B[0m",Hf6="\x1B[1m",Ff6="\x1B[2m",Vf6="\x1B[32m",qf6="\x1B[36m",zf6="\x1B[4m",Uf6=`http://localhost:${rW1}`,Bf6=$v0({clientDir:Zv0(import.meta.url,"../client"),isServerPath:lX1}),Df6=aW1();console.log("");console.log(`${Vf6}\u2713${ly} ${Hf6}Ready${ly}`);console.log("");console.log(` ${Ff6}Open in browser:${ly} ${qf6}${zf6}${Uf6}${ly}`);console.log("");Bun.serve({idleTimeout:0,port:rW1,hostname:"0.0.0.0",fetch:async(Q)=>{return await Bf6(Q)??Df6.fetch(Q)},development:!1});
1080
+ `)||"Unknown error"};if("structuredContent"in F)return{type:"json",value:F.structuredContent};return{type:"content",value:F.content}}})]});return Object.fromEntries(J)};function Jf6(Q,X){let Y=Ny(new URL(Q.url)),J=`${Y.protocol}//${Y.host}`,G=new Headers,W=["cookie","authorization"];for(let Z of W)if(Q.headers.has(Z))G.set(Z,Q.headers.get(Z));return new I7(new URL(`/mcp/gateway/${X}`,J),{requestInit:{headers:G}})}cW1.post("/:org/models/stream",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("org"),J=null;try{let G=Qf6(X,Y),W=await Q.req.json(),Z=eb6.safeParse(W);if(!Z.success)return Q.json({error:"Invalid request body",details:Z.error.issues},400);let $=Z.data,{model:K,gateway:H,messages:F,temperature:V,maxWindowSize:q=tb6,thread_id:U}=$,D=K.limits?.maxOutputTokens??sb6,B=Jf6(Q.req.raw,H.id),L=new _J({name:"mcp-mesh-proxy",version:"1.0.0"}),[M,C]=await Promise.all([mW1(F,{ignoreIncompleteToolCalls:!0}),Xf6(X,G.id,K.connectionId),L.connect(B)]);if(!C)return Q.json({error:`Model connection not found: ${K.connectionId}`},404);J=L;let E=M.find((f)=>f.role==="system"),A=E?.role==="system"?E.content:void 0,T=M.filter((f)=>f.role!=="system"),j=lW1({messages:T,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-q),R=U?{thread_id:U}:void 0,[k,y]=await Promise.all([X.createMCPProxy(C),Yf6(L,R)]),b=U91.forClient(k),h=pW1(b).languageModel(K.id);return uW1({model:h,system:A,messages:j,tools:y,temperature:V,maxOutputTokens:D,abortSignal:Q.req.raw.signal,stopWhen:a80(30),onError:async(f)=>{console.error("[models:stream] Error",f),await L.close().catch(console.error)},onFinish:async()=>{await L.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:f})=>{if(f.type==="start")return{gateway:H,model:K,created_at:new Date,thread_id:U};if(f.type==="finish-step")return{usage:{...f.usage,providerMetadata:f.providerMetadata}};return{}}})}catch(G){let W=G;if(await J?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:Y})),Q.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:Y,error:W.message,stack:W.stack})),Q.json({error:W.message},500)}});var nW1=cW1;R3();var my=null;async function Gf6(Q,X){let J=(await Q.storage.connections.list(X)).find((G)=>G.connection_url?.startsWith(ps0));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function Wf6(Q){let X=new URLSearchParams;if(Q){let[Y,J]=Q.split("/");if(Y)X.set("workspace_hint",Y);if(J)X.set("project_hint",J)}else X.set("auto_personal","true");return X}var Zf6=new iW1.PrometheusSerializer,$f6=()=>ht(v7),Kf6=()=>ft(v7);function aW1(Q={}){let X=Q.database??Kv();if(my&&my.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(my.stop()).catch((Z)=>{console.error("[EventBus] Error stopping previous worker:",Z)});let Y;if(Q.eventBus)Y=Q.eventBus;else Y=eX1(X);my=Y;let J=new d9;J.use("/*",vv0({origin:(Z)=>{if(Z.includes("localhost")||Z.includes("127.0.0.1"))return Z;return Z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),J.use("*",kv0()),J.use("*",async(Z,$)=>{if(await $(),Z.res.status>=500){let H=await Z.res.clone().text();console.error(`[5xx Response] ${Z.req.method} ${Z.req.path} - ${Z.res.status}:`,H)}}),J.get(YP.HEALTH,(Z)=>{return Z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),J.get(YP.METRICS,async(Z)=>{try{let $=await Xl.collect(),K=Zf6.serialize($.resourceMetrics);return Z.text(K,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch($){return console.error("Failed to collect metrics:",$),Z.text("# Error collecting metrics",500)}}),J.route("/api/auth/custom",YY1),J.all("/api/auth/*",async(Z)=>{return await v7.handler(Z.req.raw)}),J.route("/",SX1),J.all("/oauth-proxy/:connectionId/*",async(Z)=>{let $=Z.req.param("connectionId"),K=Z.req.path.split("/").filter(Boolean),H=K[K.length-1],F=Z.get("meshContext");if(!F)F=await n$.create(Z.req.raw),Z.set("meshContext",F);let V=await F.storage.connections.findById($);if(!V?.connection_url)return Z.json({error:"Connection not found"},404);let q=await Dy(V.connection_url),U,D=new URL(V.connection_url);if(q.ok)U=(await q.json()).authorization_servers?.[0];if(!U)U=D.origin;let B=await m40(U);if(!B.ok)return Z.json({error:"Failed to get auth server metadata"},502);let L=await B.json(),M;if(H==="authorize")M=L.authorization_endpoint;else if(H==="token")M=L.token_endpoint;else if(H==="register")M=L.registration_endpoint;if(!M)return Z.json({error:`Unknown OAuth endpoint: ${H}`},404);let C=new URL(M),E=new URL(Z.req.url);if(C.search=E.search,H==="authorize"){if(C.searchParams.has("resource"))C.searchParams.set("resource",V.connection_url);if(cs0(V.connection_url))try{let h=await Gf6(F,V.organization_id),a=Wf6(h);for(let[f,S]of a)C.searchParams.set(f,S)}catch(h){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",h)}return Z.redirect(C.toString(),302)}let A={Accept:Z.req.header("Accept")||"application/json"},T=Z.req.header("Content-Type");if(T)A["Content-Type"]=T;let j=Z.req.header("Authorization");if(j)A.Authorization=j;let R;if(Z.req.method!=="GET"&&Z.req.method!=="HEAD")if(H==="token"&&T?.includes("application/x-www-form-urlencoded")){let h=await Z.req.formData();if(h.has("resource"))h.set("resource",V.connection_url);let a=new URLSearchParams;for(let[f,S]of h.entries())a.append(f,S.toString());R=a.toString()}else R=Z.req.raw.body??void 0;let k=await fetch(C.toString(),{method:Z.req.method,headers:A,body:R,duplex:"half",redirect:"manual"}),y=new Headers,b=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[h,a]of k.headers.entries())if(!b.includes(h.toLowerCase()))y.set(h,a);return new Response(k.body,{status:k.status,statusText:k.statusText,headers:y})}),J.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(Z)=>{let K=await $f6()(Z.req.raw),H=await K.json();return Response.json(H,K)});let G=async(Z)=>{let K=await Kf6()(Z.req.raw),H=await K.json();return Response.json(H,K)};J.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",G),n$.set(uX1({db:X.db,databaseType:X.type,auth:v7,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:jD,meter:Yv0},eventBus:Y})),Promise.resolve(Y.start()).then(()=>{console.log("[EventBus] Worker started")}),J.use("*",async(Z,$)=>{if(dX1(Z.req.path))return $();let K=await n$.create(Z.req.raw);return Z.set("meshContext",K),$()}),J.get("/api/tools/management",(Z)=>{return Z.json({tools:ql,grouped:vD()})});let W=async(Z,$)=>{let K=Z.var.meshContext;if(!K.auth.user?.id&&!K.auth.apiKey?.id){let H=new URL(Z.req.url);return Z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await $()};return J.use("/mcp/:connectionId?",W),J.use("/mcp/gateway/:gatewayId?",W),J.route("/mcp",dY1),J.route("/mcp",cY1),J.route("/mcp",xX1),J.route("/api",nW1),J.post("/org/:organizationId/events/:type",async(Z)=>{let $=Z.req.param("organizationId");return await Z.var.meshContext.eventBus.publish($,Ew.SELF($),{data:await Z.req.json(),type:`public:${Z.req.param("type")}`,subject:Z.req.query("subject"),deliverAt:Z.req.query("deliverAt"),cron:Z.req.query("cron")}),Z.json({success:!0})}),J.notFound((Z)=>{return Z.json({error:"Not Found",path:Z.req.path},404)}),J.onError((Z,$)=>{console.error("Server error :",Z);let K=Z instanceof Error?Z.message:"Unknown error";return $.json({error:"Internal Server Error",message:K},500)}),J}var rW1=parseInt(process.env.PORT||"3000",10),ly="\x1B[0m",Hf6="\x1B[1m",Ff6="\x1B[2m",Vf6="\x1B[32m",qf6="\x1B[36m",zf6="\x1B[4m",Uf6=`http://localhost:${rW1}`,Bf6=$v0({clientDir:Zv0(import.meta.url,"../client"),isServerPath:lX1}),Df6=aW1();console.log("");console.log(`${Vf6}\u2713${ly} ${Hf6}Ready${ly}`);console.log("");console.log(` ${Ff6}Open in browser:${ly} ${qf6}${zf6}${Uf6}${ly}`);console.log("");Bun.serve({idleTimeout:0,port:rW1,hostname:"0.0.0.0",fetch:async(Q)=>{return await Bf6(Q)??Df6.fetch(Q)},development:!1});