@decocms/mesh 1.0.0-alpha.42 → 1.0.0-alpha.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-CP-aGRsA.js → AlertCircle-CN9Kwl46.js} +1 -1
- package/dist/client/assets/{ArrowLeft-wElnUYJ0.js → ArrowLeft-79-s1Tig.js} +1 -1
- package/dist/client/assets/{CheckCircle-B_WVChj1.js → CheckCircle-B3mUle8T.js} +1 -1
- package/dist/client/assets/{ChevronDown-133w8HOk.js → ChevronDown-BISG7iJe.js} +1 -1
- package/dist/client/assets/{Clock-DqQ41LIc.js → Clock-B9hRAV6O.js} +1 -1
- package/dist/client/assets/{Copy01-BJwDNoQC.js → Copy01-DwwmCAKD.js} +1 -1
- package/dist/client/assets/{CpuChip02-bWa1f3Y1.js → CpuChip02-CUDIgibq.js} +1 -1
- package/dist/client/assets/{DotsVertical-CYYr09mb.js → DotsVertical-DYy5f5TH.js} +1 -1
- package/dist/client/assets/{File06-Dtn5wW91.js → File06-BvEigs5K.js} +1 -1
- package/dist/client/assets/{Grid01-DZvMiQMk.js → Grid01-BJs-oJbb.js} +1 -1
- package/dist/client/assets/{Inbox01-CSe7MExo.js → Inbox01-kHBKrXPK.js} +1 -1
- package/dist/client/assets/{InfoCircle-D3bW5Omw.js → InfoCircle-CPnZwTxv.js} +1 -1
- package/dist/client/assets/{Key01-C1qHez6H.js → Key01-9qnlb6JU.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BWIXuo1e.js → LinkExternal01-BSyVD31k.js} +1 -1
- package/dist/client/assets/{Loading01-CAh3R9sn.js → Loading01-BV8yANMx.js} +1 -1
- package/dist/client/assets/{Plus-CYOELvWT.js → Plus-xI6Kev1W.js} +1 -1
- package/dist/client/assets/{SearchMd-Bq2ogvbg.js → SearchMd-DjCfdQvr.js} +1 -1
- package/dist/client/assets/{Trash01-KvM_z2HW.js → Trash01-BJ4TpHo6.js} +1 -1
- package/dist/client/assets/{Upload01-BP0jqpHq.js → Upload01-D7t7piwO.js} +1 -1
- package/dist/client/assets/{X-CafPP_Iv.js → X-Ba_LQ0uA.js} +1 -1
- package/dist/client/assets/{XClose-CqJrzETU.js → XClose-CdYSW33W.js} +1 -1
- package/dist/client/assets/{alert-dialog-BUlG7TA4.js → alert-dialog-C99NB_7U.js} +1 -1
- package/dist/client/assets/{auth-CJSooDCA.js → auth-B5WZVFkk.js} +1 -1
- package/dist/client/assets/{auth-catchall-BjCX5usv.js → auth-catchall-CfK6fR9U.js} +1 -1
- package/dist/client/assets/{avatar-Cq0eS4K8.js → avatar-BUiJ-GrU.js} +1 -1
- package/dist/client/assets/{badge-DwRxIVxi.js → badge-C2dmCTiI.js} +1 -1
- package/dist/client/assets/{button-DylnVNOq.js → button-DaIB726e.js} +1 -1
- package/dist/client/assets/{card-DxJ2CMrY.js → card-ab5xGOok.js} +1 -1
- package/dist/client/assets/{checkbox-DEErbcc0.js → checkbox-BdtTCxJp.js} +1 -1
- package/dist/client/assets/{collection-detail-CrH6CPOn.js → collection-detail-1tl8LWP6.js} +1 -1
- package/dist/client/assets/{collection-display-button-CvZ8eTT6.js → collection-display-button-GIFHS7mf.js} +1 -1
- package/dist/client/assets/{collection-header-BZWDRhRJ.js → collection-header-DtkI1-nw.js} +1 -1
- package/dist/client/assets/{collection-page-Cy4Url61.js → collection-page-xI1L4Fpn.js} +1 -1
- package/dist/client/assets/{collection-search-BEr5-om_.js → collection-search-DnsH2_jb.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-CYIQZiF8.js → collection-table-wrapper-BubIPcwq.js} +1 -1
- package/dist/client/assets/{connection-card-Cjb0De9E.js → connection-card-BF_6pa2J.js} +1 -1
- package/dist/client/assets/{connection-detail-CtapWDy0.js → connection-detail-BRzwpk76.js} +1 -1
- package/dist/client/assets/connections-CigXCMb4.js +1 -0
- package/dist/client/assets/{core-CwMiM80c.js → core-CgA420gV.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-CDHLiEAk.js → create-organization-dialog-DF2ZMrGQ.js} +1 -1
- package/dist/client/assets/{deco-chat-skeleton-DpvJuUNp.js → deco-chat-skeleton-nVcHmaH2.js} +3 -3
- package/dist/client/assets/{dialog-DHu5nMEY.js → dialog-F4-mAdwQ.js} +1 -1
- package/dist/client/assets/{dropdown-menu-DiYpBa-u.js → dropdown-menu-8EalNciV.js} +1 -1
- package/dist/client/assets/{error-boundary-xo0wHpmi.js → error-boundary-CwHJoOK0.js} +1 -1
- package/dist/client/assets/{extract-connection-data-CuVedqWo.js → extract-connection-data-BwuOti8g.js} +1 -1
- package/dist/client/assets/{form-DJrhF5P2.js → form-t1-9o1Xc.js} +1 -1
- package/dist/client/assets/{formatDistanceToNow-BbvSNUQF.js → formatDistanceToNow-bn0uK8Kq.js} +1 -1
- package/dist/client/assets/{gateway-detail-BOFhJRga.js → gateway-detail-DiXffyQT.js} +1 -1
- package/dist/client/assets/{gateways-EOO6wJEW.js → gateways-B3iAf60G.js} +1 -1
- package/dist/client/assets/{home-BFuz55uE.js → home-DLwkO16l.js} +1 -1
- package/dist/client/assets/{index-Dm4arKBM.js → index-BLXp70Cs.js} +1 -1
- package/dist/client/assets/{index-BwcY8s4g.js → index-DlWJzouE.js} +1 -1
- package/dist/client/assets/{index-DrO6_oKQ.js → index-bW54m51i.js} +2 -2
- package/dist/client/assets/{index-dUwc3ttQ.js → index-ivYQSj6r.js} +1 -1
- package/dist/client/assets/{input-KnYDv1A5.js → input-hqoHn3rB.js} +1 -1
- package/dist/client/assets/json-DQnTG-jF.js +1 -0
- package/dist/client/assets/{json-syntax-highlighter-BHL3wK0f.js → json-syntax-highlighter-BmSI5Sw5.js} +2 -2
- package/dist/client/assets/{layout-NjL7irXi.js → layout-K88BEgq4.js} +1 -1
- package/dist/client/assets/{lazy-highlighter-DfXFtweD.js → lazy-highlighter-B6O9VrsC.js} +1 -1
- package/dist/client/assets/{localstorage-keys-Bla3L5Kn.js → localstorage-keys-ooINy0c2.js} +1 -1
- package/dist/client/assets/{login-DWfPFu6G.js → login-BKM8kJjB.js} +1 -1
- package/dist/client/assets/{mcp-oauth-B3voaRxT.js → mcp-oauth-C64FsR2L.js} +1 -1
- package/dist/client/assets/{members-zioM9DX4.js → members-CpkEw3Gu.js} +1 -1
- package/dist/client/assets/{monitoring-BWq8obqP.js → monitoring-Dnvu7QbW.js} +1 -1
- package/dist/client/assets/{oauth-callback-B4ueERM_.js → oauth-callback-DarYAWxb.js} +1 -1
- package/dist/client/assets/{page-Clx7_tn2.js → page-D3T1y-th.js} +1 -1
- package/dist/client/assets/{popover-BUiNi8m6.js → popover-KAMF0wjo.js} +1 -1
- package/dist/client/assets/prism-light-B-mJYmV2.js +1 -0
- package/dist/client/assets/{resource-tabs-yB0ODQBX.js → resource-tabs-B7sOoky4.js} +1 -1
- package/dist/client/assets/{schema-DS_MXXSd.js → schema-CFJmQWLc.js} +1 -1
- package/dist/client/assets/{select-D2oQHnH-.js → select-CC9IOt3F.js} +1 -1
- package/dist/client/assets/{settings-CPxuZwVp.js → settings-BcACslVK.js} +1 -1
- package/dist/client/assets/{shell-layout-BX0g1F2C.js → shell-layout-BXzzYxxI.js} +1 -1
- package/dist/client/assets/{spinner-B-LyDgpm.js → spinner-DNqrSWXn.js} +1 -1
- package/dist/client/assets/{store-DpIupuN4.js → store--zTuNiao.js} +1 -1
- package/dist/client/assets/{store-app-detail-Dzqp2haZ.js → store-app-detail-CuKWUnVS.js} +1 -1
- package/dist/client/assets/{switch-ZVXF1B-B.js → switch-C_mSsrsm.js} +1 -1
- package/dist/client/assets/{textarea-BYzZCFR4.js → textarea-DDDYcM24.js} +1 -1
- package/dist/client/assets/{tools-list-DX1uzNKs.js → tools-list-DoRnkSTk.js} +1 -1
- package/dist/client/assets/{tooltip-C9HJ0ESh.js → tooltip-BVz8bigT.js} +1 -1
- package/dist/client/assets/{types-BzJYylI4.js → types-DG1LR17s.js} +1 -1
- package/dist/client/assets/{use-binding-zihfVeqz.js → use-binding-ydC0_BJi.js} +1 -1
- package/dist/client/assets/{use-connection-PNwxddOO.js → use-connection-D56WdXWG.js} +1 -1
- package/dist/client/assets/{use-gateway-v9UrwqWL.js → use-gateway-q-kVC_4R.js} +1 -1
- package/dist/client/assets/{use-list-state-lBd2usQq.js → use-list-state-CcrSGD2b.js} +1 -1
- package/dist/client/assets/{use-mcp-DnENzWav.js → use-mcp-BdSL3v0D.js} +1 -1
- package/dist/client/assets/{use-members-BZ9F4tXm.js → use-members-B9yjW3r9.js} +1 -1
- package/dist/client/assets/{use-mobile-BZVx-pSu.js → use-mobile-CRl6lVo4.js} +1 -1
- package/dist/client/assets/{use-organization-settings-D8NOmgEj.js → use-organization-settings-DQOAfLp9.js} +1 -1
- package/dist/client/assets/{use-tool-call-CDsX2AuI.js → use-tool-call-CLrf8wQZ.js} +1 -1
- package/dist/client/assets/useQuery-4jfol-cv.js +1 -0
- package/dist/client/assets/utils-Dk0QXc2x.js +1 -0
- package/dist/client/assets/{well-known-mcp-0xOmKc1Z.js → well-known-mcp-Dk4Ye2a8.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +1 -1
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/connections-ByAWgP1A.js +0 -1
- package/dist/client/assets/json-D3Bs6F9t.js +0 -1
- package/dist/client/assets/prism-light-CzedzUri.js +0 -1
- package/dist/client/assets/useQuery-BeDo1OnH.js +0 -1
- package/dist/client/assets/utils-CzqUBWOD.js +0 -1
package/dist/server/migrate.js
CHANGED
|
@@ -245,7 +245,7 @@ return fn.apply(this, arguments)
|
|
|
245
245
|
`;for(let W of Object.keys(Q))if(W!=="link")X+=W+": "+Q[W]+`\r
|
|
246
246
|
`;X+=`\r
|
|
247
247
|
`,this._writeRaw(X,"ascii",J)}_implicitHeader(){this.writeHead(this.statusCode)}writeHead(Q,J,X){if(this._header)throw new $Y("write");let Y=Q;if(Q|=0,Q<100||Q>999)throw new Ff(Y);if(typeof J==="string")this.statusMessage=J;else this.statusMessage||=ZX0[Q]||"unknown",X??=J;this.statusCode=Q;let W;if(this[k8]){let Z;if(Array.isArray(X)){if(X.length%2!==0)throw new y7("headers",X);for(let K=0;K<X.length;K+=2)Z=X[K+0],this.removeHeader(String(Z));for(let K=0;K<X.length;K+=2)if(Z=X[K],Z)this.appendHeader(String(Z),X[K+1])}else if(X){let K=Object.keys(X);for(let H=0;H<K.length;H++)if(Z=K[H],Z)this.setHeader(Z,X[Z])}W=this[k8]}else W=X;if(Td0(this.statusMessage))throw new hG("statusMessage");let G=`HTTP/1.1 ${Q} ${this.statusMessage}\r
|
|
248
|
-
`;if(Q===204||Q===304||Q>=100&&Q<=199)this._hasBody=!1;if(this._expect_continue&&!this._sent100)this.shouldKeepAlive=!1;let $=W&&!Array.isArray(W)?W:W;return this._storeHeader(G,$??null),this}writeHeader=this.writeHead;fetchResponse;_toFetchResponse(Q,J,X,Y,W){let G=new Headers;for(let[K,H]of X)G.append(K,H);let $=this,Z=this._hasBody?new ReadableStream({start(K){for(let H of Y)K.enqueue(H);if(W)K.close();else $.on("finish",()=>{W=!0,K.close()}),$.on("_dataWritten",(H)=>{if(W)return;let F=$.dataFromDataWrittenEvent(H);K.enqueue(F)})}}):null;if(Z!=null&&typeof FixedLengthStream<"u"){let K=parseInt(G.get("content-length")??"",10);if(K>=0)Z=Z.pipeThrough(new FixedLengthStream(K))}return new Response(Z,{status:Q,statusText:J,headers:G})}}});var HX0=p(()=>{Pf();Af();KX0()});var Sf;var FX0=p(()=>{iJ0();HX0();Sf=class Sf extends $f{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=Ef(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),Rf(X)}}});var VX0=(...Q)=>{return function(X,Y){let W=(G)=>{let $=Q[G];if(!$)return Y();return $(X,()=>W(G+1))};return W(0)}};class qX0{config;tools=[];callToolMiddlewares=[];constructor(Q){this.config={...Q,capabilities:Q.capabilities??{tools:{}}}}withTool(Q){return this.tools.push(Q),this}withTools(Q){return this.tools.push(...Q),this}callToolMiddleware(...Q){return this.callToolMiddlewares.push(...Q),this}build(){let Q=this.callToolMiddlewares.length>0?VX0(...this.callToolMiddlewares):null,J=()=>{let X=new Bb({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let Y of this.tools){let W=async(K)=>{try{let H=await Y.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},G=Q?async(K)=>{let H={method:"tools/call",params:{name:Y.name,arguments:K}};return await Q(H,()=>W(K))}:W,$="shape"in Y.inputSchema?Y.inputSchema.shape:m_.object({}).shape,Z=Y.outputSchema&&"shape"in Y.outputSchema?Y.outputSchema.shape:m_.object({}).shape;X.registerTool(Y.name,{annotations:Y.annotations,description:Y.description??"",inputSchema:$,outputSchema:Z},G)}return X};return{callStreamableTool:async(X,Y)=>{let W=this.tools.find(($)=>$.name===X);if(!W)throw Error(`Tool ${X} not found`);let G=await W.handler(Y);if(!(G instanceof Response))throw Error(`Tool ${X} returned a non-response`);return G},client:{listTools:async()=>{return{tools:this.tools.map((X)=>({name:X.name,description:X.description??"",inputSchema:kZ(X.inputSchema),outputSchema:X.outputSchema?kZ(X.outputSchema):void 0}))}},callTool:async(X)=>{let Y=this.tools.find((W)=>W.name===X.name);if(!Y)return{content:[{type:"text",text:"Tool not found"}]};try{let W=await Y?.handler(X.arguments??{});return{content:[{type:"text",text:JSON.stringify(W)}],structuredContent:W}}catch(W){return{content:[{type:"text",text:`Error: ${W.message}`}]}}}},fetch:async(X)=>{let Y=new Sf({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(Y),await Y.handleMessage(X)}}}}function UX0(Q){return new qX0(Q)}var zX0=p(()=>{vQ0();o1();Cw();FX0()});var PX0=r((LX0)=>{Object.defineProperty(LX0,"__esModule",{value:!0});LX0._globalThis=void 0;LX0._globalThis=typeof globalThis==="object"?globalThis:global});var NX0=r((lG)=>{var Ad0=lG&&lG.__createBinding||(Object.create?function(Q,J,X,Y){if(Y===void 0)Y=X;Object.defineProperty(Q,Y,{enumerable:!0,get:function(){return J[X]}})}:function(Q,J,X,Y){if(Y===void 0)Y=X;Q[Y]=J[X]}),Ed0=lG&&lG.__exportStar||function(Q,J){for(var X in Q)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))Ad0(J,Q,X)};Object.defineProperty(lG,"__esModule",{value:!0});Ed0(PX0(),lG)});var BX0=r((dG)=>{var Rd0=dG&&dG.__createBinding||(Object.create?function(Q,J,X,Y){if(Y===void 0)Y=X;Object.defineProperty(Q,Y,{enumerable:!0,get:function(){return J[X]}})}:function(Q,J,X,Y){if(Y===void 0)Y=X;Q[Y]=J[X]}),Sd0=dG&&dG.__exportStar||function(Q,J){for(var X in Q)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))Rd0(J,Q,X)};Object.defineProperty(dG,"__esModule",{value:!0});Sd0(NX0(),dG)});var vf=r((wX0)=>{Object.defineProperty(wX0,"__esModule",{value:!0});wX0.VERSION=void 0;wX0.VERSION="1.9.0"});var EX0=r((TX0)=>{Object.defineProperty(TX0,"__esModule",{value:!0});TX0.isCompatible=TX0._makeCompatibilityCheck=void 0;var vd0=vf(),MX0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function DX0(Q){let J=new Set([Q]),X=new Set,Y=Q.match(MX0);if(!Y)return()=>!1;let W={major:+Y[1],minor:+Y[2],patch:+Y[3],prerelease:Y[4]};if(W.prerelease!=null)return function(K){return K===Q};function G(Z){return X.add(Z),!1}function $(Z){return J.add(Z),!0}return function(K){if(J.has(K))return!0;if(X.has(K))return!1;let H=K.match(MX0);if(!H)return G(K);let F={major:+H[1],minor:+H[2],patch:+H[3],prerelease:H[4]};if(F.prerelease!=null)return G(K);if(W.major!==F.major)return G(K);if(W.major===0){if(W.minor===F.minor&&W.patch<=F.patch)return $(K);return G(K)}if(W.minor<=F.minor)return $(K);return G(K)}}TX0._makeCompatibilityCheck=DX0;TX0.isCompatible=DX0(vd0.VERSION)});var pG=r((RX0)=>{Object.defineProperty(RX0,"__esModule",{value:!0});RX0.unregisterGlobal=RX0.getGlobal=RX0.registerGlobal=void 0;var Id0=BX0(),lZ=vf(),kd0=EX0(),_d0=lZ.VERSION.split(".")[0],Bq=Symbol.for(`opentelemetry.js.api.${_d0}`),wq=Id0._globalThis;function yd0(Q,J,X,Y=!1){var W;let G=wq[Bq]=(W=wq[Bq])!==null&&W!==void 0?W:{version:lZ.VERSION};if(!Y&&G[Q]){let $=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${Q}`);return X.error($.stack||$.message),!1}if(G.version!==lZ.VERSION){let $=Error(`@opentelemetry/api: Registration of version v${G.version} for ${Q} does not match previously registered API v${lZ.VERSION}`);return X.error($.stack||$.message),!1}return G[Q]=J,X.debug(`@opentelemetry/api: Registered a global for ${Q} v${lZ.VERSION}.`),!0}RX0.registerGlobal=yd0;function bd0(Q){var J,X;let Y=(J=wq[Bq])===null||J===void 0?void 0:J.version;if(!Y||!(0,kd0.isCompatible)(Y))return;return(X=wq[Bq])===null||X===void 0?void 0:X[Q]}RX0.getGlobal=bd0;function fd0(Q,J){J.debug(`@opentelemetry/api: Unregistering a global for ${Q} v${lZ.VERSION}.`);let X=wq[Bq];if(X)delete X[Q]}RX0.unregisterGlobal=fd0});var kX0=r((CX0)=>{Object.defineProperty(CX0,"__esModule",{value:!0});CX0.DiagComponentLogger=void 0;var md0=pG();class vX0{constructor(Q){this._namespace=Q.namespace||"DiagComponentLogger"}debug(...Q){return Oq("debug",this._namespace,Q)}error(...Q){return Oq("error",this._namespace,Q)}info(...Q){return Oq("info",this._namespace,Q)}warn(...Q){return Oq("warn",this._namespace,Q)}verbose(...Q){return Oq("verbose",this._namespace,Q)}}CX0.DiagComponentLogger=vX0;function Oq(Q,J,X){let Y=(0,md0.getGlobal)("diag");if(!Y)return;return X.unshift(J),Y[Q](...X)}});var XO=r((_X0)=>{Object.defineProperty(_X0,"__esModule",{value:!0});_X0.DiagLogLevel=void 0;var xd0;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.ERROR=30]="ERROR",Q[Q.WARN=50]="WARN",Q[Q.INFO=60]="INFO",Q[Q.DEBUG=70]="DEBUG",Q[Q.VERBOSE=80]="VERBOSE",Q[Q.ALL=9999]="ALL"})(xd0=_X0.DiagLogLevel||(_X0.DiagLogLevel={}))});var fX0=r((yX0)=>{Object.defineProperty(yX0,"__esModule",{value:!0});yX0.createLogLevelDiagLogger=void 0;var ZY=XO();function ud0(Q,J){if(Q<ZY.DiagLogLevel.NONE)Q=ZY.DiagLogLevel.NONE;else if(Q>ZY.DiagLogLevel.ALL)Q=ZY.DiagLogLevel.ALL;J=J||{};function X(Y,W){let G=J[Y];if(typeof G==="function"&&Q>=W)return G.bind(J);return function(){}}return{error:X("error",ZY.DiagLogLevel.ERROR),warn:X("warn",ZY.DiagLogLevel.WARN),info:X("info",ZY.DiagLogLevel.INFO),debug:X("debug",ZY.DiagLogLevel.DEBUG),verbose:X("verbose",ZY.DiagLogLevel.VERBOSE)}}yX0.createLogLevelDiagLogger=ud0});var cG=r((gX0)=>{Object.defineProperty(gX0,"__esModule",{value:!0});gX0.DiagAPI=void 0;var ld0=kX0(),dd0=fX0(),hX0=XO(),YO=pG(),pd0="diag";class If{constructor(){function Q(Y){return function(...W){let G=(0,YO.getGlobal)("diag");if(!G)return;return G[Y](...W)}}let J=this,X=(Y,W={logLevel:hX0.DiagLogLevel.INFO})=>{var G,$,Z;if(Y===J){let F=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return J.error((G=F.stack)!==null&&G!==void 0?G:F.message),!1}if(typeof W==="number")W={logLevel:W};let K=(0,YO.getGlobal)("diag"),H=(0,dd0.createLogLevelDiagLogger)(($=W.logLevel)!==null&&$!==void 0?$:hX0.DiagLogLevel.INFO,Y);if(K&&!W.suppressOverrideMessage){let F=(Z=Error().stack)!==null&&Z!==void 0?Z:"<failed to generate stacktrace>";K.warn(`Current logger will be overwritten from ${F}`),H.warn(`Current logger will overwrite one already registered from ${F}`)}return(0,YO.registerGlobal)("diag",H,J,!0)};J.setLogger=X,J.disable=()=>{(0,YO.unregisterGlobal)(pd0,J)},J.createComponentLogger=(Y)=>{return new ld0.DiagComponentLogger(Y)},J.verbose=Q("verbose"),J.debug=Q("debug"),J.info=Q("info"),J.warn=Q("warn"),J.error=Q("error")}static instance(){if(!this._instance)this._instance=new If;return this._instance}}gX0.DiagAPI=If});var lX0=r((xX0)=>{Object.defineProperty(xX0,"__esModule",{value:!0});xX0.BaggageImpl=void 0;class dZ{constructor(Q){this._entries=Q?new Map(Q):new Map}getEntry(Q){let J=this._entries.get(Q);if(!J)return;return Object.assign({},J)}getAllEntries(){return Array.from(this._entries.entries()).map(([Q,J])=>[Q,J])}setEntry(Q,J){let X=new dZ(this._entries);return X._entries.set(Q,J),X}removeEntry(Q){let J=new dZ(this._entries);return J._entries.delete(Q),J}removeEntries(...Q){let J=new dZ(this._entries);for(let X of Q)J._entries.delete(X);return J}clear(){return new dZ}}xX0.BaggageImpl=dZ});var cX0=r((dX0)=>{Object.defineProperty(dX0,"__esModule",{value:!0});dX0.baggageEntryMetadataSymbol=void 0;dX0.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var kf=r((nX0)=>{Object.defineProperty(nX0,"__esModule",{value:!0});nX0.baggageEntryMetadataFromString=nX0.createBaggage=void 0;var cd0=cG(),nd0=lX0(),rd0=cX0(),id0=cd0.DiagAPI.instance();function ad0(Q={}){return new nd0.BaggageImpl(new Map(Object.entries(Q)))}nX0.createBaggage=ad0;function od0(Q){if(typeof Q!=="string")id0.error(`Cannot create baggage metadata from unknown type: ${typeof Q}`),Q="";return{__TYPE__:rd0.baggageEntryMetadataSymbol,toString(){return Q}}}nX0.baggageEntryMetadataFromString=od0});var Mq=r((iX0)=>{Object.defineProperty(iX0,"__esModule",{value:!0});iX0.ROOT_CONTEXT=iX0.createContextKey=void 0;function td0(Q){return Symbol.for(Q)}iX0.createContextKey=td0;class WO{constructor(Q){let J=this;J._currentContext=Q?new Map(Q):new Map,J.getValue=(X)=>J._currentContext.get(X),J.setValue=(X,Y)=>{let W=new WO(J._currentContext);return W._currentContext.set(X,Y),W},J.deleteValue=(X)=>{let Y=new WO(J._currentContext);return Y._currentContext.delete(X),Y}}}iX0.ROOT_CONTEXT=new WO});var eX0=r((sX0)=>{Object.defineProperty(sX0,"__esModule",{value:!0});sX0.DiagConsoleLogger=void 0;var _f=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class oX0{constructor(){function Q(J){return function(...X){if(console){let Y=console[J];if(typeof Y!=="function")Y=console.log;if(typeof Y==="function")return Y.apply(console,X)}}}for(let J=0;J<_f.length;J++)this[_f[J].n]=Q(_f[J].c)}}sX0.DiagConsoleLogger=oX0});var lf=r((QY0)=>{Object.defineProperty(QY0,"__esModule",{value:!0});QY0.createNoopMeter=QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=QY0.NOOP_OBSERVABLE_GAUGE_METRIC=QY0.NOOP_OBSERVABLE_COUNTER_METRIC=QY0.NOOP_UP_DOWN_COUNTER_METRIC=QY0.NOOP_HISTOGRAM_METRIC=QY0.NOOP_GAUGE_METRIC=QY0.NOOP_COUNTER_METRIC=QY0.NOOP_METER=QY0.NoopObservableUpDownCounterMetric=QY0.NoopObservableGaugeMetric=QY0.NoopObservableCounterMetric=QY0.NoopObservableMetric=QY0.NoopHistogramMetric=QY0.NoopGaugeMetric=QY0.NoopUpDownCounterMetric=QY0.NoopCounterMetric=QY0.NoopMetric=QY0.NoopMeter=void 0;class yf{constructor(){}createGauge(Q,J){return QY0.NOOP_GAUGE_METRIC}createHistogram(Q,J){return QY0.NOOP_HISTOGRAM_METRIC}createCounter(Q,J){return QY0.NOOP_COUNTER_METRIC}createUpDownCounter(Q,J){return QY0.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(Q,J){return QY0.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(Q,J){return QY0.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(Q,J){return QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(Q,J){}removeBatchObservableCallback(Q){}}QY0.NoopMeter=yf;class pZ{}QY0.NoopMetric=pZ;class bf extends pZ{add(Q,J){}}QY0.NoopCounterMetric=bf;class ff extends pZ{add(Q,J){}}QY0.NoopUpDownCounterMetric=ff;class hf extends pZ{record(Q,J){}}QY0.NoopGaugeMetric=hf;class gf extends pZ{record(Q,J){}}QY0.NoopHistogramMetric=gf;class Dq{addCallback(Q){}removeCallback(Q){}}QY0.NoopObservableMetric=Dq;class mf extends Dq{}QY0.NoopObservableCounterMetric=mf;class xf extends Dq{}QY0.NoopObservableGaugeMetric=xf;class uf extends Dq{}QY0.NoopObservableUpDownCounterMetric=uf;QY0.NOOP_METER=new yf;QY0.NOOP_COUNTER_METRIC=new bf;QY0.NOOP_GAUGE_METRIC=new hf;QY0.NOOP_HISTOGRAM_METRIC=new gf;QY0.NOOP_UP_DOWN_COUNTER_METRIC=new ff;QY0.NOOP_OBSERVABLE_COUNTER_METRIC=new mf;QY0.NOOP_OBSERVABLE_GAUGE_METRIC=new xf;QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new uf;function Qp0(){return QY0.NOOP_METER}QY0.createNoopMeter=Qp0});var VY0=r((FY0)=>{Object.defineProperty(FY0,"__esModule",{value:!0});FY0.ValueType=void 0;var Vp0;(function(Q){Q[Q.INT=0]="INT",Q[Q.DOUBLE=1]="DOUBLE"})(Vp0=FY0.ValueType||(FY0.ValueType={}))});var pf=r((qY0)=>{Object.defineProperty(qY0,"__esModule",{value:!0});qY0.defaultTextMapSetter=qY0.defaultTextMapGetter=void 0;qY0.defaultTextMapGetter={get(Q,J){if(Q==null)return;return Q[J]},keys(Q){if(Q==null)return[];return Object.keys(Q)}};qY0.defaultTextMapSetter={set(Q,J,X){if(Q==null)return;Q[J]=X}}});var PY0=r((LY0)=>{Object.defineProperty(LY0,"__esModule",{value:!0});LY0.NoopContextManager=void 0;var Up0=Mq();class zY0{active(){return Up0.ROOT_CONTEXT}with(Q,J,X,...Y){return J.call(X,...Y)}bind(Q,J){return J}enable(){return this}disable(){return this}}LY0.NoopContextManager=zY0});var Tq=r((BY0)=>{Object.defineProperty(BY0,"__esModule",{value:!0});BY0.ContextAPI=void 0;var zp0=PY0(),cf=pG(),NY0=cG(),nf="context",Lp0=new zp0.NoopContextManager;class rf{constructor(){}static getInstance(){if(!this._instance)this._instance=new rf;return this._instance}setGlobalContextManager(Q){return(0,cf.registerGlobal)(nf,Q,NY0.DiagAPI.instance())}active(){return this._getContextManager().active()}with(Q,J,X,...Y){return this._getContextManager().with(Q,J,X,...Y)}bind(Q,J){return this._getContextManager().bind(Q,J)}_getContextManager(){return(0,cf.getGlobal)(nf)||Lp0}disable(){this._getContextManager().disable(),(0,cf.unregisterGlobal)(nf,NY0.DiagAPI.instance())}}BY0.ContextAPI=rf});var of=r((OY0)=>{Object.defineProperty(OY0,"__esModule",{value:!0});OY0.TraceFlags=void 0;var jp0;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.SAMPLED=1]="SAMPLED"})(jp0=OY0.TraceFlags||(OY0.TraceFlags={}))});var GO=r((MY0)=>{Object.defineProperty(MY0,"__esModule",{value:!0});MY0.INVALID_SPAN_CONTEXT=MY0.INVALID_TRACEID=MY0.INVALID_SPANID=void 0;var Pp0=of();MY0.INVALID_SPANID="0000000000000000";MY0.INVALID_TRACEID="00000000000000000000000000000000";MY0.INVALID_SPAN_CONTEXT={traceId:MY0.INVALID_TRACEID,spanId:MY0.INVALID_SPANID,traceFlags:Pp0.TraceFlags.NONE}});var $O=r((RY0)=>{Object.defineProperty(RY0,"__esModule",{value:!0});RY0.NonRecordingSpan=void 0;var Np0=GO();class EY0{constructor(Q=Np0.INVALID_SPAN_CONTEXT){this._spanContext=Q}spanContext(){return this._spanContext}setAttribute(Q,J){return this}setAttributes(Q){return this}addEvent(Q,J){return this}addLink(Q){return this}addLinks(Q){return this}setStatus(Q){return this}updateName(Q){return this}end(Q){}isRecording(){return!1}recordException(Q,J){}}RY0.NonRecordingSpan=EY0});var ef=r((CY0)=>{Object.defineProperty(CY0,"__esModule",{value:!0});CY0.getSpanContext=CY0.setSpanContext=CY0.deleteSpan=CY0.setSpan=CY0.getActiveSpan=CY0.getSpan=void 0;var Bp0=Mq(),wp0=$O(),Op0=Tq(),sf=(0,Bp0.createContextKey)("OpenTelemetry Context Key SPAN");function tf(Q){return Q.getValue(sf)||void 0}CY0.getSpan=tf;function Mp0(){return tf(Op0.ContextAPI.getInstance().active())}CY0.getActiveSpan=Mp0;function vY0(Q,J){return Q.setValue(sf,J)}CY0.setSpan=vY0;function Dp0(Q){return Q.deleteValue(sf)}CY0.deleteSpan=Dp0;function Tp0(Q,J){return vY0(Q,new wp0.NonRecordingSpan(J))}CY0.setSpanContext=Tp0;function Ap0(Q){var J;return(J=tf(Q))===null||J===void 0?void 0:J.spanContext()}CY0.getSpanContext=Ap0});var ZO=r((bY0)=>{Object.defineProperty(bY0,"__esModule",{value:!0});bY0.wrapSpanContext=bY0.isSpanContextValid=bY0.isValidSpanId=bY0.isValidTraceId=void 0;var kY0=GO(),Ip0=$O(),kp0=/^([0-9a-f]{32})$/i,_p0=/^[0-9a-f]{16}$/i;function _Y0(Q){return kp0.test(Q)&&Q!==kY0.INVALID_TRACEID}bY0.isValidTraceId=_Y0;function yY0(Q){return _p0.test(Q)&&Q!==kY0.INVALID_SPANID}bY0.isValidSpanId=yY0;function yp0(Q){return _Y0(Q.traceId)&&yY0(Q.spanId)}bY0.isSpanContextValid=yp0;function bp0(Q){return new Ip0.NonRecordingSpan(Q)}bY0.wrapSpanContext=bp0});var Xh=r((mY0)=>{Object.defineProperty(mY0,"__esModule",{value:!0});mY0.NoopTracer=void 0;var mp0=Tq(),hY0=ef(),Qh=$O(),xp0=ZO(),Jh=mp0.ContextAPI.getInstance();class gY0{startSpan(Q,J,X=Jh.active()){if(Boolean(J===null||J===void 0?void 0:J.root))return new Qh.NonRecordingSpan;let W=X&&(0,hY0.getSpanContext)(X);if(up0(W)&&(0,xp0.isSpanContextValid)(W))return new Qh.NonRecordingSpan(W);else return new Qh.NonRecordingSpan}startActiveSpan(Q,J,X,Y){let W,G,$;if(arguments.length<2)return;else if(arguments.length===2)$=J;else if(arguments.length===3)W=J,$=X;else W=J,G=X,$=Y;let Z=G!==null&&G!==void 0?G:Jh.active(),K=this.startSpan(Q,W,Z),H=(0,hY0.setSpan)(Z,K);return Jh.with(H,$,void 0,K)}}mY0.NoopTracer=gY0;function up0(Q){return typeof Q==="object"&&typeof Q.spanId==="string"&&typeof Q.traceId==="string"&&typeof Q.traceFlags==="number"}});var Yh=r((lY0)=>{Object.defineProperty(lY0,"__esModule",{value:!0});lY0.ProxyTracer=void 0;var lp0=Xh(),dp0=new lp0.NoopTracer;class uY0{constructor(Q,J,X,Y){this._provider=Q,this.name=J,this.version=X,this.options=Y}startSpan(Q,J,X){return this._getTracer().startSpan(Q,J,X)}startActiveSpan(Q,J,X,Y){let W=this._getTracer();return Reflect.apply(W.startActiveSpan,W,arguments)}_getTracer(){if(this._delegate)return this._delegate;let Q=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!Q)return dp0;return this._delegate=Q,this._delegate}}lY0.ProxyTracer=uY0});var rY0=r((cY0)=>{Object.defineProperty(cY0,"__esModule",{value:!0});cY0.NoopTracerProvider=void 0;var pp0=Xh();class pY0{getTracer(Q,J,X){return new pp0.NoopTracer}}cY0.NoopTracerProvider=pY0});var Wh=r((aY0)=>{Object.defineProperty(aY0,"__esModule",{value:!0});aY0.ProxyTracerProvider=void 0;var cp0=Yh(),np0=rY0(),rp0=new np0.NoopTracerProvider;class iY0{getTracer(Q,J,X){var Y;return(Y=this.getDelegateTracer(Q,J,X))!==null&&Y!==void 0?Y:new cp0.ProxyTracer(this,Q,J,X)}getDelegate(){var Q;return(Q=this._delegate)!==null&&Q!==void 0?Q:rp0}setDelegate(Q){this._delegate=Q}getDelegateTracer(Q,J,X){var Y;return(Y=this._delegate)===null||Y===void 0?void 0:Y.getTracer(Q,J,X)}}aY0.ProxyTracerProvider=iY0});var tY0=r((sY0)=>{Object.defineProperty(sY0,"__esModule",{value:!0});sY0.SamplingDecision=void 0;var ip0;(function(Q){Q[Q.NOT_RECORD=0]="NOT_RECORD",Q[Q.RECORD=1]="RECORD",Q[Q.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(ip0=sY0.SamplingDecision||(sY0.SamplingDecision={}))});var Q70=r((eY0)=>{Object.defineProperty(eY0,"__esModule",{value:!0});eY0.SpanKind=void 0;var ap0;(function(Q){Q[Q.INTERNAL=0]="INTERNAL",Q[Q.SERVER=1]="SERVER",Q[Q.CLIENT=2]="CLIENT",Q[Q.PRODUCER=3]="PRODUCER",Q[Q.CONSUMER=4]="CONSUMER"})(ap0=eY0.SpanKind||(eY0.SpanKind={}))});var X70=r((J70)=>{Object.defineProperty(J70,"__esModule",{value:!0});J70.SpanStatusCode=void 0;var op0;(function(Q){Q[Q.UNSET=0]="UNSET",Q[Q.OK=1]="OK",Q[Q.ERROR=2]="ERROR"})(op0=J70.SpanStatusCode||(J70.SpanStatusCode={}))});var G70=r((Y70)=>{Object.defineProperty(Y70,"__esModule",{value:!0});Y70.validateValue=Y70.validateKey=void 0;var Kh="[_0-9a-z-*/]",sp0=`[a-z]${Kh}{0,255}`,tp0=`[a-z0-9]${Kh}{0,240}@[a-z]${Kh}{0,13}`,ep0=new RegExp(`^(?:${sp0}|${tp0})$`),Qc0=/^[ -~]{0,255}[!-~]$/,Jc0=/,|=/;function Xc0(Q){return ep0.test(Q)}Y70.validateKey=Xc0;function Yc0(Q){return Qc0.test(Q)&&!Jc0.test(Q)}Y70.validateValue=Yc0});var q70=r((F70)=>{Object.defineProperty(F70,"__esModule",{value:!0});F70.TraceStateImpl=void 0;var $70=G70(),Z70=32,Gc0=512,K70=",",H70="=";class Hh{constructor(Q){if(this._internalState=new Map,Q)this._parse(Q)}set(Q,J){let X=this._clone();if(X._internalState.has(Q))X._internalState.delete(Q);return X._internalState.set(Q,J),X}unset(Q){let J=this._clone();return J._internalState.delete(Q),J}get(Q){return this._internalState.get(Q)}serialize(){return this._keys().reduce((Q,J)=>{return Q.push(J+H70+this.get(J)),Q},[]).join(K70)}_parse(Q){if(Q.length>Gc0)return;if(this._internalState=Q.split(K70).reverse().reduce((J,X)=>{let Y=X.trim(),W=Y.indexOf(H70);if(W!==-1){let G=Y.slice(0,W),$=Y.slice(W+1,X.length);if((0,$70.validateKey)(G)&&(0,$70.validateValue)($))J.set(G,$)}return J},new Map),this._internalState.size>Z70)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Z70))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let Q=new Hh;return Q._internalState=new Map(this._internalState),Q}}F70.TraceStateImpl=Hh});var L70=r((U70)=>{Object.defineProperty(U70,"__esModule",{value:!0});U70.createTraceState=void 0;var $c0=q70();function Zc0(Q){return new $c0.TraceStateImpl(Q)}U70.createTraceState=Zc0});var N70=r((j70)=>{Object.defineProperty(j70,"__esModule",{value:!0});j70.context=void 0;var Kc0=Tq();j70.context=Kc0.ContextAPI.getInstance()});var O70=r((B70)=>{Object.defineProperty(B70,"__esModule",{value:!0});B70.diag=void 0;var Hc0=cG();B70.diag=Hc0.DiagAPI.instance()});var T70=r((M70)=>{Object.defineProperty(M70,"__esModule",{value:!0});M70.NOOP_METER_PROVIDER=M70.NoopMeterProvider=void 0;var Fc0=lf();class Fh{getMeter(Q,J,X){return Fc0.NOOP_METER}}M70.NoopMeterProvider=Fh;M70.NOOP_METER_PROVIDER=new Fh});var S70=r((E70)=>{Object.defineProperty(E70,"__esModule",{value:!0});E70.MetricsAPI=void 0;var qc0=T70(),Vh=pG(),A70=cG(),qh="metrics";class Uh{constructor(){}static getInstance(){if(!this._instance)this._instance=new Uh;return this._instance}setGlobalMeterProvider(Q){return(0,Vh.registerGlobal)(qh,Q,A70.DiagAPI.instance())}getMeterProvider(){return(0,Vh.getGlobal)(qh)||qc0.NOOP_METER_PROVIDER}getMeter(Q,J,X){return this.getMeterProvider().getMeter(Q,J,X)}disable(){(0,Vh.unregisterGlobal)(qh,A70.DiagAPI.instance())}}E70.MetricsAPI=Uh});var I70=r((v70)=>{Object.defineProperty(v70,"__esModule",{value:!0});v70.metrics=void 0;var Uc0=S70();v70.metrics=Uc0.MetricsAPI.getInstance()});var b70=r((_70)=>{Object.defineProperty(_70,"__esModule",{value:!0});_70.NoopTextMapPropagator=void 0;class k70{inject(Q,J){}extract(Q,J){return Q}fields(){return[]}}_70.NoopTextMapPropagator=k70});var m70=r((h70)=>{Object.defineProperty(h70,"__esModule",{value:!0});h70.deleteBaggage=h70.setBaggage=h70.getActiveBaggage=h70.getBaggage=void 0;var zc0=Tq(),Lc0=Mq(),zh=(0,Lc0.createContextKey)("OpenTelemetry Baggage Key");function f70(Q){return Q.getValue(zh)||void 0}h70.getBaggage=f70;function jc0(){return f70(zc0.ContextAPI.getInstance().active())}h70.getActiveBaggage=jc0;function Pc0(Q,J){return Q.setValue(zh,J)}h70.setBaggage=Pc0;function Nc0(Q){return Q.deleteValue(zh)}h70.deleteBaggage=Nc0});var p70=r((l70)=>{Object.defineProperty(l70,"__esModule",{value:!0});l70.PropagationAPI=void 0;var Lh=pG(),Mc0=b70(),x70=pf(),KO=m70(),Dc0=kf(),u70=cG(),jh="propagation",Tc0=new Mc0.NoopTextMapPropagator;class Ph{constructor(){this.createBaggage=Dc0.createBaggage,this.getBaggage=KO.getBaggage,this.getActiveBaggage=KO.getActiveBaggage,this.setBaggage=KO.setBaggage,this.deleteBaggage=KO.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Ph;return this._instance}setGlobalPropagator(Q){return(0,Lh.registerGlobal)(jh,Q,u70.DiagAPI.instance())}inject(Q,J,X=x70.defaultTextMapSetter){return this._getGlobalPropagator().inject(Q,J,X)}extract(Q,J,X=x70.defaultTextMapGetter){return this._getGlobalPropagator().extract(Q,J,X)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,Lh.unregisterGlobal)(jh,u70.DiagAPI.instance())}_getGlobalPropagator(){return(0,Lh.getGlobal)(jh)||Tc0}}l70.PropagationAPI=Ph});var r70=r((c70)=>{Object.defineProperty(c70,"__esModule",{value:!0});c70.propagation=void 0;var Ac0=p70();c70.propagation=Ac0.PropagationAPI.getInstance()});var e70=r((s70)=>{Object.defineProperty(s70,"__esModule",{value:!0});s70.TraceAPI=void 0;var Nh=pG(),i70=Wh(),a70=ZO(),cZ=ef(),o70=cG(),Bh="trace";class wh{constructor(){this._proxyTracerProvider=new i70.ProxyTracerProvider,this.wrapSpanContext=a70.wrapSpanContext,this.isSpanContextValid=a70.isSpanContextValid,this.deleteSpan=cZ.deleteSpan,this.getSpan=cZ.getSpan,this.getActiveSpan=cZ.getActiveSpan,this.getSpanContext=cZ.getSpanContext,this.setSpan=cZ.setSpan,this.setSpanContext=cZ.setSpanContext}static getInstance(){if(!this._instance)this._instance=new wh;return this._instance}setGlobalTracerProvider(Q){let J=(0,Nh.registerGlobal)(Bh,this._proxyTracerProvider,o70.DiagAPI.instance());if(J)this._proxyTracerProvider.setDelegate(Q);return J}getTracerProvider(){return(0,Nh.getGlobal)(Bh)||this._proxyTracerProvider}getTracer(Q,J){return this.getTracerProvider().getTracer(Q,J)}disable(){(0,Nh.unregisterGlobal)(Bh,o70.DiagAPI.instance()),this._proxyTracerProvider=new i70.ProxyTracerProvider}}s70.TraceAPI=wh});var XW0=r((QW0)=>{Object.defineProperty(QW0,"__esModule",{value:!0});QW0.trace=void 0;var Ec0=e70();QW0.trace=Ec0.TraceAPI.getInstance()});var FW0=r((Z8)=>{Object.defineProperty(Z8,"__esModule",{value:!0});Z8.trace=Z8.propagation=Z8.metrics=Z8.diag=Z8.context=Z8.INVALID_SPAN_CONTEXT=Z8.INVALID_TRACEID=Z8.INVALID_SPANID=Z8.isValidSpanId=Z8.isValidTraceId=Z8.isSpanContextValid=Z8.createTraceState=Z8.TraceFlags=Z8.SpanStatusCode=Z8.SpanKind=Z8.SamplingDecision=Z8.ProxyTracerProvider=Z8.ProxyTracer=Z8.defaultTextMapSetter=Z8.defaultTextMapGetter=Z8.ValueType=Z8.createNoopMeter=Z8.DiagLogLevel=Z8.DiagConsoleLogger=Z8.ROOT_CONTEXT=Z8.createContextKey=Z8.baggageEntryMetadataFromString=void 0;var Rc0=kf();Object.defineProperty(Z8,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return Rc0.baggageEntryMetadataFromString}});var YW0=Mq();Object.defineProperty(Z8,"createContextKey",{enumerable:!0,get:function(){return YW0.createContextKey}});Object.defineProperty(Z8,"ROOT_CONTEXT",{enumerable:!0,get:function(){return YW0.ROOT_CONTEXT}});var Sc0=eX0();Object.defineProperty(Z8,"DiagConsoleLogger",{enumerable:!0,get:function(){return Sc0.DiagConsoleLogger}});var vc0=XO();Object.defineProperty(Z8,"DiagLogLevel",{enumerable:!0,get:function(){return vc0.DiagLogLevel}});var Cc0=lf();Object.defineProperty(Z8,"createNoopMeter",{enumerable:!0,get:function(){return Cc0.createNoopMeter}});var Ic0=VY0();Object.defineProperty(Z8,"ValueType",{enumerable:!0,get:function(){return Ic0.ValueType}});var WW0=pf();Object.defineProperty(Z8,"defaultTextMapGetter",{enumerable:!0,get:function(){return WW0.defaultTextMapGetter}});Object.defineProperty(Z8,"defaultTextMapSetter",{enumerable:!0,get:function(){return WW0.defaultTextMapSetter}});var kc0=Yh();Object.defineProperty(Z8,"ProxyTracer",{enumerable:!0,get:function(){return kc0.ProxyTracer}});var _c0=Wh();Object.defineProperty(Z8,"ProxyTracerProvider",{enumerable:!0,get:function(){return _c0.ProxyTracerProvider}});var yc0=tY0();Object.defineProperty(Z8,"SamplingDecision",{enumerable:!0,get:function(){return yc0.SamplingDecision}});var bc0=Q70();Object.defineProperty(Z8,"SpanKind",{enumerable:!0,get:function(){return bc0.SpanKind}});var fc0=X70();Object.defineProperty(Z8,"SpanStatusCode",{enumerable:!0,get:function(){return fc0.SpanStatusCode}});var hc0=of();Object.defineProperty(Z8,"TraceFlags",{enumerable:!0,get:function(){return hc0.TraceFlags}});var gc0=L70();Object.defineProperty(Z8,"createTraceState",{enumerable:!0,get:function(){return gc0.createTraceState}});var Oh=ZO();Object.defineProperty(Z8,"isSpanContextValid",{enumerable:!0,get:function(){return Oh.isSpanContextValid}});Object.defineProperty(Z8,"isValidTraceId",{enumerable:!0,get:function(){return Oh.isValidTraceId}});Object.defineProperty(Z8,"isValidSpanId",{enumerable:!0,get:function(){return Oh.isValidSpanId}});var Mh=GO();Object.defineProperty(Z8,"INVALID_SPANID",{enumerable:!0,get:function(){return Mh.INVALID_SPANID}});Object.defineProperty(Z8,"INVALID_TRACEID",{enumerable:!0,get:function(){return Mh.INVALID_TRACEID}});Object.defineProperty(Z8,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Mh.INVALID_SPAN_CONTEXT}});var GW0=N70();Object.defineProperty(Z8,"context",{enumerable:!0,get:function(){return GW0.context}});var $W0=O70();Object.defineProperty(Z8,"diag",{enumerable:!0,get:function(){return $W0.diag}});var ZW0=I70();Object.defineProperty(Z8,"metrics",{enumerable:!0,get:function(){return ZW0.metrics}});var KW0=r70();Object.defineProperty(Z8,"propagation",{enumerable:!0,get:function(){return KW0.propagation}});var HW0=XW0();Object.defineProperty(Z8,"trace",{enumerable:!0,get:function(){return HW0.trace}});Z8.default={context:GW0.context,diag:$W0.diag,metrics:ZW0.metrics,propagation:KW0.propagation,trace:HW0.trace}});function $1(Q){return{...Q,execute:async(J,X)=>{let Y=Date.now();return await X.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":X.organization?.id??"system","user.id":X.auth.user?.id??X.auth.apiKey?.userId??"anonymous"}},async(W)=>{try{X.toolName=Q.name,X.access.setToolName?.(Q.name);let G=await Q.handler(J,X),$=Date.now()-Y;return X.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record($,{"tool.name":Q.name,"organization.id":X.organization?.id??"system",status:"success"}),X.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),W.setStatus({code:Dh.SpanStatusCode.OK}),G}catch(G){throw X.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":G.constructor.name}),W.setStatus({code:Dh.SpanStatusCode.ERROR,message:G.message}),W.recordException(G),G}finally{W.end()}})}}}var Dh;var K4=p(()=>{Dh=R5(FW0(),1)});function s1(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function M5(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function uc0(Q){return!!(Q.auth.user||Q.auth.apiKey)}function N1(Q){if(!uc0(Q))throw Error("Authentication required")}var HO,VW0,qW0,UW0,zW0,LW0,jW0,PW0,NW0,BW0;var nZ=p(()=>{o1();HO=N.record(N.array(N.string())),VW0=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),userId:N.string().describe("ID of the user who owns this API key"),permissions:HO.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),qW0=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:HO.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:N.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:N.record(N.unknown()).optional().describe("Additional metadata to store with the API key")}),UW0=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),key:N.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:HO.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),zW0=N.object({}),LW0=N.object({items:N.array(VW0).describe("List of API keys (without key values)")}),jW0=N.object({keyId:N.string().describe("ID of the API key to update"),name:N.string().min(1).max(64).optional().describe("New name for the API key"),permissions:HO.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:N.record(N.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),PW0=N.object({item:VW0.describe("The updated API key (without key value)")}),NW0=N.object({keyId:N.string().describe("ID of the API key to delete")}),BW0=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var Th;var wW0=p(()=>{K4();nZ();Th=$1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:qW0,outputSchema:UW0,handler:async(Q,J)=>{N1(J),await J.access.check();let X=await J.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:J.organization}});return{id:X.id,name:X.name??Q.name,key:X.key,permissions:X.permissions??{},expiresAt:X.expiresAt??null,createdAt:X.createdAt}}})});var Ah;var OW0=p(()=>{K4();nZ();Ah=$1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:NW0,outputSchema:BW0,handler:async(Q,J)=>{if(N1(J),await J.access.check(),!M5(J))throw Error("User ID required to delete API key");let W=(await J.boundAuth.apiKey.list())?.find((K)=>K.id===Q.keyId);if(!W)throw Error("API key not found");let $=W.metadata?.organization?.id,Z=J.organization?.id;if($!==Z)throw Error("Cannot delete API key from another organization");return await J.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var Eh;var MW0=p(()=>{K4();nZ();Eh=$1({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:zW0,outputSchema:LW0,handler:async(Q,J)=>{N1(J),await J.access.check();let X=await J.boundAuth.apiKey.list(),Y=J.organization?.id;return{items:(X??[]).filter((G)=>{return G.metadata?.organization?.id===Y}).map((G)=>({id:G.id,name:G.name??"Unnamed Key",userId:G.userId,permissions:G.permissions??{},expiresAt:G.expiresAt??null,createdAt:G.createdAt}))}}})});var Rh;var DW0=p(()=>{K4();nZ();Rh=$1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:jW0,outputSchema:PW0,handler:async(Q,J)=>{if(N1(J),await J.access.check(),!M5(J))throw Error("User ID required to update API key");let W=(await J.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!W)throw Error(`API key not found: ${Q.keyId}`);let $=W.metadata?.organization?.id,Z=J.organization?.id;if($!==Z)throw Error("Cannot update API key from another organization");let K=await J.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:J.organization}});if(!K)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:K.id,name:K.name??Q.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt??null,createdAt:K.createdAt}}}})});var TW0=p(()=>{wW0();OW0();MW0();DW0();nZ()});var dc0,pc0,gQ,AW0,EW0;var rZ=p(()=>{o1();dc0=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),pc0=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.unknown()),outputSchema:N.record(N.unknown()).optional()}),gQ=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket"]).describe("Type of connection"),connection_url:N.string().describe("URL for the connection"),connection_token:N.string().nullable().describe("Authentication token"),connection_headers:N.record(N.string(),N.string()).nullable().describe("Custom headers"),oauth_config:dc0.nullable().describe("OAuth configuration"),configuration_state:N.record(N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(pc0).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),AW0=gQ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),EW0=gQ.partial()});var cc0,nc0,Sh;var RW0=p(()=>{uV();o1();K4();Bw();rZ();cc0=N.object({data:AW0.describe("Data for the new connection (id is auto-generated if not provided)")}),nc0=N.object({item:gQ.describe("The created connection entity")}),Sh=$1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:cc0,outputSchema:nc0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=M5(J);if(!Y)throw Error("User ID required to create connection");let W={...Q.data,organization_id:X.id,created_by:Y},G=await IZ({id:"pending",title:W.title,connection_url:W.connection_url,connection_token:W.connection_token,connection_headers:W.connection_headers}).catch(()=>null),$=G?.length?G:null,Z=await J.storage.connections.create({...W,tools:$});return await J.eventBus.publish(X.id,FZ.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});function m7(Q){function J(X,Y){if(Y.description)X=X.describe(Y.description);return X}if(Q.const!==void 0){if(typeof Q.const==="string")return J(N.literal(Q.const),Q);else if(typeof Q.const==="number")return J(N.literal(Q.const),Q);else if(typeof Q.const==="boolean")return J(N.literal(Q.const),Q);else if(Q.const===null)return J(N.null(),Q);return J(N.literal(Q.const),Q)}if(Q.type)switch(Q.type){case"string":{if(Q.enum){if(Q.enum.length===0)return J(N.string(),Q);return J(N.enum(Q.enum),Q)}let X=N.string();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.pattern!==void 0){let Y=new RegExp(Q.pattern);X=X.regex(Y)}return J(X,Q)}case"number":case"integer":{if(Q.enum){if(Q.enum.length===0)return J(N.number(),Q);let Y=Q.enum.map((W)=>N.literal(W));if(Y.length===1)return J(Y[0],Q);if(Y.length>=2){let W=N.union([Y[0],Y[1],...Y.slice(2)]);return J(W,Q)}}let X=Q.type==="integer"?N.number().int():N.number();if(Q.minimum!==void 0)X=X.min(Q.minimum);if(Q.maximum!==void 0)X=X.max(Q.maximum);if(Q.exclusiveMinimum!==void 0)X=X.gt(Q.exclusiveMinimum);if(Q.exclusiveMaximum!==void 0)X=X.lt(Q.exclusiveMaximum);if(Q.multipleOf!==void 0)X=X.multipleOf(Q.multipleOf);return J(X,Q)}case"boolean":if(Q.enum){if(Q.enum.length===0)return J(N.boolean(),Q);let X=Q.enum.map((Y)=>N.literal(Y));if(X.length===1)return J(X[0],Q);if(X.length>=2){let Y=N.union([X[0],X[1],...X.slice(2)]);return J(Y,Q)}}return J(N.boolean(),Q);case"null":return J(N.null(),Q);case"object":if(Q.properties){let X={};for(let[W,G]of Object.entries(Q.properties))X[W]=m7(G);if(Q.required&&Array.isArray(Q.required)){let W=new Set(Q.required);for(let G of Object.keys(X))if(!W.has(G))X[G]=X[G].optional()}else for(let W of Object.keys(X))X[W]=X[W].optional();let Y;if(Q.additionalProperties!==!1)Y=N.object(X).passthrough();else Y=N.object(X);return J(Y,Q)}return J(N.object({}),Q);case"array":{let X;if(Q.items)X=N.array(m7(Q.items));else X=N.array(N.any());if(Q.minItems!==void 0)X=X.min(Q.minItems);if(Q.maxItems!==void 0)X=X.max(Q.maxItems);if(Q.uniqueItems===!0)X=X.refine((Y)=>{let W=new Set;return Y.every((G)=>{if(typeof G==="string"||typeof G==="number"||typeof G==="boolean"){if(W.has(G))return!1;return W.add(G),!0}let $=JSON.stringify(G);if(W.has($))return!1;return W.add($),!0})},{message:"Array items must be unique"});return J(X,Q)}}if(Q.enum){if(Q.enum.length===0)return J(N.never(),Q);if(Q.enum.every((Y)=>typeof Y==="string"))return J(N.enum(Q.enum),Q);else{let Y=Q.enum.map((W)=>N.literal(W));if(Y.length===1)return J(Y[0],Q);if(Y.length>=2){let W=N.union([Y[0],Y[1],...Y.slice(2)]);return J(W,Q)}}}if(Q.anyOf&&Q.anyOf.length>=2){let X=Q.anyOf.map(m7);return J(N.union([X[0],X[1],...X.slice(2)]),Q)}if(Q.allOf)return J(Q.allOf.reduce((X,Y)=>N.intersection(X,m7(Y)),N.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(m7);return J(N.union([X[0],X[1],...X.slice(2)]),Q)}return J(N.any(),Q)}var SW0=p(()=>{o1()});function rc0(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function Ch(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(Ch).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${Ch(Q.cause)}`:Q.message:`${Q}`}function vW0(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function ic0(){let Q="document"in globalThis?globalThis.document:void 0;return Q&&typeof Q=="object"&&"baseURI"in Q&&typeof Q.baseURI=="string"?Q.baseURI:void 0}var vh,IW0=(Q)=>{throw TypeError(Q)},gh=(Q,J,X)=>J.has(Q)||IW0("Cannot "+X),H4=(Q,J,X)=>(gh(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),C6=(Q,J,X)=>J.has(Q)?IW0("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),c8=(Q,J,X,Y)=>(gh(Q,J,"write to private field"),J.set(Q,X),X),KY=(Q,J,X)=>(gh(Q,J,"access private method"),X),D5,nG,iZ,FO,VO,Rq,sZ,Sq,x7,aZ,tZ,oZ,Aq,zJ,Ih,kh,_h,CW0,yh,bh,Eq,fh,hh,eZ;var kW0=p(()=>{uy();vh=class vh extends Event{constructor(Q,J){var X,Y;super(Q),this.code=(X=J==null?void 0:J.code)!=null?X:void 0,this.message=(Y=J==null?void 0:J.message)!=null?Y:void 0}[Symbol.for("nodejs.util.inspect.custom")](Q,J,X){return X(vW0(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(vW0(this),J)}};eZ=class eZ extends EventTarget{constructor(Q,J){var X,Y;super(),C6(this,zJ),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,C6(this,D5),C6(this,nG),C6(this,iZ),C6(this,FO),C6(this,VO),C6(this,Rq),C6(this,sZ),C6(this,Sq,null),C6(this,x7),C6(this,aZ),C6(this,tZ,null),C6(this,oZ,null),C6(this,Aq,null),C6(this,kh,async(W)=>{var G;H4(this,aZ).reset();let{body:$,redirected:Z,status:K,headers:H}=W;if(K===204){KY(this,zJ,Eq).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Z?c8(this,iZ,new URL(W.url)):c8(this,iZ,void 0),K!==200){KY(this,zJ,Eq).call(this,`Non-200 status code (${K})`,K);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){KY(this,zJ,Eq).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(H4(this,D5)===this.CLOSED)return;c8(this,D5,this.OPEN);let F=new Event("open");if((G=H4(this,Aq))==null||G.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){KY(this,zJ,Eq).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let V=new TextDecoder,q=$.getReader(),z=!0;do{let{done:j,value:P}=await q.read();P&&H4(this,aZ).feed(V.decode(P,{stream:!j})),j&&(z=!1,H4(this,aZ).reset(),KY(this,zJ,fh).call(this))}while(z)}),C6(this,_h,(W)=>{c8(this,x7,void 0),!(W.name==="AbortError"||W.type==="aborted")&&KY(this,zJ,fh).call(this,Ch(W))}),C6(this,yh,(W)=>{typeof W.id=="string"&&c8(this,Sq,W.id);let G=new MessageEvent(W.event||"message",{data:W.data,origin:H4(this,iZ)?H4(this,iZ).origin:H4(this,nG).origin,lastEventId:W.id||""});H4(this,oZ)&&(!W.event||W.event==="message")&&H4(this,oZ).call(this,G),this.dispatchEvent(G)}),C6(this,bh,(W)=>{c8(this,Rq,W)}),C6(this,hh,()=>{c8(this,sZ,void 0),H4(this,D5)===this.CONNECTING&&KY(this,zJ,Ih).call(this)});try{if(Q instanceof URL)c8(this,nG,Q);else if(typeof Q=="string")c8(this,nG,new URL(Q,ic0()));else throw Error("Invalid URL")}catch{throw rc0("An invalid or illegal string was specified")}c8(this,aZ,Nw({onEvent:H4(this,yh),onRetry:H4(this,bh)})),c8(this,D5,this.CONNECTING),c8(this,Rq,3000),c8(this,VO,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),c8(this,FO,(Y=J==null?void 0:J.withCredentials)!=null?Y:!1),KY(this,zJ,Ih).call(this)}get readyState(){return H4(this,D5)}get url(){return H4(this,nG).href}get withCredentials(){return H4(this,FO)}get onerror(){return H4(this,tZ)}set onerror(Q){c8(this,tZ,Q)}get onmessage(){return H4(this,oZ)}set onmessage(Q){c8(this,oZ,Q)}get onopen(){return H4(this,Aq)}set onopen(Q){c8(this,Aq,Q)}addEventListener(Q,J,X){let Y=J;super.addEventListener(Q,Y,X)}removeEventListener(Q,J,X){let Y=J;super.removeEventListener(Q,Y,X)}close(){H4(this,sZ)&&clearTimeout(H4(this,sZ)),H4(this,D5)!==this.CLOSED&&(H4(this,x7)&&H4(this,x7).abort(),c8(this,D5,this.CLOSED),c8(this,x7,void 0))}};D5=new WeakMap,nG=new WeakMap,iZ=new WeakMap,FO=new WeakMap,VO=new WeakMap,Rq=new WeakMap,sZ=new WeakMap,Sq=new WeakMap,x7=new WeakMap,aZ=new WeakMap,tZ=new WeakMap,oZ=new WeakMap,Aq=new WeakMap,zJ=new WeakSet,Ih=function(){c8(this,D5,this.CONNECTING),c8(this,x7,new AbortController),H4(this,VO)(H4(this,nG),KY(this,zJ,CW0).call(this)).then(H4(this,kh)).catch(H4(this,_h))},kh=new WeakMap,_h=new WeakMap,CW0=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...H4(this,Sq)?{"Last-Event-ID":H4(this,Sq)}:void 0},cache:"no-store",signal:(Q=H4(this,x7))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},yh=new WeakMap,bh=new WeakMap,Eq=function(Q,J){var X;H4(this,D5)!==this.CLOSED&&c8(this,D5,this.CLOSED);let Y=new vh("error",{code:J,message:Q});(X=H4(this,tZ))==null||X.call(this,Y),this.dispatchEvent(Y)},fh=function(Q,J){var X;if(H4(this,D5)===this.CLOSED)return;c8(this,D5,this.CONNECTING);let Y=new vh("error",{code:J,message:Q});(X=H4(this,tZ))==null||X.call(this,Y),this.dispatchEvent(Y),c8(this,sZ,setTimeout(H4(this,hh),H4(this,Rq)))},hh=new WeakMap,eZ.CONNECTING=0,eZ.OPEN=1,eZ.CLOSED=2});class mh{constructor(Q,J){this._url=Q,this._resourceMetadataUrl=void 0,this._eventSourceInit=J===null||J===void 0?void 0:J.eventSourceInit,this._requestInit=J===null||J===void 0?void 0:J.requestInit,this._authProvider=J===null||J===void 0?void 0:J.authProvider,this._fetch=J===null||J===void 0?void 0:J.fetch}async _authThenStart(){var Q;if(!this._authProvider)throw new o5("No auth provider");let J;try{J=await k7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(X){throw(Q=this.onerror)===null||Q===void 0||Q.call(this,X),X}if(J!=="AUTHORIZED")throw new o5;return await this._startOrAuth()}async _commonHeaders(){var Q;let J={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)J.Authorization=`Bearer ${X.access_token}`}if(this._protocolVersion)J["mcp-protocol-version"]=this._protocolVersion;return new Headers({...J,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers})}_startOrAuth(){var Q,J,X;let Y=(X=(J=(Q=this===null||this===void 0?void 0:this._eventSourceInit)===null||Q===void 0?void 0:Q.fetch)!==null&&J!==void 0?J:this._fetch)!==null&&X!==void 0?X:fetch;return new Promise((W,G)=>{this._eventSource=new eZ(this._url.href,{...this._eventSourceInit,fetch:async($,Z)=>{let K=await this._commonHeaders();K.set("Accept","text/event-stream");let H=await Y($,{...Z,headers:K});if(H.status===401&&H.headers.has("www-authenticate"))this._resourceMetadataUrl=Gq(H);return H}}),this._abortController=new AbortController,this._eventSource.onerror=($)=>{var Z;if($.code===401&&this._authProvider){this._authThenStart().then(W,G);return}let K=new _W0($.code,$.message,$);G(K),(Z=this.onerror)===null||Z===void 0||Z.call(this,K)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",($)=>{var Z;let K=$;try{if(this._endpoint=new URL(K.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(H){G(H),(Z=this.onerror)===null||Z===void 0||Z.call(this,H),this.close();return}W()}),this._eventSource.onmessage=($)=>{var Z,K;let H=$,F;try{F=HJ.parse(JSON.parse(H.data))}catch(V){(Z=this.onerror)===null||Z===void 0||Z.call(this,V);return}(K=this.onmessage)===null||K===void 0||K.call(this,F)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(Q){if(!this._authProvider)throw new o5("No auth provider");if(await k7(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new o5("Failed to authorize")}async close(){var Q,J,X;(Q=this._abortController)===null||Q===void 0||Q.abort(),(J=this._eventSource)===null||J===void 0||J.close(),(X=this.onclose)===null||X===void 0||X.call(this)}async send(Q){var J,X,Y;if(!this._endpoint)throw Error("Not connected");try{let W=await this._commonHeaders();W.set("content-type","application/json");let G={...this._requestInit,method:"POST",headers:W,body:JSON.stringify(Q),signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},$=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._endpoint,G);if(!$.ok){if($.status===401&&this._authProvider){if(this._resourceMetadataUrl=Gq($),await k7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new o5;return this.send(Q)}let Z=await $.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${$.status}): ${Z}`)}}catch(W){throw(Y=this.onerror)===null||Y===void 0||Y.call(this,W),W}}setProtocolVersion(Q){this._protocolVersion=Q}}var _W0;var yW0=p(()=>{kW0();FJ();gy();_W0=class _W0 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class xh{constructor(Q){this._url=Q}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,J)=>{this._socket=new WebSocket(this._url,ac0),this._socket.onerror=(X)=>{var Y;let W="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);J(W),(Y=this.onerror)===null||Y===void 0||Y.call(this,W)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{var X;(X=this.onclose)===null||X===void 0||X.call(this)},this._socket.onmessage=(X)=>{var Y,W;let G;try{G=HJ.parse(JSON.parse(X.data))}catch($){(Y=this.onerror)===null||Y===void 0||Y.call(this,$);return}(W=this.onmessage)===null||W===void 0||W.call(this,G)}})}async close(){var Q;(Q=this._socket)===null||Q===void 0||Q.close()}send(Q){return new Promise((J,X)=>{var Y;if(!this._socket){X(Error("Not connected"));return}(Y=this._socket)===null||Y===void 0||Y.send(JSON.stringify(Q)),J()})}}var ac0="mcp";var bW0=p(()=>{FJ()});function oc0(Q){let J=Q;if(!J||typeof J!=="object"||!("method"in J))return null;switch(J.method){case"initialize":{let X=J?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:J.jsonrpc??"2.0",id:J.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var uh;var fW0=p(()=>{dy();uh=class uh extends Zq{constructor(Q,J){super(Q,J)}send(Q,J){let X=oc0(Q);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Q,J)}}});var hW0,gW0=async(Q,J,X)=>{let Y=sc0(Q.connection,J,X);if(!Y)throw Error("Unknown MCP connection type");let W=new hW0({name:Q?.name??"MCP Client",version:"1.0.0"});return await W.connect(Y),{client:W,callStreamableTool:(G,$)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let Z=new Headers(X);if(!Z.has("Authorization"))Z.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,V]of Object.entries(Q.connection.headers??{}))Z.set(F,V);let K=new URL(Q.connection.url),H=K.pathname.replace(/\/+$/,"")||"/";return K.pathname=`${H}/call-tool/${encodeURIComponent(G)}`,fetch(K.href,{method:"POST",redirect:"manual",body:JSON.stringify($),headers:Z})}}},sc0=(Q,J,X)=>{if(Q.type==="Websocket")return new xh(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let W={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...X??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let G={requestInit:{headers:W,signal:J}};if(Q.token)G.eventSourceInit={fetch:($,Z)=>{return fetch($,{...Z,headers:{...W,Accept:"text/event-stream"},signal:J})}};return new mh(new URL(Q.url),G)}return new uh(new URL(Q.url),{requestInit:{headers:W,signal:J,credentials:"include"}})};var mW0=p(()=>{Ry();yW0();bW0();FJ();fW0();hW0=class hW0 extends Wq{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},Qq,J)}}});function uW0(Q){let J=(X)=>{if("connection"in Q)return gW0({connection:Q.connection},void 0,X);return Q.client};return new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(typeof Y!=="string")throw Error("Name must be a string");if(Y==="listTools")return Z;async function W(K,H=Y){let F=Q?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await J(V);if(Q?.streamable?.[String(H)])return z(String(H),K);let{structuredContent:j,isError:P,content:B}=await q.callTool({name:String(H),arguments:K});if(P){let w=B?.[0]?.text,T=typeof w==="string"?tc0(w):null,E=T?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(T.code,T.message,T.traceId):null;if(E)throw E;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(j??B)}`)}return j}async function G(){let{client:K}=await J(),{tools:H}=await K.listTools();return H}async function $(){if(!("connection"in Q))return G();let K=Q.connection,H=JSON.stringify(K);try{if(!qO.has(H))qO.set(H,G());return await qO.get(H)}catch(F){console.error("Failed to list tools",F),qO.delete(H);return}}async function Z(){return(await $()??[]).map((H)=>xW0(H,W))}return W.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===Y);if(!H)throw Error(`Tool ${Y} not found`);return xW0(H,W)},W}})}var tc0=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},qO,xW0=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?m7(Q.inputSchema):void 0,outputSchema:Q.outputSchema?m7(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var lW0=p(()=>{SW0();mW0();qO=new Map});function UO(Q){return uW0(Q)}var JS1;var dW0=p(()=>{lW0();JS1=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>UO({connection:X});return global[J]}})});function zO(Q){return{isImplementedBy:(J)=>{for(let X of Q){let Y=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,W=J.find((G)=>Y.test(G.name));if(!W&&X.opt)continue;if(!W)return!1}return!0}}}var QK=(Q)=>{return{...zO(Q),forClient:(J)=>{return UO({client:J,streamable:Q.reduce((X,Y)=>{return X[Y.name]=Y.streamable===!0,X},{})})},forConnection:(J)=>{return UO({connection:J,streamable:Q.reduce((X,Y)=>{return X[Y.name]=Y.streamable===!0,X},{})})}}};var vq=p(()=>{dW0()});function Iq(Q){return N.object({items:N.array(Q).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function dh(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function Jn0(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function Xn0(Q){return N.object({item:Q.describe("The created entity with generated id")})}function Yn0(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function Wn0(Q){return N.object({item:Q.describe("The updated entity")})}function ch(Q){return N.object({item:Q.describe("The deleted entity")})}function XK(Q,J,X){let Y=Q.toUpperCase(),W=X?.readOnly??!1,G=[{name:`COLLECTION_${Y}_LIST`,inputSchema:Cq,outputSchema:Iq(J)},{name:`COLLECTION_${Y}_GET`,inputSchema:lh,outputSchema:dh(J)}];if(!W)G.push({name:`COLLECTION_${Y}_CREATE`,inputSchema:Jn0(J),outputSchema:Xn0(J),opt:!0},{name:`COLLECTION_${Y}_UPDATE`,inputSchema:Yn0(J),outputSchema:Wn0(J),opt:!0},{name:`COLLECTION_${Y}_DELETE`,inputSchema:ph,outputSchema:ch(J),opt:!0});return G}var JK,ec0,pW0,Qn0,Cq,lh,ph;var u7=p(()=>{o1();JK=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),ec0=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),pW0=N.lazy(()=>N.union([ec0,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(pW0)})])),Qn0=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),Cq=N.object({where:pW0.optional().describe("Filter expression"),orderBy:N.array(Qn0).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});lh=N.object({id:N.string().describe("ID of the entity to retrieve")});ph=N.object({id:N.string().describe("ID of the entity to delete")})});var Gn0,cW0,FS1;var nW0=p(()=>{o1();u7();Gn0=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.unknown()),outputSchema:N.record(N.unknown()).optional()}),cW0=JK.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Gn0).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),FS1=XK("registry_app",cW0,{readOnly:!0})});var rW0,iW0,aW0,oW0,sW0,$n0;var tW0=p(()=>{o1();vq();rW0=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),iW0=N.object({events:N.array(rW0).min(1).describe("Batch of CloudEvents to process")}),aW0=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),oW0=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),aW0).optional().describe("Per-event results keyed by event ID")}),sW0=[{name:"ON_EVENTS",inputSchema:iW0,outputSchema:oW0}],$n0=QK(sW0)});var kq,_q,yq,bq,eW0,QG0,fq,hq,gq,mq,xq,uq,lq,dq,JG0,Zn0;var XG0=p(()=>{o1();vq();kq=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),_q=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),yq=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),bq=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")})}),eW0=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QG0=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),fq=N.object({subscriptions:N.array(eW0).describe("Desired subscriptions - system will create/update/delete to match")}),hq=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(QG0).describe("Current subscriptions after sync")}),gq=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),mq=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),xq=N.object({eventId:N.string().describe("Event ID to cancel")}),uq=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),lq=N.object({eventId:N.string().describe("Event ID to acknowledge")}),dq=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),JG0=[{name:"EVENT_PUBLISH",inputSchema:kq,outputSchema:_q},{name:"EVENT_SUBSCRIBE",inputSchema:yq,outputSchema:bq},{name:"EVENT_UNSUBSCRIBE",inputSchema:gq,outputSchema:mq},{name:"EVENT_CANCEL",inputSchema:xq,outputSchema:uq},{name:"EVENT_ACK",inputSchema:lq,outputSchema:dq},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:fq,outputSchema:hq}],Zn0=QK(JG0)});var nh=p(()=>{vq();nW0();tW0();XG0()});var Kn0,Hn0,YG0;var WG0=p(()=>{o1();u7();Kn0=JK.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),gateway_id:N.string().describe("Gateway ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Hn0=XK("assistant",Kn0),YG0=[...Hn0]});var pq,HY,$G0,Fn0,ZG0,Vn0,qn0,Un0,KG0,zn0,Ln0,jn0,Pn0,Nn0,Bn0,wn0,On0,CS1,Mn0,IS1,GG0,Dn0,Tn0,rh,kS1;var HG0=p(()=>{o1();vq();u7();pq=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),pq),N.array(pq)])),HY=N.record(N.string(),N.record(N.string(),pq)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$G0=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:HY}),Fn0=N.union([N.string(),N.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),ZG0=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Fn0,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HY}),Vn0=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:HY}),qn0=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.unknown().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HY}),Un0=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:pq}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:pq}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),KG0=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:Un0.describe("Result of the tool call"),providerOptions:HY}),zn0=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:HY}),Ln0=N.object({role:N.literal("user"),content:N.array(N.union([$G0,ZG0])).describe("User message content parts (text or file)"),providerOptions:HY}),jn0=N.object({role:N.literal("assistant"),content:N.array(N.union([$G0,ZG0,Vn0,qn0,KG0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HY}),Pn0=N.object({role:N.literal("tool"),content:N.array(KG0).describe("Tool message content (tool results)"),providerOptions:HY}),Nn0=N.union([zn0,Ln0,jn0,Pn0]),Bn0=N.array(Nn0).describe("A list of messages forming the prompt"),wn0=N.object({prompt:Bn0.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),headers:N.record(N.string(),N.union([N.string(),N.undefined()])).optional().describe("Additional HTTP headers to be sent with the request"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),On0=N.object({content:N.array(N.any()).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.object({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).passthrough().transform((Q)=>({inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalTokens:Q.totalTokens,reasoningTokens:Q.reasoningTokens,...Q})).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.date().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),CS1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Mn0=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),IS1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),GG0=N.object({modelId:N.string().describe("The ID of the model"),callOptions:wn0}),Dn0=JK.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Tn0=XK("llm",Dn0,{readOnly:!0}),rh=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:Mn0},{name:"LLM_DO_STREAM",inputSchema:GG0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:GG0,outputSchema:On0},...Tn0],kS1=QK(rh)});function En0(Q){let J=[],X=0;while(X<Q.length){let Y=Q[X];if(Y==="%")J.push(".*");else if(Y==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(Y))J.push("\\"+Y);else J.push(Y);X++}return J.join("")}function l7(Q){return typeof Q==="string"||typeof Q==="number"}function LO(Q,J){if("conditions"in J){let{operator:Z,conditions:K}=J;switch(Z){case"and":return K.every((H)=>LO(Q,H));case"or":return K.some((H)=>LO(Q,H));case"not":return!K.every((H)=>LO(Q,H));default:return!0}}let{field:X,operator:Y,value:W}=J,G=X.join("."),$=ih(Q,G);switch(Y){case"eq":return $===W;case"gt":return l7($)&&l7(W)&&$>W;case"gte":return l7($)&&l7(W)&&$>=W;case"lt":return l7($)&&l7(W)&&$<W;case"lte":return l7($)&&l7(W)&&$<=W;case"in":return Array.isArray(W)&&W.includes($);case"like":if(typeof $!=="string"||typeof W!=="string")return!1;if(W.length>100)return!1;let Z=En0(W);return new RegExp(`^${Z}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof W!=="string")return!1;return $.toLowerCase().includes(W.toLowerCase());default:return!0}}function ih(Q,J){let X=J.split("."),Y=Q;for(let W of X){if(Y==null||typeof Y!=="object")return;Y=Y[W]}return Y}function Rn0(Q,J){return[...Q].sort((X,Y)=>{for(let W of J){let G=W.field.join("."),$=ih(X,G),Z=ih(Y,G),K=0;if($==null&&Z==null)continue;if($==null)K=W.nulls==="first"?-1:1;else if(Z==null)K=W.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof Z==="string")K=$.localeCompare(Z);else if(typeof $==="number"&&typeof Z==="number")K=$-Z;else K=String($).localeCompare(String(Z));if(K!==0)return W.direction==="desc"?-K:K}return 0})}var An0,Sn0,vn0,ah;var FG0=p(()=>{nh();WG0();u7();HG0();o1();K4();rZ();An0={LLM:rh,ASSISTANTS:YG0};Sn0=Cq.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),vn0=Iq(gQ),ah=$1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:Sn0,outputSchema:vn0,handler:async(Q,J)=>{await J.access.check();let X=s1(J),Y=Q.binding?typeof Q.binding==="string"?(()=>{let q=An0[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,W=Y?zO(Y):void 0,G=await J.storage.connections.list(X.id),$=W?await Promise.all(G.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return W.isImplementedBy(q.tools.map((j)=>({name:j.name,inputSchema:j.inputSchema,outputSchema:j.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):G;if(Q.where)$=$.filter((q)=>LO(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=Rn0($,Q.orderBy);let Z=$.length,K=Q.offset??0,H=Q.limit??100,F=$.slice(K,K+H),V=K+H<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Cn0,oh;var VG0=p(()=>{u7();K4();rZ();Cn0=dh(gQ),oh=$1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:lh,outputSchema:Cn0,handler:async(Q,J)=>{let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y||Y.organization_id!==X.id)return{item:null};return{item:Y}}})});var jO=(Q,J)=>{if(J===null||J===void 0)return;let X=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),Y=J;for(let W of X){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[W]}return Y};function qG0(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return J}function In0(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function kn0(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function _n0(Q,J){let X={};if(!Q||!J)return X;for(let Y of J){let W=In0(Y);if(!W)continue;let[G,$]=W,Z=jO(G,Q),K=kn0(Z);if(K){if(!X[K])X[K]=[];X[K].push($)}}return X}function UG0(Q,J){let X=_n0(Q,J);return new Set(Object.keys(X))}var zG0=()=>{};async function fn0(Q,J,X,Y){for(let G of J){let[$]=qG0(G),Z=jO($,Q);if(Z===void 0||Z===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let W=UG0(Q,J);for(let G of W){if(G===DG.SELF)continue;let $=await Y.storage.connections.findById(G);if(!$||$.organization_id!==X)throw Error(`Referenced connection not found: ${G}`);try{await Y.access.check(G)}catch(Z){throw Error(`Access denied to referenced connection: ${G}. ${Z.message}`)}}}var yn0,bn0,sh;var LG0=p(()=>{zG0();uV();o1();K4();Bw();rZ();yn0=N.object({id:N.string().describe("ID of the connection to update"),data:EW0.describe("Partial connection data to update")}),bn0=N.object({item:gQ.describe("The updated connection entity")});sh=$1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:yn0,outputSchema:bn0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let{id:Y,data:W}=Q,G=await J.storage.connections.findById(Y);if(!G||G.organization_id!==X.id)throw Error("Connection not found in organization");let $=W.configuration_state??G.configuration_state,Z=W.configuration_scopes??G.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)$=W.configuration_state;else if($===null)$={};if(W.configuration_scopes!==void 0)Z=W.configuration_scopes??[];if(Z.length>0&&$)await fn0($,Z,X.id,J)}let K=await IZ({id:G.id,title:W.title??G.title,connection_url:W.connection_url??G.connection_url,connection_token:W.connection_token??G.connection_token,connection_headers:W.connection_headers??G.connection_headers}).catch(()=>null),H=K?.length?K:null,F={...W,tools:H,configuration_state:$,configuration_scopes:Z},V=await J.storage.connections.update(Y,F);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&$&&Z.length>0)try{await(await J.createMCPProxy(Y)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:Z}})}catch(q){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",q)}return{item:V}}})});var th;var jG0=p(()=>{u7();K4();rZ();th=$1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:ph,outputSchema:ch(gQ),handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y)throw Error(`Connection not found: ${Q.id}`);if(Y.organization_id!==X.id)throw Error("Connection not found in organization");return await J.storage.connections.delete(Q.id),{item:Y}}})});var eh;var PG0=p(()=>{o1();K4();eh=$1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Q,J)=>{let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y||Y.organization_id!==X.id)throw Error("Connection not found");let W=await J.storage.connections.testConnection(Q.id);return{id:Q.id,...W}}})});var NG0=p(()=>{RW0();FG0();VG0();LG0();jG0();PG0()});import{sql as x4}from"kysely";function BG0(Q){return Q.replace(/-/g,"_")}function xn0(Q){return`app_${BG0(Q)}`}function un0(Q){return`app_role_${BG0(Q)}`}function ln0(Q){if(Q instanceof Error){let J=Q.message.toLowerCase(),X=Q.code;return X==="3F000"||X==="42704"||J.includes("schema")&&J.includes("does not exist")||J.includes("role")&&J.includes("does not exist")}return!1}async function dn0(Q,J,X){if(await x4`CREATE SCHEMA IF NOT EXISTS ${x4.id(J)}`.execute(Q),!(await x4`
|
|
248
|
+
`;if(Q===204||Q===304||Q>=100&&Q<=199)this._hasBody=!1;if(this._expect_continue&&!this._sent100)this.shouldKeepAlive=!1;let $=W&&!Array.isArray(W)?W:W;return this._storeHeader(G,$??null),this}writeHeader=this.writeHead;fetchResponse;_toFetchResponse(Q,J,X,Y,W){let G=new Headers;for(let[K,H]of X)G.append(K,H);let $=this,Z=this._hasBody?new ReadableStream({start(K){for(let H of Y)K.enqueue(H);if(W)K.close();else $.on("finish",()=>{W=!0,K.close()}),$.on("_dataWritten",(H)=>{if(W)return;let F=$.dataFromDataWrittenEvent(H);K.enqueue(F)})}}):null;if(Z!=null&&typeof FixedLengthStream<"u"){let K=parseInt(G.get("content-length")??"",10);if(K>=0)Z=Z.pipeThrough(new FixedLengthStream(K))}return new Response(Z,{status:Q,statusText:J,headers:G})}}});var HX0=p(()=>{Pf();Af();KX0()});var Sf;var FX0=p(()=>{iJ0();HX0();Sf=class Sf extends $f{constructor(Q){super({...Q,sessionIdGenerator:Q?.sessionIdGenerator})}async handleMessage(Q){let{req:J,res:X}=Ef(Q);return super.handleRequest(J,X,await Q.json().catch(()=>null)),Rf(X)}}});var VX0=(...Q)=>{return function(X,Y){let W=(G)=>{let $=Q[G];if(!$)return Y();return $(X,()=>W(G+1))};return W(0)}};class qX0{config;tools=[];callToolMiddlewares=[];constructor(Q){this.config={...Q,capabilities:Q.capabilities??{tools:{}}}}withTool(Q){return this.tools.push(Q),this}withTools(Q){return this.tools.push(...Q),this}callToolMiddleware(...Q){return this.callToolMiddlewares.push(...Q),this}build(){let Q=this.callToolMiddlewares.length>0?VX0(...this.callToolMiddlewares):null,J=()=>{let X=new Bb({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let Y of this.tools){let W=async(K)=>{try{let H=await Y.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},G=Q?async(K)=>{let H={method:"tools/call",params:{name:Y.name,arguments:K}};return await Q(H,()=>W(K))}:W,$="shape"in Y.inputSchema?Y.inputSchema.shape:m_.object({}).shape,Z=Y.outputSchema&&"shape"in Y.outputSchema?Y.outputSchema.shape:m_.object({}).shape;X.registerTool(Y.name,{annotations:Y.annotations,description:Y.description??"",inputSchema:$,outputSchema:Z},G)}return X};return{callStreamableTool:async(X,Y)=>{let W=this.tools.find(($)=>$.name===X);if(!W)throw Error(`Tool ${X} not found`);let G=await W.handler(Y);if(!(G instanceof Response))throw Error(`Tool ${X} returned a non-response`);return G},client:{listTools:async()=>{return{tools:this.tools.map((X)=>({name:X.name,description:X.description??"",inputSchema:kZ(X.inputSchema),outputSchema:X.outputSchema?kZ(X.outputSchema):void 0}))}},callTool:async(X)=>{let Y=this.tools.find((W)=>W.name===X.name);if(!Y)return{content:[{type:"text",text:"Tool not found"}]};try{let W=await Y?.handler(X.arguments??{});return{content:[{type:"text",text:JSON.stringify(W)}],structuredContent:W}}catch(W){return{content:[{type:"text",text:`Error: ${W.message}`}]}}}},fetch:async(X)=>{let Y=new Sf({enableJsonResponse:X.headers.get("Accept")?.includes("application/json")??!1});return await J().connect(Y),await Y.handleMessage(X)}}}}function UX0(Q){return new qX0(Q)}var zX0=p(()=>{vQ0();o1();Cw();FX0()});var PX0=r((LX0)=>{Object.defineProperty(LX0,"__esModule",{value:!0});LX0._globalThis=void 0;LX0._globalThis=typeof globalThis==="object"?globalThis:global});var NX0=r((lG)=>{var Ad0=lG&&lG.__createBinding||(Object.create?function(Q,J,X,Y){if(Y===void 0)Y=X;Object.defineProperty(Q,Y,{enumerable:!0,get:function(){return J[X]}})}:function(Q,J,X,Y){if(Y===void 0)Y=X;Q[Y]=J[X]}),Ed0=lG&&lG.__exportStar||function(Q,J){for(var X in Q)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))Ad0(J,Q,X)};Object.defineProperty(lG,"__esModule",{value:!0});Ed0(PX0(),lG)});var BX0=r((dG)=>{var Rd0=dG&&dG.__createBinding||(Object.create?function(Q,J,X,Y){if(Y===void 0)Y=X;Object.defineProperty(Q,Y,{enumerable:!0,get:function(){return J[X]}})}:function(Q,J,X,Y){if(Y===void 0)Y=X;Q[Y]=J[X]}),Sd0=dG&&dG.__exportStar||function(Q,J){for(var X in Q)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(J,X))Rd0(J,Q,X)};Object.defineProperty(dG,"__esModule",{value:!0});Sd0(NX0(),dG)});var vf=r((wX0)=>{Object.defineProperty(wX0,"__esModule",{value:!0});wX0.VERSION=void 0;wX0.VERSION="1.9.0"});var EX0=r((TX0)=>{Object.defineProperty(TX0,"__esModule",{value:!0});TX0.isCompatible=TX0._makeCompatibilityCheck=void 0;var vd0=vf(),MX0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function DX0(Q){let J=new Set([Q]),X=new Set,Y=Q.match(MX0);if(!Y)return()=>!1;let W={major:+Y[1],minor:+Y[2],patch:+Y[3],prerelease:Y[4]};if(W.prerelease!=null)return function(K){return K===Q};function G(Z){return X.add(Z),!1}function $(Z){return J.add(Z),!0}return function(K){if(J.has(K))return!0;if(X.has(K))return!1;let H=K.match(MX0);if(!H)return G(K);let F={major:+H[1],minor:+H[2],patch:+H[3],prerelease:H[4]};if(F.prerelease!=null)return G(K);if(W.major!==F.major)return G(K);if(W.major===0){if(W.minor===F.minor&&W.patch<=F.patch)return $(K);return G(K)}if(W.minor<=F.minor)return $(K);return G(K)}}TX0._makeCompatibilityCheck=DX0;TX0.isCompatible=DX0(vd0.VERSION)});var pG=r((RX0)=>{Object.defineProperty(RX0,"__esModule",{value:!0});RX0.unregisterGlobal=RX0.getGlobal=RX0.registerGlobal=void 0;var Id0=BX0(),lZ=vf(),kd0=EX0(),_d0=lZ.VERSION.split(".")[0],Bq=Symbol.for(`opentelemetry.js.api.${_d0}`),wq=Id0._globalThis;function yd0(Q,J,X,Y=!1){var W;let G=wq[Bq]=(W=wq[Bq])!==null&&W!==void 0?W:{version:lZ.VERSION};if(!Y&&G[Q]){let $=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${Q}`);return X.error($.stack||$.message),!1}if(G.version!==lZ.VERSION){let $=Error(`@opentelemetry/api: Registration of version v${G.version} for ${Q} does not match previously registered API v${lZ.VERSION}`);return X.error($.stack||$.message),!1}return G[Q]=J,X.debug(`@opentelemetry/api: Registered a global for ${Q} v${lZ.VERSION}.`),!0}RX0.registerGlobal=yd0;function bd0(Q){var J,X;let Y=(J=wq[Bq])===null||J===void 0?void 0:J.version;if(!Y||!(0,kd0.isCompatible)(Y))return;return(X=wq[Bq])===null||X===void 0?void 0:X[Q]}RX0.getGlobal=bd0;function fd0(Q,J){J.debug(`@opentelemetry/api: Unregistering a global for ${Q} v${lZ.VERSION}.`);let X=wq[Bq];if(X)delete X[Q]}RX0.unregisterGlobal=fd0});var kX0=r((CX0)=>{Object.defineProperty(CX0,"__esModule",{value:!0});CX0.DiagComponentLogger=void 0;var md0=pG();class vX0{constructor(Q){this._namespace=Q.namespace||"DiagComponentLogger"}debug(...Q){return Oq("debug",this._namespace,Q)}error(...Q){return Oq("error",this._namespace,Q)}info(...Q){return Oq("info",this._namespace,Q)}warn(...Q){return Oq("warn",this._namespace,Q)}verbose(...Q){return Oq("verbose",this._namespace,Q)}}CX0.DiagComponentLogger=vX0;function Oq(Q,J,X){let Y=(0,md0.getGlobal)("diag");if(!Y)return;return X.unshift(J),Y[Q](...X)}});var XO=r((_X0)=>{Object.defineProperty(_X0,"__esModule",{value:!0});_X0.DiagLogLevel=void 0;var xd0;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.ERROR=30]="ERROR",Q[Q.WARN=50]="WARN",Q[Q.INFO=60]="INFO",Q[Q.DEBUG=70]="DEBUG",Q[Q.VERBOSE=80]="VERBOSE",Q[Q.ALL=9999]="ALL"})(xd0=_X0.DiagLogLevel||(_X0.DiagLogLevel={}))});var fX0=r((yX0)=>{Object.defineProperty(yX0,"__esModule",{value:!0});yX0.createLogLevelDiagLogger=void 0;var ZY=XO();function ud0(Q,J){if(Q<ZY.DiagLogLevel.NONE)Q=ZY.DiagLogLevel.NONE;else if(Q>ZY.DiagLogLevel.ALL)Q=ZY.DiagLogLevel.ALL;J=J||{};function X(Y,W){let G=J[Y];if(typeof G==="function"&&Q>=W)return G.bind(J);return function(){}}return{error:X("error",ZY.DiagLogLevel.ERROR),warn:X("warn",ZY.DiagLogLevel.WARN),info:X("info",ZY.DiagLogLevel.INFO),debug:X("debug",ZY.DiagLogLevel.DEBUG),verbose:X("verbose",ZY.DiagLogLevel.VERBOSE)}}yX0.createLogLevelDiagLogger=ud0});var cG=r((gX0)=>{Object.defineProperty(gX0,"__esModule",{value:!0});gX0.DiagAPI=void 0;var ld0=kX0(),dd0=fX0(),hX0=XO(),YO=pG(),pd0="diag";class If{constructor(){function Q(Y){return function(...W){let G=(0,YO.getGlobal)("diag");if(!G)return;return G[Y](...W)}}let J=this,X=(Y,W={logLevel:hX0.DiagLogLevel.INFO})=>{var G,$,Z;if(Y===J){let F=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return J.error((G=F.stack)!==null&&G!==void 0?G:F.message),!1}if(typeof W==="number")W={logLevel:W};let K=(0,YO.getGlobal)("diag"),H=(0,dd0.createLogLevelDiagLogger)(($=W.logLevel)!==null&&$!==void 0?$:hX0.DiagLogLevel.INFO,Y);if(K&&!W.suppressOverrideMessage){let F=(Z=Error().stack)!==null&&Z!==void 0?Z:"<failed to generate stacktrace>";K.warn(`Current logger will be overwritten from ${F}`),H.warn(`Current logger will overwrite one already registered from ${F}`)}return(0,YO.registerGlobal)("diag",H,J,!0)};J.setLogger=X,J.disable=()=>{(0,YO.unregisterGlobal)(pd0,J)},J.createComponentLogger=(Y)=>{return new ld0.DiagComponentLogger(Y)},J.verbose=Q("verbose"),J.debug=Q("debug"),J.info=Q("info"),J.warn=Q("warn"),J.error=Q("error")}static instance(){if(!this._instance)this._instance=new If;return this._instance}}gX0.DiagAPI=If});var lX0=r((xX0)=>{Object.defineProperty(xX0,"__esModule",{value:!0});xX0.BaggageImpl=void 0;class dZ{constructor(Q){this._entries=Q?new Map(Q):new Map}getEntry(Q){let J=this._entries.get(Q);if(!J)return;return Object.assign({},J)}getAllEntries(){return Array.from(this._entries.entries()).map(([Q,J])=>[Q,J])}setEntry(Q,J){let X=new dZ(this._entries);return X._entries.set(Q,J),X}removeEntry(Q){let J=new dZ(this._entries);return J._entries.delete(Q),J}removeEntries(...Q){let J=new dZ(this._entries);for(let X of Q)J._entries.delete(X);return J}clear(){return new dZ}}xX0.BaggageImpl=dZ});var cX0=r((dX0)=>{Object.defineProperty(dX0,"__esModule",{value:!0});dX0.baggageEntryMetadataSymbol=void 0;dX0.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var kf=r((nX0)=>{Object.defineProperty(nX0,"__esModule",{value:!0});nX0.baggageEntryMetadataFromString=nX0.createBaggage=void 0;var cd0=cG(),nd0=lX0(),rd0=cX0(),id0=cd0.DiagAPI.instance();function ad0(Q={}){return new nd0.BaggageImpl(new Map(Object.entries(Q)))}nX0.createBaggage=ad0;function od0(Q){if(typeof Q!=="string")id0.error(`Cannot create baggage metadata from unknown type: ${typeof Q}`),Q="";return{__TYPE__:rd0.baggageEntryMetadataSymbol,toString(){return Q}}}nX0.baggageEntryMetadataFromString=od0});var Mq=r((iX0)=>{Object.defineProperty(iX0,"__esModule",{value:!0});iX0.ROOT_CONTEXT=iX0.createContextKey=void 0;function td0(Q){return Symbol.for(Q)}iX0.createContextKey=td0;class WO{constructor(Q){let J=this;J._currentContext=Q?new Map(Q):new Map,J.getValue=(X)=>J._currentContext.get(X),J.setValue=(X,Y)=>{let W=new WO(J._currentContext);return W._currentContext.set(X,Y),W},J.deleteValue=(X)=>{let Y=new WO(J._currentContext);return Y._currentContext.delete(X),Y}}}iX0.ROOT_CONTEXT=new WO});var eX0=r((sX0)=>{Object.defineProperty(sX0,"__esModule",{value:!0});sX0.DiagConsoleLogger=void 0;var _f=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class oX0{constructor(){function Q(J){return function(...X){if(console){let Y=console[J];if(typeof Y!=="function")Y=console.log;if(typeof Y==="function")return Y.apply(console,X)}}}for(let J=0;J<_f.length;J++)this[_f[J].n]=Q(_f[J].c)}}sX0.DiagConsoleLogger=oX0});var lf=r((QY0)=>{Object.defineProperty(QY0,"__esModule",{value:!0});QY0.createNoopMeter=QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=QY0.NOOP_OBSERVABLE_GAUGE_METRIC=QY0.NOOP_OBSERVABLE_COUNTER_METRIC=QY0.NOOP_UP_DOWN_COUNTER_METRIC=QY0.NOOP_HISTOGRAM_METRIC=QY0.NOOP_GAUGE_METRIC=QY0.NOOP_COUNTER_METRIC=QY0.NOOP_METER=QY0.NoopObservableUpDownCounterMetric=QY0.NoopObservableGaugeMetric=QY0.NoopObservableCounterMetric=QY0.NoopObservableMetric=QY0.NoopHistogramMetric=QY0.NoopGaugeMetric=QY0.NoopUpDownCounterMetric=QY0.NoopCounterMetric=QY0.NoopMetric=QY0.NoopMeter=void 0;class yf{constructor(){}createGauge(Q,J){return QY0.NOOP_GAUGE_METRIC}createHistogram(Q,J){return QY0.NOOP_HISTOGRAM_METRIC}createCounter(Q,J){return QY0.NOOP_COUNTER_METRIC}createUpDownCounter(Q,J){return QY0.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(Q,J){return QY0.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(Q,J){return QY0.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(Q,J){return QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(Q,J){}removeBatchObservableCallback(Q){}}QY0.NoopMeter=yf;class pZ{}QY0.NoopMetric=pZ;class bf extends pZ{add(Q,J){}}QY0.NoopCounterMetric=bf;class ff extends pZ{add(Q,J){}}QY0.NoopUpDownCounterMetric=ff;class hf extends pZ{record(Q,J){}}QY0.NoopGaugeMetric=hf;class gf extends pZ{record(Q,J){}}QY0.NoopHistogramMetric=gf;class Dq{addCallback(Q){}removeCallback(Q){}}QY0.NoopObservableMetric=Dq;class mf extends Dq{}QY0.NoopObservableCounterMetric=mf;class xf extends Dq{}QY0.NoopObservableGaugeMetric=xf;class uf extends Dq{}QY0.NoopObservableUpDownCounterMetric=uf;QY0.NOOP_METER=new yf;QY0.NOOP_COUNTER_METRIC=new bf;QY0.NOOP_GAUGE_METRIC=new hf;QY0.NOOP_HISTOGRAM_METRIC=new gf;QY0.NOOP_UP_DOWN_COUNTER_METRIC=new ff;QY0.NOOP_OBSERVABLE_COUNTER_METRIC=new mf;QY0.NOOP_OBSERVABLE_GAUGE_METRIC=new xf;QY0.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new uf;function Qp0(){return QY0.NOOP_METER}QY0.createNoopMeter=Qp0});var VY0=r((FY0)=>{Object.defineProperty(FY0,"__esModule",{value:!0});FY0.ValueType=void 0;var Vp0;(function(Q){Q[Q.INT=0]="INT",Q[Q.DOUBLE=1]="DOUBLE"})(Vp0=FY0.ValueType||(FY0.ValueType={}))});var pf=r((qY0)=>{Object.defineProperty(qY0,"__esModule",{value:!0});qY0.defaultTextMapSetter=qY0.defaultTextMapGetter=void 0;qY0.defaultTextMapGetter={get(Q,J){if(Q==null)return;return Q[J]},keys(Q){if(Q==null)return[];return Object.keys(Q)}};qY0.defaultTextMapSetter={set(Q,J,X){if(Q==null)return;Q[J]=X}}});var PY0=r((LY0)=>{Object.defineProperty(LY0,"__esModule",{value:!0});LY0.NoopContextManager=void 0;var Up0=Mq();class zY0{active(){return Up0.ROOT_CONTEXT}with(Q,J,X,...Y){return J.call(X,...Y)}bind(Q,J){return J}enable(){return this}disable(){return this}}LY0.NoopContextManager=zY0});var Tq=r((BY0)=>{Object.defineProperty(BY0,"__esModule",{value:!0});BY0.ContextAPI=void 0;var zp0=PY0(),cf=pG(),NY0=cG(),nf="context",Lp0=new zp0.NoopContextManager;class rf{constructor(){}static getInstance(){if(!this._instance)this._instance=new rf;return this._instance}setGlobalContextManager(Q){return(0,cf.registerGlobal)(nf,Q,NY0.DiagAPI.instance())}active(){return this._getContextManager().active()}with(Q,J,X,...Y){return this._getContextManager().with(Q,J,X,...Y)}bind(Q,J){return this._getContextManager().bind(Q,J)}_getContextManager(){return(0,cf.getGlobal)(nf)||Lp0}disable(){this._getContextManager().disable(),(0,cf.unregisterGlobal)(nf,NY0.DiagAPI.instance())}}BY0.ContextAPI=rf});var of=r((OY0)=>{Object.defineProperty(OY0,"__esModule",{value:!0});OY0.TraceFlags=void 0;var jp0;(function(Q){Q[Q.NONE=0]="NONE",Q[Q.SAMPLED=1]="SAMPLED"})(jp0=OY0.TraceFlags||(OY0.TraceFlags={}))});var GO=r((MY0)=>{Object.defineProperty(MY0,"__esModule",{value:!0});MY0.INVALID_SPAN_CONTEXT=MY0.INVALID_TRACEID=MY0.INVALID_SPANID=void 0;var Pp0=of();MY0.INVALID_SPANID="0000000000000000";MY0.INVALID_TRACEID="00000000000000000000000000000000";MY0.INVALID_SPAN_CONTEXT={traceId:MY0.INVALID_TRACEID,spanId:MY0.INVALID_SPANID,traceFlags:Pp0.TraceFlags.NONE}});var $O=r((RY0)=>{Object.defineProperty(RY0,"__esModule",{value:!0});RY0.NonRecordingSpan=void 0;var Np0=GO();class EY0{constructor(Q=Np0.INVALID_SPAN_CONTEXT){this._spanContext=Q}spanContext(){return this._spanContext}setAttribute(Q,J){return this}setAttributes(Q){return this}addEvent(Q,J){return this}addLink(Q){return this}addLinks(Q){return this}setStatus(Q){return this}updateName(Q){return this}end(Q){}isRecording(){return!1}recordException(Q,J){}}RY0.NonRecordingSpan=EY0});var ef=r((CY0)=>{Object.defineProperty(CY0,"__esModule",{value:!0});CY0.getSpanContext=CY0.setSpanContext=CY0.deleteSpan=CY0.setSpan=CY0.getActiveSpan=CY0.getSpan=void 0;var Bp0=Mq(),wp0=$O(),Op0=Tq(),sf=(0,Bp0.createContextKey)("OpenTelemetry Context Key SPAN");function tf(Q){return Q.getValue(sf)||void 0}CY0.getSpan=tf;function Mp0(){return tf(Op0.ContextAPI.getInstance().active())}CY0.getActiveSpan=Mp0;function vY0(Q,J){return Q.setValue(sf,J)}CY0.setSpan=vY0;function Dp0(Q){return Q.deleteValue(sf)}CY0.deleteSpan=Dp0;function Tp0(Q,J){return vY0(Q,new wp0.NonRecordingSpan(J))}CY0.setSpanContext=Tp0;function Ap0(Q){var J;return(J=tf(Q))===null||J===void 0?void 0:J.spanContext()}CY0.getSpanContext=Ap0});var ZO=r((bY0)=>{Object.defineProperty(bY0,"__esModule",{value:!0});bY0.wrapSpanContext=bY0.isSpanContextValid=bY0.isValidSpanId=bY0.isValidTraceId=void 0;var kY0=GO(),Ip0=$O(),kp0=/^([0-9a-f]{32})$/i,_p0=/^[0-9a-f]{16}$/i;function _Y0(Q){return kp0.test(Q)&&Q!==kY0.INVALID_TRACEID}bY0.isValidTraceId=_Y0;function yY0(Q){return _p0.test(Q)&&Q!==kY0.INVALID_SPANID}bY0.isValidSpanId=yY0;function yp0(Q){return _Y0(Q.traceId)&&yY0(Q.spanId)}bY0.isSpanContextValid=yp0;function bp0(Q){return new Ip0.NonRecordingSpan(Q)}bY0.wrapSpanContext=bp0});var Xh=r((mY0)=>{Object.defineProperty(mY0,"__esModule",{value:!0});mY0.NoopTracer=void 0;var mp0=Tq(),hY0=ef(),Qh=$O(),xp0=ZO(),Jh=mp0.ContextAPI.getInstance();class gY0{startSpan(Q,J,X=Jh.active()){if(Boolean(J===null||J===void 0?void 0:J.root))return new Qh.NonRecordingSpan;let W=X&&(0,hY0.getSpanContext)(X);if(up0(W)&&(0,xp0.isSpanContextValid)(W))return new Qh.NonRecordingSpan(W);else return new Qh.NonRecordingSpan}startActiveSpan(Q,J,X,Y){let W,G,$;if(arguments.length<2)return;else if(arguments.length===2)$=J;else if(arguments.length===3)W=J,$=X;else W=J,G=X,$=Y;let Z=G!==null&&G!==void 0?G:Jh.active(),K=this.startSpan(Q,W,Z),H=(0,hY0.setSpan)(Z,K);return Jh.with(H,$,void 0,K)}}mY0.NoopTracer=gY0;function up0(Q){return typeof Q==="object"&&typeof Q.spanId==="string"&&typeof Q.traceId==="string"&&typeof Q.traceFlags==="number"}});var Yh=r((lY0)=>{Object.defineProperty(lY0,"__esModule",{value:!0});lY0.ProxyTracer=void 0;var lp0=Xh(),dp0=new lp0.NoopTracer;class uY0{constructor(Q,J,X,Y){this._provider=Q,this.name=J,this.version=X,this.options=Y}startSpan(Q,J,X){return this._getTracer().startSpan(Q,J,X)}startActiveSpan(Q,J,X,Y){let W=this._getTracer();return Reflect.apply(W.startActiveSpan,W,arguments)}_getTracer(){if(this._delegate)return this._delegate;let Q=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!Q)return dp0;return this._delegate=Q,this._delegate}}lY0.ProxyTracer=uY0});var rY0=r((cY0)=>{Object.defineProperty(cY0,"__esModule",{value:!0});cY0.NoopTracerProvider=void 0;var pp0=Xh();class pY0{getTracer(Q,J,X){return new pp0.NoopTracer}}cY0.NoopTracerProvider=pY0});var Wh=r((aY0)=>{Object.defineProperty(aY0,"__esModule",{value:!0});aY0.ProxyTracerProvider=void 0;var cp0=Yh(),np0=rY0(),rp0=new np0.NoopTracerProvider;class iY0{getTracer(Q,J,X){var Y;return(Y=this.getDelegateTracer(Q,J,X))!==null&&Y!==void 0?Y:new cp0.ProxyTracer(this,Q,J,X)}getDelegate(){var Q;return(Q=this._delegate)!==null&&Q!==void 0?Q:rp0}setDelegate(Q){this._delegate=Q}getDelegateTracer(Q,J,X){var Y;return(Y=this._delegate)===null||Y===void 0?void 0:Y.getTracer(Q,J,X)}}aY0.ProxyTracerProvider=iY0});var tY0=r((sY0)=>{Object.defineProperty(sY0,"__esModule",{value:!0});sY0.SamplingDecision=void 0;var ip0;(function(Q){Q[Q.NOT_RECORD=0]="NOT_RECORD",Q[Q.RECORD=1]="RECORD",Q[Q.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(ip0=sY0.SamplingDecision||(sY0.SamplingDecision={}))});var Q70=r((eY0)=>{Object.defineProperty(eY0,"__esModule",{value:!0});eY0.SpanKind=void 0;var ap0;(function(Q){Q[Q.INTERNAL=0]="INTERNAL",Q[Q.SERVER=1]="SERVER",Q[Q.CLIENT=2]="CLIENT",Q[Q.PRODUCER=3]="PRODUCER",Q[Q.CONSUMER=4]="CONSUMER"})(ap0=eY0.SpanKind||(eY0.SpanKind={}))});var X70=r((J70)=>{Object.defineProperty(J70,"__esModule",{value:!0});J70.SpanStatusCode=void 0;var op0;(function(Q){Q[Q.UNSET=0]="UNSET",Q[Q.OK=1]="OK",Q[Q.ERROR=2]="ERROR"})(op0=J70.SpanStatusCode||(J70.SpanStatusCode={}))});var G70=r((Y70)=>{Object.defineProperty(Y70,"__esModule",{value:!0});Y70.validateValue=Y70.validateKey=void 0;var Kh="[_0-9a-z-*/]",sp0=`[a-z]${Kh}{0,255}`,tp0=`[a-z0-9]${Kh}{0,240}@[a-z]${Kh}{0,13}`,ep0=new RegExp(`^(?:${sp0}|${tp0})$`),Qc0=/^[ -~]{0,255}[!-~]$/,Jc0=/,|=/;function Xc0(Q){return ep0.test(Q)}Y70.validateKey=Xc0;function Yc0(Q){return Qc0.test(Q)&&!Jc0.test(Q)}Y70.validateValue=Yc0});var q70=r((F70)=>{Object.defineProperty(F70,"__esModule",{value:!0});F70.TraceStateImpl=void 0;var $70=G70(),Z70=32,Gc0=512,K70=",",H70="=";class Hh{constructor(Q){if(this._internalState=new Map,Q)this._parse(Q)}set(Q,J){let X=this._clone();if(X._internalState.has(Q))X._internalState.delete(Q);return X._internalState.set(Q,J),X}unset(Q){let J=this._clone();return J._internalState.delete(Q),J}get(Q){return this._internalState.get(Q)}serialize(){return this._keys().reduce((Q,J)=>{return Q.push(J+H70+this.get(J)),Q},[]).join(K70)}_parse(Q){if(Q.length>Gc0)return;if(this._internalState=Q.split(K70).reverse().reduce((J,X)=>{let Y=X.trim(),W=Y.indexOf(H70);if(W!==-1){let G=Y.slice(0,W),$=Y.slice(W+1,X.length);if((0,$70.validateKey)(G)&&(0,$70.validateValue)($))J.set(G,$)}return J},new Map),this._internalState.size>Z70)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Z70))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let Q=new Hh;return Q._internalState=new Map(this._internalState),Q}}F70.TraceStateImpl=Hh});var L70=r((U70)=>{Object.defineProperty(U70,"__esModule",{value:!0});U70.createTraceState=void 0;var $c0=q70();function Zc0(Q){return new $c0.TraceStateImpl(Q)}U70.createTraceState=Zc0});var N70=r((j70)=>{Object.defineProperty(j70,"__esModule",{value:!0});j70.context=void 0;var Kc0=Tq();j70.context=Kc0.ContextAPI.getInstance()});var O70=r((B70)=>{Object.defineProperty(B70,"__esModule",{value:!0});B70.diag=void 0;var Hc0=cG();B70.diag=Hc0.DiagAPI.instance()});var T70=r((M70)=>{Object.defineProperty(M70,"__esModule",{value:!0});M70.NOOP_METER_PROVIDER=M70.NoopMeterProvider=void 0;var Fc0=lf();class Fh{getMeter(Q,J,X){return Fc0.NOOP_METER}}M70.NoopMeterProvider=Fh;M70.NOOP_METER_PROVIDER=new Fh});var S70=r((E70)=>{Object.defineProperty(E70,"__esModule",{value:!0});E70.MetricsAPI=void 0;var qc0=T70(),Vh=pG(),A70=cG(),qh="metrics";class Uh{constructor(){}static getInstance(){if(!this._instance)this._instance=new Uh;return this._instance}setGlobalMeterProvider(Q){return(0,Vh.registerGlobal)(qh,Q,A70.DiagAPI.instance())}getMeterProvider(){return(0,Vh.getGlobal)(qh)||qc0.NOOP_METER_PROVIDER}getMeter(Q,J,X){return this.getMeterProvider().getMeter(Q,J,X)}disable(){(0,Vh.unregisterGlobal)(qh,A70.DiagAPI.instance())}}E70.MetricsAPI=Uh});var I70=r((v70)=>{Object.defineProperty(v70,"__esModule",{value:!0});v70.metrics=void 0;var Uc0=S70();v70.metrics=Uc0.MetricsAPI.getInstance()});var b70=r((_70)=>{Object.defineProperty(_70,"__esModule",{value:!0});_70.NoopTextMapPropagator=void 0;class k70{inject(Q,J){}extract(Q,J){return Q}fields(){return[]}}_70.NoopTextMapPropagator=k70});var m70=r((h70)=>{Object.defineProperty(h70,"__esModule",{value:!0});h70.deleteBaggage=h70.setBaggage=h70.getActiveBaggage=h70.getBaggage=void 0;var zc0=Tq(),Lc0=Mq(),zh=(0,Lc0.createContextKey)("OpenTelemetry Baggage Key");function f70(Q){return Q.getValue(zh)||void 0}h70.getBaggage=f70;function jc0(){return f70(zc0.ContextAPI.getInstance().active())}h70.getActiveBaggage=jc0;function Pc0(Q,J){return Q.setValue(zh,J)}h70.setBaggage=Pc0;function Nc0(Q){return Q.deleteValue(zh)}h70.deleteBaggage=Nc0});var p70=r((l70)=>{Object.defineProperty(l70,"__esModule",{value:!0});l70.PropagationAPI=void 0;var Lh=pG(),Mc0=b70(),x70=pf(),KO=m70(),Dc0=kf(),u70=cG(),jh="propagation",Tc0=new Mc0.NoopTextMapPropagator;class Ph{constructor(){this.createBaggage=Dc0.createBaggage,this.getBaggage=KO.getBaggage,this.getActiveBaggage=KO.getActiveBaggage,this.setBaggage=KO.setBaggage,this.deleteBaggage=KO.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Ph;return this._instance}setGlobalPropagator(Q){return(0,Lh.registerGlobal)(jh,Q,u70.DiagAPI.instance())}inject(Q,J,X=x70.defaultTextMapSetter){return this._getGlobalPropagator().inject(Q,J,X)}extract(Q,J,X=x70.defaultTextMapGetter){return this._getGlobalPropagator().extract(Q,J,X)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,Lh.unregisterGlobal)(jh,u70.DiagAPI.instance())}_getGlobalPropagator(){return(0,Lh.getGlobal)(jh)||Tc0}}l70.PropagationAPI=Ph});var r70=r((c70)=>{Object.defineProperty(c70,"__esModule",{value:!0});c70.propagation=void 0;var Ac0=p70();c70.propagation=Ac0.PropagationAPI.getInstance()});var e70=r((s70)=>{Object.defineProperty(s70,"__esModule",{value:!0});s70.TraceAPI=void 0;var Nh=pG(),i70=Wh(),a70=ZO(),cZ=ef(),o70=cG(),Bh="trace";class wh{constructor(){this._proxyTracerProvider=new i70.ProxyTracerProvider,this.wrapSpanContext=a70.wrapSpanContext,this.isSpanContextValid=a70.isSpanContextValid,this.deleteSpan=cZ.deleteSpan,this.getSpan=cZ.getSpan,this.getActiveSpan=cZ.getActiveSpan,this.getSpanContext=cZ.getSpanContext,this.setSpan=cZ.setSpan,this.setSpanContext=cZ.setSpanContext}static getInstance(){if(!this._instance)this._instance=new wh;return this._instance}setGlobalTracerProvider(Q){let J=(0,Nh.registerGlobal)(Bh,this._proxyTracerProvider,o70.DiagAPI.instance());if(J)this._proxyTracerProvider.setDelegate(Q);return J}getTracerProvider(){return(0,Nh.getGlobal)(Bh)||this._proxyTracerProvider}getTracer(Q,J){return this.getTracerProvider().getTracer(Q,J)}disable(){(0,Nh.unregisterGlobal)(Bh,o70.DiagAPI.instance()),this._proxyTracerProvider=new i70.ProxyTracerProvider}}s70.TraceAPI=wh});var XW0=r((QW0)=>{Object.defineProperty(QW0,"__esModule",{value:!0});QW0.trace=void 0;var Ec0=e70();QW0.trace=Ec0.TraceAPI.getInstance()});var FW0=r((Z8)=>{Object.defineProperty(Z8,"__esModule",{value:!0});Z8.trace=Z8.propagation=Z8.metrics=Z8.diag=Z8.context=Z8.INVALID_SPAN_CONTEXT=Z8.INVALID_TRACEID=Z8.INVALID_SPANID=Z8.isValidSpanId=Z8.isValidTraceId=Z8.isSpanContextValid=Z8.createTraceState=Z8.TraceFlags=Z8.SpanStatusCode=Z8.SpanKind=Z8.SamplingDecision=Z8.ProxyTracerProvider=Z8.ProxyTracer=Z8.defaultTextMapSetter=Z8.defaultTextMapGetter=Z8.ValueType=Z8.createNoopMeter=Z8.DiagLogLevel=Z8.DiagConsoleLogger=Z8.ROOT_CONTEXT=Z8.createContextKey=Z8.baggageEntryMetadataFromString=void 0;var Rc0=kf();Object.defineProperty(Z8,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return Rc0.baggageEntryMetadataFromString}});var YW0=Mq();Object.defineProperty(Z8,"createContextKey",{enumerable:!0,get:function(){return YW0.createContextKey}});Object.defineProperty(Z8,"ROOT_CONTEXT",{enumerable:!0,get:function(){return YW0.ROOT_CONTEXT}});var Sc0=eX0();Object.defineProperty(Z8,"DiagConsoleLogger",{enumerable:!0,get:function(){return Sc0.DiagConsoleLogger}});var vc0=XO();Object.defineProperty(Z8,"DiagLogLevel",{enumerable:!0,get:function(){return vc0.DiagLogLevel}});var Cc0=lf();Object.defineProperty(Z8,"createNoopMeter",{enumerable:!0,get:function(){return Cc0.createNoopMeter}});var Ic0=VY0();Object.defineProperty(Z8,"ValueType",{enumerable:!0,get:function(){return Ic0.ValueType}});var WW0=pf();Object.defineProperty(Z8,"defaultTextMapGetter",{enumerable:!0,get:function(){return WW0.defaultTextMapGetter}});Object.defineProperty(Z8,"defaultTextMapSetter",{enumerable:!0,get:function(){return WW0.defaultTextMapSetter}});var kc0=Yh();Object.defineProperty(Z8,"ProxyTracer",{enumerable:!0,get:function(){return kc0.ProxyTracer}});var _c0=Wh();Object.defineProperty(Z8,"ProxyTracerProvider",{enumerable:!0,get:function(){return _c0.ProxyTracerProvider}});var yc0=tY0();Object.defineProperty(Z8,"SamplingDecision",{enumerable:!0,get:function(){return yc0.SamplingDecision}});var bc0=Q70();Object.defineProperty(Z8,"SpanKind",{enumerable:!0,get:function(){return bc0.SpanKind}});var fc0=X70();Object.defineProperty(Z8,"SpanStatusCode",{enumerable:!0,get:function(){return fc0.SpanStatusCode}});var hc0=of();Object.defineProperty(Z8,"TraceFlags",{enumerable:!0,get:function(){return hc0.TraceFlags}});var gc0=L70();Object.defineProperty(Z8,"createTraceState",{enumerable:!0,get:function(){return gc0.createTraceState}});var Oh=ZO();Object.defineProperty(Z8,"isSpanContextValid",{enumerable:!0,get:function(){return Oh.isSpanContextValid}});Object.defineProperty(Z8,"isValidTraceId",{enumerable:!0,get:function(){return Oh.isValidTraceId}});Object.defineProperty(Z8,"isValidSpanId",{enumerable:!0,get:function(){return Oh.isValidSpanId}});var Mh=GO();Object.defineProperty(Z8,"INVALID_SPANID",{enumerable:!0,get:function(){return Mh.INVALID_SPANID}});Object.defineProperty(Z8,"INVALID_TRACEID",{enumerable:!0,get:function(){return Mh.INVALID_TRACEID}});Object.defineProperty(Z8,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Mh.INVALID_SPAN_CONTEXT}});var GW0=N70();Object.defineProperty(Z8,"context",{enumerable:!0,get:function(){return GW0.context}});var $W0=O70();Object.defineProperty(Z8,"diag",{enumerable:!0,get:function(){return $W0.diag}});var ZW0=I70();Object.defineProperty(Z8,"metrics",{enumerable:!0,get:function(){return ZW0.metrics}});var KW0=r70();Object.defineProperty(Z8,"propagation",{enumerable:!0,get:function(){return KW0.propagation}});var HW0=XW0();Object.defineProperty(Z8,"trace",{enumerable:!0,get:function(){return HW0.trace}});Z8.default={context:GW0.context,diag:$W0.diag,metrics:ZW0.metrics,propagation:KW0.propagation,trace:HW0.trace}});function $1(Q){return{...Q,execute:async(J,X)=>{let Y=Date.now();return await X.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":X.organization?.id??"system","user.id":X.auth.user?.id??X.auth.apiKey?.userId??"anonymous"}},async(W)=>{try{X.toolName=Q.name,X.access.setToolName?.(Q.name);let G=await Q.handler(J,X),$=Date.now()-Y;return X.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record($,{"tool.name":Q.name,"organization.id":X.organization?.id??"system",status:"success"}),X.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),W.setStatus({code:Dh.SpanStatusCode.OK}),G}catch(G){throw X.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":G.constructor.name}),W.setStatus({code:Dh.SpanStatusCode.ERROR,message:G.message}),W.recordException(G),G}finally{W.end()}})}}}var Dh;var K4=p(()=>{Dh=R5(FW0(),1)});function s1(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function M5(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function uc0(Q){return!!(Q.auth.user||Q.auth.apiKey)}function N1(Q){if(!uc0(Q))throw Error("Authentication required")}var HO,VW0,qW0,UW0,zW0,LW0,jW0,PW0,NW0,BW0;var nZ=p(()=>{o1();HO=N.record(N.array(N.string())),VW0=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),userId:N.string().describe("ID of the user who owns this API key"),permissions:HO.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),qW0=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:HO.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:N.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:N.record(N.unknown()).optional().describe("Additional metadata to store with the API key")}),UW0=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),key:N.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:HO.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:N.union([N.string(),N.date()]).nullable().optional().describe("Expiration date of the API key"),createdAt:N.union([N.string(),N.date()]).describe("When the API key was created")}),zW0=N.object({}),LW0=N.object({items:N.array(VW0).describe("List of API keys (without key values)")}),jW0=N.object({keyId:N.string().describe("ID of the API key to update"),name:N.string().min(1).max(64).optional().describe("New name for the API key"),permissions:HO.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:N.record(N.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),PW0=N.object({item:VW0.describe("The updated API key (without key value)")}),NW0=N.object({keyId:N.string().describe("ID of the API key to delete")}),BW0=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var Th;var wW0=p(()=>{K4();nZ();Th=$1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:qW0,outputSchema:UW0,handler:async(Q,J)=>{N1(J),await J.access.check();let X=await J.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:J.organization}});return{id:X.id,name:X.name??Q.name,key:X.key,permissions:X.permissions??{},expiresAt:X.expiresAt??null,createdAt:X.createdAt}}})});var Ah;var OW0=p(()=>{K4();nZ();Ah=$1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:NW0,outputSchema:BW0,handler:async(Q,J)=>{if(N1(J),await J.access.check(),!M5(J))throw Error("User ID required to delete API key");let W=(await J.boundAuth.apiKey.list())?.find((K)=>K.id===Q.keyId);if(!W)throw Error("API key not found");let $=W.metadata?.organization?.id,Z=J.organization?.id;if($!==Z)throw Error("Cannot delete API key from another organization");return await J.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var Eh;var MW0=p(()=>{K4();nZ();Eh=$1({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:zW0,outputSchema:LW0,handler:async(Q,J)=>{N1(J),await J.access.check();let X=await J.boundAuth.apiKey.list(),Y=J.organization?.id;return{items:(X??[]).filter((G)=>{return G.metadata?.organization?.id===Y}).map((G)=>({id:G.id,name:G.name??"Unnamed Key",userId:G.userId,permissions:G.permissions??{},expiresAt:G.expiresAt??null,createdAt:G.createdAt}))}}})});var Rh;var DW0=p(()=>{K4();nZ();Rh=$1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:jW0,outputSchema:PW0,handler:async(Q,J)=>{if(N1(J),await J.access.check(),!M5(J))throw Error("User ID required to update API key");let W=(await J.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!W)throw Error(`API key not found: ${Q.keyId}`);let $=W.metadata?.organization?.id,Z=J.organization?.id;if($!==Z)throw Error("Cannot update API key from another organization");let K=await J.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:J.organization}});if(!K)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:K.id,name:K.name??Q.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt??null,createdAt:K.createdAt}}}})});var TW0=p(()=>{wW0();OW0();MW0();DW0();nZ()});var dc0,pc0,gQ,AW0,EW0;var rZ=p(()=>{o1();dc0=N.object({authorizationEndpoint:N.string().url(),tokenEndpoint:N.string().url(),introspectionEndpoint:N.string().url().optional(),clientId:N.string(),clientSecret:N.string().optional(),scopes:N.array(N.string()),grantType:N.enum(["authorization_code","client_credentials"])}),pc0=N.object({name:N.string(),description:N.string().optional(),inputSchema:N.record(N.unknown()),outputSchema:N.record(N.unknown()).optional()}),gQ=N.object({id:N.string().describe("Unique identifier for the connection"),title:N.string().describe("Human-readable name for the connection"),created_at:N.string().describe("When the connection was created"),updated_at:N.string().describe("When the connection was last updated"),created_by:N.string().describe("User ID who created the connection"),updated_by:N.string().optional().describe("User ID who last updated the connection"),organization_id:N.string().describe("Organization ID this connection belongs to"),description:N.string().nullable().describe("Description of the connection"),icon:N.string().nullable().describe("Icon URL for the connection"),app_name:N.string().nullable().describe("Associated app name"),app_id:N.string().nullable().describe("Associated app ID"),connection_type:N.enum(["HTTP","SSE","Websocket"]).describe("Type of connection"),connection_url:N.string().describe("URL for the connection"),connection_token:N.string().nullable().describe("Authentication token"),connection_headers:N.record(N.string(),N.string()).nullable().describe("Custom headers"),oauth_config:dc0.nullable().describe("OAuth configuration"),configuration_state:N.record(N.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:N.array(N.string()).nullable().optional().describe("Configuration scopes"),metadata:N.record(N.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:N.array(pc0).nullable().describe("Discovered tools from MCP"),bindings:N.array(N.string()).nullable().describe("Detected bindings"),status:N.enum(["active","inactive","error"]).describe("Current status")}),AW0=gQ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}),EW0=gQ.partial()});var cc0,nc0,Sh;var RW0=p(()=>{uV();o1();K4();Bw();rZ();cc0=N.object({data:AW0.describe("Data for the new connection (id is auto-generated if not provided)")}),nc0=N.object({item:gQ.describe("The created connection entity")}),Sh=$1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:cc0,outputSchema:nc0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=M5(J);if(!Y)throw Error("User ID required to create connection");let W={...Q.data,organization_id:X.id,created_by:Y},G=await IZ({id:"pending",title:W.title,connection_url:W.connection_url,connection_token:W.connection_token,connection_headers:W.connection_headers}).catch(()=>null),$=G?.length?G:null,Z=await J.storage.connections.create({...W,tools:$});return await J.eventBus.publish(X.id,FZ.SELF(X.id),{type:"connection.created",data:Z}),{item:Z}}})});function m7(Q){function J(X,Y){if(Y.description)X=X.describe(Y.description);return X}if(Q.const!==void 0){if(typeof Q.const==="string")return J(N.literal(Q.const),Q);else if(typeof Q.const==="number")return J(N.literal(Q.const),Q);else if(typeof Q.const==="boolean")return J(N.literal(Q.const),Q);else if(Q.const===null)return J(N.null(),Q);return J(N.literal(Q.const),Q)}if(Q.type)switch(Q.type){case"string":{if(Q.enum){if(Q.enum.length===0)return J(N.string(),Q);return J(N.enum(Q.enum),Q)}let X=N.string();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.pattern!==void 0){let Y=new RegExp(Q.pattern);X=X.regex(Y)}return J(X,Q)}case"number":case"integer":{if(Q.enum){if(Q.enum.length===0)return J(N.number(),Q);let Y=Q.enum.map((W)=>N.literal(W));if(Y.length===1)return J(Y[0],Q);if(Y.length>=2){let W=N.union([Y[0],Y[1],...Y.slice(2)]);return J(W,Q)}}let X=Q.type==="integer"?N.number().int():N.number();if(Q.minimum!==void 0)X=X.min(Q.minimum);if(Q.maximum!==void 0)X=X.max(Q.maximum);if(Q.exclusiveMinimum!==void 0)X=X.gt(Q.exclusiveMinimum);if(Q.exclusiveMaximum!==void 0)X=X.lt(Q.exclusiveMaximum);if(Q.multipleOf!==void 0)X=X.multipleOf(Q.multipleOf);return J(X,Q)}case"boolean":if(Q.enum){if(Q.enum.length===0)return J(N.boolean(),Q);let X=Q.enum.map((Y)=>N.literal(Y));if(X.length===1)return J(X[0],Q);if(X.length>=2){let Y=N.union([X[0],X[1],...X.slice(2)]);return J(Y,Q)}}return J(N.boolean(),Q);case"null":return J(N.null(),Q);case"object":if(Q.properties){let X={};for(let[W,G]of Object.entries(Q.properties))X[W]=m7(G);if(Q.required&&Array.isArray(Q.required)){let W=new Set(Q.required);for(let G of Object.keys(X))if(!W.has(G))X[G]=X[G].optional()}else for(let W of Object.keys(X))X[W]=X[W].optional();let Y;if(Q.additionalProperties!==!1)Y=N.object(X).passthrough();else Y=N.object(X);return J(Y,Q)}return J(N.object({}),Q);case"array":{let X;if(Q.items)X=N.array(m7(Q.items));else X=N.array(N.any());if(Q.minItems!==void 0)X=X.min(Q.minItems);if(Q.maxItems!==void 0)X=X.max(Q.maxItems);if(Q.uniqueItems===!0)X=X.refine((Y)=>{let W=new Set;return Y.every((G)=>{if(typeof G==="string"||typeof G==="number"||typeof G==="boolean"){if(W.has(G))return!1;return W.add(G),!0}let $=JSON.stringify(G);if(W.has($))return!1;return W.add($),!0})},{message:"Array items must be unique"});return J(X,Q)}}if(Q.enum){if(Q.enum.length===0)return J(N.never(),Q);if(Q.enum.every((Y)=>typeof Y==="string"))return J(N.enum(Q.enum),Q);else{let Y=Q.enum.map((W)=>N.literal(W));if(Y.length===1)return J(Y[0],Q);if(Y.length>=2){let W=N.union([Y[0],Y[1],...Y.slice(2)]);return J(W,Q)}}}if(Q.anyOf&&Q.anyOf.length>=2){let X=Q.anyOf.map(m7);return J(N.union([X[0],X[1],...X.slice(2)]),Q)}if(Q.allOf)return J(Q.allOf.reduce((X,Y)=>N.intersection(X,m7(Y)),N.object({})),Q);if(Q.oneOf&&Q.oneOf.length>=2){let X=Q.oneOf.map(m7);return J(N.union([X[0],X[1],...X.slice(2)]),Q)}return J(N.any(),Q)}var SW0=p(()=>{o1()});function rc0(Q){let J=globalThis.DOMException;return typeof J=="function"?new J(Q,"SyntaxError"):SyntaxError(Q)}function Ch(Q){return Q instanceof Error?"errors"in Q&&Array.isArray(Q.errors)?Q.errors.map(Ch).join(", "):("cause"in Q)&&Q.cause instanceof Error?`${Q}: ${Ch(Q.cause)}`:Q.message:`${Q}`}function vW0(Q){return{type:Q.type,message:Q.message,code:Q.code,defaultPrevented:Q.defaultPrevented,cancelable:Q.cancelable,timeStamp:Q.timeStamp}}function ic0(){let Q="document"in globalThis?globalThis.document:void 0;return Q&&typeof Q=="object"&&"baseURI"in Q&&typeof Q.baseURI=="string"?Q.baseURI:void 0}var vh,IW0=(Q)=>{throw TypeError(Q)},gh=(Q,J,X)=>J.has(Q)||IW0("Cannot "+X),H4=(Q,J,X)=>(gh(Q,J,"read from private field"),X?X.call(Q):J.get(Q)),C6=(Q,J,X)=>J.has(Q)?IW0("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(Q):J.set(Q,X),c8=(Q,J,X,Y)=>(gh(Q,J,"write to private field"),J.set(Q,X),X),KY=(Q,J,X)=>(gh(Q,J,"access private method"),X),D5,nG,iZ,FO,VO,Rq,sZ,Sq,x7,aZ,tZ,oZ,Aq,zJ,Ih,kh,_h,CW0,yh,bh,Eq,fh,hh,eZ;var kW0=p(()=>{uy();vh=class vh extends Event{constructor(Q,J){var X,Y;super(Q),this.code=(X=J==null?void 0:J.code)!=null?X:void 0,this.message=(Y=J==null?void 0:J.message)!=null?Y:void 0}[Symbol.for("nodejs.util.inspect.custom")](Q,J,X){return X(vW0(this),J)}[Symbol.for("Deno.customInspect")](Q,J){return Q(vW0(this),J)}};eZ=class eZ extends EventTarget{constructor(Q,J){var X,Y;super(),C6(this,zJ),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,C6(this,D5),C6(this,nG),C6(this,iZ),C6(this,FO),C6(this,VO),C6(this,Rq),C6(this,sZ),C6(this,Sq,null),C6(this,x7),C6(this,aZ),C6(this,tZ,null),C6(this,oZ,null),C6(this,Aq,null),C6(this,kh,async(W)=>{var G;H4(this,aZ).reset();let{body:$,redirected:Z,status:K,headers:H}=W;if(K===204){KY(this,zJ,Eq).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Z?c8(this,iZ,new URL(W.url)):c8(this,iZ,void 0),K!==200){KY(this,zJ,Eq).call(this,`Non-200 status code (${K})`,K);return}if(!(H.get("content-type")||"").startsWith("text/event-stream")){KY(this,zJ,Eq).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(H4(this,D5)===this.CLOSED)return;c8(this,D5,this.OPEN);let F=new Event("open");if((G=H4(this,Aq))==null||G.call(this,F),this.dispatchEvent(F),typeof $!="object"||!$||!("getReader"in $)){KY(this,zJ,Eq).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let V=new TextDecoder,q=$.getReader(),z=!0;do{let{done:j,value:P}=await q.read();P&&H4(this,aZ).feed(V.decode(P,{stream:!j})),j&&(z=!1,H4(this,aZ).reset(),KY(this,zJ,fh).call(this))}while(z)}),C6(this,_h,(W)=>{c8(this,x7,void 0),!(W.name==="AbortError"||W.type==="aborted")&&KY(this,zJ,fh).call(this,Ch(W))}),C6(this,yh,(W)=>{typeof W.id=="string"&&c8(this,Sq,W.id);let G=new MessageEvent(W.event||"message",{data:W.data,origin:H4(this,iZ)?H4(this,iZ).origin:H4(this,nG).origin,lastEventId:W.id||""});H4(this,oZ)&&(!W.event||W.event==="message")&&H4(this,oZ).call(this,G),this.dispatchEvent(G)}),C6(this,bh,(W)=>{c8(this,Rq,W)}),C6(this,hh,()=>{c8(this,sZ,void 0),H4(this,D5)===this.CONNECTING&&KY(this,zJ,Ih).call(this)});try{if(Q instanceof URL)c8(this,nG,Q);else if(typeof Q=="string")c8(this,nG,new URL(Q,ic0()));else throw Error("Invalid URL")}catch{throw rc0("An invalid or illegal string was specified")}c8(this,aZ,Nw({onEvent:H4(this,yh),onRetry:H4(this,bh)})),c8(this,D5,this.CONNECTING),c8(this,Rq,3000),c8(this,VO,(X=J==null?void 0:J.fetch)!=null?X:globalThis.fetch),c8(this,FO,(Y=J==null?void 0:J.withCredentials)!=null?Y:!1),KY(this,zJ,Ih).call(this)}get readyState(){return H4(this,D5)}get url(){return H4(this,nG).href}get withCredentials(){return H4(this,FO)}get onerror(){return H4(this,tZ)}set onerror(Q){c8(this,tZ,Q)}get onmessage(){return H4(this,oZ)}set onmessage(Q){c8(this,oZ,Q)}get onopen(){return H4(this,Aq)}set onopen(Q){c8(this,Aq,Q)}addEventListener(Q,J,X){let Y=J;super.addEventListener(Q,Y,X)}removeEventListener(Q,J,X){let Y=J;super.removeEventListener(Q,Y,X)}close(){H4(this,sZ)&&clearTimeout(H4(this,sZ)),H4(this,D5)!==this.CLOSED&&(H4(this,x7)&&H4(this,x7).abort(),c8(this,D5,this.CLOSED),c8(this,x7,void 0))}};D5=new WeakMap,nG=new WeakMap,iZ=new WeakMap,FO=new WeakMap,VO=new WeakMap,Rq=new WeakMap,sZ=new WeakMap,Sq=new WeakMap,x7=new WeakMap,aZ=new WeakMap,tZ=new WeakMap,oZ=new WeakMap,Aq=new WeakMap,zJ=new WeakSet,Ih=function(){c8(this,D5,this.CONNECTING),c8(this,x7,new AbortController),H4(this,VO)(H4(this,nG),KY(this,zJ,CW0).call(this)).then(H4(this,kh)).catch(H4(this,_h))},kh=new WeakMap,_h=new WeakMap,CW0=function(){var Q;let J={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...H4(this,Sq)?{"Last-Event-ID":H4(this,Sq)}:void 0},cache:"no-store",signal:(Q=H4(this,x7))==null?void 0:Q.signal};return"window"in globalThis&&(J.credentials=this.withCredentials?"include":"same-origin"),J},yh=new WeakMap,bh=new WeakMap,Eq=function(Q,J){var X;H4(this,D5)!==this.CLOSED&&c8(this,D5,this.CLOSED);let Y=new vh("error",{code:J,message:Q});(X=H4(this,tZ))==null||X.call(this,Y),this.dispatchEvent(Y)},fh=function(Q,J){var X;if(H4(this,D5)===this.CLOSED)return;c8(this,D5,this.CONNECTING);let Y=new vh("error",{code:J,message:Q});(X=H4(this,tZ))==null||X.call(this,Y),this.dispatchEvent(Y),c8(this,sZ,setTimeout(H4(this,hh),H4(this,Rq)))},hh=new WeakMap,eZ.CONNECTING=0,eZ.OPEN=1,eZ.CLOSED=2});class mh{constructor(Q,J){this._url=Q,this._resourceMetadataUrl=void 0,this._eventSourceInit=J===null||J===void 0?void 0:J.eventSourceInit,this._requestInit=J===null||J===void 0?void 0:J.requestInit,this._authProvider=J===null||J===void 0?void 0:J.authProvider,this._fetch=J===null||J===void 0?void 0:J.fetch}async _authThenStart(){var Q;if(!this._authProvider)throw new o5("No auth provider");let J;try{J=await k7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(X){throw(Q=this.onerror)===null||Q===void 0||Q.call(this,X),X}if(J!=="AUTHORIZED")throw new o5;return await this._startOrAuth()}async _commonHeaders(){var Q;let J={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)J.Authorization=`Bearer ${X.access_token}`}if(this._protocolVersion)J["mcp-protocol-version"]=this._protocolVersion;return new Headers({...J,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers})}_startOrAuth(){var Q,J,X;let Y=(X=(J=(Q=this===null||this===void 0?void 0:this._eventSourceInit)===null||Q===void 0?void 0:Q.fetch)!==null&&J!==void 0?J:this._fetch)!==null&&X!==void 0?X:fetch;return new Promise((W,G)=>{this._eventSource=new eZ(this._url.href,{...this._eventSourceInit,fetch:async($,Z)=>{let K=await this._commonHeaders();K.set("Accept","text/event-stream");let H=await Y($,{...Z,headers:K});if(H.status===401&&H.headers.has("www-authenticate"))this._resourceMetadataUrl=Gq(H);return H}}),this._abortController=new AbortController,this._eventSource.onerror=($)=>{var Z;if($.code===401&&this._authProvider){this._authThenStart().then(W,G);return}let K=new _W0($.code,$.message,$);G(K),(Z=this.onerror)===null||Z===void 0||Z.call(this,K)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",($)=>{var Z;let K=$;try{if(this._endpoint=new URL(K.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(H){G(H),(Z=this.onerror)===null||Z===void 0||Z.call(this,H),this.close();return}W()}),this._eventSource.onmessage=($)=>{var Z,K;let H=$,F;try{F=HJ.parse(JSON.parse(H.data))}catch(V){(Z=this.onerror)===null||Z===void 0||Z.call(this,V);return}(K=this.onmessage)===null||K===void 0||K.call(this,F)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(Q){if(!this._authProvider)throw new o5("No auth provider");if(await k7(this._authProvider,{serverUrl:this._url,authorizationCode:Q,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new o5("Failed to authorize")}async close(){var Q,J,X;(Q=this._abortController)===null||Q===void 0||Q.abort(),(J=this._eventSource)===null||J===void 0||J.close(),(X=this.onclose)===null||X===void 0||X.call(this)}async send(Q){var J,X,Y;if(!this._endpoint)throw Error("Not connected");try{let W=await this._commonHeaders();W.set("content-type","application/json");let G={...this._requestInit,method:"POST",headers:W,body:JSON.stringify(Q),signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},$=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._endpoint,G);if(!$.ok){if($.status===401&&this._authProvider){if(this._resourceMetadataUrl=Gq($),await k7(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new o5;return this.send(Q)}let Z=await $.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${$.status}): ${Z}`)}}catch(W){throw(Y=this.onerror)===null||Y===void 0||Y.call(this,W),W}}setProtocolVersion(Q){this._protocolVersion=Q}}var _W0;var yW0=p(()=>{kW0();FJ();gy();_W0=class _W0 extends Error{constructor(Q,J,X){super(`SSE error: ${J}`);this.code=Q,this.event=X}}});class xh{constructor(Q){this._url=Q}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,J)=>{this._socket=new WebSocket(this._url,ac0),this._socket.onerror=(X)=>{var Y;let W="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);J(W),(Y=this.onerror)===null||Y===void 0||Y.call(this,W)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{var X;(X=this.onclose)===null||X===void 0||X.call(this)},this._socket.onmessage=(X)=>{var Y,W;let G;try{G=HJ.parse(JSON.parse(X.data))}catch($){(Y=this.onerror)===null||Y===void 0||Y.call(this,$);return}(W=this.onmessage)===null||W===void 0||W.call(this,G)}})}async close(){var Q;(Q=this._socket)===null||Q===void 0||Q.close()}send(Q){return new Promise((J,X)=>{var Y;if(!this._socket){X(Error("Not connected"));return}(Y=this._socket)===null||Y===void 0||Y.send(JSON.stringify(Q)),J()})}}var ac0="mcp";var bW0=p(()=>{FJ()});function oc0(Q){let J=Q;if(!J||typeof J!=="object"||!("method"in J))return null;switch(J.method){case"initialize":{let X=J?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:J.jsonrpc??"2.0",id:J.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var uh;var fW0=p(()=>{dy();uh=class uh extends Zq{constructor(Q,J){super(Q,J)}send(Q,J){let X=oc0(Q);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Q,J)}}});var hW0,gW0=async(Q,J,X)=>{let Y=sc0(Q.connection,J,X);if(!Y)throw Error("Unknown MCP connection type");let W=new hW0({name:Q?.name??"MCP Client",version:"1.0.0"});return await W.connect(Y),{client:W,callStreamableTool:(G,$)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let Z=new Headers(X);if(!Z.has("Authorization"))Z.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,V]of Object.entries(Q.connection.headers??{}))Z.set(F,V);let K=new URL(Q.connection.url),H=K.pathname.replace(/\/+$/,"")||"/";return K.pathname=`${H}/call-tool/${encodeURIComponent(G)}`,fetch(K.href,{method:"POST",redirect:"manual",body:JSON.stringify($),headers:Z})}}},sc0=(Q,J,X)=>{if(Q.type==="Websocket")return new xh(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let W={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...X??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let G={requestInit:{headers:W,signal:J}};if(Q.token)G.eventSourceInit={fetch:($,Z)=>{return fetch($,{...Z,headers:{...W,Accept:"text/event-stream"},signal:J})}};return new mh(new URL(Q.url),G)}return new uh(new URL(Q.url),{requestInit:{headers:W,signal:J,credentials:"include"}})};var mW0=p(()=>{Ry();yW0();bW0();FJ();fW0();hW0=class hW0 extends Wq{constructor(Q,J){super(Q,J)}async listTools(Q,J){return await this.request({method:"tools/list",params:Q},Qq,J)}}});function uW0(Q){let J=(X)=>{if("connection"in Q)return gW0({connection:Q.connection},void 0,X);return Q.client};return new Proxy({},{get(X,Y){if(Y==="toJSON")return null;if(typeof Y!=="string")throw Error("Name must be a string");if(Y==="listTools")return Z;async function W(K,H=Y){let F=Q?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await J(V);if(Q?.streamable?.[String(H)])return z(String(H),K);let{structuredContent:j,isError:P,content:B}=await q.callTool({name:String(H),arguments:K});if(P){let w=B?.[0]?.text,T=typeof w==="string"?tc0(w):null,E=T?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(T.code,T.message,T.traceId):null;if(E)throw E;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(j??B)}`)}return j}async function G(){let{client:K}=await J(),{tools:H}=await K.listTools();return H}async function $(){if(!("connection"in Q))return G();let K=Q.connection,H=JSON.stringify(K);try{if(!qO.has(H))qO.set(H,G());return await qO.get(H)}catch(F){console.error("Failed to list tools",F),qO.delete(H);return}}async function Z(){return(await $()??[]).map((H)=>xW0(H,W))}return W.asTool=async()=>{let H=(await $()??[]).find((F)=>F.name===Y);if(!H)throw Error(`Tool ${Y} not found`);return xW0(H,W)},W}})}var tc0=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},qO,xW0=(Q,J)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?m7(Q.inputSchema):void 0,outputSchema:Q.outputSchema?m7(Q.outputSchema):void 0,execute:(X)=>{return J(X.context,Q.name)}}};var lW0=p(()=>{SW0();mW0();qO=new Map});function UO(Q){return uW0(Q)}var JS1;var dW0=p(()=>{lW0();JS1=new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(J==="forConnection")return(X)=>UO({connection:X});return global[J]}})});function zO(Q){return{isImplementedBy:(J)=>{for(let X of Q){let Y=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,W=J.find((G)=>Y.test(G.name));if(!W&&X.opt)continue;if(!W)return!1}return!0}}}var QK=(Q)=>{return{...zO(Q),forClient:(J)=>{return UO({client:J,streamable:Q.reduce((X,Y)=>{return X[Y.name]=Y.streamable===!0,X},{})})},forConnection:(J)=>{return UO({connection:J,streamable:Q.reduce((X,Y)=>{return X[Y.name]=Y.streamable===!0,X},{})})}}};var vq=p(()=>{dW0()});function Iq(Q){return N.object({items:N.array(Q).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function dh(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function Jn0(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function Xn0(Q){return N.object({item:Q.describe("The created entity with generated id")})}function Yn0(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function Wn0(Q){return N.object({item:Q.describe("The updated entity")})}function ch(Q){return N.object({item:Q.describe("The deleted entity")})}function XK(Q,J,X){let Y=Q.toUpperCase(),W=X?.readOnly??!1,G=[{name:`COLLECTION_${Y}_LIST`,inputSchema:Cq,outputSchema:Iq(J)},{name:`COLLECTION_${Y}_GET`,inputSchema:lh,outputSchema:dh(J)}];if(!W)G.push({name:`COLLECTION_${Y}_CREATE`,inputSchema:Jn0(J),outputSchema:Xn0(J),opt:!0},{name:`COLLECTION_${Y}_UPDATE`,inputSchema:Yn0(J),outputSchema:Wn0(J),opt:!0},{name:`COLLECTION_${Y}_DELETE`,inputSchema:ph,outputSchema:ch(J),opt:!0});return G}var JK,ec0,pW0,Qn0,Cq,lh,ph;var u7=p(()=>{o1();JK=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),ec0=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),pW0=N.lazy(()=>N.union([ec0,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(pW0)})])),Qn0=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),Cq=N.object({where:pW0.optional().describe("Filter expression"),orderBy:N.array(Qn0).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});lh=N.object({id:N.string().describe("ID of the entity to retrieve")});ph=N.object({id:N.string().describe("ID of the entity to delete")})});var Gn0,cW0,FS1;var nW0=p(()=>{o1();u7();Gn0=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.unknown()),outputSchema:N.record(N.unknown()).optional()}),cW0=JK.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Gn0).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),FS1=XK("registry_app",cW0,{readOnly:!0})});var rW0,iW0,aW0,oW0,sW0,$n0;var tW0=p(()=>{o1();vq();rW0=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),iW0=N.object({events:N.array(rW0).min(1).describe("Batch of CloudEvents to process")}),aW0=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),oW0=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),aW0).optional().describe("Per-event results keyed by event ID")}),sW0=[{name:"ON_EVENTS",inputSchema:iW0,outputSchema:oW0}],$n0=QK(sW0)});var kq,_q,yq,bq,eW0,QG0,fq,hq,gq,mq,xq,uq,lq,dq,JG0,Zn0;var XG0=p(()=>{o1();vq();kq=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),_q=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),yq=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),bq=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")})}),eW0=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),QG0=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),fq=N.object({subscriptions:N.array(eW0).describe("Desired subscriptions - system will create/update/delete to match")}),hq=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(QG0).describe("Current subscriptions after sync")}),gq=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),mq=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),xq=N.object({eventId:N.string().describe("Event ID to cancel")}),uq=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),lq=N.object({eventId:N.string().describe("Event ID to acknowledge")}),dq=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),JG0=[{name:"EVENT_PUBLISH",inputSchema:kq,outputSchema:_q},{name:"EVENT_SUBSCRIBE",inputSchema:yq,outputSchema:bq},{name:"EVENT_UNSUBSCRIBE",inputSchema:gq,outputSchema:mq},{name:"EVENT_CANCEL",inputSchema:xq,outputSchema:uq},{name:"EVENT_ACK",inputSchema:lq,outputSchema:dq},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:fq,outputSchema:hq}],Zn0=QK(JG0)});var nh=p(()=>{vq();nW0();tW0();XG0()});var Kn0,Hn0,YG0;var WG0=p(()=>{o1();u7();Kn0=JK.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),gateway_id:N.string().describe("Gateway ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Hn0=XK("assistant",Kn0),YG0=[...Hn0]});var pq,HY,$G0,Fn0,ZG0,Vn0,qn0,Un0,KG0,zn0,Ln0,jn0,Pn0,Nn0,Bn0,wn0,On0,CS1,Mn0,IS1,GG0,Dn0,Tn0,rh,kS1;var HG0=p(()=>{o1();vq();u7();pq=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),pq),N.array(pq)])),HY=N.record(N.string(),N.record(N.string(),pq)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),$G0=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:HY}),Fn0=N.union([N.string(),N.instanceof(Uint8Array)]).describe("File data as base64 encoded string, URL string, or Uint8Array"),ZG0=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:Fn0,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HY}),Vn0=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:HY}),qn0=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.unknown().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HY}),Un0=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:pq}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:pq}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),KG0=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:Un0.describe("Result of the tool call"),providerOptions:HY}),zn0=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:HY}),Ln0=N.object({role:N.literal("user"),content:N.array(N.union([$G0,ZG0])).describe("User message content parts (text or file)"),providerOptions:HY}),jn0=N.object({role:N.literal("assistant"),content:N.array(N.union([$G0,ZG0,Vn0,qn0,KG0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HY}),Pn0=N.object({role:N.literal("tool"),content:N.array(KG0).describe("Tool message content (tool results)"),providerOptions:HY}),Nn0=N.union([zn0,Ln0,jn0,Pn0]),Bn0=N.array(Nn0).describe("A list of messages forming the prompt"),wn0=N.object({prompt:Bn0.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),headers:N.record(N.string(),N.union([N.string(),N.undefined()])).optional().describe("Additional HTTP headers to be sent with the request"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),On0=N.object({content:N.array(N.any()).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.object({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).passthrough().transform((Q)=>({inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalTokens:Q.totalTokens,reasoningTokens:Q.reasoningTokens,...Q})).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.date().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),CS1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Mn0=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),IS1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),GG0=N.object({modelId:N.string().describe("The ID of the model"),callOptions:wn0}),Dn0=JK.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Tn0=XK("llm",Dn0,{readOnly:!0}),rh=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:Mn0},{name:"LLM_DO_STREAM",inputSchema:GG0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:GG0,outputSchema:On0},...Tn0],kS1=QK(rh)});function En0(Q){let J=[],X=0;while(X<Q.length){let Y=Q[X];if(Y==="%")J.push(".*");else if(Y==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(Y))J.push("\\"+Y);else J.push(Y);X++}return J.join("")}function l7(Q){return typeof Q==="string"||typeof Q==="number"}function LO(Q,J){if("conditions"in J){let{operator:Z,conditions:K}=J;switch(Z){case"and":return K.every((H)=>LO(Q,H));case"or":return K.some((H)=>LO(Q,H));case"not":return!K.every((H)=>LO(Q,H));default:return!0}}let{field:X,operator:Y,value:W}=J,G=X.join("."),$=ih(Q,G);switch(Y){case"eq":return $===W;case"gt":return l7($)&&l7(W)&&$>W;case"gte":return l7($)&&l7(W)&&$>=W;case"lt":return l7($)&&l7(W)&&$<W;case"lte":return l7($)&&l7(W)&&$<=W;case"in":return Array.isArray(W)&&W.includes($);case"like":if(typeof $!=="string"||typeof W!=="string")return!1;if(W.length>100)return!1;let Z=En0(W);return new RegExp(`^${Z}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof W!=="string")return!1;return $.toLowerCase().includes(W.toLowerCase());default:return!0}}function ih(Q,J){let X=J.split("."),Y=Q;for(let W of X){if(Y==null||typeof Y!=="object")return;Y=Y[W]}return Y}function Rn0(Q,J){return[...Q].sort((X,Y)=>{for(let W of J){let G=W.field.join("."),$=ih(X,G),Z=ih(Y,G),K=0;if($==null&&Z==null)continue;if($==null)K=W.nulls==="first"?-1:1;else if(Z==null)K=W.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof Z==="string")K=$.localeCompare(Z);else if(typeof $==="number"&&typeof Z==="number")K=$-Z;else K=String($).localeCompare(String(Z));if(K!==0)return W.direction==="desc"?-K:K}return 0})}var An0,Sn0,vn0,ah;var FG0=p(()=>{nh();WG0();u7();HG0();o1();K4();rZ();An0={LLM:rh,ASSISTANTS:YG0};Sn0=Cq.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),vn0=Iq(gQ),ah=$1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:Sn0,outputSchema:vn0,handler:async(Q,J)=>{await J.access.check();let X=s1(J),Y=Q.binding?typeof Q.binding==="string"?(()=>{let q=An0[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,W=Y?zO(Y):void 0,G=await J.storage.connections.list(X.id),$=W?await Promise.all(G.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return W.isImplementedBy(q.tools.map((j)=>({name:j.name,inputSchema:j.inputSchema,outputSchema:j.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):G;if(Q.where)$=$.filter((q)=>LO(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)$=Rn0($,Q.orderBy);let Z=$.length,K=Q.offset??0,H=Q.limit??100,F=$.slice(K,K+H),V=K+H<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Cn0,oh;var VG0=p(()=>{u7();K4();rZ();Cn0=dh(gQ),oh=$1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:lh,outputSchema:Cn0,handler:async(Q,J)=>{let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y||Y.organization_id!==X.id)return{item:null};return{item:Y}}})});var jO=(Q,J)=>{if(J===null||J===void 0)return;let X=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),Y=J;for(let W of X){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[W]}return Y};function qG0(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return J}function In0(Q){let J=Q.split("::");if(J.length!==2||!J[0]||!J[1])return null;return J}function kn0(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let J=Q.value;if(typeof J==="string")return J}return null}function _n0(Q,J){let X={};if(!Q||!J)return X;for(let Y of J){let W=In0(Y);if(!W)continue;let[G,$]=W,Z=jO(G,Q),K=kn0(Z);if(K){if(!X[K])X[K]=[];X[K].push($)}}return X}function UG0(Q,J){let X=_n0(Q,J);return new Set(Object.keys(X).filter((Y)=>Y!=="*"))}var zG0=()=>{};async function fn0(Q,J,X,Y){for(let G of J){let[$]=qG0(G),Z=jO($,Q);if(Z===void 0||Z===null)throw Error(`Scope references key "${$}" but it's not present in state`)}let W=UG0(Q,J);for(let G of W){if(G===DG.SELF)continue;let $=await Y.storage.connections.findById(G);if(!$||$.organization_id!==X)throw Error(`Referenced connection not found: ${G}`);try{await Y.access.check(G)}catch(Z){throw Error(`Access denied to referenced connection: ${G}. ${Z.message}`)}}}var yn0,bn0,sh;var LG0=p(()=>{zG0();uV();o1();K4();Bw();rZ();yn0=N.object({id:N.string().describe("ID of the connection to update"),data:EW0.describe("Partial connection data to update")}),bn0=N.object({item:gQ.describe("The updated connection entity")});sh=$1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:yn0,outputSchema:bn0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let{id:Y,data:W}=Q,G=await J.storage.connections.findById(Y);if(!G||G.organization_id!==X.id)throw Error("Connection not found in organization");let $=W.configuration_state??G.configuration_state,Z=W.configuration_scopes??G.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)$=W.configuration_state;else if($===null)$={};if(W.configuration_scopes!==void 0)Z=W.configuration_scopes??[];if(Z.length>0&&$)await fn0($,Z,X.id,J)}let K=await IZ({id:G.id,title:W.title??G.title,connection_url:W.connection_url??G.connection_url,connection_token:W.connection_token??G.connection_token,connection_headers:W.connection_headers??G.connection_headers}).catch(()=>null),H=K?.length?K:null,F={...W,tools:H,configuration_state:$,configuration_scopes:Z},V=await J.storage.connections.update(Y,F);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&$&&Z.length>0)try{await(await J.createMCPProxy(Y)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:Z}})}catch(q){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",q)}return{item:V}}})});var th;var jG0=p(()=>{u7();K4();rZ();th=$1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:ph,outputSchema:ch(gQ),handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y)throw Error(`Connection not found: ${Q.id}`);if(Y.organization_id!==X.id)throw Error("Connection not found in organization");return await J.storage.connections.delete(Q.id),{item:Y}}})});var eh;var PG0=p(()=>{o1();K4();eh=$1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Q,J)=>{let X=s1(J);await J.access.check();let Y=await J.storage.connections.findById(Q.id);if(!Y||Y.organization_id!==X.id)throw Error("Connection not found");let W=await J.storage.connections.testConnection(Q.id);return{id:Q.id,...W}}})});var NG0=p(()=>{RW0();FG0();VG0();LG0();jG0();PG0()});import{sql as x4}from"kysely";function BG0(Q){return Q.replace(/-/g,"_")}function xn0(Q){return`app_${BG0(Q)}`}function un0(Q){return`app_role_${BG0(Q)}`}function ln0(Q){if(Q instanceof Error){let J=Q.message.toLowerCase(),X=Q.code;return X==="3F000"||X==="42704"||J.includes("schema")&&J.includes("does not exist")||J.includes("role")&&J.includes("does not exist")}return!1}async function dn0(Q,J,X){if(await x4`CREATE SCHEMA IF NOT EXISTS ${x4.id(J)}`.execute(Q),!(await x4`
|
|
249
249
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${X}) as exists
|
|
250
250
|
`.execute(Q)).rows[0]?.exists)await x4`CREATE ROLE ${x4.id(X)} NOLOGIN`.execute(Q);await x4`GRANT USAGE, CREATE ON SCHEMA ${x4.id(J)} TO ${x4.id(X)}`.execute(Q),await x4`GRANT ALL ON ALL TABLES IN SCHEMA ${x4.id(J)} TO ${x4.id(X)}`.execute(Q),await x4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${x4.id(J)} TO ${x4.id(X)}`.execute(Q),await x4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${x4.id(J)} GRANT ALL ON TABLES TO ${x4.id(X)}`.execute(Q),await x4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${x4.id(J)} GRANT ALL ON SEQUENCES TO ${x4.id(X)}`.execute(Q),await x4`REVOKE ALL ON SCHEMA public FROM ${x4.id(X)}`.execute(Q)}async function pn0(Q,J,X,Y){try{return await Q.transaction().execute(async(W)=>{return await x4`SET LOCAL ROLE ${x4.id(X)}`.execute(W),await x4`SET LOCAL search_path TO ${x4.id(J)}`.execute(W),await x4.raw(Y).execute(W)})}catch(W){if(ln0(W))return await dn0(Q,J,X),await Q.transaction().execute(async(G)=>{return await x4`SET LOCAL ROLE ${x4.id(X)}`.execute(G),await x4`SET LOCAL search_path TO ${x4.id(J)}`.execute(G),await x4.raw(Y).execute(G)});throw W}}var gn0,mn0,wG0;var OG0=p(()=>{o1();K4();gn0=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()}),mn0=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});wG0=$1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:mn0,outputSchema:N.lazy(()=>N.object({result:N.array(gn0)})),handler:async(Q,J)=>{if(N1(J),await J.access.check(),!J.connectionId)throw Error("Connection context required for database access");let X=xn0(J.connectionId),Y=un0(J.connectionId),W=Q.sql;for(let $=0;$<(Q.params?.length??0);$++){let Z=Q.params?.[$];W=W.replace("?",typeof Z==="string"?`'${Z}'`:`${Z}`)}return{result:[{results:(await pn0(J.db,X,Y,W)).rows,success:!0}]}}})});var MG0,nn0,DG0;var FY=p(()=>{o1();nh();MG0=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),nn0=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.union([N.string(),N.date()]).describe("Created timestamp"),updatedAt:N.union([N.string(),N.date()]).describe("Updated timestamp")}),DG0=N.object({subscriptions:N.array(nn0).describe("List of subscriptions")})});var Qg;var TG0=p(()=>{K4();FY();Qg=$1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:kq,outputSchema:_q,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let W=await J.eventBus.publish(X.id,Y,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:W.id,type:W.type,source:W.source,time:W.time}}})});var Jg;var AG0=p(()=>{K4();FY();Jg=$1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:yq,outputSchema:bq,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let W=await J.eventBus.subscribe(X.id,{connectionId:Y,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt,updatedAt:W.updatedAt}}}})});var Xg;var EG0=p(()=>{K4();FY();Xg=$1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:gq,outputSchema:mq,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let W=await J.eventBus.getSubscription(X.id,Q.subscriptionId);if(!W)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(W.connectionId!==Y)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await J.eventBus.unsubscribe(X.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var Yg;var RG0=p(()=>{K4();FY();Yg=$1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:xq,outputSchema:uq,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await J.eventBus.getEvent(X.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await J.eventBus.cancelEvent(X.id,Q.eventId,Y)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Q.eventId}}})});var Wg;var SG0=p(()=>{K4();FY();Wg=$1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:lq,outputSchema:dq,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await J.eventBus.ackEvent(X.id,Q.eventId,Y)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Q.eventId}}})});var Gg;var vG0=p(()=>{K4();FY();Gg=$1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:MG0,outputSchema:DG0,handler:async(Q,J)=>{N1(J);let X=s1(J);return await J.access.check(),{subscriptions:(await J.eventBus.listSubscriptions(X.id,Q.connectionId)).map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt,updatedAt:W.updatedAt}))}}})});var $g;var CG0=p(()=>{uV();K4();FY();$g=$1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:fq,outputSchema:hq,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=J.connectionId;if(!Y)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let W=await J.eventBus.syncSubscriptions(X.id,{connectionId:Y,subscriptions:Q.subscriptions}),G=W.subscriptions.filter(($)=>$.eventType?.startsWith("cron/")&&$.publisher===FZ.SELF(X.id));return await Promise.all(G.map(async($)=>{let Z=$.eventType.split("/")[1];Z&&await J.eventBus.publish(X.id,FZ.SELF(X.id),{type:$.eventType,cron:Z,data:{}})})),{created:W.created,updated:W.updated,deleted:W.deleted,unchanged:W.unchanged,subscriptions:W.subscriptions.map(($)=>({id:$.id,connectionId:$.connectionId,eventType:$.eventType,publisher:$.publisher,filter:$.filter,enabled:$.enabled,createdAt:$.createdAt,updatedAt:$.updatedAt}))}}})});var IG0=p(()=>{TG0();AG0();EG0();RG0();SG0();vG0();CG0();FY()});var Zg,Kg,in0,HX,kG0,_G0;var YK=p(()=>{o1();Zg=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),Kg=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),in0=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),HX=N.object({id:N.string().describe("Unique identifier for the gateway"),title:N.string().describe("Human-readable name for the gateway"),description:N.string().nullable().describe("Description of the gateway"),icon:N.string().nullable().optional().describe("Icon URL for the gateway"),created_at:N.string().describe("When the gateway was created"),updated_at:N.string().describe("When the gateway was last updated"),created_by:N.string().describe("User ID who created the gateway"),updated_by:N.string().optional().describe("User ID who last updated the gateway"),organization_id:N.string().describe("Organization ID this gateway belongs to"),tool_selection_strategy:Kg.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:Zg.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),is_default:N.boolean().describe("Whether this is the default gateway for the organization"),connections:N.array(in0).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),kG0=N.object({title:N.string().min(1).max(255).describe("Name for the gateway"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_strategy:Kg.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:Zg.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:N.boolean().optional().default(!1).describe("Whether this is the default gateway for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),_G0=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_strategy:Kg.optional().describe("New gateway behavior strategy"),tool_selection_mode:Zg.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),is_default:N.boolean().optional().describe("Set as default gateway for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var an0,on0,Hg;var yG0=p(()=>{o1();K4();YK();an0=N.object({data:kG0.describe("Data for the new gateway")}),on0=N.object({item:HX.describe("The created gateway entity")}),Hg=$1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:an0,outputSchema:on0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=M5(J);if(!Y)throw Error("User ID required to create gateway");let W={title:Q.data.title,description:Q.data.description??null,toolSelectionStrategy:Q.data.tool_selection_strategy??"passthrough",toolSelectionMode:Q.data.tool_selection_mode??"inclusion",icon:Q.data.icon??null,status:Q.data.status,isDefault:Q.data.is_default??!1,connections:Q.data.connections.map(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??null}))},G=await J.storage.gateways.create(X.id,Y,W);return{item:{id:G.id,title:G.title,description:G.description,icon:G.icon,organization_id:G.organizationId,tool_selection_strategy:G.toolSelectionStrategy,tool_selection_mode:G.toolSelectionMode,status:G.status,is_default:G.isDefault,connections:G.connections.map(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:G.createdAt,updated_at:G.updatedAt,created_by:G.createdBy,updated_by:G.updatedBy??void 0}}}})});function sn0(Q){let J=[],X=0;while(X<Q.length){let Y=Q[X];if(Y==="%")J.push(".*");else if(Y==="_")J.push(".");else if(/[.*+?^${}()|[\]\\]/.test(Y))J.push("\\"+Y);else J.push(Y);X++}return J.join("")}function d7(Q){return typeof Q==="string"||typeof Q==="number"}function Fg(Q,J){let X=J.split("."),Y=Q;for(let W of X){if(Y==null||typeof Y!=="object")return;Y=Y[W]}return Y}function tn0(Q,J){return Q.connections.some((X)=>X.connection_id===J)}function PO(Q,J){if("conditions"in J){let{operator:Z,conditions:K}=J;switch(Z){case"and":return K.every((H)=>PO(Q,H));case"or":return K.some((H)=>PO(Q,H));case"not":return!K.every((H)=>PO(Q,H));default:return!0}}let{field:X,operator:Y,value:W}=J,G=X.join(".");if(G==="connection_id"){if(Y!=="eq"||typeof W!=="string")return!1;return tn0(Q,W)}let $=Fg(Q,G);switch(Y){case"eq":return $===W;case"gt":return d7($)&&d7(W)&&$>W;case"gte":return d7($)&&d7(W)&&$>=W;case"lt":return d7($)&&d7(W)&&$<W;case"lte":return d7($)&&d7(W)&&$<=W;case"in":return Array.isArray(W)&&W.includes($);case"like":if(typeof $!=="string"||typeof W!=="string")return!1;if(W.length>100)return!1;let Z=sn0(W);return new RegExp(`^${Z}$`,"i").test($);case"contains":if(typeof $!=="string"||typeof W!=="string")return!1;return $.toLowerCase().includes(W.toLowerCase());default:return!0}}function en0(Q,J){return[...Q].sort((X,Y)=>{for(let W of J){let G=W.field.join("."),$=Fg(X,G),Z=Fg(Y,G),K=0;if($==null&&Z==null)continue;if($==null)K=W.nulls==="first"?-1:1;else if(Z==null)K=W.nulls==="first"?1:-1;else if(typeof $==="string"&&typeof Z==="string")K=$.localeCompare(Z);else if(typeof $==="number"&&typeof Z==="number")K=$-Z;else K=String($).localeCompare(String(Z));if(K!==0)return W.direction==="desc"?-K:K}return 0})}var Qr0,Jr0,Vg;var bG0=p(()=>{u7();K4();YK();Qr0=Cq,Jr0=Iq(HX),Vg=$1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:Qr0,outputSchema:Jr0,handler:async(Q,J)=>{await J.access.check();let X=s1(J),Y=Q.where&&!("conditions"in Q.where)&&Q.where.field.join(".")==="connection_id"&&Q.where.operator==="eq"&&typeof Q.where.value==="string"?Q.where.value:void 0,G=(Y?await J.storage.gateways.listByConnectionId(X.id,Y):await J.storage.gateways.list(X.id)).map((V)=>({id:V.id,title:V.title,description:V.description,icon:V.icon,is_default:V.isDefault,organization_id:V.organizationId,tool_selection_strategy:V.toolSelectionStrategy,tool_selection_mode:V.toolSelectionMode,status:V.status,connections:V.connections.map((q)=>({connection_id:q.connectionId,selected_tools:q.selectedTools,selected_resources:q.selectedResources,selected_prompts:q.selectedPrompts})),created_at:V.createdAt,updated_at:V.updatedAt,created_by:V.createdBy,updated_by:V.updatedBy??void 0}));if(Q.where)G=G.filter((V)=>PO(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)G=en0(G,Q.orderBy);let $=G.length,Z=Q.offset??0,K=Q.limit??100,H=G.slice(Z,Z+K),F=Z+K<$;return{items:H,totalCount:$,hasMore:F}}})});var Xr0,Yr0,qg;var fG0=p(()=>{o1();K4();YK();Xr0=N.object({id:N.string().describe("ID of the gateway to retrieve")}),Yr0=N.object({item:HX.nullable().describe("The retrieved gateway, or null if not found")}),qg=$1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:Xr0,outputSchema:Yr0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=await J.storage.gateways.findById(Q.id);if(Y&&Y.organizationId!==X.id)return{item:null};if(!Y)return{item:null};return{item:{id:Y.id,title:Y.title,description:Y.description,icon:Y.icon,organization_id:Y.organizationId,tool_selection_strategy:Y.toolSelectionStrategy,tool_selection_mode:Y.toolSelectionMode,status:Y.status,is_default:Y.isDefault,connections:Y.connections.map((W)=>({connection_id:W.connectionId,selected_tools:W.selectedTools,selected_resources:W.selectedResources,selected_prompts:W.selectedPrompts})),created_at:Y.createdAt,updated_at:Y.updatedAt,created_by:Y.createdBy,updated_by:Y.updatedBy??void 0}}}})});var Wr0,Gr0,Ug;var hG0=p(()=>{o1();K4();YK();Wr0=N.object({id:N.string().describe("ID of the gateway to update"),data:_G0.describe("Partial gateway data to update")}),Gr0=N.object({item:HX.describe("The updated gateway entity")}),Ug=$1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:Wr0,outputSchema:Gr0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=M5(J);if(!Y)throw Error("User ID required to update gateway");let W=await J.storage.gateways.findById(Q.id);if(!W)throw Error(`Gateway not found: ${Q.id}`);if(W.organizationId!==X.id)throw Error(`Gateway not found: ${Q.id}`);let G={};if(Q.data.title!==void 0)G.title=Q.data.title;if(Q.data.description!==void 0)G.description=Q.data.description;if(Q.data.tool_selection_strategy!==void 0)G.toolSelectionStrategy=Q.data.tool_selection_strategy;if(Q.data.tool_selection_mode!==void 0)G.toolSelectionMode=Q.data.tool_selection_mode;if(Q.data.icon!==void 0)G.icon=Q.data.icon;if(Q.data.status!==void 0)G.status=Q.data.status;if(Q.data.is_default!==void 0)G.isDefault=Q.data.is_default;if(Q.data.connections!==void 0)G.connections=Q.data.connections.map((Z)=>({connectionId:Z.connection_id,selectedTools:Z.selected_tools??null,selectedResources:Z.selected_resources??null,selectedPrompts:Z.selected_prompts??null}));let $=await J.storage.gateways.update(Q.id,Y,G);return{item:{id:$.id,title:$.title,description:$.description,icon:$.icon,organization_id:$.organizationId,tool_selection_strategy:$.toolSelectionStrategy,tool_selection_mode:$.toolSelectionMode,status:$.status,is_default:$.isDefault,connections:$.connections.map((Z)=>({connection_id:Z.connectionId,selected_tools:Z.selectedTools,selected_resources:Z.selectedResources,selected_prompts:Z.selectedPrompts})),created_at:$.createdAt,updated_at:$.updatedAt,created_by:$.createdBy,updated_by:$.updatedBy??void 0}}}})});var $r0,Zr0,zg;var gG0=p(()=>{o1();K4();YK();$r0=N.object({id:N.string().describe("ID of the gateway to delete")}),Zr0=N.object({item:HX.describe("The deleted gateway entity")}),zg=$1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:$r0,outputSchema:Zr0,handler:async(Q,J)=>{N1(J);let X=s1(J);await J.access.check();let Y=await J.storage.gateways.findById(Q.id);if(!Y)throw Error(`Gateway not found: ${Q.id}`);if(Y.organizationId!==X.id)throw Error(`Gateway not found: ${Q.id}`);if(Y.isDefault)throw Error("Cannot delete the default gateway. Set another gateway as default first.");return await J.storage.gateways.delete(Q.id),{item:{id:Y.id,title:Y.title,description:Y.description,icon:Y.icon,organization_id:Y.organizationId,tool_selection_strategy:Y.toolSelectionStrategy,tool_selection_mode:Y.toolSelectionMode,status:Y.status,is_default:Y.isDefault,connections:Y.connections.map((W)=>({connection_id:W.connectionId,selected_tools:W.selectedTools,selected_resources:W.selectedResources,selected_prompts:W.selectedPrompts})),created_at:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updated_at:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt,created_by:Y.createdBy,updated_by:Y.updatedBy??void 0}}}})});var mG0=p(()=>{yG0();bG0();fG0();hG0();gG0()});var Hr0,Lg;var xG0=p(()=>{K4();o1();Hr0=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.unknown()).describe("Redacted tool input"),output:N.record(N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:N.string().nullish().describe("Gateway ID if routed through a gateway")}),Lg=$1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),gatewayId:N.string().optional().describe("Filter by gateway ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(100).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination")}),outputSchema:N.object({logs:N.array(Hr0).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Q,J)=>{let Y={organizationId:s1(J).id,connectionId:Q.connectionId,gatewayId:Q.gatewayId,toolName:Q.toolName,isError:Q.isError,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0,limit:Q.limit,offset:Q.offset},W=await J.storage.monitoring.query(Y);return{logs:W.logs.map((G)=>({...G,timestamp:G.timestamp instanceof Date?G.timestamp.toISOString():G.timestamp})),total:W.total,offset:Q.offset,limit:Q.limit}}})});var jg;var uG0=p(()=>{K4();o1();jg=$1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Q,J)=>{let Y={organizationId:s1(J).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},W=await J.storage.monitoring.getStats(Y);return{...W,errorRatePercent:(W.errorRate*100).toFixed(2)}}})});var lG0=p(()=>{xG0();uG0()});var Pg;var dG0=p(()=>{o1();K4();Pg=$1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional()}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=M5(J);if(!X)throw Error("User ID required to create organization");let Y=await J.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:X});if(!Y)throw Error("Failed to create organization");return Y}})});var Ng;var pG0=p(()=>{o1();K4();Ng=$1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}))}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=M5(J),Y=Q.userId||X;if(!Y)throw Error("User ID required to list organizations");return{organizations:await J.boundAuth.organization.list(Y)}}})});var Bg;var cG0=p(()=>{o1();K4();Bg=$1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()]),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=await J.boundAuth.organization.get();if(!X)throw Error("No active organization found");return X}})});var wg;var nG0=p(()=>{o1();K4();wg=$1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,J)=>{N1(J),await J.access.check();let X={};if(Q.name)X.name=Q.name;if(Q.slug)X.slug=Q.slug;if(Q.description)X.metadata={description:Q.description};let Y=await J.boundAuth.organization.update({organizationId:Q.id,data:X});if(!Y)throw Error("Failed to update organization");return Y}})});var Og;var rG0=p(()=>{o1();K4();Og=$1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Q,J)=>{return N1(J),await J.access.check(),await J.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var cq;var Mg=p(()=>{o1();cq=N.object({title:N.string(),url:N.string(),connectionId:N.string(),icon:N.string()})});var Dg;var iG0=p(()=>{o1();K4();Mg();Dg=$1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(cq).nullable().optional(),createdAt:N.union([N.date(),N.string()]).optional(),updatedAt:N.union([N.date(),N.string()]).optional()}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Y=await J.storage.organizationSettings.get(X);if(!Y)return{organizationId:X};return Y}})});var Tg;var aG0=p(()=>{o1();K4();Mg();Tg=$1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(cq).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(cq).nullable().optional(),createdAt:N.union([N.date(),N.string()]),updatedAt:N.union([N.date(),N.string()])}),handler:async(Q,J)=>{if(N1(J),await J.access.check(),J.organization&&J.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");return await J.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items})}})});var Ag;var oG0=p(()=>{o1();K4();Ag=$1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.union([N.date(),N.string()])}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Y=await J.boundAuth.organization.addMember({organizationId:X,userId:Q.userId,role:Q.role});if(!Y)throw Error("Failed to add member");return Y}})});var Eg;var sG0=p(()=>{o1();K4();Eg=$1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");return await J.boundAuth.organization.removeMember({organizationId:X,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var Rg;var tG0=p(()=>{o1();K4();Rg=$1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.union([N.date(),N.string()]),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Y=await J.boundAuth.organization.listMembers({organizationId:X,limit:Q.limit,offset:Q.offset});return{members:Array.isArray(Y)?Y:[]}}})});var Sg;var eG0=p(()=>{o1();K4();Sg=$1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.union([N.date(),N.string()]),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Q,J)=>{N1(J),await J.access.check();let X=Q.organizationId||J.organization?.id;if(!X)throw Error("Organization ID required (no active organization in context)");let Y=await J.boundAuth.organization.updateMemberRole({organizationId:X,memberId:Q.memberId,role:Q.role});if(!Y)throw Error("Failed to update member role");return Y}})});var Q$0=p(()=>{dG0();pG0();cG0();nG0();rG0();iG0();aG0();oG0();sG0();tG0();eG0()});var X$0={};X4(X$0,{managementMCP:()=>qr0,ALL_TOOLS:()=>J$0});var J$0,qr0=(Q)=>{let J=J$0.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema,outputSchema:Y.outputSchema,handler:async(W)=>{return Q.access.setToolName(Y.name),await Y.execute(W,Q)}}));return UX0({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var Y$0=p(()=>{zX0();TW0();NG0();OG0();IG0();mG0();lG0();Q$0();J$0=[Pg,Ng,Bg,wg,Og,Dg,Tg,Ag,Eg,Rg,Sg,Sh,ah,oh,sh,th,eh,Hg,Vg,qg,Ug,zg,wG0,Lg,jg,Th,Eh,Rh,Ah,Qg,Jg,Xg,Yg,Wg,Gg,$g]});fO();import{Migrator as q$0}from"kysely";var cg={benchmark:()=>Promise.resolve().then(() => (pg(),dg)).then((Q)=>Q.seed)};async function ng(Q,J){let X=cg[J];if(!X)throw Error(`Unknown seed: ${J}. Available: ${Object.keys(cg).join(", ")}`);let Y=await X();console.log(`\uD83C\uDF31 Running seed: ${J}`);let W=await Y(Q);return console.log(`\u2705 Seed "${J}" completed`),W}UX();QQ();UX();QQ();M9();b6();var o8=(Q,J="ms")=>{return new Date(Date.now()+(J==="sec"?Q*1000:Q))},pL=new WeakMap;function Zd(Q,J){let X=J.fields,Y={};for(let W in Q){let G=X[W];if(!G){Y[W]=Q[W];continue}if(G.returned===!1)continue;Y[W]=Q[W]}return Y}function cL(Q,J){if(!pL.has(Q))pL.set(Q,new Map);let X=pL.get(Q);if(X.has(J))return X.get(J);let Y={...J==="user"?Q.user?.additionalFields:{},...J==="session"?Q.session?.additionalFields:{}};for(let W of Q.plugins||[])if(W.schema&&W.schema[J])Y={...Y,...W.schema[J].fields};return pL.get(Q).set(J,Y),Y}function f6(Q,J){return{...Zd(J,{fields:cL(Q,"user")}),id:J.id}}function vJ(Q,J){return Zd(J,{fields:cL(Q,"session")})}function aR(Q,J){let X=J.action||"create",Y=J.fields,W=Object.assign(Object.create(null),null);for(let G in Y){if(G in Q){if(Y[G].input===!1){if(Y[G].defaultValue!==void 0){if(X!=="update"){W[G]=Y[G].defaultValue;continue}}if(Q[G])throw new m("BAD_REQUEST",{message:`${G} is not allowed to be set`});continue}if(Y[G].validator?.input&&Q[G]!==void 0){W[G]=Y[G].validator.input["~standard"].validate(Q[G]);continue}if(Y[G].transform?.input&&Q[G]!==void 0){W[G]=Y[G].transform?.input(Q[G]);continue}W[G]=Q[G];continue}if(Y[G].defaultValue!==void 0&&X==="create"){if(typeof Y[G].defaultValue==="function"){W[G]=Y[G].defaultValue();continue}W[G]=Y[G].defaultValue;continue}if(Y[G].required&&X==="create")throw new m("BAD_REQUEST",{message:`${G} is required`})}return W}function nL(Q,J={},X){return aR(J,{fields:cL(Q,"user"),action:X})}function oR(Q,J){return aR(J,{fields:cL(Q,"session")})}function g9(Q,J){if(!J)return Q;for(let X in J){let Y=J[X]?.modelName;if(Y)Q[X].modelName=Y;for(let W in Q[X].fields){let G=J[X]?.fields?.[W];if(!G)continue;Q[X].fields[W].fieldName=G}}return Q}Z5();x1();var QV0="127.0.0.1";function hY(Q,J){if(J.advanced?.ipAddress?.disableIpTracking)return null;if(AX()||l$())return QV0;let X="headers"in Q?Q.headers:Q,Y=J.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let W of Y){let G="get"in X?X.get(W):X[W];if(typeof G==="string"){let $=G.split(",")[0].trim();if(JV0($))return $}}return null}function JV0(Q){if(EW().safeParse(Q).success)return!0;if(RW().safeParse(Q).success)return!0;return!1}D9();TJ();Z5();K6();import{sql as IJ}from"kysely";async function qd(Q,J){let X;if(!Q.database){let Y=S5(Q),W=Object.keys(Y).reduce(($,Z)=>{return $[Z]=[],$},{}),{memoryAdapter:G}=await Promise.resolve().then(() => (Vd(),Fd));X=G(W)(Q)}else if(typeof Q.database==="function")X=Q.database(Q);else X=await J(Q);if(!X.transaction)A1.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),X.transaction=async(Y)=>{return Y(X)};return X}async function XS(Q){return qd(Q,async(J)=>{let{createKyselyAdapter:X}=await Promise.resolve().then(() => (JS(),QS)),{kysely:Y,databaseType:W,transaction:G}=await X(J);if(!Y)throw new L1("Failed to initialize database adapter");let{kyselyAdapter:$}=await Promise.resolve().then(() => (JS(),QS));return $(Y,{type:W||"sqlite",debugLogs:J.database&&"debugLogs"in J.database?J.database.debugLogs:!1,transaction:G})(J)})}function Ud(Q,J){let X=J.hooks;async function Y(K,H,F){let V=await v5(),q=K;for(let P of X||[]){let B=P[H]?.create?.before;if(B){let w=await B(q,V);if(w===!1)return null;if(typeof w==="object"&&"data"in w)q={...q,...w.data}}}let z=F?await F.fn(q):null,j=!F||F.executeMainFn?await(await l4(Q)).create({model:H,data:q,forceAllowId:!0}):z;for(let P of X||[]){let B=P[H]?.create?.after;if(B)await B(j,V)}return j}async function W(K,H,F,V){let q=await v5(),z=K;for(let B of X||[]){let w=B[F]?.update?.before;if(w){let T=await w(K,q);if(T===!1)return null;if(typeof T==="object"&&"data"in T)z={...z,...T.data}}}let j=V?await V.fn(z):null,P=!V||V.executeMainFn?await(await l4(Q)).update({model:F,update:z,where:H}):j;for(let B of X||[]){let w=B[F]?.update?.after;if(w)await w(P,q)}return P}async function G(K,H,F,V){let q=await v5(),z=K;for(let B of X||[]){let w=B[F]?.update?.before;if(w){let T=await w(K,q);if(T===!1)return null;if(typeof T==="object"&&"data"in T)z={...z,...T.data}}}let j=V?await V.fn(z):null,P=!V||V.executeMainFn?await(await l4(Q)).updateMany({model:F,update:z,where:H}):j;for(let B of X||[]){let w=B[F]?.update?.after;if(w)await w(P,q)}return P}async function $(K,H,F){let V=await v5(),q=null;try{q=(await(await l4(Q)).findMany({model:H,where:K,limit:1}))[0]||null}catch(P){}if(q)for(let P of X||[]){let B=P[H]?.delete?.before;if(B){if(await B(q,V)===!1)return null}}let z=F?await F.fn(K):null,j=!F||F.executeMainFn?await(await l4(Q)).delete({model:H,where:K}):z;if(q)for(let P of X||[]){let B=P[H]?.delete?.after;if(B)await B(q,V)}return j}async function Z(K,H,F){let V=await v5(),q=[];try{q=await(await l4(Q)).findMany({model:H,where:K})}catch(P){}for(let P of q)for(let B of X||[]){let w=B[H]?.delete?.before;if(w){if(await w(P,V)===!1)return null}}let z=F?await F.fn(K):null,j=!F||F.executeMainFn?await(await l4(Q)).deleteMany({model:H,where:K}):z;for(let P of q)for(let B of X||[]){let w=B[H]?.delete?.after;if(w)await w(P,V)}return j}return{createWithHooks:Y,updateWithHooks:W,updateManyWithHooks:G,deleteWithHooks:$,deleteManyWithHooks:Z}}var eL=(Q,J)=>{let{logger:X,options:Y}=J,W=Y.secondaryStorage,G=Y.session?.expiresIn||604800,{createWithHooks:$,updateWithHooks:Z,updateManyWithHooks:K,deleteWithHooks:H,deleteManyWithHooks:F}=Ud(Q,J);async function V(q){if(!W)return;let z=await W.get(`active-sessions-${q.id}`);if(!z)return;let j=Date.now(),P=(o4(z)||[]).filter((B)=>B.expiresAt>j);await Promise.all(P.map(async({token:B})=>{let w=await W.get(B);if(!w)return;let T=o4(w);if(!T)return;let E=Math.max(Math.floor(new Date(T.session.expiresAt).getTime()-j)/1000,0);await W.set(B,JSON.stringify({session:T.session,user:q}),Math.floor(E))}))}return{createOAuthUser:async(q,z)=>{return fK(Q,async()=>{let j=await $({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:j,account:await $({...z,userId:j.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await $({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await $({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(W){let z=await W.get(`active-sessions-${q}`);if(!z)return[];let j=o4(z)||[],P=Date.now(),B=j.filter((T)=>T.expiresAt>P),w=[];for(let T of B){let E=await W.get(T.token);if(E){let A=o4(E);if(!A)return[];let M=vJ(J.options,{...A.session,expiresAt:new Date(A.session.expiresAt)});w.push(M)}}return w}return await(await l4(Q)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,z,j,P)=>{return await(await l4(Q)).findMany({model:"user",limit:q,offset:z,sortBy:j,where:P})},countTotalUsers:async(q)=>{let z=await(await l4(Q)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(W)await W.delete(`active-sessions-${q}`);if(!W||Y.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,j,P)=>{let B=await v5().catch(()=>null),w=B?.headers||B?.request?.headers,{id:T,...E}=j||{},A=oR(B?.context.options??Y,{}),M={ipAddress:B?.request||B?.headers?hY(B?.request||B?.headers,B?.context.options)||"":"",userAgent:w?.get("user-agent")||"",...E,expiresAt:z?o8(86400,"sec"):o8(G,"sec"),userId:q,token:P6(32),createdAt:new Date,updatedAt:new Date,...A,...P?E:{}};return await $(M,"session",W?{fn:async(D)=>{let S=await W.get(`active-sessions-${q}`),v=[],I=Date.now();if(S)v=o4(S)||[],v=v.filter((d)=>d.expiresAt>I);let k=v.sort((d,t)=>d.expiresAt-t.expiresAt),_=k.at(-1)?.expiresAt;if(k.push({token:M.token,expiresAt:M.expiresAt.getTime()}),!_||_<M.expiresAt.getTime())_=M.expiresAt.getTime();let f=Math.max(Math.floor((_-I)/1000),0);if(f>0)await W.set(`active-sessions-${q}`,JSON.stringify(k),f);let y=await Q.findOne({model:"user",where:[{field:"id",value:q}]}),u=Math.max(Math.floor((M.expiresAt.getTime()-I)/1000),0);if(u>0)await W.set(M.token,JSON.stringify({session:D,user:y}),u);return D},executeMainFn:Y.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(W){let B=await W.get(q);if(!B&&!Y.session?.storeSessionInDatabase)return null;if(B){let w=o4(B);if(!w)return null;return{session:vJ(J.options,{...w.session,expiresAt:new Date(w.session.expiresAt),createdAt:new Date(w.session.createdAt),updatedAt:new Date(w.session.updatedAt)}),user:f6(J.options,{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)})}}}let z=await(await l4(Q)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:j,...P}=z;if(!j)return null;return{session:vJ(J.options,P),user:f6(J.options,j)}},findSessions:async(q)=>{if(W){let j=[];for(let P of q){let B=await W.get(P);if(B){let w=o4(B);if(!w)return[];let T={session:{...w.session,expiresAt:new Date(w.session.expiresAt)},user:{...w.user,createdAt:new Date(w.user.createdAt),updatedAt:new Date(w.user.updatedAt)}};j.push(T)}}return j}let z=await(await l4(Q)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((j)=>!j.user))return[];return z.map((j)=>{let{user:P,...B}=j;return{session:B,user:P}})},updateSession:async(q,z)=>{return await Z(z,[{field:"token",value:q}],"session",W?{async fn(j){let P=await W.get(q),B=null;if(P){let w=o4(P);if(!w)return null;return B={...w.session,...j},B}else return null},executeMainFn:Y.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(W){let z=await W.get(q);if(z){let{session:j}=o4(z)??{};if(!j){X.error("Session not found in secondary storage");return}let P=j.userId,B=await W.get(`active-sessions-${P}`);if(B){let w=o4(B)||[],T=Date.now(),E=w.filter((M)=>M.expiresAt>T&&M.token!==q),A=E.sort((M,D)=>M.expiresAt-D.expiresAt).at(-1)?.expiresAt;if(E.length>0&&A&&A>Date.now())await W.set(`active-sessions-${P}`,JSON.stringify(E),Math.floor((A-T)/1000));else await W.delete(`active-sessions-${P}`)}else X.error("Active sessions list not found in secondary storage")}if(await W.delete(q),!Y.session?.storeSessionInDatabase||J.options.session?.preserveSessionInDatabase)return}await(await l4(Q)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(W){if(typeof q==="string"){let z=await W.get(`active-sessions-${q}`),j=z?o4(z):[];if(!j)return;for(let P of j)await W.delete(P.token)}else for(let z of q)if(await W.get(z))await W.delete(z);if(!Y.session?.storeSessionInDatabase||J.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,j)=>{let P=await(await l4(Q)).findMany({model:"account",where:[{value:z,field:"accountId"}],join:{user:!0}}).then((B)=>{return B.find((w)=>w.providerId===j)});if(P)if(P.user)return{user:P.user,accounts:[P]};else{let B=await(await l4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(B)return{user:B,accounts:[P]};return null}else{let B=await(await l4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(B)return{user:B,accounts:await(await l4(Q)).findMany({model:"account",where:[{value:B.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,z)=>{let j=await(await l4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!j)return null;let{account:P,...B}=j;return{user:B,accounts:P??[]}},findUserById:async(q)=>{if(!q)return null;return await(await l4(Q)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await $({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let j=await Z(z,[{field:"id",value:q}],"user",void 0);return await V(j),await V(j),j},updateUserByEmail:async(q,z)=>{let j=await Z(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(j),await V(j),j},updatePassword:async(q,z)=>{await K({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await l4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await l4(Q)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await l4(Q)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await l4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await Z(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await $({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await l4(Q)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!Y.verification?.disableCleanup)await(await l4(Q)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return z[0]},deleteVerificationValue:async(q)=>{await(await l4(Q)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await l4(Q)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await Z(z,[{field:"id",value:q}],"verification",void 0)}}};function zd(Q){let J=S5(Q),X={};for(let Y in J){let W=J[Y],G=W.fields,$={};if(Object.entries(G).forEach(([Z,K])=>{if($[K.fieldName||Z]=K,K.references){let H=J[K.references.model];if(H)$[K.fieldName||Z].references={...K.references,model:H.modelName,field:K.references.field}}}),X[W.modelName]){X[W.modelName].fields={...X[W.modelName].fields,...$};continue}X[W.modelName]={fields:$,order:W.order||1/0}}return X}var ZV0={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function Ld(Q,J,X){function Y(G){return G.toLowerCase().split("(")[0].trim()}if(J==="string[]"||J==="number[]")return Q.toLowerCase().includes("json");let W=ZV0[X];return(Array.isArray(J)?W.string.map((G)=>G.toLowerCase()):W[J].map((G)=>G.toLowerCase())).includes(Y(Q))}async function KV0(Q){try{let J=await IJ`SHOW search_path`.execute(Q);if(J.rows[0]?.search_path)return J.rows[0].search_path.split(",").map((X)=>X.trim()).map((X)=>X.replace(/^["']|["']$/g,"")).filter((X)=>!X.startsWith("$"))[0]||"public"}catch(J){}return"public"}async function iH(Q){let J=zd(Q),X=p$(Q.logger),{kysely:Y,databaseType:W}=await eq(Q);if(!W)X.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),W="sqlite";if(!Y)X.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let G="public";if(W==="postgres"){G=await KV0(Y),X.debug(`PostgreSQL migration: Using schema '${G}' (from search_path)`);try{if(!(await IJ`
|
|
251
251
|
SELECT schema_name
|