@decocms/mesh 1.0.0-alpha.19 → 1.0.0-alpha.20

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 (95) hide show
  1. package/dist/README.md +2 -3
  2. package/dist/client/assets/{alert-dialog-BWlSDWeK.js → alert-dialog-6yQ_ytNz.js} +3 -3
  3. package/dist/client/assets/{auth-DNx6G3kk.js → auth-CSz5ame9.js} +1 -1
  4. package/dist/client/assets/{auth-catchall-DEBHeqih.js → auth-catchall-CJDp3FDD.js} +1 -1
  5. package/dist/client/assets/{avatar-BE4yUJKP.js → avatar-D9WKKc2H.js} +1 -1
  6. package/dist/client/assets/{badge-D1_SzxO5.js → badge-BxwpfgK4.js} +1 -1
  7. package/dist/client/assets/{button-BN_zWXnf.js → button-C-_NjPPs.js} +1 -1
  8. package/dist/client/assets/{card-6GjFVmi6.js → card-5q0yQ-4E.js} +1 -1
  9. package/dist/client/assets/{checkbox-Ddv4lDVe.js → checkbox-CniIxwAN.js} +1 -1
  10. package/dist/client/assets/{circle-alert-Cd33B5N6.js → circle-alert-DWlc7ruY.js} +1 -1
  11. package/dist/client/assets/{collection-detail-BVEPn-2g.js → collection-detail-F3buxrPU.js} +1 -1
  12. package/dist/client/assets/collection-display-button-CYjIv9ET.js +1 -0
  13. package/dist/client/assets/collection-header-BElwf-Gz.js +1 -0
  14. package/dist/client/assets/{collection-page-Q6RNGv5C.js → collection-page-B6r2HLtn.js} +1 -1
  15. package/dist/client/assets/{collection-search-DRvKW-m6.js → collection-search-OBebmCrY.js} +1 -1
  16. package/dist/client/assets/{collection-table-wrapper-pohJqEDN.js → collection-table-wrapper-CWTQ_xvQ.js} +1 -1
  17. package/dist/client/assets/connection-card-DMTXuLLY.js +1 -0
  18. package/dist/client/assets/{connection-detail-CUm3upXk.js → connection-detail-ButZpcgF.js} +1 -1
  19. package/dist/client/assets/connections-wbTmJe7J.js +1 -0
  20. package/dist/client/assets/{create-organization-dialog-DJBTViXu.js → create-organization-dialog-B024WWuD.js} +1 -1
  21. package/dist/client/assets/{dialog-fLfI7M0R.js → dialog-v2GF-04Y.js} +1 -1
  22. package/dist/client/assets/{dropdown-menu-DLU49g1s.js → dropdown-menu-BMFf3tlf.js} +1 -1
  23. package/dist/client/assets/{empty-state-BzOX9EED.js → empty-state-DodoFFAj.js} +1 -1
  24. package/dist/client/assets/{error-boundary-D2G9VNgl.js → error-boundary-Cy_msdg7.js} +1 -1
  25. package/dist/client/assets/{extract-connection-data-C-h71gs0.js → extract-connection-data-BlicUoX6.js} +1 -1
  26. package/dist/client/assets/{form-DBnbAoFC.js → form-WEgfE5pE.js} +1 -1
  27. package/dist/client/assets/gateway-detail-CfQ0095F.js +1 -0
  28. package/dist/client/assets/{gateways-DZxsdiyu.js → gateways-CUtt8cOw.js} +1 -1
  29. package/dist/client/assets/{home-YhKf26x_.js → home-CXur84Cq.js} +1 -1
  30. package/dist/client/assets/{icon-DR1spsQB.js → icon-BWVVSGuI.js} +1 -1
  31. package/dist/client/assets/{index-y5VrHE-k.js → index-C3nlWW5L.js} +1 -1
  32. package/dist/client/assets/index-CEo77-MZ.js +118 -0
  33. package/dist/client/assets/{index-C0T6ZAhQ.js → index-CZk1llWx.js} +1 -1
  34. package/dist/client/assets/{index-JzoFd-IB.js → index-D49hLMyP.js} +1 -1
  35. package/dist/client/assets/index-yMf3L_oA.css +1 -0
  36. package/dist/client/assets/{input-CcvqgZcX.js → input-5ozmLchN.js} +1 -1
  37. package/dist/client/assets/layout-DLv0sB-y.js +1 -0
  38. package/dist/client/assets/{lazy-highlighter-BSQ1zjWm.js → lazy-highlighter-bi9pmmha.js} +1 -1
  39. package/dist/client/assets/{localstorage-keys-Z7g5bnTn.js → localstorage-keys-yS7s4iFl.js} +1 -1
  40. package/dist/client/assets/{login-itVUOHeo.js → login-DobNRNrA.js} +1 -1
  41. package/dist/client/assets/{mcp-oauth-BXs8Us6i.js → mcp-oauth-37Mxf9Z0.js} +1 -1
  42. package/dist/client/assets/members-zAFo6qid.js +3 -0
  43. package/dist/client/assets/monitoring-CNFmTfT0.js +1 -0
  44. package/dist/client/assets/monitoring-stats-row-DB9E7eLj.js +42 -0
  45. package/dist/client/assets/{oauth-callback-DAHrWM48.js → oauth-callback-T5DmL3Ao.js} +1 -1
  46. package/dist/client/assets/page-BIqETU0M.js +21 -0
  47. package/dist/client/assets/page-BZV40eAE.css +1 -0
  48. package/dist/client/assets/{popover-pxHCkQCT.js → popover-BCVOzsms.js} +1 -1
  49. package/dist/client/assets/{prism-ChIE02BQ.js → prism-iL5zefv5.js} +1 -1
  50. package/dist/client/assets/{resource-tabs-O3UgRbzl.js → resource-tabs-DhcI51JE.js} +1 -1
  51. package/dist/client/assets/{schema-Ds6vBzkt.js → schema-DcHM5DMj.js} +1 -1
  52. package/dist/client/assets/{select-DmtIA5gb.js → select-DFzO4KN0.js} +1 -1
  53. package/dist/client/assets/{settings-MfgRanQ8.js → settings-D0vYaEZr.js} +1 -1
  54. package/dist/client/assets/{shell-layout-CLztFOn5.js → shell-layout-D34ddYiL.js} +5 -5
  55. package/dist/client/assets/{spinner-CSfjXmps.js → spinner-DnJmPtgh.js} +1 -1
  56. package/dist/client/assets/store-C5PNHQD9.js +1 -0
  57. package/dist/client/assets/store-app-detail-D3a6jhJ2.js +1 -0
  58. package/dist/client/assets/{switch-BZhZuO_s.js → switch-G-S3tsxP.js} +1 -1
  59. package/dist/client/assets/{textarea-ChlVYzjs.js → textarea-DpLnh_Mr.js} +1 -1
  60. package/dist/client/assets/{tool-set-selector-G8wTCLog.js → tool-set-selector-Yam11D5m.js} +1 -1
  61. package/dist/client/assets/{tooltip-D_78gfFh.js → tooltip-Bdp6F_4z.js} +1 -1
  62. package/dist/client/assets/{upload-B-eQsTwv.js → upload-BJHCH8vW.js} +1 -1
  63. package/dist/client/assets/{use-binding-Bb2paZzF.js → use-binding-BZj4JXob.js} +2 -2
  64. package/dist/client/assets/{use-connection-DxtpeU7L.js → use-connection-_IstvAFb.js} +1 -1
  65. package/dist/client/assets/{use-gateway-q9TGaBqh.js → use-gateway-pw5jbc7Q.js} +1 -1
  66. package/dist/client/assets/{use-list-state-DAjBDT6m.js → use-list-state-DKMQTiNs.js} +1 -1
  67. package/dist/client/assets/use-mcp-Dj_7v_nd.js +1 -0
  68. package/dist/client/assets/{use-members-CWZ6LTt7.js → use-members-fC3DA3xN.js} +1 -1
  69. package/dist/client/assets/{use-mobile-MtwUZMiZ.js → use-mobile-D6cBfH0_.js} +1 -1
  70. package/dist/client/assets/{use-organization-settings-DdMFS3RF.js → use-organization-settings-DdaiS6Jy.js} +1 -1
  71. package/dist/client/assets/{use-tool-call-BRFgmS8T.js → use-tool-call--kgIN5TM.js} +1 -1
  72. package/dist/client/assets/useQuery-DVO6EBFl.js +1 -0
  73. package/dist/client/assets/utils-ANvY6Qf5.js +1 -0
  74. package/dist/client/index.html +2 -2
  75. package/dist/server/cli.js +3 -3
  76. package/dist/server/migrate.js +1 -1
  77. package/dist/server/server.js +2 -2
  78. package/package.json +3 -1
  79. package/dist/client/assets/collection-display-button-D2Zl4v_d.js +0 -1
  80. package/dist/client/assets/collection-header-C0Jrsz0s.js +0 -1
  81. package/dist/client/assets/connection-card-DsobEce7.js +0 -1
  82. package/dist/client/assets/connections-D43mp84Z.js +0 -1
  83. package/dist/client/assets/gateway-detail-CwiZdxYg.js +0 -1
  84. package/dist/client/assets/index-XU02Lc4Q.css +0 -1
  85. package/dist/client/assets/index-YfohaNt1.js +0 -118
  86. package/dist/client/assets/layout-BlUr8W2A.js +0 -1
  87. package/dist/client/assets/members-BT9zPsL2.js +0 -1
  88. package/dist/client/assets/monitoring-DQPV_C4N.js +0 -1
  89. package/dist/client/assets/monitoring-stats-row-CP625QzH.js +0 -42
  90. package/dist/client/assets/page-Dcuv0l3T.js +0 -1
  91. package/dist/client/assets/store-DAkjxR6I.js +0 -1
  92. package/dist/client/assets/store-app-detail-DwCGQM9s.js +0 -1
  93. package/dist/client/assets/use-mcp-CcUDnETM.js +0 -1
  94. package/dist/client/assets/useQuery-CJPC8H_4.js +0 -1
  95. package/dist/client/assets/utils-pyyeDP1p.js +0 -1
@@ -1019,7 +1019,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1019
1019
  </script>
1020
1020
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${Y}></script>
1021
1021
  </body>
1022
- </html>`},xk=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:E0("/open-api/generate-schema",{method:"GET"},async(X)=>{let Y=await n00(X.context,X.context.options);return X.json(Y)}),openAPIReference:E0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new m("NOT_FOUND");let Y=await n00(X.context,X.context.options);return new Response(xk0(Y,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};O9();DJ();Z6();y6();x1();var BL1=D4(async()=>{return{}}),OL1=D4({use:[T8]},async(Q)=>{return{session:Q.context.session}}),ML1=i4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var DL1=Number.POSITIVE_INFINITY;var i00=R(),lk0=z1(["pending","accepted","rejected","canceled"]).default("pending"),TL1=s({id:R().default(N6),name:R(),slug:R(),logo:R().nullish().optional(),metadata:X1(R(),ZQ()).or(R().transform((Q)=>JSON.parse(Q))).optional(),createdAt:R1()}),AL1=s({id:R().default(N6),organizationId:R(),userId:w1.string(),role:i00,createdAt:R1().default(()=>new Date)}),EL1=s({id:R().default(N6),organizationId:R(),email:R(),role:i00,status:lk0,teamId:R().nullish(),inviterId:R(),expiresAt:R1(),createdAt:R1().default(()=>new Date)}),RL1=s({id:R().default(N6),name:R().min(1),organizationId:R(),createdAt:R1(),updatedAt:R1().optional()}),SL1=s({id:R().default(N6),teamId:R(),userId:R(),createdAt:R1().default(()=>new Date)}),vL1=s({id:R().default(N6),organizationId:R(),role:R(),permission:X1(R(),a0(R())),createdAt:R1().default(()=>new Date),updatedAt:R1().optional()}),r00=["admin","member","owner"],CL1=S8([z1(r00),a0(z1(r00))]);E8();Z6();y6();var xL1=i4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();M9();Z6();y6();C6();V8();var dk0=i4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Z6();y6();var pk0=i4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var e3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as a00,readFileSync as o00}from"fs";var eP={emailAndPassword:{enabled:!0}},s00=process.env.CONFIG_PATH||"./config.json",t00=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function ck0(){if(a00(s00))try{let Q=o00(s00,"utf-8"),J=JSON.parse(Q);return{auth:eP,monitoring:e3,...J}}catch{return{auth:eP,monitoring:e3}}if(a00(t00))try{let Q=o00(t00,"utf-8");return{auth:JSON.parse(Q),monitoring:e3}}catch{return{auth:eP,monitoring:e3}}return{auth:eP,monitoring:e3}}var uk=ck0();import{existsSync as ff0,mkdirSync as hf0}from"fs";import{Kysely as w80,PostgresDialect as B80,sql as P80}from"kysely";import{BunWorkerDialect as O80}from"kysely-bun-worker";import*as M80 from"path";var kQ=E5(P_(),1),mP1=kQ.default.Client,M_=kQ.default.Pool,xP1=kQ.default.Connection,uP1=kQ.default.types,lP1=kQ.default.Query,dP1=kQ.default.DatabaseError,pP1=kQ.default.escapeIdentifier,cP1=kQ.default.escapeLiteral,nP1=kQ.default.Result,rP1=kQ.default.TypeOverrides,iP1=kQ.default.defaults;function gf0(Q){let J=new M_({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new B80({pool:J});return{type:"postgres",db:new w80({dialect:X}),pool:J}}function D80(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function T80(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!ff0(J))try{hf0(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function mf0(Q){let J=D80(Q.connectionString);J=T80(J);let X=new O80({url:J||":memory:"}),Y=new w80({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)P80`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(J!==":memory:"){let W=Q.options?.busyTimeout||5000;P80`PRAGMA busy_timeout = ${W};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function A80(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,Y=X?.protocol.replace(":","")??J.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function T_(){return process.env.DATABASE_URL||`file:${M80.join(process.cwd(),"data/mesh.db")}`}function E80(Q){let J=A80(Q);if(J.type==="postgres")return new B80({pool:new M_({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=D80(J.connectionString);return X=T80(X),new O80({url:X||":memory:"})}function xf0(Q){let J=A80(Q);if(J.type==="postgres")return gf0(J);return mf0(J)}async function A_(Q){if(await Q.db.destroy(),Q.type==="postgres"&&!Q.pool.ended)await Q.pool.end()}var D_=null;function gF(){if(!D_)D_=xf0(T_());return D_}class E_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:Y})});if(!W.ok)throw Error(`Failed to send email: ${W.statusText}`)}}class R_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:Y}]})});if(!W.ok){let G=await W.text();throw Error(`Failed to send email via SendGrid: ${W.statusText} - ${G}`)}}}var uf0=(Q)=>{let J=new E_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},lf0=(Q)=>{let J=new R_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},df0={resend:uf0,sendgrid:lf0};function Fw(Q){let J=df0[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Vw(Q,J){return Q.find((X)=>X.id===J)}var R80=(Q,J)=>{let X=Vw(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let Y=Fw(X);return{sendMagicLink:async({email:W,url:G})=>{await Y({to:W,subject:"Magic Link",html:`<p>Click <a href="${G}">here</a> to login</p>`})}}};mF();import{createCipheriv as pf0,createDecipheriv as cf0,randomBytes as C80}from"crypto";var I80="aes-256-gcm",xF=16,k80=16,_80=32;class S_{key;constructor(Q){if(Buffer.from(Q,"base64").length===_80)this.key=Buffer.from(Q,"base64");else{let J=K1("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=C80(xF),X=pf0(I80,this.key,J),Y=X.update(Q,"utf8");Y=Buffer.concat([Y,X.final()]);let W=X.getAuthTag();return Buffer.concat([J,W,Y]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,xF),Y=J.subarray(xF,xF+k80),W=J.subarray(xF+k80),G=cf0(I80,this.key,X);G.setAuthTag(Y);let $=G.update(W);return $=Buffer.concat([$,G.final()]),$.toString("utf8")}static generateKey(){return C80(_80).toString("base64")}}import{webcrypto as b80}from"crypto";var y80="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var nf0=128,DG,qZ;function rf0(Q){if(!DG||DG.length<Q)DG=Buffer.allocUnsafe(Q*nf0),b80.getRandomValues(DG),qZ=0;else if(qZ+Q>DG.length)b80.getRandomValues(DG),qZ=0;qZ+=Q}function f80(Q=21){rf0(Q|=0);let J="";for(let X=qZ-Q;X<qZ;X++)J+=y80[DG[X]&63];return J}function B7(Q){return`${Q}_${f80()}`}var if0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class v_{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??B7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let W=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(W).execute();let G=await this.findById(J);if(!G)throw Error(`Failed to create connection with id: ${J}`);return G}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let W=await this.findById(Q);if(!W)throw Error("Connection not found");return W}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let Y=await this.findById(Q);if(!Y)throw Error("Connection not found after update");return Y}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let Y=Date.now();try{let W=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(Q){let J={};for(let[X,Y]of Object.entries(Q)){if(Y===void 0)continue;if(X==="connection_token"&&Y)J[X]=await this.vault.encrypt(Y);else if(X==="configuration_state"&&Y){let W=JSON.stringify(Y);J[X]=await this.vault.encrypt(W)}else if(if0.includes(X))J[X]=Y?JSON.stringify(Y):null;else J[X]=Y}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let X=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let Y=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:Y(Q.connection_headers),oauth_config:Y(Q.oauth_config),configuration_state:X,configuration_scopes:Y(Q.configuration_scopes),metadata:Y(Q.metadata),tools:Y(Q.tools),bindings:Y(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class C_{db;constructor(Q){this.db=Q}async create(Q,J,X){let Y=B7("gw"),W=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:W,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:W}))).execute();let Z=await this.findByIdInternal($,Y);if(!Z)throw Error(`Failed to create gateway with id: ${Y}`);return Z});if(await this.db.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Y,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:W}))).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create gateway with id: ${Y}`);return G}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let Y=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,Y)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((G)=>G.id);if(X.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),W=new Map;for(let G of Y){let $=W.get(G.gateway_id)??[];$.push(G),W.set(G.gateway_id,$)}return J.map((G)=>this.deserializeGatewayWithConnections(G,W.get(G.id)??[]))}async listByConnectionId(Q,J){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let W=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",Q).execute();if(W.length===0)return[];let G=W.map((K)=>K.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",G).execute(),Z=new Map;for(let K of $){let H=Z.get(K.gateway_id)??[];H.push(K),Z.set(K.gateway_id,H)}return W.map((K)=>this.deserializeGatewayWithConnections(K,Z.get(K.id)??[]))}async update(Q,J,X){let Y=new Date().toISOString(),W={updated_at:Y,updated_by:J};if(X.title!==void 0)W.title=X.title;if(X.description!==void 0)W.description=X.description;if(X.toolSelectionStrategy!==void 0)W.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)W.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)W.icon=X.icon;if(X.status!==void 0)W.status=X.status;if(X.isDefault===!1)W.is_default=0;if(X.isDefault===!0)W.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await Z.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await Z.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await Z.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute()}let G=await this.findById(Q);if(!G)throw Error("Gateway not found after update");return G}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let Y=new Date().toISOString();await this.db.transaction().execute(async(G)=>{await G.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await G.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:J}).where("id","=",Q).execute()});let W=await this.findById(Q);if(!W)throw Error("Gateway not found after setting default");return W}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}NB();RB();function ln0(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (mG0(),gG0));return Q.map((J)=>{return{name:J.name,inputSchema:IZ(J.inputSchema),outputSchema:J.outputSchema?IZ(J.outputSchema):void 0,description:J.description}})},data:v80(process.env.BASE_URL||"http://localhost:3000")},{data:S80()}]}async function xG0(Q,J){try{let X=gF(),Y=new S_(process.env.ENCRYPTION_KEY||""),W=new v_(X.db,Y),G=new C_(X.db),$=ln0(),Z=[];await Promise.all($.map(async(K)=>{let H=null;if(K.permissions)H=(await YK.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await K.getTools?.()??await CZ({id:"pending",title:K.data.title,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),F=K.data.id?`${Q}_${K.data.id}`:void 0,V=await W.create({...K.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:K.data.connection_token??H});Z.push(V.id)})),await G.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:Z.map((K)=>({connectionId:K}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var uG0=["owner","admin"];var dn0=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},lG0=(Q)=>{if(Q.providerId==="microsoft")return dn0(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function pn0(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var dG0=["labs","hub","studio","workspace","systems","core","cloud","works"],pG0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function cn0(){let Q=Math.floor(Math.random()*pG0.length),J=Math.floor(Math.random()*dG0.length),X=pG0[Q]??"deco",Y=dG0[J]??"studio";return`${X}-${Y}`}var nn0=Object.values(eR()).map((Q)=>Q.map((J)=>J.name)).flat(),rn0={...mP,self:["*",...nn0]},LO=XX(rn0),in0=LO.newRole({self:["*"],...BF.statements}),an0=LO.newRole({self:["*"],...BF.statements}),on0=LO.newRole({self:["*"],...BF.statements}),cG0=Object.values(eR()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),o5=uk.auth,nG0=void 0;if(o5.inviteEmailProviderId&&o5.emailProviders&&o5.emailProviders.length>0){let Q=Vw(o5.emailProviders,o5.inviteEmailProviderId);if(Q){let J=Fw(Q);nG0=async(X)=>{let Y=X.inviter.user?.name||X.inviter.user?.email,W=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1022
+ </html>`},xk=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:E0("/open-api/generate-schema",{method:"GET"},async(X)=>{let Y=await n00(X.context,X.context.options);return X.json(Y)}),openAPIReference:E0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new m("NOT_FOUND");let Y=await n00(X.context,X.context.options);return new Response(xk0(Y,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};O9();DJ();Z6();y6();x1();var BL1=D4(async()=>{return{}}),OL1=D4({use:[T8]},async(Q)=>{return{session:Q.context.session}}),ML1=i4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var DL1=Number.POSITIVE_INFINITY;var i00=R(),lk0=z1(["pending","accepted","rejected","canceled"]).default("pending"),TL1=s({id:R().default(N6),name:R(),slug:R(),logo:R().nullish().optional(),metadata:X1(R(),ZQ()).or(R().transform((Q)=>JSON.parse(Q))).optional(),createdAt:R1()}),AL1=s({id:R().default(N6),organizationId:R(),userId:w1.string(),role:i00,createdAt:R1().default(()=>new Date)}),EL1=s({id:R().default(N6),organizationId:R(),email:R(),role:i00,status:lk0,teamId:R().nullish(),inviterId:R(),expiresAt:R1(),createdAt:R1().default(()=>new Date)}),RL1=s({id:R().default(N6),name:R().min(1),organizationId:R(),createdAt:R1(),updatedAt:R1().optional()}),SL1=s({id:R().default(N6),teamId:R(),userId:R(),createdAt:R1().default(()=>new Date)}),vL1=s({id:R().default(N6),organizationId:R(),role:R(),permission:X1(R(),a0(R())),createdAt:R1().default(()=>new Date),updatedAt:R1().optional()}),r00=["admin","member","owner"],CL1=S8([z1(r00),a0(z1(r00))]);E8();Z6();y6();var xL1=i4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();M9();Z6();y6();C6();V8();var dk0=i4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Z6();y6();var pk0=i4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var e3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as a00,readFileSync as o00}from"fs";var eP={emailAndPassword:{enabled:!0}},s00=process.env.CONFIG_PATH||"./config.json",t00=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function ck0(){if(a00(s00))try{let Q=o00(s00,"utf-8"),J=JSON.parse(Q);return{auth:eP,monitoring:e3,...J}}catch{return{auth:eP,monitoring:e3}}if(a00(t00))try{let Q=o00(t00,"utf-8");return{auth:JSON.parse(Q),monitoring:e3}}catch{return{auth:eP,monitoring:e3}}return{auth:eP,monitoring:e3}}var uk=ck0();import{existsSync as ff0,mkdirSync as hf0}from"fs";import{Kysely as w80,PostgresDialect as B80,sql as P80}from"kysely";import{BunWorkerDialect as O80}from"kysely-bun-worker";import*as M80 from"path";var kQ=E5(P_(),1),mP1=kQ.default.Client,M_=kQ.default.Pool,xP1=kQ.default.Connection,uP1=kQ.default.types,lP1=kQ.default.Query,dP1=kQ.default.DatabaseError,pP1=kQ.default.escapeIdentifier,cP1=kQ.default.escapeLiteral,nP1=kQ.default.Result,rP1=kQ.default.TypeOverrides,iP1=kQ.default.defaults;function gf0(Q){let J=new M_({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new B80({pool:J});return{type:"postgres",db:new w80({dialect:X}),pool:J}}function D80(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function T80(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!ff0(J))try{hf0(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function mf0(Q){let J=D80(Q.connectionString);J=T80(J);let X=new O80({url:J||":memory:"}),Y=new w80({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)P80`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(J!==":memory:"){let W=Q.options?.busyTimeout||5000;P80`PRAGMA busy_timeout = ${W};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function A80(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,Y=X?.protocol.replace(":","")??J.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function T_(){return process.env.DATABASE_URL||`file:${M80.join(process.cwd(),"data/mesh.db")}`}function E80(Q){let J=A80(Q);if(J.type==="postgres")return new B80({pool:new M_({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=D80(J.connectionString);return X=T80(X),new O80({url:X||":memory:"})}function xf0(Q){let J=A80(Q);if(J.type==="postgres")return gf0(J);return mf0(J)}async function A_(Q){if(await Q.db.destroy(),Q.type==="postgres"&&!Q.pool.ended)await Q.pool.end()}var D_=null;function gF(){if(!D_)D_=xf0(T_());return D_}class E_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:Y})});if(!W.ok)throw Error(`Failed to send email: ${W.statusText}`)}}class R_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:Y}]})});if(!W.ok){let G=await W.text();throw Error(`Failed to send email via SendGrid: ${W.statusText} - ${G}`)}}}var uf0=(Q)=>{let J=new E_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},lf0=(Q)=>{let J=new R_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},df0={resend:uf0,sendgrid:lf0};function Fw(Q){let J=df0[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Vw(Q,J){return Q.find((X)=>X.id===J)}var R80=(Q,J)=>{let X=Vw(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let Y=Fw(X);return{sendMagicLink:async({email:W,url:G})=>{await Y({to:W,subject:"Magic Link",html:`<p>Click <a href="${G}">here</a> to login</p>`})}}};mF();import{createCipheriv as pf0,createDecipheriv as cf0,randomBytes as C80}from"crypto";var I80="aes-256-gcm",xF=16,k80=16,_80=32;class S_{key;constructor(Q){if(Buffer.from(Q,"base64").length===_80)this.key=Buffer.from(Q,"base64");else{let J=K1("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=C80(xF),X=pf0(I80,this.key,J),Y=X.update(Q,"utf8");Y=Buffer.concat([Y,X.final()]);let W=X.getAuthTag();return Buffer.concat([J,W,Y]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,xF),Y=J.subarray(xF,xF+k80),W=J.subarray(xF+k80),G=cf0(I80,this.key,X);G.setAuthTag(Y);let $=G.update(W);return $=Buffer.concat([$,G.final()]),$.toString("utf8")}static generateKey(){return C80(_80).toString("base64")}}import{webcrypto as b80}from"crypto";var y80="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var nf0=128,DG,qZ;function rf0(Q){if(!DG||DG.length<Q)DG=Buffer.allocUnsafe(Q*nf0),b80.getRandomValues(DG),qZ=0;else if(qZ+Q>DG.length)b80.getRandomValues(DG),qZ=0;qZ+=Q}function f80(Q=21){rf0(Q|=0);let J="";for(let X=qZ-Q;X<qZ;X++)J+=y80[DG[X]&63];return J}function B7(Q){return`${Q}_${f80()}`}var if0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class v_{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??B7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let W=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(W).execute();let G=await this.findById(J);if(!G)throw Error(`Failed to create connection with id: ${J}`);return G}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let W=await this.findById(Q);if(!W)throw Error("Connection not found");return W}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let Y=await this.findById(Q);if(!Y)throw Error("Connection not found after update");return Y}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let Y=Date.now();try{let W=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(Q){let J={};for(let[X,Y]of Object.entries(Q)){if(Y===void 0)continue;if(X==="connection_token"&&Y)J[X]=await this.vault.encrypt(Y);else if(X==="configuration_state"&&Y){let W=JSON.stringify(Y);J[X]=await this.vault.encrypt(W)}else if(if0.includes(X))J[X]=Y?JSON.stringify(Y):null;else J[X]=Y}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let X=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let Y=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:Y(Q.connection_headers),oauth_config:Y(Q.oauth_config),configuration_state:X,configuration_scopes:Y(Q.configuration_scopes),metadata:Y(Q.metadata),tools:Y(Q.tools),bindings:Y(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class C_{db;constructor(Q){this.db=Q}async create(Q,J,X){let Y=B7("gw"),W=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:W,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:W}))).execute();let Z=await this.findByIdInternal($,Y);if(!Z)throw Error(`Failed to create gateway with id: ${Y}`);return Z});if(await this.db.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Y,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:W}))).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create gateway with id: ${Y}`);return G}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let Y=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,Y)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((G)=>G.id);if(X.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),W=new Map;for(let G of Y){let $=W.get(G.gateway_id)??[];$.push(G),W.set(G.gateway_id,$)}return J.map((G)=>this.deserializeGatewayWithConnections(G,W.get(G.id)??[]))}async listByConnectionId(Q,J){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let W=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",Q).execute();if(W.length===0)return[];let G=W.map((K)=>K.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",G).execute(),Z=new Map;for(let K of $){let H=Z.get(K.gateway_id)??[];H.push(K),Z.set(K.gateway_id,H)}return W.map((K)=>this.deserializeGatewayWithConnections(K,Z.get(K.id)??[]))}async update(Q,J,X){let Y=new Date().toISOString(),W={updated_at:Y,updated_by:J};if(X.title!==void 0)W.title=X.title;if(X.description!==void 0)W.description=X.description;if(X.toolSelectionStrategy!==void 0)W.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)W.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)W.icon=X.icon;if(X.status!==void 0)W.status=X.status;if(X.isDefault===!1)W.is_default=0;if(X.isDefault===!0)W.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await Z.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await Z.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await Z.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute()}let G=await this.findById(Q);if(!G)throw Error("Gateway not found after update");return G}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let Y=new Date().toISOString();await this.db.transaction().execute(async(G)=>{await G.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await G.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:J}).where("id","=",Q).execute()});let W=await this.findById(Q);if(!W)throw Error("Gateway not found after setting default");return W}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}NB();RB();function ln0(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (mG0(),gG0));return Q.map((J)=>{return{name:J.name,inputSchema:IZ(J.inputSchema),outputSchema:J.outputSchema?IZ(J.outputSchema):void 0,description:J.description}})},data:v80(process.env.BASE_URL||"http://localhost:3000")},{data:S80()}]}async function xG0(Q,J){try{let X=gF(),Y=new S_(process.env.ENCRYPTION_KEY||""),W=new v_(X.db,Y),G=new C_(X.db),$=ln0(),Z=[];await Promise.all($.map(async(K)=>{let H=null;if(K.permissions)H=(await YK.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await K.getTools?.()??await CZ({id:"pending",title:K.data.title,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),F=K.data.id?`${Q}_${K.data.id}`:void 0,V=await W.create({...K.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:K.data.connection_token??H});Z.push(V.id)})),await G.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:Z.map((K)=>({connectionId:K}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var uG0=["owner","admin"];var dn0=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},lG0=(Q)=>{if(Q.providerId==="microsoft")return dn0(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function pn0(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var dG0=["labs","hub","studio","workspace","systems","core","cloud","works"],pG0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function cn0(){let Q=Math.floor(Math.random()*pG0.length),J=Math.floor(Math.random()*dG0.length),X=pG0[Q]??"deco",Y=dG0[J]??"studio";return`${X}-${Y}`}var nn0=Object.values(eR()).map((Q)=>Q.map((J)=>J.name)).flat(),rn0={...mP,self:["*",...nn0]},LO=XX(rn0),in0=LO.newRole({self:["*"],...BF.statements}),an0=LO.newRole({self:["*"],...BF.statements}),on0=LO.newRole({self:["*"],...BF.statements}),cG0=Object.values(eR()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),o5=uk.auth,nG0=void 0;if(o5.inviteEmailProviderId&&o5.emailProviders&&o5.emailProviders.length>0){let Q=Vw(o5.emailProviders,o5.inviteEmailProviderId);if(Q){let J=Fw(Q);nG0=async(X)=>{let Y=X.inviter.user?.name||X.inviter.user?.email,W=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1023
1023
  <h2>You've been invited!</h2>
1024
1024
  <p>${Y} has invited you to join <strong>${X.organization.name}</strong>.</p>
1025
1025
  <p><a href="${W}">Click here to accept the invitation</a></p>
@@ -1061,7 +1061,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1061
1061
  </script>
1062
1062
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${G}></script>
1063
1063
  </body>
1064
- </html>`},P00=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:p0("/open-api/generate-schema",{method:"GET"},async(X)=>{let G=await P01(X.context,X.context.options);return X.json(G)}),openAPIReference:p0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new c("NOT_FOUND");let G=await P01(X.context,X.context.options);return new Response(zB4(G,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};VQ();y7();Y9();p9();z4();var Qw6=Q6(async()=>{return{}}),Jw6=Q6({use:[q8]},async(Q)=>{return{session:Q.context.session}}),Xw6=E6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var Yw6=Number.POSITIVE_INFINITY;var T01=S(),NB4=v1(["pending","accepted","rejected","canceled"]).default("pending"),Gw6=J0({id:S().default(z9),name:S(),slug:S(),logo:S().nullish().optional(),metadata:L1(S(),CX()).or(S().transform((Q)=>JSON.parse(Q))).optional(),createdAt:o1()}),Ww6=J0({id:S().default(z9),organizationId:S(),userId:b1.string(),role:T01,createdAt:o1().default(()=>new Date)}),$w6=J0({id:S().default(z9),organizationId:S(),email:S(),role:T01,status:NB4,teamId:S().nullish(),inviterId:S(),expiresAt:o1(),createdAt:o1().default(()=>new Date)}),Kw6=J0({id:S().default(z9),name:S().min(1),organizationId:S(),createdAt:o1(),updatedAt:o1().optional()}),Zw6=J0({id:S().default(z9),teamId:S(),userId:S(),createdAt:o1().default(()=>new Date)}),Hw6=J0({id:S().default(z9),organizationId:S(),role:S(),permission:L1(S(),F1(S())),createdAt:o1().default(()=>new Date),updatedAt:o1().optional()}),M01=["admin","member","owner"],qw6=D8([v1(M01),F1(v1(M01))]);E8();Y9();p9();var ww6=E6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();zQ();Y9();p9();u9();e6();var BB4=E6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Y9();p9();var OB4=E6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var SH={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as A01,readFileSync as E01}from"fs";var Jv={emailAndPassword:{enabled:!0}},j01=process.env.CONFIG_PATH||"./config.json",I01=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function DB4(){if(A01(j01))try{let Q=E01(j01,"utf-8"),J=JSON.parse(Q);return{auth:Jv,monitoring:SH,...J}}catch{return{auth:Jv,monitoring:SH}}if(A01(I01))try{let Q=E01(I01,"utf-8");return{auth:JSON.parse(Q),monitoring:SH}}catch{return{auth:Jv,monitoring:SH}}return{auth:Jv,monitoring:SH}}var Xv=DB4();function C01(){return{...SH,...Xv.monitoring}}import{existsSync as Hw4,mkdirSync as qw4}from"fs";import{Kysely as a41,PostgresDialect as o41,sql as r41}from"kysely";import{BunWorkerDialect as s41}from"kysely-bun-worker";import*as t41 from"path";var yX=i4(t00(),1),O26=yX.default.Client,X10=yX.default.Pool,D26=yX.default.Connection,L26=yX.default.types,w26=yX.default.Query,P26=yX.default.DatabaseError,M26=yX.default.escapeIdentifier,T26=yX.default.escapeLiteral,A26=yX.default.Result,E26=yX.default.TypeOverrides,j26=yX.default.defaults;function Fw4(Q){let J=new X10({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new o41({pool:J});return{type:"postgres",db:new a41({dialect:X}),pool:J}}function e41(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function Q61(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!Hw4(J))try{qw4(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function Vw4(Q){let J=e41(Q.connectionString);J=Q61(J);let X=new s41({url:J||":memory:"}),G=new a41({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)r41`PRAGMA journal_mode = WAL;`.execute(G).catch(()=>{});if(J!==":memory:"){let Y=Q.options?.busyTimeout||5000;r41`PRAGMA busy_timeout = ${Y};`.execute(G).catch(()=>{})}return{type:"sqlite",db:G}}function J61(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,G=X?.protocol.replace(":","")??J.split("://")[0];switch(G){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${G}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function G10(){return process.env.DATABASE_URL||`file:${t41.join(process.cwd(),"data/mesh.db")}`}function X61(Q){let J=J61(Q);if(J.type==="postgres")return new o41({pool:new X10({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=e41(J.connectionString);return X=Q61(X),new s41({url:X||":memory:"})}function zw4(Q){let J=J61(Q);if(J.type==="postgres")return Fw4(J);return Vw4(J)}var Y10=null;function Uv(){if(!Y10)Y10=zw4(G10());return Y10}class W10{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:G})});if(!Y.ok)throw Error(`Failed to send email: ${Y.statusText}`)}}class $10{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:G}]})});if(!Y.ok){let W=await Y.text();throw Error(`Failed to send email via SendGrid: ${Y.statusText} - ${W}`)}}}var Uw4=(Q)=>{let J=new W10(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},Nw4=(Q)=>{let J=new $10(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},Bw4={resend:Uw4,sendgrid:Nw4};function Nv(Q){let J=Bw4[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Bv(Q,J){return Q.find((X)=>X.id===J)}var Y61=(Q,J)=>{let X=Bv(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let G=Nv(X);return{sendMagicLink:async({email:Y,url:W})=>{await G({to:Y,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};_H();import{createCipheriv as Ow4,createDecipheriv as Dw4,randomBytes as $61}from"crypto";var K61="aes-256-gcm",jw=16,Z61=16,H61=32;class Iw{key;constructor(Q){if(Buffer.from(Q,"base64").length===H61)this.key=Buffer.from(Q,"base64");else{let J=E0("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=$61(jw),X=Ow4(K61,this.key,J),G=X.update(Q,"utf8");G=Buffer.concat([G,X.final()]);let Y=X.getAuthTag();return Buffer.concat([J,Y,G]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,jw),G=J.subarray(jw,jw+Z61),Y=J.subarray(jw+Z61),W=Dw4(K61,this.key,X);W.setAuthTag(G);let $=W.update(Y);return $=Buffer.concat([$,W.final()]),$.toString("utf8")}static generateKey(){return $61(H61).toString("base64")}}import{webcrypto as F61}from"crypto";var q61="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Lw4=128,yH,dz;function ww4(Q){if(!yH||yH.length<Q)yH=Buffer.allocUnsafe(Q*Lw4),F61.getRandomValues(yH),dz=0;else if(dz+Q>yH.length)F61.getRandomValues(yH),dz=0;dz+=Q}function V61(Q=21){ww4(Q|=0);let J="";for(let X=dz-Q;X<dz;X++)J+=q61[yH[X]&63];return J}function a7(Q){return`${Q}_${V61()}`}var Pw4=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Cw{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??a7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let Y=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(Y).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create connection with id: ${J}`);return W}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let G=await X.executeTakeFirst();return G?this.deserializeConnection(G):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");return Y}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let G=await this.findById(Q);if(!G)throw Error("Connection not found after update");return G}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let G=Date.now();try{let Y=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:Y.ok||Y.status===404,latencyMs:Date.now()-G}}catch{return{healthy:!1,latencyMs:Date.now()-G}}}async serializeConnection(Q){let J={};for(let[X,G]of Object.entries(Q)){if(G===void 0)continue;if(X==="connection_token"&&G)J[X]=await this.vault.encrypt(G);else if(X==="configuration_state"&&G){let Y=JSON.stringify(G);J[X]=await this.vault.encrypt(Y)}else if(Pw4.includes(X))J[X]=G?JSON.stringify(G):null;else J[X]=G}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(Y){console.error("Failed to decrypt connection token:",Y)}let X=null;if(Q.configuration_state)try{let Y=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(Y)}catch(Y){console.error("Failed to decrypt configuration state:",Y)}let G=(Y)=>{if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:G(Q.connection_headers),oauth_config:G(Q.oauth_config),configuration_state:X,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Rw{db;constructor(Q){this.db=Q}async create(Q,J,X){let G=a7("gw"),Y=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:a7("gwc"),gateway_id:G,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:Y}))).execute();let K=await this.findByIdInternal($,G);if(!K)throw Error(`Failed to create gateway with id: ${G}`);return K});if(await this.db.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:a7("gwc"),gateway_id:G,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute();let W=await this.findById(G);if(!W)throw Error(`Failed to create gateway with id: ${G}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let G=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,G)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((W)=>W.id);if(X.length===0)return[];let G=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),Y=new Map;for(let W of G){let $=Y.get(W.gateway_id)??[];$.push(W),Y.set(W.gateway_id,$)}return J.map((W)=>this.deserializeGatewayWithConnections(W,Y.get(W.id)??[]))}async listByConnectionId(Q,J){let G=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((Z)=>Z.gateway_id);if(G.length===0)return[];let Y=await this.db.selectFrom("gateways").selectAll().where("id","in",G).where("organization_id","=",Q).execute();if(Y.length===0)return[];let W=Y.map((Z)=>Z.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),K=new Map;for(let Z of $){let H=K.get(Z.gateway_id)??[];H.push(Z),K.set(Z.gateway_id,H)}return Y.map((Z)=>this.deserializeGatewayWithConnections(Z,K.get(Z.id)??[]))}async update(Q,J,X){let G=new Date().toISOString(),Y={updated_at:G,updated_by:J};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.toolSelectionStrategy!==void 0)Y.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)Y.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.isDefault===!1)Y.is_default=0;if(X.isDefault===!0)Y.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(K)=>{if(await K.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await K.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await K.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await K.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:a7("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:G}))).execute()}})}else if(await this.db.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:a7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:G}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let G=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:G,updated_by:J}).where("id","=",Q).execute()});let Y=await this.findById(Q);if(!Y)throw Error("Gateway not found after setting default");return Y}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((G)=>({connectionId:G.connection_id,selectedTools:this.parseJson(G.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}wk();Sk();function oj4(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (K90(),VY1));return Q.map((J)=>{return{name:J.name,inputSchema:qU(J.inputSchema),outputSchema:J.outputSchema?qU(J.outputSchema):void 0,description:J.description}})},data:W61(process.env.BASE_URL||"http://localhost:3000")},{data:G61()}]}async function zY1(Q,J){try{let X=Uv(),G=new Iw(process.env.ENCRYPTION_KEY||""),Y=new Cw(X.db,G),W=new Rw(X.db),$=oj4(),K=[];await Promise.all($.map(async(Z)=>{let H=null;if(Z.permissions)H=(await CW.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await Z.getTools?.()??await HU({id:"pending",title:Z.data.title,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=Z.data.id?`${Q}_${Z.data.id}`:void 0,V=await Y.create({...Z.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:Z.data.connection_token??H});K.push(V.id)})),await W.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:K.map((Z)=>({connectionId:Z}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var Z90=["owner","admin","user"],UY1=["owner","admin"];var sj4=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},NY1=(Q)=>{if(Q.providerId==="microsoft")return sj4(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function tj4(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var BY1=["labs","hub","studio","workspace","systems","core","cloud","works"],OY1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function ej4(){let Q=Math.floor(Math.random()*OY1.length),J=Math.floor(Math.random()*BY1.length),X=OY1[Q]??"deco",G=BY1[J]??"studio";return`${X}-${G}`}var QI4=Object.values(eB()).map((Q)=>Q.map((J)=>J.name)).flat(),JI4={...mS,self:["*",...QI4]},U_=r7(JI4),XI4=U_.newRole({self:["*"],...Zw.statements}),YI4=U_.newRole({self:["*"],...Zw.statements}),GI4=U_.newRole({self:["*"],...Zw.statements}),DY1=Object.values(eB()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),K9=Xv.auth,LY1=void 0;if(K9.inviteEmailProviderId&&K9.emailProviders&&K9.emailProviders.length>0){let Q=Bv(K9.emailProviders,K9.inviteEmailProviderId);if(Q){let J=Nv(Q);LY1=async(X)=>{let G=X.inviter.user?.name||X.inviter.user?.email,Y=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1064
+ </html>`},P00=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:p0("/open-api/generate-schema",{method:"GET"},async(X)=>{let G=await P01(X.context,X.context.options);return X.json(G)}),openAPIReference:p0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new c("NOT_FOUND");let G=await P01(X.context,X.context.options);return new Response(zB4(G,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};VQ();y7();Y9();p9();z4();var Qw6=Q6(async()=>{return{}}),Jw6=Q6({use:[q8]},async(Q)=>{return{session:Q.context.session}}),Xw6=E6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var Yw6=Number.POSITIVE_INFINITY;var T01=S(),NB4=v1(["pending","accepted","rejected","canceled"]).default("pending"),Gw6=J0({id:S().default(z9),name:S(),slug:S(),logo:S().nullish().optional(),metadata:L1(S(),CX()).or(S().transform((Q)=>JSON.parse(Q))).optional(),createdAt:o1()}),Ww6=J0({id:S().default(z9),organizationId:S(),userId:b1.string(),role:T01,createdAt:o1().default(()=>new Date)}),$w6=J0({id:S().default(z9),organizationId:S(),email:S(),role:T01,status:NB4,teamId:S().nullish(),inviterId:S(),expiresAt:o1(),createdAt:o1().default(()=>new Date)}),Kw6=J0({id:S().default(z9),name:S().min(1),organizationId:S(),createdAt:o1(),updatedAt:o1().optional()}),Zw6=J0({id:S().default(z9),teamId:S(),userId:S(),createdAt:o1().default(()=>new Date)}),Hw6=J0({id:S().default(z9),organizationId:S(),role:S(),permission:L1(S(),F1(S())),createdAt:o1().default(()=>new Date),updatedAt:o1().optional()}),M01=["admin","member","owner"],qw6=D8([v1(M01),F1(v1(M01))]);E8();Y9();p9();var ww6=E6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();zQ();Y9();p9();u9();e6();var BB4=E6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Y9();p9();var OB4=E6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var SH={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as A01,readFileSync as E01}from"fs";var Jv={emailAndPassword:{enabled:!0}},j01=process.env.CONFIG_PATH||"./config.json",I01=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function DB4(){if(A01(j01))try{let Q=E01(j01,"utf-8"),J=JSON.parse(Q);return{auth:Jv,monitoring:SH,...J}}catch{return{auth:Jv,monitoring:SH}}if(A01(I01))try{let Q=E01(I01,"utf-8");return{auth:JSON.parse(Q),monitoring:SH}}catch{return{auth:Jv,monitoring:SH}}return{auth:Jv,monitoring:SH}}var Xv=DB4();function C01(){return{...SH,...Xv.monitoring}}import{existsSync as Hw4,mkdirSync as qw4}from"fs";import{Kysely as a41,PostgresDialect as o41,sql as r41}from"kysely";import{BunWorkerDialect as s41}from"kysely-bun-worker";import*as t41 from"path";var yX=i4(t00(),1),O26=yX.default.Client,X10=yX.default.Pool,D26=yX.default.Connection,L26=yX.default.types,w26=yX.default.Query,P26=yX.default.DatabaseError,M26=yX.default.escapeIdentifier,T26=yX.default.escapeLiteral,A26=yX.default.Result,E26=yX.default.TypeOverrides,j26=yX.default.defaults;function Fw4(Q){let J=new X10({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new o41({pool:J});return{type:"postgres",db:new a41({dialect:X}),pool:J}}function e41(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function Q61(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!Hw4(J))try{qw4(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function Vw4(Q){let J=e41(Q.connectionString);J=Q61(J);let X=new s41({url:J||":memory:"}),G=new a41({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)r41`PRAGMA journal_mode = WAL;`.execute(G).catch(()=>{});if(J!==":memory:"){let Y=Q.options?.busyTimeout||5000;r41`PRAGMA busy_timeout = ${Y};`.execute(G).catch(()=>{})}return{type:"sqlite",db:G}}function J61(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,G=X?.protocol.replace(":","")??J.split("://")[0];switch(G){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${G}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function G10(){return process.env.DATABASE_URL||`file:${t41.join(process.cwd(),"data/mesh.db")}`}function X61(Q){let J=J61(Q);if(J.type==="postgres")return new o41({pool:new X10({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=e41(J.connectionString);return X=Q61(X),new s41({url:X||":memory:"})}function zw4(Q){let J=J61(Q);if(J.type==="postgres")return Fw4(J);return Vw4(J)}var Y10=null;function Uv(){if(!Y10)Y10=zw4(G10());return Y10}class W10{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:G})});if(!Y.ok)throw Error(`Failed to send email: ${Y.statusText}`)}}class $10{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:G}]})});if(!Y.ok){let W=await Y.text();throw Error(`Failed to send email via SendGrid: ${Y.statusText} - ${W}`)}}}var Uw4=(Q)=>{let J=new W10(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},Nw4=(Q)=>{let J=new $10(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},Bw4={resend:Uw4,sendgrid:Nw4};function Nv(Q){let J=Bw4[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Bv(Q,J){return Q.find((X)=>X.id===J)}var Y61=(Q,J)=>{let X=Bv(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let G=Nv(X);return{sendMagicLink:async({email:Y,url:W})=>{await G({to:Y,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};_H();import{createCipheriv as Ow4,createDecipheriv as Dw4,randomBytes as $61}from"crypto";var K61="aes-256-gcm",jw=16,Z61=16,H61=32;class Iw{key;constructor(Q){if(Buffer.from(Q,"base64").length===H61)this.key=Buffer.from(Q,"base64");else{let J=E0("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=$61(jw),X=Ow4(K61,this.key,J),G=X.update(Q,"utf8");G=Buffer.concat([G,X.final()]);let Y=X.getAuthTag();return Buffer.concat([J,Y,G]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,jw),G=J.subarray(jw,jw+Z61),Y=J.subarray(jw+Z61),W=Dw4(K61,this.key,X);W.setAuthTag(G);let $=W.update(Y);return $=Buffer.concat([$,W.final()]),$.toString("utf8")}static generateKey(){return $61(H61).toString("base64")}}import{webcrypto as F61}from"crypto";var q61="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Lw4=128,yH,dz;function ww4(Q){if(!yH||yH.length<Q)yH=Buffer.allocUnsafe(Q*Lw4),F61.getRandomValues(yH),dz=0;else if(dz+Q>yH.length)F61.getRandomValues(yH),dz=0;dz+=Q}function V61(Q=21){ww4(Q|=0);let J="";for(let X=dz-Q;X<dz;X++)J+=q61[yH[X]&63];return J}function a7(Q){return`${Q}_${V61()}`}var Pw4=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Cw{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??a7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let Y=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(Y).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create connection with id: ${J}`);return W}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let G=await X.executeTakeFirst();return G?this.deserializeConnection(G):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");return Y}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let G=await this.findById(Q);if(!G)throw Error("Connection not found after update");return G}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let G=Date.now();try{let Y=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:Y.ok||Y.status===404,latencyMs:Date.now()-G}}catch{return{healthy:!1,latencyMs:Date.now()-G}}}async serializeConnection(Q){let J={};for(let[X,G]of Object.entries(Q)){if(G===void 0)continue;if(X==="connection_token"&&G)J[X]=await this.vault.encrypt(G);else if(X==="configuration_state"&&G){let Y=JSON.stringify(G);J[X]=await this.vault.encrypt(Y)}else if(Pw4.includes(X))J[X]=G?JSON.stringify(G):null;else J[X]=G}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(Y){console.error("Failed to decrypt connection token:",Y)}let X=null;if(Q.configuration_state)try{let Y=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(Y)}catch(Y){console.error("Failed to decrypt configuration state:",Y)}let G=(Y)=>{if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:G(Q.connection_headers),oauth_config:G(Q.oauth_config),configuration_state:X,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Rw{db;constructor(Q){this.db=Q}async create(Q,J,X){let G=a7("gw"),Y=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:a7("gwc"),gateway_id:G,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:Y}))).execute();let K=await this.findByIdInternal($,G);if(!K)throw Error(`Failed to create gateway with id: ${G}`);return K});if(await this.db.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:a7("gwc"),gateway_id:G,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute();let W=await this.findById(G);if(!W)throw Error(`Failed to create gateway with id: ${G}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let G=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,G)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((W)=>W.id);if(X.length===0)return[];let G=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),Y=new Map;for(let W of G){let $=Y.get(W.gateway_id)??[];$.push(W),Y.set(W.gateway_id,$)}return J.map((W)=>this.deserializeGatewayWithConnections(W,Y.get(W.id)??[]))}async listByConnectionId(Q,J){let G=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((Z)=>Z.gateway_id);if(G.length===0)return[];let Y=await this.db.selectFrom("gateways").selectAll().where("id","in",G).where("organization_id","=",Q).execute();if(Y.length===0)return[];let W=Y.map((Z)=>Z.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),K=new Map;for(let Z of $){let H=K.get(Z.gateway_id)??[];H.push(Z),K.set(Z.gateway_id,H)}return Y.map((Z)=>this.deserializeGatewayWithConnections(Z,K.get(Z.id)??[]))}async update(Q,J,X){let G=new Date().toISOString(),Y={updated_at:G,updated_by:J};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.toolSelectionStrategy!==void 0)Y.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)Y.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.isDefault===!1)Y.is_default=0;if(X.isDefault===!0)Y.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(K)=>{if(await K.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await K.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await K.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await K.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:a7("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:G}))).execute()}})}else if(await this.db.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:a7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:G}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let G=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:G,updated_by:J}).where("id","=",Q).execute()});let Y=await this.findById(Q);if(!Y)throw Error("Gateway not found after setting default");return Y}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((G)=>({connectionId:G.connection_id,selectedTools:this.parseJson(G.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}wk();Sk();function oj4(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (K90(),VY1));return Q.map((J)=>{return{name:J.name,inputSchema:qU(J.inputSchema),outputSchema:J.outputSchema?qU(J.outputSchema):void 0,description:J.description}})},data:W61(process.env.BASE_URL||"http://localhost:3000")},{data:G61()}]}async function zY1(Q,J){try{let X=Uv(),G=new Iw(process.env.ENCRYPTION_KEY||""),Y=new Cw(X.db,G),W=new Rw(X.db),$=oj4(),K=[];await Promise.all($.map(async(Z)=>{let H=null;if(Z.permissions)H=(await CW.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await Z.getTools?.()??await HU({id:"pending",title:Z.data.title,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=Z.data.id?`${Q}_${Z.data.id}`:void 0,V=await Y.create({...Z.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:Z.data.connection_token??H});K.push(V.id)})),await W.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway for organization",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:K.map((Z)=>({connectionId:Z}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var Z90=["owner","admin","user"],UY1=["owner","admin"];var sj4=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},NY1=(Q)=>{if(Q.providerId==="microsoft")return sj4(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function tj4(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var BY1=["labs","hub","studio","workspace","systems","core","cloud","works"],OY1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function ej4(){let Q=Math.floor(Math.random()*OY1.length),J=Math.floor(Math.random()*BY1.length),X=OY1[Q]??"deco",G=BY1[J]??"studio";return`${X}-${G}`}var QI4=Object.values(eB()).map((Q)=>Q.map((J)=>J.name)).flat(),JI4={...mS,self:["*",...QI4]},U_=r7(JI4),XI4=U_.newRole({self:["*"],...Zw.statements}),YI4=U_.newRole({self:["*"],...Zw.statements}),GI4=U_.newRole({self:["*"],...Zw.statements}),DY1=Object.values(eB()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),K9=Xv.auth,LY1=void 0;if(K9.inviteEmailProviderId&&K9.emailProviders&&K9.emailProviders.length>0){let Q=Bv(K9.emailProviders,K9.inviteEmailProviderId);if(Q){let J=Nv(Q);LY1=async(X)=>{let G=X.inviter.user?.name||X.inviter.user?.email,Y=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
1065
1065
  <h2>You've been invited!</h2>
1066
1066
  <p>${G} has invited you to join <strong>${X.organization.name}</strong>.</p>
1067
1067
  <p><a href="${Y}">Click here to accept the invitation</a></p>
@@ -1114,7 +1114,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
1114
1114
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
1115
1115
 
1116
1116
  Option 2 - OIDC token:
1117
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:$,statusCode:Y,cause:W})}},KK1="GatewayInvalidRequestError",Hy4=`vercel.ai.gateway.error.${KK1}`,l$1=Symbol.for(Hy4),d$1,p$1,qy4=class extends(p$1=gJ,d$1=l$1,p$1){constructor({message:Q="Invalid request",statusCode:J=400,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[d$1]=!0,this.name=KK1,this.type="invalid_request_error"}static isInstance(Q){return gJ.hasMarker(Q)&&l$1 in Q}},ZK1="GatewayRateLimitError",Fy4=`vercel.ai.gateway.error.${ZK1}`,c$1=Symbol.for(Fy4),n$1,i$1,Vy4=class extends(i$1=gJ,n$1=c$1,i$1){constructor({message:Q="Rate limit exceeded",statusCode:J=429,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[n$1]=!0,this.name=ZK1,this.type="rate_limit_exceeded"}static isInstance(Q){return gJ.hasMarker(Q)&&c$1 in Q}},HK1="GatewayModelNotFoundError",zy4=`vercel.ai.gateway.error.${HK1}`,r$1=Symbol.for(zy4),Uy4=wQ(()=>u5(I.object({modelId:I.string()}))),a$1,o$1,Ny4=class extends(o$1=gJ,a$1=r$1,o$1){constructor({message:Q="Model not found",statusCode:J=404,modelId:X,cause:G}={}){super({message:Q,statusCode:J,cause:G});this[a$1]=!0,this.name=HK1,this.type="model_not_found",this.modelId=X}static isInstance(Q){return gJ.hasMarker(Q)&&r$1 in Q}},qK1="GatewayInternalServerError",By4=`vercel.ai.gateway.error.${qK1}`,s$1=Symbol.for(By4),t$1,e$1,QK1=class extends(e$1=gJ,t$1=s$1,e$1){constructor({message:Q="Internal server error",statusCode:J=500,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[t$1]=!0,this.name=qK1,this.type="internal_server_error"}static isInstance(Q){return gJ.hasMarker(Q)&&s$1 in Q}},FK1="GatewayResponseError",Oy4=`vercel.ai.gateway.error.${FK1}`,JK1=Symbol.for(Oy4),XK1,YK1,Dy4=class extends(YK1=gJ,XK1=JK1,YK1){constructor({message:Q="Invalid response from Gateway",statusCode:J=502,response:X,validationError:G,cause:Y}={}){super({message:Q,statusCode:J,cause:Y});this[XK1]=!0,this.name=FK1,this.type="response_error",this.response=X,this.validationError=G}static isInstance(Q){return gJ.hasMarker(Q)&&JK1 in Q}};async function GK1({response:Q,statusCode:J,defaultMessage:X="Gateway request failed",cause:G,authMethod:Y}){let W=await PQ({value:Q,schema:Ly4});if(!W.success)return new Dy4({message:`Invalid error response format: ${X}`,statusCode:J,response:Q,validationError:W.error,cause:G});let $=W.value,K=$.error.type,Z=$.error.message;switch(K){case"authentication_error":return ky.createContextualError({apiKeyProvided:Y==="api-key",oidcTokenProvided:Y==="oidc",statusCode:J,cause:G});case"invalid_request_error":return new qy4({message:Z,statusCode:J,cause:G});case"rate_limit_exceeded":return new Vy4({message:Z,statusCode:J,cause:G});case"model_not_found":{let H=await PQ({value:$.error.param,schema:Uy4});return new Ny4({message:Z,statusCode:J,modelId:H.success?H.value.modelId:void 0,cause:G})}case"internal_server_error":return new QK1({message:Z,statusCode:J,cause:G});default:return new QK1({message:Z,statusCode:J,cause:G})}}var Ly4=wQ(()=>u5(I.object({error:I.object({message:I.string(),type:I.string().nullish(),param:I.unknown().nullish(),code:I.union([I.string(),I.number()]).nullish()})})));function QZ(Q,J){var X;if(gJ.isInstance(Q))return Q;if(Z9.isInstance(Q))return GK1({response:wy4(Q),statusCode:(X=Q.statusCode)!=null?X:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:J});return GK1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:J})}function wy4(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(J){return Q.responseBody}return{}}var VK1="ai-gateway-auth-method";async function oU(Q){let J=await PQ({value:Q[VK1],schema:Py4});return J.success?J.value:void 0}var Py4=wQ(()=>u5(I.union([I.literal("api-key"),I.literal("oidc")]))),WK1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await nX0({url:`${this.config.baseURL}/config`,headers:await L5(this.config.headers()),successfulResponseHandler:uW(My4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(J)=>J}),fetch:this.config.fetch});return Q}catch(Q){throw await QZ(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:J}=await nX0({url:`${Q.origin}/v1/credits`,headers:await L5(this.config.headers()),successfulResponseHandler:uW(Ty4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return J}catch(Q){throw await QZ(Q)}}},My4=wQ(()=>u5(I.object({models:I.array(I.object({id:I.string(),name:I.string(),description:I.string().nullish(),pricing:I.object({input:I.string(),output:I.string(),input_cache_read:I.string().nullish(),input_cache_write:I.string().nullish()}).transform(({input:Q,output:J,input_cache_read:X,input_cache_write:G})=>({input:Q,output:J,...X?{cachedInputTokens:X}:{},...G?{cacheCreationInputTokens:G}:{}})).nullish(),specification:I.object({specificationVersion:I.literal("v3"),provider:I.string(),modelId:I.string()}),modelType:I.enum(["language","embedding","image"]).nullish()}))}))),Ty4=wQ(()=>u5(I.object({balance:I.string(),total_used:I.string()}).transform(({balance:Q,total_used:J})=>({balance:Q,totalUsed:J})))),Ay4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:J,...X}=Q;return{args:this.maybeEncodeFileParts(X),warnings:[]}}async doGenerate(Q){let{args:J,warnings:X}=await this.getArgs(Q),{abortSignal:G}=Q,Y=await L5(this.config.headers());try{let{responseHeaders:W,value:$,rawValue:K}=await Uq({url:this.getUrl(),headers:Vq(Y,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await L5(this.config.o11yHeaders)),body:J,successfulResponseHandler:uW(I.any()),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(Z)=>Z}),...G&&{abortSignal:G},fetch:this.config.fetch});return{...$,request:{body:J},response:{headers:W,body:K},warnings:X}}catch(W){throw await QZ(W,await oU(Y))}}async doStream(Q){let{args:J,warnings:X}=await this.getArgs(Q),{abortSignal:G}=Q,Y=await L5(this.config.headers());try{let{value:W,responseHeaders:$}=await Uq({url:this.getUrl(),headers:Vq(Y,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await L5(this.config.o11yHeaders)),body:J,successfulResponseHandler:mW1(I.any()),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(K)=>K}),...G&&{abortSignal:G},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start(K){if(X.length>0)K.enqueue({type:"stream-start",warnings:X})},transform(K,Z){if(K.success){let H=K.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);Z.enqueue(H)}else Z.error(K.error)}})),request:{body:J},response:{headers:$}}}catch(W){throw await QZ(W,await oU(Y))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let J of Q.prompt)for(let X of J.content)if(this.isFilePart(X)){let G=X;if(G.data instanceof Uint8Array){let Y=Uint8Array.from(G.data),W=Buffer.from(Y).toString("base64");G.data=new URL(`data:${G.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,J){return{"ai-language-model-specification-version":"2","ai-language-model-id":Q,"ai-language-model-streaming":String(J)}}},Ey4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:J,abortSignal:X,providerOptions:G}){var Y;let W=await L5(this.config.headers());try{let{responseHeaders:$,value:K,rawValue:Z}=await Uq({url:this.getUrl(),headers:Vq(W,J!=null?J:{},this.getModelConfigHeaders(),await L5(this.config.o11yHeaders)),body:{values:Q,...G?{providerOptions:G}:{}},successfulResponseHandler:uW(jy4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(H)=>H}),...X&&{abortSignal:X},fetch:this.config.fetch});return{embeddings:K.embeddings,usage:(Y=K.usage)!=null?Y:void 0,providerMetadata:K.providerMetadata,response:{headers:$,body:Z},warnings:[]}}catch($){throw await QZ($,await oU(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},jy4=wQ(()=>u5(I.object({embeddings:I.array(I.array(I.number())),usage:I.object({tokens:I.number()}).nullish(),providerMetadata:I.record(I.string(),I.record(I.string(),I.unknown())).optional()}))),Iy4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:J,size:X,aspectRatio:G,seed:Y,providerOptions:W,headers:$,abortSignal:K}){var Z;let H=await L5(this.config.headers());try{let{responseHeaders:q,value:F,rawValue:V}=await Uq({url:this.getUrl(),headers:Vq(H,$!=null?$:{},this.getModelConfigHeaders(),await L5(this.config.o11yHeaders)),body:{prompt:Q,n:J,...X&&{size:X},...G&&{aspectRatio:G},...Y&&{seed:Y},...W&&{providerOptions:W}},successfulResponseHandler:uW(Ry4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(z)=>z}),...K&&{abortSignal:K},fetch:this.config.fetch});return{images:F.images,warnings:(Z=F.warnings)!=null?Z:[],providerMetadata:F.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw QZ(q,await oU(H))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},Cy4=I.object({images:I.array(I.unknown()).optional()}).catchall(I.unknown()),Ry4=I.object({images:I.array(I.string()),warnings:I.array(I.object({type:I.literal("other"),message:I.string()})).optional(),providerMetadata:I.record(I.string(),Cy4).optional()});async function Sy4(){var Q;return(Q=zK1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var vy4="3.0.0",ky4="0.0.1";function _y4(Q={}){var J,X;let G=null,Y=null,W=(J=Q.metadataCacheRefreshMillis)!=null?J:300000,$=0,K=(X=lW1(Q.baseURL))!=null?X:"https://ai-gateway.vercel.sh/v3/ai",Z=async()=>{let N=await yy4(Q);if(N)return lX({Authorization:`Bearer ${N.token}`,"ai-gateway-protocol-version":ky4,[VK1]:N.authMethod,...Q.headers},`ai-sdk/gateway/${vy4}`);throw ky.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},H=()=>{let N=TM({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),D=TM({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=TM({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let A=await Sy4();return{...N&&{"ai-o11y-deployment-id":N},...D&&{"ai-o11y-environment":D},...w&&{"ai-o11y-region":w},...A&&{"ai-o11y-request-id":A}}}},q=(N)=>{return new Ay4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})},F=async()=>{var N,D,w;let A=(w=(D=(N=Q._internal)==null?void 0:N.currentDate)==null?void 0:D.call(N).getTime())!=null?w:Date.now();if(!G||A-$>W)$=A,G=new WK1({baseURL:K,headers:Z,fetch:Q.fetch}).getAvailableModels().then((M)=>{return Y=M,M}).catch(async(M)=>{throw await QZ(M,await oU(await Z()))});return Y?Promise.resolve(Y):G},V=async()=>{return new WK1({baseURL:K,headers:Z,fetch:Q.fetch}).getCredits().catch(async(N)=>{throw await QZ(N,await oU(await Z()))})},z=function(N){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return q(N)};z.specificationVersion="v3",z.getAvailableModels=F,z.getCredits=V,z.imageModel=(N)=>{return new Iy4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})},z.languageModel=q;let U=(N)=>{return new Ey4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})};return z.embeddingModel=U,z.textEmbeddingModel=U,z}var NK1=_y4();async function yy4(Q){let J=TM({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(J)return{token:J,authMethod:"api-key"};try{return{token:await UK1.getVercelOidcToken(),authMethod:"oidc"}}catch(X){return null}}var $Z1=i4(q1(),1),DY0=i4(q1(),1);var hy4=Object.defineProperty,fy4=(Q,J)=>{for(var X in J)hy4(Q,X,{get:J[X],enumerable:!0})},AK1="AI_InvalidArgumentError",EK1=`vercel.ai.error.${AK1}`,by4=Symbol.for(EK1),jK1,WG=class extends E1{constructor({parameter:Q,value:J,message:X}){super({name:AK1,message:`Invalid argument for parameter ${Q}: ${X}`});this[jK1]=!0,this.parameter=Q,this.value=J}static isInstance(Q){return E1.hasMarker(Q,EK1)}};jK1=by4;var xy4="AI_InvalidStreamPartError",gy4=`vercel.ai.error.${xy4}`,uy4=Symbol.for(gy4),my4;my4=uy4;var IK1="AI_InvalidToolInputError",CK1=`vercel.ai.error.${IK1}`,ly4=Symbol.for(CK1),RK1,TY0=class extends E1{constructor({toolInput:Q,toolName:J,cause:X,message:G=`Invalid input for tool ${J}: ${XG(X)}`}){super({name:IK1,message:G,cause:X});this[RK1]=!0,this.toolInput=Q,this.toolName=J}static isInstance(Q){return E1.hasMarker(Q,CK1)}};RK1=ly4;var dy4="AI_NoImageGeneratedError",py4=`vercel.ai.error.${dy4}`,cy4=Symbol.for(py4),ny4;ny4=cy4;var SK1="AI_NoObjectGeneratedError",vK1=`vercel.ai.error.${SK1}`,iy4=Symbol.for(vK1),kK1,JZ=class extends E1{constructor({message:Q="No object generated.",cause:J,text:X,response:G,usage:Y,finishReason:W}){super({name:SK1,message:Q,cause:J});this[kK1]=!0,this.text=X,this.response=G,this.usage=Y,this.finishReason=W}static isInstance(Q){return E1.hasMarker(Q,vK1)}};kK1=iy4;var _K1="AI_NoOutputGeneratedError",yK1=`vercel.ai.error.${_K1}`,ry4=Symbol.for(yK1),hK1,ay4=class extends E1{constructor({message:Q="No output generated.",cause:J}={}){super({name:_K1,message:Q,cause:J});this[hK1]=!0}static isInstance(Q){return E1.hasMarker(Q,yK1)}};hK1=ry4;var fK1="AI_NoSuchToolError",bK1=`vercel.ai.error.${fK1}`,oy4=Symbol.for(bK1),xK1,BY0=class extends E1{constructor({toolName:Q,availableTools:J=void 0,message:X=`Model tried to call unavailable tool '${Q}'. ${J===void 0?"No tools are available.":`Available tools: ${J.join(", ")}.`}`}){super({name:fK1,message:X});this[xK1]=!0,this.toolName=Q,this.availableTools=J}static isInstance(Q){return E1.hasMarker(Q,bK1)}};xK1=oy4;var gK1="AI_ToolCallRepairError",uK1=`vercel.ai.error.${gK1}`,sy4=Symbol.for(uK1),mK1,ty4=class extends E1{constructor({cause:Q,originalError:J,message:X=`Error repairing tool call: ${XG(Q)}`}){super({name:gK1,message:X,cause:Q});this[mK1]=!0,this.originalError=J}static isInstance(Q){return E1.hasMarker(Q,uK1)}};mK1=sy4;var ey4=class extends E1{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}},Qh4="AI_InvalidDataContentError",Jh4=`vercel.ai.error.${Qh4}`,Xh4=Symbol.for(Jh4),Yh4;Yh4=Xh4;var lK1="AI_InvalidMessageRoleError",dK1=`vercel.ai.error.${lK1}`,Gh4=Symbol.for(dK1),pK1,Wh4=class extends E1{constructor({role:Q,message:J=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lK1,message:J});this[pK1]=!0,this.role=Q}static isInstance(Q){return E1.hasMarker(Q,dK1)}};pK1=Gh4;var cK1="AI_MessageConversionError",nK1=`vercel.ai.error.${cK1}`,$h4=Symbol.for(nK1),iK1,Kh4=class extends E1{constructor({originalMessage:Q,message:J}){super({name:cK1,message:J});this[iK1]=!0,this.originalMessage=Q}static isInstance(Q){return E1.hasMarker(Q,nK1)}};iK1=$h4;var rK1="AI_RetryError",aK1=`vercel.ai.error.${rK1}`,Zh4=Symbol.for(aK1),oK1,BK1=class extends E1{constructor({message:Q,reason:J,errors:X}){super({name:rK1,message:Q});this[oK1]=!0,this.reason=J,this.errors=X,this.lastError=X[X.length-1]}static isInstance(Q){return E1.hasMarker(Q,aK1)}};oK1=Zh4;function Hh4({warning:Q,provider:J,model:X}){let G=`AI SDK Warning (${J} / ${X}):`;switch(Q.type){case"unsupported":{let Y=`${G} The feature "${Q.feature}" is not supported.`;if(Q.details)Y+=` ${Q.details}`;return Y}case"compatibility":{let Y=`${G} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)Y+=` ${Q.details}`;return Y}case"other":return`${G} ${Q.message}`;default:return`${G} ${JSON.stringify(Q,null,2)}`}}var qh4="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",OK1=!1,sK1=(Q)=>{if(Q.warnings.length===0)return;let J=globalThis.AI_SDK_LOG_WARNINGS;if(J===!1)return;if(typeof J==="function"){J(Q);return}if(!OK1)OK1=!0,console.info(qh4);for(let X of Q.warnings)console.warn(Hh4({warning:X,provider:Q.provider,model:Q.model}))};function Fh4({provider:Q,modelId:J}){sK1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:J})}function Vh4(Q){if(Q.specificationVersion==="v3")return Q;return Fh4({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(J,X){switch(X){case"specificationVersion":return"v3";case"doGenerate":return async(...G)=>{let Y=await J.doGenerate(...G);return{...Y,finishReason:tK1(Y.finishReason),usage:eK1(Y.usage)}};case"doStream":return async(...G)=>{let Y=await J.doStream(...G);return{...Y,stream:zh4(Y.stream)}};default:return J[X]}}})}function zh4(Q){return Q.pipeThrough(new TransformStream({transform(J,X){switch(J.type){case"finish":X.enqueue({...J,finishReason:tK1(J.finishReason),usage:eK1(J.usage)});break;default:X.enqueue(J);break}}}))}function tK1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function eK1(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 QZ1(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let J=Q;throw new ey4({version:J.specificationVersion,provider:J.provider,modelId:J.modelId})}return Vh4(Q)}return Uh4().languageModel(Q)}function Uh4(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:NK1}var Nh4=[{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 Bh4=(Q)=>{let J=typeof Q==="string"?cU(Q):Q,X=(J[6]&127)<<21|(J[7]&127)<<14|(J[8]&127)<<7|J[9]&127;return J.slice(X+10)};function Oh4(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?Bh4(Q):Q}function Dh4({data:Q,signatures:J}){let X=Oh4(Q),G=typeof X==="string"?cU(X.substring(0,Math.min(X.length,24))):X;for(let Y of J)if(G.length>=Y.bytesPrefix.length&&Y.bytesPrefix.every((W,$)=>W===null||G[$]===W))return Y.mediaType;return}var Lh4="6.0.1",wh4=async({url:Q})=>{var J;let X=Q.toString();try{let G=await fetch(X,{headers:lX({},`ai-sdk/${Lh4}`,eK())});if(!G.ok)throw new wy({url:X,statusCode:G.status,statusText:G.statusText});return{data:new Uint8Array(await G.arrayBuffer()),mediaType:(J=G.headers.get("content-type"))!=null?J:void 0}}catch(G){if(wy.isInstance(G))throw G;throw new wy({url:X,cause:G})}},Ph4=(Q=wh4)=>(J)=>Promise.all(J.map(async(X)=>X.isUrlSupportedByModel?null:Q(X)));function Mh4(Q){try{let[J,X]=Q.split(",");return{mediaType:J.split(";")[0].split(":")[1],base64Content:X}}catch(J){return{mediaType:void 0,base64Content:void 0}}}var JZ1=I.union([I.string(),I.instanceof(Uint8Array),I.instanceof(ArrayBuffer),I.custom((Q)=>{var J,X;return(X=(J=globalThis.Buffer)==null?void 0:J.isBuffer(Q))!=null?X:!1},{message:"Must be a Buffer"})]);function XZ1(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(J){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:J,base64Content:X}=Mh4(Q.toString());if(J==null||X==null)throw new E1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:X,mediaType:J}}return{data:Q,mediaType:void 0}}function Th4(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return PM(new Uint8Array(Q));return PM(Q)}function hy(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function Ah4({prompt:Q,supportedUrls:J,download:X=Ph4()}){let G=await jh4(Q.messages,X,J),Y=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:hy(Q.system).map(($)=>({role:"system",content:$.content,providerOptions:$.providerOptions})):[],...Q.messages.map(($)=>Eh4({message:$,downloadedAssets:G}))],W=[];for(let $ of Y){if($.role!=="tool"){W.push($);continue}let K=W.at(-1);if((K==null?void 0:K.role)==="tool")K.content.push(...$.content);else W.push($)}return W}function Eh4({message:Q,downloadedAssets:J}){let X=Q.role;switch(X){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((G)=>Ih4(G,J)).filter((G)=>G.type!=="text"||G.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((G)=>G.type!=="text"||G.text!==""||G.providerOptions!=null).filter((G)=>G.type!=="tool-approval-request").map((G)=>{let Y=G.providerOptions;switch(G.type){case"file":{let{data:W,mediaType:$}=XZ1(G.data);return{type:"file",data:W,filename:G.filename,mediaType:$!=null?$:G.mediaType,providerOptions:Y}}case"reasoning":return{type:"reasoning",text:G.text,providerOptions:Y};case"text":return{type:"text",text:G.text,providerOptions:Y};case"tool-call":return{type:"tool-call",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,providerExecuted:G.providerExecuted,providerOptions:Y};case"tool-result":return{type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,output:DK1(G.output),providerOptions:Y}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((G)=>G.type!=="tool-approval-response").map((G)=>({type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,output:DK1(G.output),providerOptions:G.providerOptions})),providerOptions:Q.providerOptions};default:throw new Wh4({role:X})}}async function jh4(Q,J,X){let G=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 $;let K=($=W.mediaType)!=null?$:W.type==="image"?"image/*":void 0,Z=W.type==="image"?W.image:W.data;if(typeof Z==="string")try{Z=new URL(Z)}catch(H){}return{mediaType:K,data:Z}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&_W1({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:X})})),Y=await J(G);return Object.fromEntries(Y.map((W,$)=>W==null?null:[G[$].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function Ih4(Q,J){var X;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let G,Y=Q.type;switch(Y){case"image":G=Q.image;break;case"file":G=Q.data;break;default:throw Error(`Unsupported part type: ${Y}`)}let{data:W,mediaType:$}=XZ1(G),K=$!=null?$:Q.mediaType,Z=W;if(Z instanceof URL){let H=J[Z.toString()];if(H)Z=H.data,K!=null||(K=H.mediaType)}switch(Y){case"image":{if(Z instanceof Uint8Array||typeof Z==="string")K=(X=Dh4({data:Z,signatures:Nh4}))!=null?X:K;return{type:"file",mediaType:K!=null?K:"image/*",filename:void 0,data:Z,providerOptions:Q.providerOptions}}case"file":{if(K==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:K,filename:Q.filename,data:Z,providerOptions:Q.providerOptions}}}}function DK1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((J)=>{if(J.type!=="media")return J;if(J.mediaType.startsWith("image/"))return{type:"image-data",data:J.data,mediaType:J.mediaType};return{type:"file-data",data:J.data,mediaType:J.mediaType}})}}async function tU({toolCallId:Q,input:J,output:X,tool:G,errorMode:Y}){if(Y==="text")return{type:"error-text",value:XG(X)};else if(Y==="json")return{type:"error-json",value:LK1(X)};if(G==null?void 0:G.toModelOutput)return await G.toModelOutput({toolCallId:Q,input:J,output:X});return typeof X==="string"?{type:"text",value:X}:{type:"json",value:LK1(X)}}function LK1(Q){return Q===void 0?null:Q}function Ch4({maxOutputTokens:Q,temperature:J,topP:X,topK:G,presencePenalty:Y,frequencyPenalty:W,seed:$,stopSequences:K}){if(Q!=null){if(!Number.isInteger(Q))throw new WG({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new WG({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(J!=null){if(typeof J!=="number")throw new WG({parameter:"temperature",value:J,message:"temperature must be a number"})}if(X!=null){if(typeof X!=="number")throw new WG({parameter:"topP",value:X,message:"topP must be a number"})}if(G!=null){if(typeof G!=="number")throw new WG({parameter:"topK",value:G,message:"topK must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new WG({parameter:"presencePenalty",value:Y,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new WG({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if($!=null){if(!Number.isInteger($))throw new WG({parameter:"seed",value:$,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:J,topP:X,topK:G,presencePenalty:Y,frequencyPenalty:W,stopSequences:K,seed:$}}function Rh4(Q){return Q!=null&&Object.keys(Q).length>0}async function Sh4({tools:Q,toolChoice:J,activeTools:X}){if(!Rh4(Q))return{tools:void 0,toolChoice:void 0};let G=X!=null?Object.entries(Q).filter(([W])=>X.includes(W)):Object.entries(Q),Y=[];for(let[W,$]of G){let K=$.type;switch(K){case void 0:case"dynamic":case"function":Y.push({type:"function",name:W,description:$.description,inputSchema:await gW($.inputSchema).jsonSchema,...$.inputExamples!=null?{inputExamples:$.inputExamples}:{},providerOptions:$.providerOptions,...$.strict!=null?{strict:$.strict}:{}});break;case"provider":Y.push({type:"provider",name:W,id:$.id,args:$.args});break;default:throw Error(`Unsupported tool type: ${K}`)}}return{tools:Y,toolChoice:J==null?{type:"auto"}:typeof J==="string"?{type:J}:{type:"tool",toolName:J.toolName}}}var SM=I.lazy(()=>I.union([I.null(),I.string(),I.number(),I.boolean(),I.record(I.string(),SM.optional()),I.array(SM)])),t1=I.record(I.string(),I.record(I.string(),SM.optional())),YZ1=I.object({type:I.literal("text"),text:I.string(),providerOptions:t1.optional()}),vh4=I.object({type:I.literal("image"),image:I.union([JZ1,I.instanceof(URL)]),mediaType:I.string().optional(),providerOptions:t1.optional()}),GZ1=I.object({type:I.literal("file"),data:I.union([JZ1,I.instanceof(URL)]),filename:I.string().optional(),mediaType:I.string(),providerOptions:t1.optional()}),kh4=I.object({type:I.literal("reasoning"),text:I.string(),providerOptions:t1.optional()}),_h4=I.object({type:I.literal("tool-call"),toolCallId:I.string(),toolName:I.string(),input:I.unknown(),providerOptions:t1.optional(),providerExecuted:I.boolean().optional()}),yh4=I.discriminatedUnion("type",[I.object({type:I.literal("text"),value:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("json"),value:SM,providerOptions:t1.optional()}),I.object({type:I.literal("execution-denied"),reason:I.string().optional(),providerOptions:t1.optional()}),I.object({type:I.literal("error-text"),value:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("error-json"),value:SM,providerOptions:t1.optional()}),I.object({type:I.literal("content"),value:I.array(I.union([I.object({type:I.literal("text"),text:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("media"),data:I.string(),mediaType:I.string()}),I.object({type:I.literal("file-data"),data:I.string(),mediaType:I.string(),filename:I.string().optional(),providerOptions:t1.optional()}),I.object({type:I.literal("file-url"),url:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("file-id"),fileId:I.union([I.string(),I.record(I.string(),I.string())]),providerOptions:t1.optional()}),I.object({type:I.literal("image-data"),data:I.string(),mediaType:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("image-url"),url:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("image-file-id"),fileId:I.union([I.string(),I.record(I.string(),I.string())]),providerOptions:t1.optional()}),I.object({type:I.literal("custom"),providerOptions:t1.optional()})]))})]),WZ1=I.object({type:I.literal("tool-result"),toolCallId:I.string(),toolName:I.string(),output:yh4,providerOptions:t1.optional()}),hh4=I.object({type:I.literal("tool-approval-request"),approvalId:I.string(),toolCallId:I.string()}),fh4=I.object({type:I.literal("tool-approval-response"),approvalId:I.string(),approved:I.boolean(),reason:I.string().optional()}),bh4=I.object({role:I.literal("system"),content:I.string(),providerOptions:t1.optional()}),xh4=I.object({role:I.literal("user"),content:I.union([I.string(),I.array(I.union([YZ1,vh4,GZ1]))]),providerOptions:t1.optional()}),gh4=I.object({role:I.literal("assistant"),content:I.union([I.string(),I.array(I.union([YZ1,GZ1,kh4,_h4,WZ1,hh4]))]),providerOptions:t1.optional()}),uh4=I.object({role:I.literal("tool"),content:I.array(I.union([WZ1,fh4])),providerOptions:t1.optional()}),mh4=I.union([bh4,xh4,gh4,uh4]);async function lh4(Q){if(Q.prompt==null&&Q.messages==null)throw new Yq({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new Yq({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!hy(Q.system).every((G)=>typeof G==="object"&&G!==null&&("role"in G)&&G.role==="system"))throw new Yq({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let J;if(Q.prompt!=null&&typeof Q.prompt==="string")J=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))J=Q.prompt;else if(Q.messages!=null)J=Q.messages;else throw new Yq({prompt:Q,message:"prompt or messages must be defined"});if(J.length===0)throw new Yq({prompt:Q,message:"messages must not be empty"});let X=await PQ({value:J,schema:I.array(mh4)});if(!X.success)throw new Yq({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:X.error});return{messages:J,system:Q.system}}function dh4(Q){if(!ky.isInstance(Q))return Q;let J=(process==null?void 0:"production")==="production",X="https://ai-sdk.dev/unauthenticated-ai-gateway";if(J)return new E1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${X}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
1117
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:$,statusCode:Y,cause:W})}},KK1="GatewayInvalidRequestError",Hy4=`vercel.ai.gateway.error.${KK1}`,l$1=Symbol.for(Hy4),d$1,p$1,qy4=class extends(p$1=gJ,d$1=l$1,p$1){constructor({message:Q="Invalid request",statusCode:J=400,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[d$1]=!0,this.name=KK1,this.type="invalid_request_error"}static isInstance(Q){return gJ.hasMarker(Q)&&l$1 in Q}},ZK1="GatewayRateLimitError",Fy4=`vercel.ai.gateway.error.${ZK1}`,c$1=Symbol.for(Fy4),n$1,i$1,Vy4=class extends(i$1=gJ,n$1=c$1,i$1){constructor({message:Q="Rate limit exceeded",statusCode:J=429,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[n$1]=!0,this.name=ZK1,this.type="rate_limit_exceeded"}static isInstance(Q){return gJ.hasMarker(Q)&&c$1 in Q}},HK1="GatewayModelNotFoundError",zy4=`vercel.ai.gateway.error.${HK1}`,r$1=Symbol.for(zy4),Uy4=wQ(()=>u5(I.object({modelId:I.string()}))),a$1,o$1,Ny4=class extends(o$1=gJ,a$1=r$1,o$1){constructor({message:Q="Model not found",statusCode:J=404,modelId:X,cause:G}={}){super({message:Q,statusCode:J,cause:G});this[a$1]=!0,this.name=HK1,this.type="model_not_found",this.modelId=X}static isInstance(Q){return gJ.hasMarker(Q)&&r$1 in Q}},qK1="GatewayInternalServerError",By4=`vercel.ai.gateway.error.${qK1}`,s$1=Symbol.for(By4),t$1,e$1,QK1=class extends(e$1=gJ,t$1=s$1,e$1){constructor({message:Q="Internal server error",statusCode:J=500,cause:X}={}){super({message:Q,statusCode:J,cause:X});this[t$1]=!0,this.name=qK1,this.type="internal_server_error"}static isInstance(Q){return gJ.hasMarker(Q)&&s$1 in Q}},FK1="GatewayResponseError",Oy4=`vercel.ai.gateway.error.${FK1}`,JK1=Symbol.for(Oy4),XK1,YK1,Dy4=class extends(YK1=gJ,XK1=JK1,YK1){constructor({message:Q="Invalid response from Gateway",statusCode:J=502,response:X,validationError:G,cause:Y}={}){super({message:Q,statusCode:J,cause:Y});this[XK1]=!0,this.name=FK1,this.type="response_error",this.response=X,this.validationError=G}static isInstance(Q){return gJ.hasMarker(Q)&&JK1 in Q}};async function GK1({response:Q,statusCode:J,defaultMessage:X="Gateway request failed",cause:G,authMethod:Y}){let W=await PQ({value:Q,schema:Ly4});if(!W.success)return new Dy4({message:`Invalid error response format: ${X}`,statusCode:J,response:Q,validationError:W.error,cause:G});let $=W.value,K=$.error.type,Z=$.error.message;switch(K){case"authentication_error":return ky.createContextualError({apiKeyProvided:Y==="api-key",oidcTokenProvided:Y==="oidc",statusCode:J,cause:G});case"invalid_request_error":return new qy4({message:Z,statusCode:J,cause:G});case"rate_limit_exceeded":return new Vy4({message:Z,statusCode:J,cause:G});case"model_not_found":{let H=await PQ({value:$.error.param,schema:Uy4});return new Ny4({message:Z,statusCode:J,modelId:H.success?H.value.modelId:void 0,cause:G})}case"internal_server_error":return new QK1({message:Z,statusCode:J,cause:G});default:return new QK1({message:Z,statusCode:J,cause:G})}}var Ly4=wQ(()=>u5(I.object({error:I.object({message:I.string(),type:I.string().nullish(),param:I.unknown().nullish(),code:I.union([I.string(),I.number()]).nullish()})})));function QZ(Q,J){var X;if(gJ.isInstance(Q))return Q;if(Z9.isInstance(Q))return GK1({response:wy4(Q),statusCode:(X=Q.statusCode)!=null?X:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:J});return GK1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:J})}function wy4(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(J){return Q.responseBody}return{}}var VK1="ai-gateway-auth-method";async function oU(Q){let J=await PQ({value:Q[VK1],schema:Py4});return J.success?J.value:void 0}var Py4=wQ(()=>u5(I.union([I.literal("api-key"),I.literal("oidc")]))),WK1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await nX0({url:`${this.config.baseURL}/config`,headers:await L5(this.config.headers()),successfulResponseHandler:uW(My4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(J)=>J}),fetch:this.config.fetch});return Q}catch(Q){throw await QZ(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:J}=await nX0({url:`${Q.origin}/v1/credits`,headers:await L5(this.config.headers()),successfulResponseHandler:uW(Ty4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return J}catch(Q){throw await QZ(Q)}}},My4=wQ(()=>u5(I.object({models:I.array(I.object({id:I.string(),name:I.string(),description:I.string().nullish(),pricing:I.object({input:I.string(),output:I.string(),input_cache_read:I.string().nullish(),input_cache_write:I.string().nullish()}).transform(({input:Q,output:J,input_cache_read:X,input_cache_write:G})=>({input:Q,output:J,...X?{cachedInputTokens:X}:{},...G?{cacheCreationInputTokens:G}:{}})).nullish(),specification:I.object({specificationVersion:I.literal("v3"),provider:I.string(),modelId:I.string()}),modelType:I.enum(["language","embedding","image"]).nullish()}))}))),Ty4=wQ(()=>u5(I.object({balance:I.string(),total_used:I.string()}).transform(({balance:Q,total_used:J})=>({balance:Q,totalUsed:J})))),Ay4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:J,...X}=Q;return{args:this.maybeEncodeFileParts(X),warnings:[]}}async doGenerate(Q){let{args:J,warnings:X}=await this.getArgs(Q),{abortSignal:G}=Q,Y=await L5(this.config.headers());try{let{responseHeaders:W,value:$,rawValue:K}=await Uq({url:this.getUrl(),headers:Vq(Y,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await L5(this.config.o11yHeaders)),body:J,successfulResponseHandler:uW(I.any()),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(Z)=>Z}),...G&&{abortSignal:G},fetch:this.config.fetch});return{...$,request:{body:J},response:{headers:W,body:K},warnings:X}}catch(W){throw await QZ(W,await oU(Y))}}async doStream(Q){let{args:J,warnings:X}=await this.getArgs(Q),{abortSignal:G}=Q,Y=await L5(this.config.headers());try{let{value:W,responseHeaders:$}=await Uq({url:this.getUrl(),headers:Vq(Y,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await L5(this.config.o11yHeaders)),body:J,successfulResponseHandler:mW1(I.any()),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(K)=>K}),...G&&{abortSignal:G},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start(K){if(X.length>0)K.enqueue({type:"stream-start",warnings:X})},transform(K,Z){if(K.success){let H=K.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);Z.enqueue(H)}else Z.error(K.error)}})),request:{body:J},response:{headers:$}}}catch(W){throw await QZ(W,await oU(Y))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let J of Q.prompt)for(let X of J.content)if(this.isFilePart(X)){let G=X;if(G.data instanceof Uint8Array){let Y=Uint8Array.from(G.data),W=Buffer.from(Y).toString("base64");G.data=new URL(`data:${G.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,J){return{"ai-language-model-specification-version":"2","ai-language-model-id":Q,"ai-language-model-streaming":String(J)}}},Ey4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:J,abortSignal:X,providerOptions:G}){var Y;let W=await L5(this.config.headers());try{let{responseHeaders:$,value:K,rawValue:Z}=await Uq({url:this.getUrl(),headers:Vq(W,J!=null?J:{},this.getModelConfigHeaders(),await L5(this.config.o11yHeaders)),body:{values:Q,...G?{providerOptions:G}:{}},successfulResponseHandler:uW(jy4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(H)=>H}),...X&&{abortSignal:X},fetch:this.config.fetch});return{embeddings:K.embeddings,usage:(Y=K.usage)!=null?Y:void 0,providerMetadata:K.providerMetadata,response:{headers:$,body:Z},warnings:[]}}catch($){throw await QZ($,await oU(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},jy4=wQ(()=>u5(I.object({embeddings:I.array(I.array(I.number())),usage:I.object({tokens:I.number()}).nullish(),providerMetadata:I.record(I.string(),I.record(I.string(),I.unknown())).optional()}))),Iy4=class{constructor(Q,J){this.modelId=Q,this.config=J,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:J,size:X,aspectRatio:G,seed:Y,providerOptions:W,headers:$,abortSignal:K}){var Z;let H=await L5(this.config.headers());try{let{responseHeaders:q,value:F,rawValue:V}=await Uq({url:this.getUrl(),headers:Vq(H,$!=null?$:{},this.getModelConfigHeaders(),await L5(this.config.o11yHeaders)),body:{prompt:Q,n:J,...X&&{size:X},...G&&{aspectRatio:G},...Y&&{seed:Y},...W&&{providerOptions:W}},successfulResponseHandler:uW(Ry4),failedResponseHandler:GG({errorSchema:I.any(),errorToMessage:(z)=>z}),...K&&{abortSignal:K},fetch:this.config.fetch});return{images:F.images,warnings:(Z=F.warnings)!=null?Z:[],providerMetadata:F.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw QZ(q,await oU(H))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},Cy4=I.object({images:I.array(I.unknown()).optional()}).catchall(I.unknown()),Ry4=I.object({images:I.array(I.string()),warnings:I.array(I.object({type:I.literal("other"),message:I.string()})).optional(),providerMetadata:I.record(I.string(),Cy4).optional()});async function Sy4(){var Q;return(Q=zK1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var vy4="3.0.1",ky4="0.0.1";function _y4(Q={}){var J,X;let G=null,Y=null,W=(J=Q.metadataCacheRefreshMillis)!=null?J:300000,$=0,K=(X=lW1(Q.baseURL))!=null?X:"https://ai-gateway.vercel.sh/v3/ai",Z=async()=>{let N=await yy4(Q);if(N)return lX({Authorization:`Bearer ${N.token}`,"ai-gateway-protocol-version":ky4,[VK1]:N.authMethod,...Q.headers},`ai-sdk/gateway/${vy4}`);throw ky.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},H=()=>{let N=TM({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),D=TM({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=TM({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let A=await Sy4();return{...N&&{"ai-o11y-deployment-id":N},...D&&{"ai-o11y-environment":D},...w&&{"ai-o11y-region":w},...A&&{"ai-o11y-request-id":A}}}},q=(N)=>{return new Ay4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})},F=async()=>{var N,D,w;let A=(w=(D=(N=Q._internal)==null?void 0:N.currentDate)==null?void 0:D.call(N).getTime())!=null?w:Date.now();if(!G||A-$>W)$=A,G=new WK1({baseURL:K,headers:Z,fetch:Q.fetch}).getAvailableModels().then((M)=>{return Y=M,M}).catch(async(M)=>{throw await QZ(M,await oU(await Z()))});return Y?Promise.resolve(Y):G},V=async()=>{return new WK1({baseURL:K,headers:Z,fetch:Q.fetch}).getCredits().catch(async(N)=>{throw await QZ(N,await oU(await Z()))})},z=function(N){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return q(N)};z.specificationVersion="v3",z.getAvailableModels=F,z.getCredits=V,z.imageModel=(N)=>{return new Iy4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})},z.languageModel=q;let U=(N)=>{return new Ey4(N,{provider:"gateway",baseURL:K,headers:Z,fetch:Q.fetch,o11yHeaders:H()})};return z.embeddingModel=U,z.textEmbeddingModel=U,z}var NK1=_y4();async function yy4(Q){let J=TM({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(J)return{token:J,authMethod:"api-key"};try{return{token:await UK1.getVercelOidcToken(),authMethod:"oidc"}}catch(X){return null}}var $Z1=i4(q1(),1),DY0=i4(q1(),1);var hy4=Object.defineProperty,fy4=(Q,J)=>{for(var X in J)hy4(Q,X,{get:J[X],enumerable:!0})},AK1="AI_InvalidArgumentError",EK1=`vercel.ai.error.${AK1}`,by4=Symbol.for(EK1),jK1,WG=class extends E1{constructor({parameter:Q,value:J,message:X}){super({name:AK1,message:`Invalid argument for parameter ${Q}: ${X}`});this[jK1]=!0,this.parameter=Q,this.value=J}static isInstance(Q){return E1.hasMarker(Q,EK1)}};jK1=by4;var xy4="AI_InvalidStreamPartError",gy4=`vercel.ai.error.${xy4}`,uy4=Symbol.for(gy4),my4;my4=uy4;var IK1="AI_InvalidToolInputError",CK1=`vercel.ai.error.${IK1}`,ly4=Symbol.for(CK1),RK1,TY0=class extends E1{constructor({toolInput:Q,toolName:J,cause:X,message:G=`Invalid input for tool ${J}: ${XG(X)}`}){super({name:IK1,message:G,cause:X});this[RK1]=!0,this.toolInput=Q,this.toolName=J}static isInstance(Q){return E1.hasMarker(Q,CK1)}};RK1=ly4;var dy4="AI_NoImageGeneratedError",py4=`vercel.ai.error.${dy4}`,cy4=Symbol.for(py4),ny4;ny4=cy4;var SK1="AI_NoObjectGeneratedError",vK1=`vercel.ai.error.${SK1}`,iy4=Symbol.for(vK1),kK1,JZ=class extends E1{constructor({message:Q="No object generated.",cause:J,text:X,response:G,usage:Y,finishReason:W}){super({name:SK1,message:Q,cause:J});this[kK1]=!0,this.text=X,this.response=G,this.usage=Y,this.finishReason=W}static isInstance(Q){return E1.hasMarker(Q,vK1)}};kK1=iy4;var _K1="AI_NoOutputGeneratedError",yK1=`vercel.ai.error.${_K1}`,ry4=Symbol.for(yK1),hK1,ay4=class extends E1{constructor({message:Q="No output generated.",cause:J}={}){super({name:_K1,message:Q,cause:J});this[hK1]=!0}static isInstance(Q){return E1.hasMarker(Q,yK1)}};hK1=ry4;var fK1="AI_NoSuchToolError",bK1=`vercel.ai.error.${fK1}`,oy4=Symbol.for(bK1),xK1,BY0=class extends E1{constructor({toolName:Q,availableTools:J=void 0,message:X=`Model tried to call unavailable tool '${Q}'. ${J===void 0?"No tools are available.":`Available tools: ${J.join(", ")}.`}`}){super({name:fK1,message:X});this[xK1]=!0,this.toolName=Q,this.availableTools=J}static isInstance(Q){return E1.hasMarker(Q,bK1)}};xK1=oy4;var gK1="AI_ToolCallRepairError",uK1=`vercel.ai.error.${gK1}`,sy4=Symbol.for(uK1),mK1,ty4=class extends E1{constructor({cause:Q,originalError:J,message:X=`Error repairing tool call: ${XG(Q)}`}){super({name:gK1,message:X,cause:Q});this[mK1]=!0,this.originalError=J}static isInstance(Q){return E1.hasMarker(Q,uK1)}};mK1=sy4;var ey4=class extends E1{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}},Qh4="AI_InvalidDataContentError",Jh4=`vercel.ai.error.${Qh4}`,Xh4=Symbol.for(Jh4),Yh4;Yh4=Xh4;var lK1="AI_InvalidMessageRoleError",dK1=`vercel.ai.error.${lK1}`,Gh4=Symbol.for(dK1),pK1,Wh4=class extends E1{constructor({role:Q,message:J=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lK1,message:J});this[pK1]=!0,this.role=Q}static isInstance(Q){return E1.hasMarker(Q,dK1)}};pK1=Gh4;var cK1="AI_MessageConversionError",nK1=`vercel.ai.error.${cK1}`,$h4=Symbol.for(nK1),iK1,Kh4=class extends E1{constructor({originalMessage:Q,message:J}){super({name:cK1,message:J});this[iK1]=!0,this.originalMessage=Q}static isInstance(Q){return E1.hasMarker(Q,nK1)}};iK1=$h4;var rK1="AI_RetryError",aK1=`vercel.ai.error.${rK1}`,Zh4=Symbol.for(aK1),oK1,BK1=class extends E1{constructor({message:Q,reason:J,errors:X}){super({name:rK1,message:Q});this[oK1]=!0,this.reason=J,this.errors=X,this.lastError=X[X.length-1]}static isInstance(Q){return E1.hasMarker(Q,aK1)}};oK1=Zh4;function Hh4({warning:Q,provider:J,model:X}){let G=`AI SDK Warning (${J} / ${X}):`;switch(Q.type){case"unsupported":{let Y=`${G} The feature "${Q.feature}" is not supported.`;if(Q.details)Y+=` ${Q.details}`;return Y}case"compatibility":{let Y=`${G} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)Y+=` ${Q.details}`;return Y}case"other":return`${G} ${Q.message}`;default:return`${G} ${JSON.stringify(Q,null,2)}`}}var qh4="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",OK1=!1,sK1=(Q)=>{if(Q.warnings.length===0)return;let J=globalThis.AI_SDK_LOG_WARNINGS;if(J===!1)return;if(typeof J==="function"){J(Q);return}if(!OK1)OK1=!0,console.info(qh4);for(let X of Q.warnings)console.warn(Hh4({warning:X,provider:Q.provider,model:Q.model}))};function Fh4({provider:Q,modelId:J}){sK1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:J})}function Vh4(Q){if(Q.specificationVersion==="v3")return Q;return Fh4({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(J,X){switch(X){case"specificationVersion":return"v3";case"doGenerate":return async(...G)=>{let Y=await J.doGenerate(...G);return{...Y,finishReason:tK1(Y.finishReason),usage:eK1(Y.usage)}};case"doStream":return async(...G)=>{let Y=await J.doStream(...G);return{...Y,stream:zh4(Y.stream)}};default:return J[X]}}})}function zh4(Q){return Q.pipeThrough(new TransformStream({transform(J,X){switch(J.type){case"finish":X.enqueue({...J,finishReason:tK1(J.finishReason),usage:eK1(J.usage)});break;default:X.enqueue(J);break}}}))}function tK1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function eK1(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 QZ1(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let J=Q;throw new ey4({version:J.specificationVersion,provider:J.provider,modelId:J.modelId})}return Vh4(Q)}return Uh4().languageModel(Q)}function Uh4(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:NK1}var Nh4=[{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 Bh4=(Q)=>{let J=typeof Q==="string"?cU(Q):Q,X=(J[6]&127)<<21|(J[7]&127)<<14|(J[8]&127)<<7|J[9]&127;return J.slice(X+10)};function Oh4(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?Bh4(Q):Q}function Dh4({data:Q,signatures:J}){let X=Oh4(Q),G=typeof X==="string"?cU(X.substring(0,Math.min(X.length,24))):X;for(let Y of J)if(G.length>=Y.bytesPrefix.length&&Y.bytesPrefix.every((W,$)=>W===null||G[$]===W))return Y.mediaType;return}var Lh4="6.0.2",wh4=async({url:Q})=>{var J;let X=Q.toString();try{let G=await fetch(X,{headers:lX({},`ai-sdk/${Lh4}`,eK())});if(!G.ok)throw new wy({url:X,statusCode:G.status,statusText:G.statusText});return{data:new Uint8Array(await G.arrayBuffer()),mediaType:(J=G.headers.get("content-type"))!=null?J:void 0}}catch(G){if(wy.isInstance(G))throw G;throw new wy({url:X,cause:G})}},Ph4=(Q=wh4)=>(J)=>Promise.all(J.map(async(X)=>X.isUrlSupportedByModel?null:Q(X)));function Mh4(Q){try{let[J,X]=Q.split(",");return{mediaType:J.split(";")[0].split(":")[1],base64Content:X}}catch(J){return{mediaType:void 0,base64Content:void 0}}}var JZ1=I.union([I.string(),I.instanceof(Uint8Array),I.instanceof(ArrayBuffer),I.custom((Q)=>{var J,X;return(X=(J=globalThis.Buffer)==null?void 0:J.isBuffer(Q))!=null?X:!1},{message:"Must be a Buffer"})]);function XZ1(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(J){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:J,base64Content:X}=Mh4(Q.toString());if(J==null||X==null)throw new E1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:X,mediaType:J}}return{data:Q,mediaType:void 0}}function Th4(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return PM(new Uint8Array(Q));return PM(Q)}function hy(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function Ah4({prompt:Q,supportedUrls:J,download:X=Ph4()}){let G=await jh4(Q.messages,X,J),Y=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:hy(Q.system).map(($)=>({role:"system",content:$.content,providerOptions:$.providerOptions})):[],...Q.messages.map(($)=>Eh4({message:$,downloadedAssets:G}))],W=[];for(let $ of Y){if($.role!=="tool"){W.push($);continue}let K=W.at(-1);if((K==null?void 0:K.role)==="tool")K.content.push(...$.content);else W.push($)}return W}function Eh4({message:Q,downloadedAssets:J}){let X=Q.role;switch(X){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((G)=>Ih4(G,J)).filter((G)=>G.type!=="text"||G.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((G)=>G.type!=="text"||G.text!==""||G.providerOptions!=null).filter((G)=>G.type!=="tool-approval-request").map((G)=>{let Y=G.providerOptions;switch(G.type){case"file":{let{data:W,mediaType:$}=XZ1(G.data);return{type:"file",data:W,filename:G.filename,mediaType:$!=null?$:G.mediaType,providerOptions:Y}}case"reasoning":return{type:"reasoning",text:G.text,providerOptions:Y};case"text":return{type:"text",text:G.text,providerOptions:Y};case"tool-call":return{type:"tool-call",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,providerExecuted:G.providerExecuted,providerOptions:Y};case"tool-result":return{type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,output:DK1(G.output),providerOptions:Y}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((G)=>G.type!=="tool-approval-response").map((G)=>({type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,output:DK1(G.output),providerOptions:G.providerOptions})),providerOptions:Q.providerOptions};default:throw new Wh4({role:X})}}async function jh4(Q,J,X){let G=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 $;let K=($=W.mediaType)!=null?$:W.type==="image"?"image/*":void 0,Z=W.type==="image"?W.image:W.data;if(typeof Z==="string")try{Z=new URL(Z)}catch(H){}return{mediaType:K,data:Z}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&_W1({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:X})})),Y=await J(G);return Object.fromEntries(Y.map((W,$)=>W==null?null:[G[$].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function Ih4(Q,J){var X;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let G,Y=Q.type;switch(Y){case"image":G=Q.image;break;case"file":G=Q.data;break;default:throw Error(`Unsupported part type: ${Y}`)}let{data:W,mediaType:$}=XZ1(G),K=$!=null?$:Q.mediaType,Z=W;if(Z instanceof URL){let H=J[Z.toString()];if(H)Z=H.data,K!=null||(K=H.mediaType)}switch(Y){case"image":{if(Z instanceof Uint8Array||typeof Z==="string")K=(X=Dh4({data:Z,signatures:Nh4}))!=null?X:K;return{type:"file",mediaType:K!=null?K:"image/*",filename:void 0,data:Z,providerOptions:Q.providerOptions}}case"file":{if(K==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:K,filename:Q.filename,data:Z,providerOptions:Q.providerOptions}}}}function DK1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((J)=>{if(J.type!=="media")return J;if(J.mediaType.startsWith("image/"))return{type:"image-data",data:J.data,mediaType:J.mediaType};return{type:"file-data",data:J.data,mediaType:J.mediaType}})}}async function tU({toolCallId:Q,input:J,output:X,tool:G,errorMode:Y}){if(Y==="text")return{type:"error-text",value:XG(X)};else if(Y==="json")return{type:"error-json",value:LK1(X)};if(G==null?void 0:G.toModelOutput)return await G.toModelOutput({toolCallId:Q,input:J,output:X});return typeof X==="string"?{type:"text",value:X}:{type:"json",value:LK1(X)}}function LK1(Q){return Q===void 0?null:Q}function Ch4({maxOutputTokens:Q,temperature:J,topP:X,topK:G,presencePenalty:Y,frequencyPenalty:W,seed:$,stopSequences:K}){if(Q!=null){if(!Number.isInteger(Q))throw new WG({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new WG({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(J!=null){if(typeof J!=="number")throw new WG({parameter:"temperature",value:J,message:"temperature must be a number"})}if(X!=null){if(typeof X!=="number")throw new WG({parameter:"topP",value:X,message:"topP must be a number"})}if(G!=null){if(typeof G!=="number")throw new WG({parameter:"topK",value:G,message:"topK must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new WG({parameter:"presencePenalty",value:Y,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new WG({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if($!=null){if(!Number.isInteger($))throw new WG({parameter:"seed",value:$,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:J,topP:X,topK:G,presencePenalty:Y,frequencyPenalty:W,stopSequences:K,seed:$}}function Rh4(Q){return Q!=null&&Object.keys(Q).length>0}async function Sh4({tools:Q,toolChoice:J,activeTools:X}){if(!Rh4(Q))return{tools:void 0,toolChoice:void 0};let G=X!=null?Object.entries(Q).filter(([W])=>X.includes(W)):Object.entries(Q),Y=[];for(let[W,$]of G){let K=$.type;switch(K){case void 0:case"dynamic":case"function":Y.push({type:"function",name:W,description:$.description,inputSchema:await gW($.inputSchema).jsonSchema,...$.inputExamples!=null?{inputExamples:$.inputExamples}:{},providerOptions:$.providerOptions,...$.strict!=null?{strict:$.strict}:{}});break;case"provider":Y.push({type:"provider",name:W,id:$.id,args:$.args});break;default:throw Error(`Unsupported tool type: ${K}`)}}return{tools:Y,toolChoice:J==null?{type:"auto"}:typeof J==="string"?{type:J}:{type:"tool",toolName:J.toolName}}}var SM=I.lazy(()=>I.union([I.null(),I.string(),I.number(),I.boolean(),I.record(I.string(),SM.optional()),I.array(SM)])),t1=I.record(I.string(),I.record(I.string(),SM.optional())),YZ1=I.object({type:I.literal("text"),text:I.string(),providerOptions:t1.optional()}),vh4=I.object({type:I.literal("image"),image:I.union([JZ1,I.instanceof(URL)]),mediaType:I.string().optional(),providerOptions:t1.optional()}),GZ1=I.object({type:I.literal("file"),data:I.union([JZ1,I.instanceof(URL)]),filename:I.string().optional(),mediaType:I.string(),providerOptions:t1.optional()}),kh4=I.object({type:I.literal("reasoning"),text:I.string(),providerOptions:t1.optional()}),_h4=I.object({type:I.literal("tool-call"),toolCallId:I.string(),toolName:I.string(),input:I.unknown(),providerOptions:t1.optional(),providerExecuted:I.boolean().optional()}),yh4=I.discriminatedUnion("type",[I.object({type:I.literal("text"),value:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("json"),value:SM,providerOptions:t1.optional()}),I.object({type:I.literal("execution-denied"),reason:I.string().optional(),providerOptions:t1.optional()}),I.object({type:I.literal("error-text"),value:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("error-json"),value:SM,providerOptions:t1.optional()}),I.object({type:I.literal("content"),value:I.array(I.union([I.object({type:I.literal("text"),text:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("media"),data:I.string(),mediaType:I.string()}),I.object({type:I.literal("file-data"),data:I.string(),mediaType:I.string(),filename:I.string().optional(),providerOptions:t1.optional()}),I.object({type:I.literal("file-url"),url:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("file-id"),fileId:I.union([I.string(),I.record(I.string(),I.string())]),providerOptions:t1.optional()}),I.object({type:I.literal("image-data"),data:I.string(),mediaType:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("image-url"),url:I.string(),providerOptions:t1.optional()}),I.object({type:I.literal("image-file-id"),fileId:I.union([I.string(),I.record(I.string(),I.string())]),providerOptions:t1.optional()}),I.object({type:I.literal("custom"),providerOptions:t1.optional()})]))})]),WZ1=I.object({type:I.literal("tool-result"),toolCallId:I.string(),toolName:I.string(),output:yh4,providerOptions:t1.optional()}),hh4=I.object({type:I.literal("tool-approval-request"),approvalId:I.string(),toolCallId:I.string()}),fh4=I.object({type:I.literal("tool-approval-response"),approvalId:I.string(),approved:I.boolean(),reason:I.string().optional()}),bh4=I.object({role:I.literal("system"),content:I.string(),providerOptions:t1.optional()}),xh4=I.object({role:I.literal("user"),content:I.union([I.string(),I.array(I.union([YZ1,vh4,GZ1]))]),providerOptions:t1.optional()}),gh4=I.object({role:I.literal("assistant"),content:I.union([I.string(),I.array(I.union([YZ1,GZ1,kh4,_h4,WZ1,hh4]))]),providerOptions:t1.optional()}),uh4=I.object({role:I.literal("tool"),content:I.array(I.union([WZ1,fh4])),providerOptions:t1.optional()}),mh4=I.union([bh4,xh4,gh4,uh4]);async function lh4(Q){if(Q.prompt==null&&Q.messages==null)throw new Yq({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new Yq({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!hy(Q.system).every((G)=>typeof G==="object"&&G!==null&&("role"in G)&&G.role==="system"))throw new Yq({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let J;if(Q.prompt!=null&&typeof Q.prompt==="string")J=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))J=Q.prompt;else if(Q.messages!=null)J=Q.messages;else throw new Yq({prompt:Q,message:"prompt or messages must be defined"});if(J.length===0)throw new Yq({prompt:Q,message:"messages must not be empty"});let X=await PQ({value:J,schema:I.array(mh4)});if(!X.success)throw new Yq({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:X.error});return{messages:J,system:Q.system}}function dh4(Q){if(!ky.isInstance(Q))return Q;let J=(process==null?void 0:"production")==="production",X="https://ai-sdk.dev/unauthenticated-ai-gateway";if(J)return new E1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${X}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
1118
1118
 
1119
1119
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
1120
1120
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/mesh",
3
- "version": "1.0.0-alpha.19",
3
+ "version": "1.0.0-alpha.20",
4
4
  "description": "MCP Mesh - Self-hostable MCP Gateway for managing AI connections and tools",
5
5
  "license": "MIT",
6
6
  "author": "Deco team",
@@ -36,6 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@ai-sdk/mcp": "^1.0.0",
39
+ "@xyflow/react": "^12.10.0",
39
40
  "kysely": "^0.28.8",
40
41
  "kysely-bun-worker": "^0.6.0"
41
42
  },
@@ -80,6 +81,7 @@
80
81
  "@types/react-syntax-highlighter": "^15.5.13",
81
82
  "@vercel/nft": "^1.1.1",
82
83
  "@vitejs/plugin-react": "^5.1.0",
84
+ "@xyflow/react": "^12.10.0",
83
85
  "ai": "^6.0.1",
84
86
  "babel-plugin-react-compiler": "^1.0.0",
85
87
  "better-auth": "1.4.5",
@@ -1 +0,0 @@
1
- import{c as F,r as R,j as t}from"./index-YfohaNt1.js";import{B as G}from"./button-BN_zWXnf.js";import{c as H,D as J,a as Q,b as U}from"./dropdown-menu-DLU49g1s.js";import{I as w}from"./icon-DR1spsQB.js";import{d as X,b as Y,a as Z,T as ee}from"./tooltip-D_78gfFh.js";import{c as L}from"./utils-pyyeDP1p.js";function ne(W){const e=F.c(47),{viewMode:r,onViewModeChange:i,sortKey:I,sortDirection:y,onSort:N,sortOptions:v}=W;let _;e[0]!==v?(_=v===void 0?[]:v,e[0]=v,e[1]=_):_=e[1];const C=_,E=R.useRef(null),B=R.useRef(null);let z;e[2]===Symbol.for("react.memo_cache_sentinel")?(z={left:0,width:0,opacity:0},e[2]=z):z=e[2];const[j,q]=R.useState(z);let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=s=>{if(!s.current)return;const{offsetLeft:o,offsetWidth:A}=s.current;q({left:o,width:A,opacity:1})},e[3]=k):k=e[3];const V=k;let S,T;e[4]!==r?(S=()=>{V(r==="table"?E:B)},T=[r],e[4]=r,e[5]=S,e[6]=T):(S=e[5],T=e[6]),R.useEffect(S,T);let l;e[7]!==r?(l=s=>{s&&setTimeout(()=>{V(r==="table"?E:B)},0)},e[7]=r,e[8]=l):l=e[8];let D;e[9]===Symbol.for("react.memo_cache_sentinel")?(D=t.jsx(X,{children:t.jsxs(Y,{children:[t.jsx(Z,{asChild:!0,children:t.jsx(J,{asChild:!0,children:t.jsx(G,{variant:"outline",size:"icon",className:"size-7 border border-input",children:t.jsx(w,{name:"tune",size:16})})})}),t.jsx(ee,{children:"Search filters"})]})}),e[9]=D):D=e[9];let n;e[10]!==i?(n=()=>{i("table")},e[10]=i,e[11]=n):n=e[11];const O=r==="table"?"text-foreground":"text-muted-foreground";let a;e[12]!==O?(a=L("transition-colors ease-out duration-200",O),e[12]=O,e[13]=a):a=e[13];let c;e[14]!==a?(c=t.jsx(w,{name:"table_rows",size:16,className:a}),e[14]=a,e[15]=c):c=e[15];let d;e[16]!==c||e[17]!==n?(d=t.jsx("button",{ref:E,type:"button",onClick:n,className:"relative z-10 flex-1 flex items-center justify-center gap-2 h-12 px-4 rounded-lg",children:c}),e[16]=c,e[17]=n,e[18]=d):d=e[18];let f;e[19]!==i?(f=()=>{i("cards")},e[19]=i,e[20]=f):f=e[20];const P=r==="cards"?"text-foreground":"text-muted-foreground";let u;e[21]!==P?(u=L("transition-colors ease-out duration-200",P),e[21]=P,e[22]=u):u=e[22];let m;e[23]!==u?(m=t.jsx(w,{name:"grid_view",size:16,className:u}),e[23]=u,e[24]=m):m=e[24];let x;e[25]!==f||e[26]!==m?(x=t.jsx("button",{ref:B,type:"button",onClick:f,className:"relative z-10 flex-1 flex items-center justify-center gap-2 h-12 px-4 rounded-lg",children:m}),e[25]=f,e[26]=m,e[27]=x):x=e[27];const $=`${j.left}px`,K=`${j.width}px`;let p;e[28]!==j.opacity||e[29]!==$||e[30]!==K?(p=t.jsx("div",{className:"absolute z-0 h-12 bg-background border border-border rounded-lg transition-all ease-out duration-200",style:{left:$,width:K,opacity:j.opacity}}),e[28]=j.opacity,e[29]=$,e[30]=K,e[31]=p):p=e[31];let h;e[32]!==d||e[33]!==x||e[34]!==p?(h=t.jsx("div",{className:"p-2 border-b border-border",children:t.jsx("div",{className:"relative bg-muted rounded-lg p-1",children:t.jsxs("div",{className:"relative flex gap-0",children:[d,x,p]})})}),e[32]=d,e[33]=x,e[34]=p,e[35]=h):h=e[35];let b;e[36]!==N||e[37]!==y||e[38]!==I||e[39]!==C?(b=C.length>0&&N&&t.jsxs("div",{className:"p-2",children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-mono font-normal text-muted-foreground uppercase tracking-wide",children:"Sort by"}),C.map(s=>{const o=I===s.id;return t.jsx(H,{onClick:()=>N(s.id),className:L("h-8 px-2 py-0 cursor-pointer",o&&"bg-accent"),children:t.jsxs("div",{className:"flex items-center gap-2 w-full",children:[o&&t.jsx(w,{name:"check",size:16,className:"text-foreground shrink-0"}),!o&&t.jsx("div",{className:"w-4 shrink-0"}),t.jsx("span",{className:"text-sm text-foreground flex-1",children:s.label}),o&&y&&t.jsx(w,{name:y==="asc"?"arrow_upward":"arrow_downward",size:16,className:"text-foreground shrink-0"})]})},s.id)})]}),e[36]=N,e[37]=y,e[38]=I,e[39]=C,e[40]=b):b=e[40];let g;e[41]!==h||e[42]!==b?(g=t.jsxs(Q,{align:"end",className:"w-[200px] p-0 gap-0",children:[h,b]}),e[41]=h,e[42]=b,e[43]=g):g=e[43];let M;return e[44]!==g||e[45]!==l?(M=t.jsxs(U,{onOpenChange:l,children:[D,g]}),e[44]=g,e[45]=l,e[46]=M):M=e[46],M}export{ne as C};
@@ -1 +0,0 @@
1
- import{c as j,j as i}from"./index-YfohaNt1.js";import{C as b}from"./collection-display-button-D2Zl4v_d.js";function g(h){const e=j.c(17),{title:d,viewMode:r,onViewModeChange:l,sortKey:m,sortDirection:f,onSort:x,sortOptions:n,ctaButton:p}=h;let c;e[0]!==n?(c=n===void 0?[]:n,e[0]=n,e[1]=c):c=e[1];const u=c;let t;e[2]!==d?(t=i.jsx("h1",{className:"text-base font-medium text-foreground",children:d}),e[2]=d,e[3]=t):t=e[3];let s;e[4]!==x||e[5]!==l||e[6]!==f||e[7]!==m||e[8]!==u||e[9]!==r?(s=r&&l&&i.jsx(b,{viewMode:r,onViewModeChange:l,sortKey:m,sortDirection:f,onSort:x,sortOptions:u}),e[4]=x,e[5]=l,e[6]=f,e[7]=m,e[8]=u,e[9]=r,e[10]=s):s=e[10];let o;e[11]!==p||e[12]!==s?(o=i.jsxs("div",{className:"flex items-center gap-2",children:[s,p]}),e[11]=p,e[12]=s,e[13]=o):o=e[13];let a;return e[14]!==t||e[15]!==o?(a=i.jsx("div",{className:"shrink-0 w-full border-b border-border h-12",children:i.jsxs("div",{className:"flex items-center justify-between gap-3 h-12 px-4",children:[t,o]})}),e[14]=t,e[15]=o,e[16]=a):a=e[16],a}export{g as C};
@@ -1 +0,0 @@
1
- import{c as S,j as s}from"./index-YfohaNt1.js";import{B as _}from"./badge-D1_SzxO5.js";import{C as A}from"./card-6GjFVmi6.js";import{c as j}from"./utils-pyyeDP1p.js";import{I as $}from"./use-connection-DxtpeU7L.js";function L(v){const t=S.c(44),{connection:e,onClick:N,headerActions:i,footer:C,className:b,size:R,fallbackIcon:k}=v,z=R===void 0?"md":R,I=z==="sm"?"p-4":"p-6",w=z==="sm"?"text-sm":"text-base",B=z==="sm"?"text-xs":"text-base",E=N&&"hover:bg-muted/50";let o;t[0]!==b||t[1]!==E?(o=j("cursor-pointer transition-colors group",E,b),t[0]=b,t[1]=E,t[2]=o):o=t[2];let l;t[3]!==I?(l=j("flex flex-col gap-4 relative",I),t[3]=I,t[4]=l):l=t[4];let a;t[5]!==e.icon||t[6]!==e.title||t[7]!==k?(a=s.jsx($,{icon:e.icon,name:e.title,size:"md",className:"shrink-0 shadow-sm",fallbackIcon:k}),t[5]=e.icon,t[6]=e.title,t[7]=k,t[8]=a):a=t[8];let n;t[9]!==e.status||t[10]!==i?(n=e.status&&s.jsx(_,{variant:e.status==="active"?"default":"outline",className:j("text-xs transition-opacity",i&&"opacity-100 group-hover:opacity-0"),children:e.status}),t[9]=e.status,t[10]=i,t[11]=n):n=t[11];let c;t[12]!==i?(c=i&&s.jsx("div",{className:j("absolute top-0 right-0 transition-opacity","opacity-0 group-hover:opacity-100"),onClick:D,children:i}),t[12]=i,t[13]=c):c=t[13];let r;t[14]!==n||t[15]!==c?(r=s.jsxs("div",{className:"relative",children:[n,c]}),t[14]=n,t[15]=c,t[16]=r):r=t[16];let m;t[17]!==a||t[18]!==r?(m=s.jsxs("div",{className:"flex items-start justify-between",children:[a,r]}),t[17]=a,t[18]=r,t[19]=m):m=t[19];let p;t[20]!==w?(p=j("font-medium text-foreground truncate",w),t[20]=w,t[21]=p):p=t[21];let d;t[22]!==e.title||t[23]!==p?(d=s.jsx("h3",{className:p,children:e.title}),t[22]=e.title,t[23]=p,t[24]=d):d=t[24];let f;t[25]!==B?(f=j("text-muted-foreground line-clamp-2",B),t[25]=B,t[26]=f):f=t[26];const P=e.description||"No description";let x;t[27]!==f||t[28]!==P?(x=s.jsx("p",{className:f,children:P}),t[27]=f,t[28]=P,t[29]=x):x=t[29];let u;t[30]!==d||t[31]!==x?(u=s.jsxs("div",{className:"flex flex-col gap-0",children:[d,x]}),t[30]=d,t[31]=x,t[32]=u):u=t[32];let h;t[33]!==C?(h=C&&s.jsx("div",{onClick:q,children:C}),t[33]=C,t[34]=h):h=t[34];let g;t[35]!==u||t[36]!==h||t[37]!==l||t[38]!==m?(g=s.jsxs("div",{className:l,children:[m,u,h]}),t[35]=u,t[36]=h,t[37]=l,t[38]=m,t[39]=g):g=t[39];let y;return t[40]!==N||t[41]!==g||t[42]!==o?(y=s.jsx(A,{className:o,onClick:N,children:g}),t[40]=N,t[41]=g,t[42]=o,t[43]=y):y=t[43],y}function q(v){return v.stopPropagation()}function D(v){return v.stopPropagation()}export{L as C};
@@ -1 +0,0 @@
1
- import{c as Ae,j as t,r as Ne,a5 as ze,b as Ee,a as Fe,ar as Ke,as as Be}from"./index-YfohaNt1.js";import{C as He}from"./schema-Ds6vBzkt.js";import{C as Oe}from"./collection-header-C0Jrsz0s.js";import{C as Re}from"./collection-page-Q6RNGv5C.js";import{C as Ve}from"./collection-search-DRvKW-m6.js";import{C as Le}from"./collection-table-wrapper-pohJqEDN.js";import{C as Ue}from"./connection-card-DsobEce7.js";import{E as De}from"./empty-state-BzOX9EED.js";import{E as We}from"./error-boundary-D2G9VNgl.js";import{d as qe,b as Ge,I as Je}from"./use-connection-DxtpeU7L.js";import{u as Qe}from"./use-list-state-DAjBDT6m.js";import{u as Xe}from"./tooltip-D_78gfFh.js";import{c as Ye,b as Ze,d as et,A as tt,e as nt,g as ot,a as st,f as it}from"./alert-dialog-BWlSDWeK.js";import{B as rt}from"./badge-D1_SzxO5.js";import{B as E}from"./button-BN_zWXnf.js";import{a as ct,b as lt,D as at,f as dt,c as mt,d as ut}from"./dialog-fLfI7M0R.js";import{b as Me,D as Pe,a as Te,c as pe}from"./dropdown-menu-DLU49g1s.js";import{F,a as pt,b as K,c as B,d as H,f as O}from"./form-DBnbAoFC.js";import{I as m}from"./icon-DR1spsQB.js";import{I as Ie}from"./input-CcvqgZcX.js";import{c as ht,a as ft,S as gt,b as xt,d as ke}from"./select-DmtIA5gb.js";import{T as jt}from"./textarea-ChlVYzjs.js";import{g as _t}from"./generate-id-Dyweu44Y.js";import"./collection-display-button-D2Zl4v_d.js";import"./utils-pyyeDP1p.js";import"./card-6GjFVmi6.js";import"./use-mobile-MtwUZMiZ.js";const Ct=He.pick({title:!0,description:!0,connection_type:!0,connection_url:!0,connection_token:!0}).partial({description:!0,connection_token:!0});function St(e,n){switch(n.type){case"edit":return{mode:"editing",connection:n.connection};case"delete":return{mode:"deleting",connection:n.connection};case"close":return{mode:"idle"}}}function yt(){const e=Ae.c(120),{org:n}=Xe(),r=ze();let R;e[0]===Symbol.for("react.memo_cache_sentinel")?(R={strict:!1},e[0]=R):R=e[0];const $e=Ee(R),{data:he}=Fe.useSession();let V;e[1]!==n.slug?(V={namespace:n.slug,resource:"connections"},e[1]=n.slug,e[2]=V):V=e[2];const o=Qe(V),d=qe(),z=Ge(o);let L;e[3]===Symbol.for("react.memo_cache_sentinel")?(L={mode:"idle"},e[3]=L):L=e[3];const[l,u]=Ne.useReducer(St,L),U=$e.action==="create";let W;e[4]!==r||e[5]!==n.slug?(W=()=>{r({to:"/$org/mcps",params:{org:n.slug},search:{action:"create"}})},e[4]=r,e[5]=n.slug,e[6]=W):W=e[6];const fe=W;let q;e[7]!==r||e[8]!==n.slug?(q=()=>{r({to:"/$org/mcps",params:{org:n.slug},search:{}})},e[7]=r,e[8]=n.slug,e[9]=q):q=e[9];const p=q;let G;e[10]===Symbol.for("react.memo_cache_sentinel")?(G={resolver:Ke(Ct),defaultValues:{title:"",description:null,connection_type:"HTTP",connection_url:"",connection_token:null}},e[10]=G):G=e[10];const i=Be(G),c=l.mode==="editing"?l.connection:null;let J,Q;e[11]!==c||e[12]!==i?(J=()=>{c?i.reset({title:c.title,description:c.description,connection_type:c.connection_type,connection_url:c.connection_url,connection_token:null}):i.reset({title:"",description:null,connection_type:"HTTP",connection_url:"",connection_token:null})},Q=[c,i],e[11]=c,e[12]=i,e[13]=J,e[14]=Q):(J=e[13],Q=e[14]),Ne.useEffect(J,Q);let X;e[15]!==d||e[16]!==l.connection||e[17]!==l.mode?(X=async()=>{if(l.mode!=="deleting")return;const s=l.connection.id;u({type:"close"});try{await d.delete.mutateAsync(s)}catch{}},e[15]=d,e[16]=l.connection,e[17]=l.mode,e[18]=X):X=e[18];const ge=X;let Y;e[19]!==d||e[20]!==p||e[21]!==c||e[22]!==i||e[23]!==r||e[24]!==n.id||e[25]!==n.slug||e[26]!==he?.user?.id?(Y=async s=>{if(c){await d.update.mutateAsync({id:c.id,data:{title:s.title,description:s.description||null,connection_type:s.connection_type,connection_url:s.connection_url,...s.connection_token&&{connection_token:s.connection_token}}}),u({type:"close"}),i.reset();return}const a=_t("conn");await d.create.mutateAsync({id:a,title:s.title,description:s.description||null,connection_type:s.connection_type,connection_url:s.connection_url,connection_token:s.connection_token||null,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:he?.user?.id||"system",organization_id:n.id,icon:null,app_name:null,app_id:null,connection_headers:null,oauth_config:null,configuration_state:null,metadata:null,tools:null,bindings:null,status:"inactive"}),p(),i.reset(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:a}})},e[19]=d,e[20]=p,e[21]=c,e[22]=i,e[23]=r,e[24]=n.id,e[25]=n.slug,e[26]=he?.user?.id,e[27]=Y):Y=e[27];const xe=Y;let Z;e[28]!==p||e[29]!==i||e[30]!==U?(Z=s=>{s||(U?p():u({type:"close"}),i.reset())},e[28]=p,e[29]=i,e[30]=U,e[31]=Z):Z=e[31];const h=Z;let ee,te,ne,oe,se,ie;e[32]===Symbol.for("react.memo_cache_sentinel")?(ee={id:"icon",header:"",render:Ft,cellClassName:"w-16 shrink-0",wrap:!0},te={id:"title",header:"Name",render:Et,cellClassName:"w-48 min-w-0 shrink-0",sortable:!0},ne={id:"description",header:"Description",render:zt,cellClassName:"flex-1 min-w-0",wrap:!0,sortable:!0},oe={id:"connection_type",header:"Type",accessor:$t,cellClassName:"w-24 shrink-0",sortable:!0},se={id:"connection_url",header:"URL",render:At,wrap:!0,cellClassName:"w-48 min-w-0 shrink-0"},ie={id:"status",header:"Status",render:Tt,cellClassName:"w-24 shrink-0",sortable:!0},e[32]=ee,e[33]=te,e[34]=ne,e[35]=oe,e[36]=se,e[37]=ie):(ee=e[32],te=e[33],ne=e[34],oe=e[35],se=e[36],ie=e[37]);let re;e[38]!==r||e[39]!==n.slug?(re=[ee,te,ne,oe,se,ie,{id:"actions",header:"",render:s=>t.jsxs(Me,{children:[t.jsx(Pe,{asChild:!0,children:t.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Pt,children:t.jsx(m,{name:"more_vert",size:20})})}),t.jsxs(Te,{align:"end",onClick:Mt,children:[t.jsxs(pe,{onClick:a=>{a.stopPropagation(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}})},children:[t.jsx(m,{name:"visibility",size:16}),"Inspect"]}),t.jsxs(pe,{variant:"destructive",onClick:a=>{a.stopPropagation(),u({type:"delete",connection:s})},children:[t.jsx(m,{name:"delete",size:16}),"Delete"]})]})]}),cellClassName:"w-12 shrink-0"}],e[38]=r,e[39]=n.slug,e[40]=re):re=e[40];const je=re;let ce;e[41]!==fe?(ce=t.jsx(E,{onClick:fe,size:"sm",className:"h-7 px-3 rounded-lg text-sm font-medium",children:"Connect MCP Server"}),e[41]=fe,e[42]=ce):ce=e[42];const _e=ce,Ce=U||l.mode==="editing",Se=c?"Edit Connection":"Create New Connection";let f;e[43]!==Se?(f=t.jsx(ct,{children:Se}),e[43]=Se,e[44]=f):f=e[44];const ye=c?"Update the connection details below.":"Add a new connection to your organization. Fill in the details below.";let g;e[45]!==ye?(g=t.jsx(lt,{children:ye}),e[45]=ye,e[46]=g):g=e[46];let x;e[47]!==f||e[48]!==g?(x=t.jsxs(at,{children:[f,g]}),e[47]=f,e[48]=g,e[49]=x):x=e[49];let j;e[50]!==i||e[51]!==xe?(j=i.handleSubmit(xe),e[50]=i,e[51]=xe,e[52]=j):j=e[52];let _;e[53]!==i.control?(_=t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(F,{control:i.control,name:"title",render:It}),t.jsx(F,{control:i.control,name:"description",render:Nt}),t.jsx(F,{control:i.control,name:"connection_type",render:kt}),t.jsx(F,{control:i.control,name:"connection_url",render:Dt}),t.jsx(F,{control:i.control,name:"connection_token",render:wt})]}),e[53]=i.control,e[54]=_):_=e[54];let C;e[55]!==h?(C=t.jsx(E,{type:"button",variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e[55]=h,e[56]=C):C=e[56];const ve=i.formState.isSubmitting?"Saving...":c?"Update Connection":"Create Connection";let S;e[57]!==i.formState.isSubmitting||e[58]!==ve?(S=t.jsx(E,{type:"submit",disabled:i.formState.isSubmitting,className:"min-w-40",children:ve}),e[57]=i.formState.isSubmitting,e[58]=ve,e[59]=S):S=e[59];let y;e[60]!==C||e[61]!==S?(y=t.jsxs(dt,{children:[C,S]}),e[60]=C,e[61]=S,e[62]=y):y=e[62];let v;e[63]!==j||e[64]!==_||e[65]!==y?(v=t.jsxs("form",{onSubmit:j,children:[_,y]}),e[63]=j,e[64]=_,e[65]=y,e[66]=v):v=e[66];let b;e[67]!==i||e[68]!==v?(b=t.jsx(pt,{...i,children:v}),e[67]=i,e[68]=v,e[69]=b):b=e[69];let w;e[70]!==x||e[71]!==b?(w=t.jsxs(mt,{className:"sm:max-w-[525px]",children:[x,b]}),e[70]=x,e[71]=b,e[72]=w):w=e[72];let D;e[73]!==h||e[74]!==Ce||e[75]!==w?(D=t.jsx(ut,{open:Ce,onOpenChange:h,children:w}),e[73]=h,e[74]=Ce,e[75]=w,e[76]=D):D=e[76];const be=l.mode==="deleting";let le;e[77]===Symbol.for("react.memo_cache_sentinel")?(le=s=>!s&&u({type:"close"}),e[77]=le):le=e[77];let ae;e[78]===Symbol.for("react.memo_cache_sentinel")?(ae=t.jsx(Ye,{children:"Delete Connection?"}),e[78]=ae):ae=e[78];const we=l.mode==="deleting"&&l.connection.title;let k;e[79]!==we?(k=t.jsxs(Ze,{children:[ae,t.jsxs(et,{children:["This action cannot be undone. This will permanently delete"," ",t.jsx("span",{className:"font-medium text-foreground",children:we}),"."]})]}),e[79]=we,e[80]=k):k=e[80];let de;e[81]===Symbol.for("react.memo_cache_sentinel")?(de=t.jsx(tt,{children:"Cancel"}),e[81]=de):de=e[81];let N;e[82]!==ge?(N=t.jsxs(nt,{children:[de,t.jsx(ot,{onClick:ge,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]}),e[82]=ge,e[83]=N):N=e[83];let I;e[84]!==k||e[85]!==N?(I=t.jsxs(st,{children:[k,N]}),e[84]=k,e[85]=N,e[86]=I):I=e[86];let M;e[87]!==be||e[88]!==I?(M=t.jsx(it,{open:be,onOpenChange:le,children:I}),e[87]=be,e[88]=I,e[89]=M):M=e[89];let me;e[90]===Symbol.for("react.memo_cache_sentinel")?(me=[{id:"title",label:"Name"},{id:"description",label:"Description"},{id:"connection_type",label:"Type"},{id:"status",label:"Status"}],e[90]=me):me=e[90];let P;e[91]!==_e||e[92]!==o.handleSort||e[93]!==o.setViewMode||e[94]!==o.sortDirection||e[95]!==o.sortKey||e[96]!==o.viewMode?(P=t.jsx(Oe,{title:"MCP Servers",viewMode:o.viewMode,onViewModeChange:o.setViewMode,sortKey:o.sortKey,sortDirection:o.sortDirection,onSort:o.handleSort,sortOptions:me,ctaButton:_e}),e[91]=_e,e[92]=o.handleSort,e[93]=o.setViewMode,e[94]=o.sortDirection,e[95]=o.sortKey,e[96]=o.viewMode,e[97]=P):P=e[97];let T;e[98]!==o?(T=s=>{s.key==="Escape"&&(o.setSearch(""),s.target.blur())},e[98]=o,e[99]=T):T=e[99];let A;e[100]!==o.search||e[101]!==o.setSearch||e[102]!==T?(A=t.jsx(Ve,{value:o.search,onChange:o.setSearch,placeholder:"Search for an MCP Server...",onKeyDown:T}),e[100]=o.search,e[101]=o.setSearch,e[102]=T,e[103]=A):A=e[103];let $;e[104]!==je||e[105]!==z||e[106]!==o.handleSort||e[107]!==o.search||e[108]!==o.sortDirection||e[109]!==o.sortKey||e[110]!==o.viewMode||e[111]!==r||e[112]!==n.slug?($=o.viewMode==="cards"?t.jsx("div",{className:"flex-1 overflow-auto p-5",children:z.length===0?t.jsx(De,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:(o.search,"No MCP Servers found"),description:o.search?`No MCP Servers match "${o.search}"`:"Create a connection to get started."}):t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4",children:z.map(s=>t.jsx(Ue,{connection:s,fallbackIcon:"extension",onClick:()=>r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}}),headerActions:t.jsxs(Me,{children:[t.jsx(Pe,{asChild:!0,children:t.jsx(E,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:bt,children:t.jsx(m,{name:"more_vert",size:20})})}),t.jsxs(Te,{align:"end",onClick:vt,children:[t.jsxs(pe,{onClick:a=>{a.stopPropagation(),r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}})},children:[t.jsx(m,{name:"visibility",size:16}),"Inspect"]}),t.jsxs(pe,{variant:"destructive",onClick:a=>{a.stopPropagation(),u({type:"delete",connection:s})},children:[t.jsx(m,{name:"delete",size:16}),"Delete"]})]})]})},s.id))})}):t.jsx(Le,{columns:je,data:z,isLoading:!1,sortKey:o.sortKey,sortDirection:o.sortDirection,onSort:o.handleSort,onRowClick:s=>r({to:"/$org/mcps/$connectionId",params:{org:n.slug,connectionId:s.id}}),emptyState:o.search?t.jsx(De,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:"No MCP Servers found",description:`No MCP Servers match "${o.search}"`}):t.jsx(De,{image:t.jsx("img",{src:"/emptystate-mcp.svg",alt:"",width:500,height:223,"aria-hidden":"true"}),title:"No MCP Servers found",description:"Create a connection to get started."})}),e[104]=je,e[105]=z,e[106]=o.handleSort,e[107]=o.search,e[108]=o.sortDirection,e[109]=o.sortKey,e[110]=o.viewMode,e[111]=r,e[112]=n.slug,e[113]=$):$=e[113];let ue;return e[114]!==D||e[115]!==M||e[116]!==P||e[117]!==A||e[118]!==$?(ue=t.jsxs(Re,{children:[D,M,P,A,$]}),e[114]=D,e[115]=M,e[116]=P,e[117]=A,e[118]=$,e[119]=ue):ue=e[119],ue}function vt(e){return e.stopPropagation()}function bt(e){return e.stopPropagation()}function wt(e){const{field:n}=e;return t.jsxs(K,{children:[t.jsx(B,{children:"Token (optional)"}),t.jsx(H,{children:t.jsx(Ie,{type:"password",placeholder:"Bearer token or API key",...n,value:n.value??""})}),t.jsx(O,{})]})}function Dt(e){const{field:n}=e;return t.jsxs(K,{children:[t.jsx(B,{children:"URL *"}),t.jsx(H,{children:t.jsx(Ie,{placeholder:"https://example.com/mcp",...n})}),t.jsx(O,{})]})}function kt(e){const{field:n}=e;return t.jsxs(K,{children:[t.jsx(B,{children:"Type *"}),t.jsxs(ht,{value:n.value,onValueChange:n.onChange,children:[t.jsx(H,{children:t.jsx(ft,{children:t.jsx(gt,{})})}),t.jsxs(xt,{children:[t.jsx(ke,{value:"HTTP",children:"HTTP"}),t.jsx(ke,{value:"SSE",children:"SSE"}),t.jsx(ke,{value:"Websocket",children:"Websocket"})]})]}),t.jsx(O,{})]})}function Nt(e){const{field:n}=e;return t.jsxs(K,{children:[t.jsx(B,{children:"Description"}),t.jsx(H,{children:t.jsx(jt,{placeholder:"A brief description of this connection",rows:3,...n,value:n.value??""})}),t.jsx(O,{})]})}function It(e){const{field:n}=e;return t.jsxs(K,{children:[t.jsx(B,{children:"Name *"}),t.jsx(H,{children:t.jsx(Ie,{placeholder:"My Connection",...n})}),t.jsx(O,{})]})}function Mt(e){return e.stopPropagation()}function Pt(e){return e.stopPropagation()}function Tt(e){return t.jsx(rt,{variant:e.status==="active"?"default":"outline",children:e.status})}function At(e){return t.jsx("span",{className:"text-sm text-muted-foreground block truncate",children:e.connection_url})}function $t(e){return t.jsx("span",{className:"text-sm font-medium",children:e.connection_type})}function zt(e){return t.jsx("span",{className:"text-sm text-foreground line-clamp-2",children:e.description||"—"})}function Et(e){return t.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:e.title})}function Ft(e){return t.jsx(Je,{icon:e.icon,name:e.title,size:"sm",className:"shrink-0 shadow-sm",fallbackIcon:"extension"})}function un(){const e=Ae.c(1);let n;return e[0]===Symbol.for("react.memo_cache_sentinel")?(n=t.jsx(We,{children:t.jsx(Ne.Suspense,{fallback:t.jsx("div",{className:"flex h-full items-center justify-center",children:t.jsx(m,{name:"progress_activity",size:32,className:"animate-spin text-muted-foreground"})}),children:t.jsx(yt,{})})}),e[0]=n):n=e[0],n}export{un as default};