planx 19.139.0 → 19.140.3

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/session.main.mjs CHANGED
@@ -275,9 +275,9 @@ this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names`):R
275
275
  `)}var Qti,_Xt,bXt,xXt=p(()=>{Zw();d0e();Qti="",_Xt="",bXt=Object.freeze({})});var CXt=p(()=>{xXt()});var b1,AXt=p(()=>{b1={up(t,e){t.curRow=Math.max(0,t.curRow-e)},down(t,e){t.curRow+=e,t.ensureRow(t.curRow)},forward(t,e){t.curCol+=e},back(t,e){t.curCol=Math.max(0,t.curCol-e)},toColumn(t,e){t.curCol=Math.max(0,e)},position(t,e,r){t.curRow=Math.max(0,e),t.curCol=Math.max(0,r),t.ensureRow(t.curRow)},prevLine(t,e){t.curRow=Math.max(0,t.curRow-e),t.curCol=0},nextLine(t,e){t.curRow+=e,t.ensureRow(t.curRow),t.curCol=0},verticalAbsolute(t,e){t.curRow=Math.max(0,e),t.ensureRow(t.curRow)}}});var OXt=p(()=>{AXt()});var pd,PXt=p(()=>{pd={getViewportTop(t){return Math.max(0,t.chars.length-t._viewportRows)},absToVpRel(t,e){return e-pd.getViewportTop(t)},vpRelToAbs(t,e){return pd.getViewportTop(t)+e},curVpRel(t){return pd.absToVpRel(t,t.curRow)},isCursorAtScrollTop(t){return pd.curVpRel(t)===t._scrollTop},isCursorAtScrollBottom(t){return t._scrollBottom<9999&&pd.curVpRel(t)===t._scrollBottom},vpToAbsSticky(t,e){let r=pd.vpRelToAbs(t,e-1),n=t._stickyCupAbsRow.get(e);return n!==void 0&&n>=pd.getViewportTop(t)&&n<t.chars.length?n:(t._stickyCupAbsRow.set(e,r),r)}}});var DXt=p(()=>{PXt()});function NO(){return{rowsAnsi:null,chars:[],stys:[],cursor:null,cursorVisible:null,viewportTop:null}}var NXt=p(()=>{});var kXt=p(()=>{NXt()});var RXt,Jti,Zti,tK,MXt=p(()=>{pZt();EZt();xZt();DZt();MZt();FZt();GZt();QZt();XZt();aXt();yXt();CXt();OXt();DXt();kXt();RXt=Object.freeze({}),Jti=1e4,Zti=Jti-1,tK=class{constructor(){this.chars=[[]],this.stys=[[]],this.curRow=0,this.curCol=0,this._st=RXt,this._rowAnsiCache=[],this._pendingEsc="",this._altMode=!1,this._savedMain=null,this._scrollTop=0,this._scrollBottom=Zti,this._cursorVisible=!0,this._tabStops=new Set,this._inSyncUpdate=!1,this._applicationCursorKeyMode=!1,this._bracketedPasteMode=!1,this._savedCursorPos=null,this._stickyCupAbsRow=new Map,this._cursorStyle=0,this._viewportRows=40,this._viewportCols=80,this._parseStyles=RXt,this._encoders=new Set,this._feedListeners=new Set}isInSyncUpdate(){return this._inSyncUpdate}isApplicationCursorKeyMode(){return this._applicationCursorKeyMode}isBracketedPasteMode(){return this._bracketedPasteMode}getCursorStyle(){return this._cursorStyle}get viewportRows(){return this._viewportRows}get cursorRow(){return this.curRow}get cursorCol(){return this.curCol}get viewportTopRow(){return this.getViewportTop()}getViewportTop(){return pd.getViewportTop(this)}setViewportSize(e,r){LZt(this,e,r)}setStyles(e){this._st=Object.freeze(e)}absToVpRel(e){return pd.absToVpRel(this,e)}vpRelToAbs(e){return pd.vpRelToAbs(this,e)}get curVpRel(){return pd.curVpRel(this)}get isCursorAtScrollTop(){return pd.isCursorAtScrollTop(this)}get isCursorAtScrollBottom(){return pd.isCursorAtScrollBottom(this)}vpToAbsSticky(e){return pd.vpToAbsSticky(this,e)}markRowDirty(e){this._rowAnsiCache[e]=void 0}markAllDirty(){this._rowAnsiCache.length=0}ensureRow(e){for(;this.chars.length<=e;)this.chars.push([]),this.stys.push([])}saveCursorPos(){lXt(this)}restoreCursorPos(){uXt(this)}writeChar(e){qZt(this,e)}writeRun(e,r,n){BZt(this,e,r,n)}writeText(e){VZt(this,e)}newline(){UZt(this)}carriageReturn(){this.curCol=0}clearLine(e){HZt(this,e)}eraseInDisplay(e){IZt(this,e)}toSegments(){return OZt(this)}feed(e){wZt(this,e);for(let r of this._feedListeners)try{r()}catch{}}onFeed(e){return this._feedListeners.add(e),()=>{this._feedListeners.delete(e)}}cursorUp(e){b1.up(this,e)}cursorDown(e){b1.down(this,e)}cursorForward(e){b1.forward(this,e)}cursorBack(e){b1.back(this,e)}cursorToColumn(e){b1.toColumn(this,e)}cursorPosition(e,r){b1.position(this,e,r)}cursorPrevLine(e){b1.prevLine(this,e)}cursorNextLine(e){b1.nextLine(this,e)}verticalPositionAbsolute(e){b1.verticalAbsolute(this,e)}scrollRegionUp(){zZt(this)}scrollRegionDown(){KZt(this)}feedText(e,r,n){JZt(this,e,r,n)}reverseIndex(){dXt(this)}index(){fXt(this)}nextLine(){this.newline()}reset(){pXt(this)}insertLines(e){eXt(this,e)}deleteLines(e){tXt(this,e)}insertChars(e){rXt(this,e)}deleteChars(e){nXt(this,e)}eraseChars(e){iXt(this,e)}tabStop(){sXt(this)}nextTabStop(e){return hXt(this,e)}enterAltScreen(){NZt(this)}exitAltScreen(){kZt(this)}trimScrollbackIfOver(){mXt(this)}serializeRow(e){return wXt(this,e)}rowsAsAnsi(){return p0e(this)}getScreenAnsi(){return SXt(this)}getViewportSnapshot(){return EXt(this)}getScrollbackAnsi(e){return IXt(this,e)}getViewportScrollback(e){return TXt(this,e)}_registerEncoder(e){this._encoders.add(e)}_unregisterEncoder(e){this._encoders.delete(e)}_emitPassthroughCsi(e){for(let r of this._encoders)r._onPassthroughCsi(e)}_emitPendingResetScreen(){for(let e of this._encoders)e._onPendingResetScreen()}_emitPendingSyncWrap(){for(let e of this._encoders)e._onPendingSyncWrap()}_emitSnapshotInvalidated(){for(let e of this._encoders)e._onSnapshotInvalidated()}_captureSnapshot(){return gXt(this)}_computeDelta(e,r){return dZt(this,e,r)}}});var h0e=p(()=>{MXt()});var m0e,LXt=p(()=>{h0e();m0e=class{constructor(e){this.grid=e,this.prev=NO(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1,this.forceFullRefreshOnBsuExit=!1,e._registerEncoder(this)}dispose(){this.grid._unregisterEncoder(this)}encodeDelta(){if(this.grid.isInSyncUpdate())return"";this.forceFullRefreshOnBsuExit&&(this.prev=NO(),this.forceFullRefreshOnBsuExit=!1);let e=this.grid._computeDelta(this.prev,{passthroughCsi:this.pendingPassthrough,resetScreen:this.pendingResetScreen,syncWrap:this.pendingSyncWrap});return this.prev=e.next,this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1,e.ansi}isInBatchedSyncUpdate(){return this.grid.isInSyncUpdate()}snapshot(){return this.isInBatchedSyncUpdate()?null:{prev:this.prev,pendingPassthrough:this.pendingPassthrough,pendingResetScreen:this.pendingResetScreen,pendingSyncWrap:this.pendingSyncWrap}}restore(e){if(e===null){this.forceFullRefreshOnBsuExit=!0;return}this.prev=e.prev,this.pendingPassthrough=e.pendingPassthrough,this.pendingResetScreen=e.pendingResetScreen,this.pendingSyncWrap=e.pendingSyncWrap}markBaseline(){this.prev=this.grid._captureSnapshot(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1}resetSnapshot(){this.prev=NO(),this.pendingPassthrough=[],this.pendingResetScreen=!1,this.pendingSyncWrap=!1}_onPassthroughCsi(e){this.pendingPassthrough.push(e)}_onPendingResetScreen(){this.pendingResetScreen=!0,this.prev=NO()}_onPendingSyncWrap(){this.pendingSyncWrap=!0}_onSnapshotInvalidated(){this.prev=NO()}}});var $Xt=p(()=>{LXt()});var FXt=p(()=>{Zw();h0e()});var jXt=p(()=>{FXt()});var qXt=p(()=>{});var BXt=p(()=>{qXt()});var VUe=p(()=>{h0e();$Xt();jXt();Zw();BXt();d0e()});var g0e=p(()=>{qM();_1();XJt();VUe()});function UXt(t,e){let r=t.cursorRow,n=t.cursorCol,i=t.viewportRows,s=t.getScrollbackAnsi(e);if(s.length===0)return VXt;let o=s.split(`
276
276
  `),a=Math.min(o.length,r+1),c=o.slice(0,a),l=c.slice(-i).map(b=>b.replace(/\s+$/,"")),u=0;for(;l.length>1&&l[0]==="";)l.shift(),u++;let d=l,f=c.length-d.length,h=r-f,m=Math.max(1,Math.min(h+1,d.length+1)),g=h>=0&&h<d.length?`\x1B[${m};${n+1}H\x1B[K`:`\x1B[${m};${n+1}H`,_=d.map((b,w)=>`\x1B[${w+1};1H${b}\x1B[K`).join("");return VXt+_+g}var VXt,HXt=p(()=>{VXt="\x1B[0m\x1B[H\x1B[2J\x1B[3J"});var Xti,v0e,UUe=p(()=>{g0e();HXt();Xti=5e3,v0e=class{constructor(e,r){this.queryService=e,this.messages$=r}handleData(e,r){let n=this.queryService.sessionMap()[e];if(!n){console.warn(`[PtyDataHandler] output dropped: session missing in sessionMap sessionId=${e} dataLen=${r.length}`);return}this.updateOutputBuffer(n,r),this.messages$.next({type:"session:server:pty-manager:session-data",sessionId:e,data:r})}handleExit(e,r,n){this.processExit(e,r,n)}destroy(){}processExit(e,r,n){let i=this.queryService.sessionMap()[e];i&&(i.status="terminated",this.queryService.removeSession(e),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:e,exitCode:r,signal:n}))}updateOutputBuffer(e,r){this.ensureGrid(e).feed(this.augmentClearWithScrollback(r))}augmentClearWithScrollback(e){return e.replace(/(?<!\x1b\[3J)\x1b\[2J(?!\x1b\[3J)/g,"\x1B[3J\x1B[2J")}ensureGrid(e){let r=e.grid;if(r)return r;let n=new tK;return e.grid=n,Object.defineProperty(e,"outputBuffer",{get(){return UXt(n,Xti)},set(i){},enumerable:!0,configurable:!0}),n}}});import{existsSync as eri,realpathSync as tri}from"fs";import HUe from"path";function WXt(){let t=process.argv[1];if(t)try{let e=HUe.dirname(tri(t)),r=HUe.join(e,"tmux-shim");return eri(HUe.join(r,"tmux"))?r:void 0}catch{return}}var WUe=p(()=>{});function GXt(){return E(this,void 0,void 0,function*(){return(yield import("node-pty")).spawn})}var zXt=p(()=>{ce()});function KXt(t){var e;let r=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.parentEnv),(e=t.optionsEnv)!==null&&e!==void 0?e:{}),{PATH:[t.shim,t.systemPath].filter(Boolean).join(":"),TERM:"xterm-256color",COLORTERM:"truecolor",FORCE_COLOR:"1",PLANX_SESSION_NAME:t.name,PLANX_SESSION_ID:t.id}),t.parentId?{PLANX_PARENT_SESSION_ID:t.parentId}:{}),{PLANX_SERVER_ID:t.serverId,PLANX_SERVER_NAME:t.serverName}),t.shim?{PLANX_TMUX_SHIM_DIR:t.shim}:{}),t.transportPortFile?{PLANX_TRANSPORT_PORT_FILE:t.transportPortFile}:{});return delete r.TMUX,delete r.TMUX_PANE,t.transportPortFile||delete r.PLANX_TRANSPORT_PORT_FILE,r}var YXt=p(()=>{});var QXt=p(()=>{YXt()});import rri from"os";var JXt,nri,iri,sri,y0e,GUe=p(()=>{ce();JXt=Ie(at());lf();UUe();WUe();zXt();QXt();nri=500,iri=500,sri=25,y0e=class{constructor(e,r,n=Hw,i=nUe){this.config=e,this.queryService=r,this.escalateKillFn=n,this.resolvePgidFn=i,this.ptyMap=new Map,this.exitedSessions=new Set,this.messages$=new JXt.ReplaySubject(50),this._shimResolved=!1,this.dataHandler=new v0e(this.queryService,this.messages$)}ensureGrid(e){return this.dataHandler.ensureGrid(e)}get shimDir(){return this._shimResolved||(this._shimDir=WXt(),this._shimResolved=!0),this._shimDir}createSession(e){return E(this,void 0,void 0,function*(){var r;if(this.queryService.sessionMap()[e.id])throw new Error(`Session already exists: ${e.id}`);if(e.parentId&&!this.queryService.getSession(e.parentId))throw new Error(`Parent session not found: ${e.parentId}`);let n=(r=this.config.shell)!==null&&r!==void 0?r:rri.platform()==="win32"?"powershell.exe":"/bin/zsh",i=e.command?["-c",e.command]:["-i","-l"],s={id:e.id,name:e.name,parentId:e.parentId,cwd:e.cwd,env:e.env,createdAt:new Date,lastAccessedAt:new Date,updatedAt:new Date,status:"active",command:e.command||n};this.queryService.updateSession(s);let o=this.queryService.resolveEnv(s),a=this.queryService.resolveCwd(s);try{console.error(`DIAG_SPAWNPTY_BEFORE id=${e.id} shell=${n} ts=${Date.now()}`)}catch{}let c=yield this.spawnPty(e.id,e.name,n,i,{cwd:a,env:o});try{console.error(`DIAG_SPAWNPTY_AFTER pid=${JSON.stringify(c.pid)} pidType=${typeof c.pid} ptyKeys=${Object.keys(c).join(",").slice(0,200)} ts=${Date.now()}`)}catch{}s.pid=c.pid;try{console.error(`DIAG_SPAWNPTY_ASSIGNED session.pid=${JSON.stringify(s.pid)} session.status=${JSON.stringify(s.status)} sessionKeys=${Object.keys(s).join(",")} ts=${Date.now()}`)}catch{}return this.queryService.updateSession(s),this.ptyMap.set(e.id,c),this.messages$.next({type:"session:server:pty-manager:session-created",sessionId:e.id,parentSessionId:e.parentId}),s})}spawnPty(e,r,n,i,s){return E(this,void 0,void 0,function*(){var o,a,c,l;let u=(o=this.queryService.getSession(e))===null||o===void 0?void 0:o.parentId,d=this.shimDir,f=yield GXt(),h=KXt({parentEnv:(a=this.config.parentEnv)!==null&&a!==void 0?a:{},optionsEnv:s?.env,shim:d,systemPath:(c=this.config.systemPath)!==null&&c!==void 0?c:"",id:e,name:r,parentId:u,serverId:this.config.serverId,serverName:this.config.serverName,transportPortFile:this.config.transportPortFile}),m=f(n,i,{name:"xterm-256color",cols:80,rows:30,cwd:(l=s?.cwd)!==null&&l!==void 0?l:process.cwd(),env:h});m.onData(g=>this.dataHandler.handleData(e,g)),m.onExit(({exitCode:g,signal:_})=>{this.exitedSessions.add(e),this.dataHandler.handleExit(e,g??-1,_??0)});let y=this.queryService.getSession(e);return y&&(y.promptBootstrapped=!0),setTimeout(()=>{try{m.write(`
277
277
  `)}catch{}},100),m})}destroySession(e){return E(this,void 0,void 0,function*(){for(let n of this.queryService.getChildSessions(e))yield this.destroySession(n.id);let r=this.ptyMap.get(e);if(r?.pid&&!this.exitedSessions.has(e)){let n=this.resolvePgidFn(r.pid)===r.pid;yield this.escalateKillFn(r.pid,{killFn:(i,s)=>process.kill(n?-i:i,s),termTimeoutMs:nri,killTimeoutMs:iri,pollMs:sri})}this.queryService.removeSession(e),this.ptyMap.delete(e),this.exitedSessions.delete(e),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:e})})}destroyAllSessions(){return E(this,void 0,void 0,function*(){let e=Object.keys(this.queryService.sessionMap()),r=0,n=[];for(let i of e)try{yield this.destroySession(i),r++}catch(s){n.push(`${i}: ${s.message}`)}return{deletedCount:r,errors:n}})}}});var ZXt,_0e,zUe=p(()=>{ZXt="\0@machina/silent\0",_0e=class{constructor(e){this.queryService=e}attach(e,r){var n,i;let s=this.queryService.getSession(e);if(!s)throw new Error(`session(${e}) not found.`);s.lastAccessedAt=new Date,s.status="active";let o=r.get(e);return!s.promptBootstrapped&&((i=(n=s.outputBuffer)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)<50&&o&&(s.promptBootstrapped=!0,setTimeout(()=>o.write(`
278
- `),100)),s}input(e,r,n){let i=this.queryService.getSession(e);if(!i)throw new Error("Session not found");let s=n.get(e);if(r&&!s&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${e} knownPtyIds=${[...n.keys()].join(",")}`),r&&s){if(r.startsWith(ZXt)){let o=r.slice(ZXt.length);s.write(`\x1B[8m${o}\x1B[0m\x1B[2K\r`)}else s.write(r);i.lastAccessedAt=new Date}}resize(e,r,n,i){let s=this.queryService.getSession(e);if(!s)throw new Error("Session not found");let o=i.get(e);if(!r||!n||!o||o.cols===r&&o.rows===n)return;o.resize(r,n);let a=s.grid;a&&a.setViewportSize(n,r)}renameSession(e,r){let n=this.queryService.sessionMap()[e];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${e}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession(Object.assign(Object.assign({},n),{name:r,updatedAt:new Date})),this.queryService.getSession(e)}}});var GM,KUe,b0e,YUe=p(()=>{ce();GM=Ie(at());lf();KUe=class{isProcessRunning(e){return fd(e)}isPtyValid(e){return!!(e.pid&&e.pid!==void 0)}},b0e=class{constructor(e,r,n=()=>[]){this.getSession=e,this.destroySession=r,this.listSessions=n,this.destroy$=new GM.ReplaySubject(1),this.validator=new KUe}start(){this.subscription=(0,GM.interval)(3e4).pipe((0,GM.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){var e;this.destroy$.next(),(e=this.subscription)===null||e===void 0||e.unsubscribe()}performHealthCheck(){return E(this,void 0,void 0,function*(){for(let e of this.listSessions())yield this.checkSessionHealth(e)})}checkSessionHealth(e){return E(this,void 0,void 0,function*(){return this.validator.isPtyValid(e)?this.validator.isProcessRunning(e.pid)?!0:(yield this.destroySession(e.id),!1):(yield this.onUnhealthySession(e.id),!1)})}onUnhealthySession(e){return E(this,void 0,void 0,function*(){let r=this.getSession(e);r&&(r.status="terminated",yield this.destroySession(e))})}}});var zM,w0e=p(()=>{ce();rUe();GUe();zUe();YUe();zM=class{constructor(e){this.queryService=new Nge,this.factoryService=new y0e(e,this.queryService),this.ioService=new _0e(this.queryService),this.healthCheckService=new b0e(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(e){return this.factoryService.createSession(e)}destroySession(e){return this.factoryService.destroySession(e)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(e){return this.queryService.getSession(e)}getChildSessions(e){return this.queryService.getChildSessions(e)}getPty(e){return this.factoryService.ptyMap.get(e)}getScrollback(e,r){let n=this.queryService.getSession(e);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(e){let r=this.queryService.getSession(e);return r?this.factoryService.ensureGrid(r):null}attach(e){return this.ioService.attach(e,this.factoryService.ptyMap)}input(e,r){this.ioService.input(e,r,this.factoryService.ptyMap)}resize(e,r,n){this.ioService.resize(e,r,n,this.factoryService.ptyMap)}renameSession(e,r){let n=this.ioService.renameSession(e,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:e,name:r}),n}start(){this.healthCheckService.start()}stop(){return E(this,void 0,void 0,function*(){this.healthCheckService.stop(),yield this.factoryService.destroyAllSessions()})}}});var XXt={};fr(XXt,{readSessionEnvironment:()=>z0});import ori from"os";function z0(){var t,e,r,n,i;return{serverId:(t=process.env.PLANX_SERVER_ID)!==null&&t!==void 0?t:"local",serverName:(e=process.env.PLANX_SERVER_NAME)!==null&&e!==void 0?e:"local",shell:(r=process.env.SHELL)!==null&&r!==void 0?r:ori.platform()==="win32"?"powershell.exe":"/bin/zsh",systemPath:(n=process.env.PATH)!==null&&n!==void 0?n:"",parentEnv:process.env,transportPortFile:(i=process.env.PLANX_TRANSPORT_PORT_FILE)!==null&&i!==void 0?i:null,sessionPort:(()=>{var s;let o=parseInt((s=process.env.PLANX_SESSION_PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)?null:o})(),wtPort:(()=>{var s;let o=parseInt((s=process.env.PLANX_SESSION_WT_PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)||o<=0?null:o})(),port:(()=>{var s;let o=parseInt((s=process.env.PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)||o<=0?null:o})()}}var kO=p(()=>{});var rK,QUe,qc,S0e=p(()=>{ce();de();rK=Ie(at());w0e();kO();de();QUe=new Ve("SESSION_SERVER_CONFIG",{providedIn:"root",factory:()=>()=>{var t;let e=z0();return{serverId:e.serverId,serverName:e.serverName,shell:e.shell,systemPath:e.systemPath,parentEnv:e.parentEnv,transportPortFile:(t=e.transportPortFile)!==null&&t!==void 0?t:void 0}}}),qc=class{constructor(){this.getConfig=q(QUe),this.messageSubscriptions=[],this.message$=new rK.Subject}get manager(){return this._manager||(this._manager=new zM(this.getConfig()),this.messageSubscriptions.push(this._manager.messages$.pipe((0,rK.filter)(e=>e.type==="session:server:pty-manager:session-data")).subscribe(e=>{this.message$.next({type:"[session.server.pty] data",sessionId:e.sessionId,data:e.data})})),this.messageSubscriptions.push(this._manager.messages$.pipe((0,rK.filter)(e=>e.type==="session:server:pty-manager:session-exit")).subscribe(e=>{this.message$.next({type:"[session.server.pty] exit",sessionId:e.sessionId,exitCode:e.exitCode,signal:e.signal})}))),this._manager}start(){return E(this,void 0,void 0,function*(){this.manager.start()})}stop(){return E(this,void 0,void 0,function*(){this._manager&&(yield this._manager.stop());for(let e of this.messageSubscriptions)e.unsubscribe();this.messageSubscriptions=[]})}};qc.\u0275fac=function(e){return new(e||qc)};qc.\u0275prov=le({token:qc,factory:qc.\u0275fac,providedIn:"root"})});function nK(t,e){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),{allowPeersPublicKeys:e.allowPeersPublicKeys}),e.identity?{identity:e.identity}:{}),e.name!==void 0?{name:e.name}:{}),e.roles?{roles:e.roles}:{}),e.allowPeersMode!==void 0?{allowPeersMode:e.allowPeersMode}:{})}function Xw(t,e){return E(this,arguments,void 0,function*(r,n,i=[],s){let o=r.getKeyPair(),a=r.getPeerId(),c=yield n.toUuid(o.publicKey),l={};l[c]=o.publicKey;let u={};for(let d of i){if(!d)continue;let f=yield n.toUuid(d);l[f]=d;let h=s?.[d];h&&(u[f]=h)}return Object.assign({peerId:a,publicKey:o.publicKey,signalingId:c,privateKey:o.privateKey,peers:l},s?{peersMeta:u}:{})})}var eer=p(()=>{ce()});var ter=p(()=>{eer()});var rer=p(()=>{});var JUe=p(()=>{rer()});function RO(t){return E(this,void 0,void 0,function*(){let e=new TextEncoder().encode(t),r=yield crypto.subtle.digest("SHA-256",e),n=new Uint8Array(r).slice(0,16);n[0]=32,n[1]=1,n[2]=0,n[3]=42,n[6]=n[6]&15|128,n[8]=n[8]&63|128;let i=Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("");return[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20,32)].join("-")})}function ZUe(t){let e=t.replace(/-/g,"");if(e.length!==32)throw new Error(`peerIdToBytes: invalid peerId format "${t}" (expected 32 hex chars)`);let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}var ner=p(()=>{ce();JUe()});var ier,ser=p(()=>{ier={maxAgeMs:3e4,now:()=>Date.now()}});var iK=p(()=>{ner();ser();JUe()});var oer=p(()=>{});var aer=p(()=>{oer()});var cer=p(()=>{ter();iK();aer()});var ler=p(()=>{cer()});function uer(t){return new ReadableStream({start(e){e.enqueue(t),e.close()}})}function der(t){return E(this,void 0,void 0,function*(){return new Uint8Array(yield new Response(t).arrayBuffer())})}function fer(t){return E(this,void 0,void 0,function*(){let e=new CompressionStream("deflate-raw");return der(uer(t).pipeThrough(e))})}function per(t){return E(this,void 0,void 0,function*(){let e=new DecompressionStream("deflate-raw");return der(uer(t).pipeThrough(e))})}var her=p(()=>{ce()});var mer=p(()=>{her()});var zl,ger=p(()=>{ce();iK();de();zl=class{getPeerId(e){return E(this,void 0,void 0,function*(){return RO(e.publicKey)})}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};zl.\u0275fac=function(e){return new(e||zl)};zl.\u0275prov=le({token:zl,factory:zl.\u0275fac})});var sK=p(()=>{ger()});var Ex,ver=p(()=>{ce();sK();de();Ex=class extends zl{constructor(){super(...arguments),this.counter=0}generateKeyPair(){return E(this,void 0,void 0,function*(){return this.counter++,{publicKey:`mockPublicKey_${this.counter}_${Date.now()}`,privateKey:`mockPrivateKey_${this.counter}_${Date.now()}`,algorithm:"P-256",createdAt:new Date}})}};Ex.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Ex)))(r||Ex)}})();Ex.\u0275prov=le({token:Ex,factory:Ex.\u0275fac})});var yer=p(()=>{ver()});var E0e=p(()=>{sK();yer()});var Bc,_er=p(()=>{ce();de();Bc=class{encrypt(e,r){return E(this,void 0,void 0,function*(){return this.encryptBytes(new TextEncoder().encode(e),r)})}decrypt(e,r,n){return E(this,void 0,void 0,function*(){return new TextDecoder().decode(yield this.decryptBytes(e,r,n))})}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Bc.\u0275fac=function(e){return new(e||Bc)};Bc.\u0275prov=le({token:Bc,factory:Bc.\u0275fac})});var KM=p(()=>{_er()});var Ix,ber=p(()=>{ce();KM();de();Ix=class extends Bc{deriveSharedKey(e,r){return E(this,void 0,void 0,function*(){let n=this.base64ToBuffer(e),i=yield crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),s=this.base64ToBuffer(r),o=yield crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]),a=yield crypto.subtle.deriveBits({name:"ECDH",public:o},i,256),c=yield crypto.subtle.digest("SHA-256",a);return crypto.subtle.importKey("raw",c,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])})}encryptBytes(e,r){return E(this,void 0,void 0,function*(){let n=crypto.getRandomValues(new Uint8Array(12)),i=yield crypto.subtle.encrypt({name:"AES-GCM",iv:n},r,e);return{encrypted:this.bufferToBase64(i),iv:this.bufferToBase64(n.buffer)}})}decryptBytes(e,r,n){return E(this,void 0,void 0,function*(){let i=yield crypto.subtle.decrypt({name:"AES-GCM",iv:this.base64ToBuffer(r)},n,this.base64ToBuffer(e));return new Uint8Array(i)})}};Ix.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Ix)))(r||Ix)}})();Ix.\u0275prov=le({token:Ix,factory:Ix.\u0275fac})});var XUe=p(()=>{ber()});var Tx,wer=p(()=>{ce();KM();de();Tx=class extends Bc{deriveSharedKey(e,r){return E(this,void 0,void 0,function*(){return{}})}encryptBytes(e,r){return E(this,void 0,void 0,function*(){let n="";for(let i of e)n+=String.fromCharCode(i);return{encrypted:btoa(n),iv:btoa("mock-iv-12byte")}})}decryptBytes(e,r,n){return E(this,void 0,void 0,function*(){let i=atob(e);return Uint8Array.from(i,s=>s.charCodeAt(0))})}};Tx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Tx)))(r||Tx)}})();Tx.\u0275prov=le({token:Tx,factory:Tx.\u0275fac})});var Ser=p(()=>{wer()});var eHe=p(()=>{KM();XUe();Ser()});function YM(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new Error(`Invalid UUID 8-4-4-4-12: ${t}`);let e=t.replace(/-/g,"");return[0,4,8,12,16,20,24,28].map(r=>e.slice(r,r+4)).join(":")}function Eer(t){if(!/^[0-9a-f]{1,4}(:[0-9a-f]{1,4}){7}$/.test(t))throw new Error(`Invalid IPv6 literal (8 group form required): ${t}`);let r=t.split(":").map(n=>n.padStart(4,"0")).join("");return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}var yc,Ier=p(()=>{ce();de();yc=class{sha256(e){return E(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")})}toUuid(e){return E(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n).slice(0,16);i[0]=32,i[1]=1,i[2]=0,i[3]=42,i[6]=i[6]&15|128,i[8]=i[8]&63|128;let s=Array.from(i).map(o=>o.toString(16).padStart(2,"0")).join("");return[s.slice(0,8),s.slice(8,12),s.slice(12,16),s.slice(16,20),s.slice(20,32)].join("-")})}};yc.\u0275fac=function(e){return new(e||yc)};yc.\u0275prov=le({token:yc,factory:yc.\u0275fac,providedIn:"root"})});var QM=p(()=>{Ier()});var K0,Ter=p(()=>{QM();de();K0=class extends yc{};K0.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(K0)))(r||K0)}})();K0.\u0275prov=le({token:K0,factory:K0.\u0275fac})});var oK=p(()=>{Ter()});var xer=p(()=>{QM();oK()});var nc,Cer=p(()=>{ce();iK();de();nc=class{canonicalStringify(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(i=>this.canonicalStringify(i)).join(",")+"]":"{"+Object.keys(e).sort().filter(i=>e[i]!==void 0).map(i=>JSON.stringify(i)+":"+this.canonicalStringify(e[i])).join(",")+"}"}sign(e,r){return E(this,void 0,void 0,function*(){let n=this.canonicalStringify(e),i=yield this.createSignature(n,r);return{payload:e,signature:i}})}verify(e,r){return E(this,void 0,void 0,function*(){try{let n=this.canonicalStringify(e.payload);return(yield this.verifySignature(n,e.signature,r))?{valid:!0,verifiedBy:r}:{valid:!1,error:"Signature verification failed"}}catch(n){return{valid:!1,error:`Verification error: ${n}`}}})}validateTimestamp(e,r=ier){let i=(r.now?r.now():Date.now())-e;return i>=0&&i<=r.maxAgeMs}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};nc.\u0275fac=function(e){return new(e||nc)};nc.\u0275prov=le({token:nc,factory:nc.\u0275fac})});var JM=p(()=>{Cer()});var tHe,xx,Aer=p(()=>{ce();JM();de();tHe="|||",xx=class extends nc{createSignature(e,r){return E(this,void 0,void 0,function*(){return btoa(`mock_sig${tHe}${e}${tHe}${r.substring(0,10)}`)})}verifySignature(e,r,n){return E(this,void 0,void 0,function*(){try{let s=atob(r).split(tHe);return s.length===3&&s[0]==="mock_sig"&&s[1]===e}catch{return!1}})}};xx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(xx)))(r||xx)}})();xx.\u0275prov=le({token:xx,factory:xx.\u0275fac})});var Oer=p(()=>{Aer()});var rHe=p(()=>{JM();Oer()});var Kl,Per=p(()=>{de();Kl=class{};Kl.\u0275fac=function(e){return new(e||Kl)};Kl.\u0275prov=le({token:Kl,factory:Kl.\u0275fac})});var aK=p(()=>{Per()});var Cx,Der=p(()=>{ce();aK();de();Cx=class extends Kl{constructor(){super(...arguments),this.storage=null,this.backups=[]}save(e){return E(this,void 0,void 0,function*(){this.storage=Object.assign({},e)})}load(){return E(this,void 0,void 0,function*(){return this.storage?Object.assign({},this.storage):null})}exists(){return E(this,void 0,void 0,function*(){return this.storage!==null})}delete(){return E(this,void 0,void 0,function*(){this.storage=null})}saveBackup(e,r){return E(this,void 0,void 0,function*(){this.backups.push({keyPair:Object.assign({},e),rotatedAt:r})})}loadBackups(){return E(this,void 0,void 0,function*(){return this.backups.map(e=>({keyPair:Object.assign({},e.keyPair),rotatedAt:e.rotatedAt}))})}cleanupBackups(e){return E(this,void 0,void 0,function*(){let r=Date.now()-e;this.backups=this.backups.filter(n=>n.rotatedAt>r)})}};Cx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Cx)))(r||Cx)}})();Cx.\u0275prov=le({token:Cx,factory:Cx.\u0275fac})});var Ner=p(()=>{Der()});var I0e=p(()=>{aK();Ner()});var ni,ker=p(()=>{ce();de();iK();I0e();E0e();de();ni=class{constructor(){this.keyGenerator=q(zl),this.storage=q(Kl),this.keyPair=null,this.peerId=null,this._initialized=ps(!1)}initialize(){return E(this,void 0,void 0,function*(){if(this._initialized())return;let e=yield this.storage.load();e?this.keyPair=e:(this.keyPair=yield this.keyGenerator.generateKeyPair(),yield this.storage.save(this.keyPair)),this.peerId=yield RO(this.keyPair.publicKey),this._initialized.set(!0)})}getKeyPair(){if(!this.keyPair)throw new Error("KeyManager not initialized");return this.keyPair}getPeerId(){if(!this.peerId)throw new Error("KeyManager not initialized");return this.peerId}isInitialized(){return this._initialized()}waitForInitialization(){return E(this,arguments,void 0,function*(e=1e4){if(this._initialized())return;let r=Date.now(),n=50;return new Promise((i,s)=>{let o=()=>{if(this._initialized()){i();return}if(Date.now()-r>e){s(new Error("KeyManager initialization timeout"));return}setTimeout(o,n)};o()})})}reset(){return E(this,void 0,void 0,function*(){yield this.storage.delete(),this.keyPair=null,this.peerId=null,this._initialized.set(!1),yield this.initialize()})}rotateKeyPair(){return E(this,void 0,void 0,function*(){if(!this.keyPair)throw new Error("KeyManager not initialized");yield this.storage.saveBackup(this.keyPair,Date.now());let e=yield this.keyGenerator.generateKeyPair();return yield this.storage.save(e),this.keyPair=e,this.peerId=yield RO(e.publicKey),e})}getBackupKeyPairs(){return E(this,void 0,void 0,function*(){return this.storage.loadBackups()})}cleanupOldBackups(){return E(this,arguments,void 0,function*(e=10080*60*1e3){yield this.storage.cleanupBackups(e)})}};ni.\u0275fac=function(e){return new(e||ni)};ni.\u0275prov=le({token:ni,factory:ni.\u0275fac,providedIn:"root"})});var Rer=p(()=>{ker()});var Mer=p(()=>{I0e();E0e();eHe();QM();oK();rHe()});var Ler=p(()=>{Mer()});var nHe=p(()=>{mer();E0e();eHe();xer();rHe();Rer();Ler()});var $er=p(()=>{I0e()});function w1(t){return[{provide:ZM,useFactory:t,multi:!0}]}var ZM,Fer=p(()=>{de();ZM=new Ve("SIGNALING_CHANNELS")});function S1(t){return typeof t=="object"&&t!==null&&"encrypted"in t&&"iv"in t&&typeof t.encrypted=="string"&&typeof t.iv=="string"}var jer=p(()=>{});var qer=p(()=>{});var eS,Ber=p(()=>{de();eS=new Ve("SIGNALING_MESSAGE_SENDER")});function Ver(t){return"lost"in t&&t.lost===!0}var Uer=p(()=>{});var Her=p(()=>{Fer();jer();qer();Ber();Uer()});var Y0,Wer=p(()=>{ce();de();Rt();QM();de();Y0=class{constructor(){this.logger=qe("SignalingIdService"),this.hashAdapter=q(yc)}generateId(e){return E(this,void 0,void 0,function*(){return yield this.hashAdapter.toUuid(e)})}findPublicKeyByHash(e,r){return E(this,void 0,void 0,function*(){for(let n of r)if((yield this.generateId(n))===e)return n;return null})}isHashedId(e){return/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e)}};Y0.\u0275fac=function(e){return new(e||Y0)};Y0.\u0275prov=le({token:Y0,factory:Y0.\u0275fac,providedIn:"root"})});var Ger=p(()=>{Wer()});var T0e,MO,zer=p(()=>{T0e={prod:{hasuraUrl:"https://graphql-prod.machina.at/v1/graphql",apiNextUrl:"https://api.machina.at",signalingUrl:"https://signaling.machina.at",firebaseDatabaseUrl:"https://x-x-machina-default-rtdb.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"},stg:{hasuraUrl:"https://graphql-stg.machina.at/v1/graphql",apiNextUrl:"https://api.stg.machina.at",signalingUrl:"https://signaling-stg.machina.at",firebaseDatabaseUrl:"https://x-x-machina-stg.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://x-x-machina-invoice.web.app"}},MO={PLANX_GRAPHQL_URL:T0e.prod.hasuraUrl,PLANX_CLOUD_API_URL:T0e.prod.apiNextUrl,PLANX_SIGNALING_URL:T0e.prod.signalingUrl,PLANX_FIREBASE_DATABASE_URL:T0e.prod.firebaseDatabaseUrl,PLANX_SIGNALING_BACKEND:"",PLANX_NOSTR_RELAYS:"wss://nos.lol,wss://relay.snort.social"}});var x0e=p(()=>{zer()});var tS,Ker=p(()=>{de();tS=new Ve("TRPC_CLIENT")});var LO,Yer=p(()=>{LO=class t{static in(e,r){return new t(e,r)}constructor(e,r){var n;this.controller=new AbortController,this.timer=null,this.now=(n=r?.now)!==null&&n!==void 0?n:(()=>Date.now()),this.at=this.now()+Math.max(0,e);let i=()=>this.abort();e<=0?i():this.timer=setTimeout(i,e),r?.parent&&(r.parent.aborted?i():r.parent.addEventListener("abort",i,{once:!0}))}get signal(){return this.controller.signal}remaining(){return Math.max(0,this.at-this.now())}expired(){return this.remaining()===0}child(e){return new t(Math.min(e,this.remaining()),{now:this.now,parent:this.signal})}split(e){let r=Math.min(1,Math.max(0,e));return this.child(Math.floor(this.remaining()*r))}abort(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.controller.signal.aborted||this.controller.abort()}dispose(){this.abort()}}});var Qer=p(()=>{Ker();Yer()});var ari,cri,lri,uri,dri,Pr,Jer=p(()=>{ari={name:"port-forward",prefix:"pf:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`pf:${t}`,parseLabel:t=>t.startsWith("pf:")?t.slice(3):null},cri={name:"heartbeat",prefix:"__heartbeat__",profile:"heartbeat",defaultCap:1,defaultBackpressureProfile:"control",buildLabel:()=>"__heartbeat__",parseLabel:t=>t==="__heartbeat__"?"":null},lri={name:"l7-http",prefix:"l7:http:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`l7:http:${t}`,parseLabel:t=>t.startsWith("l7:http:")?t.slice(8):null},uri={name:"l7-datagram",prefix:"l7:dg:",profile:"unreliable",defaultCap:8,defaultBackpressureProfile:"terminal",buildLabel:t=>`l7:dg:${t}`,parseLabel:t=>t.startsWith("l7:dg:")?t.slice(6):null},dri={name:"l7-qpack",prefix:"l7:qpack:",profile:"reliable-ordered",defaultCap:8,defaultBackpressureProfile:"control",buildLabel:t=>`l7:qpack:${t}`,parseLabel:t=>t.startsWith("l7:qpack:")?t.slice(9):null},Pr={portForward:ari,heartbeat:cri,l7Http:lri,l7Dg:uri,l7Qpack:dri}});var Zer=p(()=>{Jer()});function sHe(t){return function(e,r,n){let i=Reflect.getMetadata(iHe,e.constructor)||[];return i.push({messageType:t,methodName:r}),Reflect.defineMetadata(iHe,i,e.constructor),n}}function Xer(t){return Reflect.getMetadata(iHe,t.constructor)||[]}var iHe,etr=p(()=>{x8();iHe=Symbol("messageHandlers")});var oHe=p(()=>{etr()});var C0e,XM,ttr=p(()=>{ce();Rt();oHe();C0e=class extends Error{constructor(e){super(`No handler found for message type: ${e}`),this.messageType=e,this.code="HANDLER_NOT_FOUND",this.name="HandlerNotFoundError"}},XM=class{constructor(){this.logger=qe(this.constructor.name)}handle(e,r){return E(this,void 0,void 0,function*(){let i=Xer(e).find(s=>s.messageType===r.type);if(i){let s=e[i.methodName];typeof s=="function"&&(yield s.call(e,r))}else throw this.logger.warn("No handler found for message type:",r.type),new C0e(r.type)})}}});var rtr=p(()=>{oHe();ttr()});function aHe(t){return t.replace(/^http(s?):\/\//,"ws$1://")}var ntr=p(()=>{});function A0e(t,e){let r=YM(t),n=e.replace(/^\//,"");return`https://[${r}]:10/${n}`}var itr=p(()=>{nHe()});var cHe=p(()=>{ntr();itr()});var yr=p(()=>{ler();nHe();$er();Her();Ger();x0e();Qer();Zer();rtr();cHe()});var O0e,str=p(()=>{yr();yr();O0e=class extends XM{}});var otr=p(()=>{str()});import*as Ax from"node:fs";import*as atr from"node:path";var Q0,lHe=p(()=>{Rt();de();Q0=class t{constructor(){this.logger=qe("SessionOutputRecorderService"),this.fd=null,this.buffer=[],this.flushTimer=null,this.enabled=!1}start(e){this.enabled=!0;let r=t.DIR;Ax.mkdirSync(r,{recursive:!0});let n=`${e.slice(0,16)}_${Date.now()}.jsonl`,i=atr.join(r,n);this.fd=Ax.openSync(i,"a"),this.flushTimer=setInterval(()=>this.flush(),t.FLUSH_INTERVAL_MS),this.logger.info("Recording started",{filepath:i})}record(e){if(!this.enabled)return;let r=JSON.stringify(Object.assign({ts:performance.now(),iso:new Date().toISOString()},e));this.buffer.push(r)}flush(){if(this.buffer.length===0||this.fd===null)return;let e=this.buffer.join(`
278
+ `),100)),s}input(e,r,n){let i=this.queryService.getSession(e);if(!i)throw new Error("Session not found");let s=n.get(e);if(r&&!s&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${e} knownPtyIds=${[...n.keys()].join(",")}`),r&&s){if(r.startsWith(ZXt)){let o=r.slice(ZXt.length);s.write(`\x1B[8m${o}\x1B[0m\x1B[2K\r`)}else s.write(r);i.lastAccessedAt=new Date}}resize(e,r,n,i){let s=this.queryService.getSession(e);if(!s)throw new Error("Session not found");let o=i.get(e);if(!r||!n||!o||o.cols===r&&o.rows===n)return;o.resize(r,n);let a=s.grid;a&&a.setViewportSize(n,r)}renameSession(e,r){let n=this.queryService.sessionMap()[e];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${e}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession(Object.assign(Object.assign({},n),{name:r,updatedAt:new Date})),this.queryService.getSession(e)}}});var GM,KUe,b0e,YUe=p(()=>{ce();GM=Ie(at());lf();KUe=class{isProcessRunning(e){return fd(e)}isPtyValid(e){return!!(e.pid&&e.pid!==void 0)}},b0e=class{constructor(e,r,n=()=>[]){this.getSession=e,this.destroySession=r,this.listSessions=n,this.destroy$=new GM.ReplaySubject(1),this.validator=new KUe}start(){this.subscription=(0,GM.interval)(3e4).pipe((0,GM.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){var e;this.destroy$.next(),(e=this.subscription)===null||e===void 0||e.unsubscribe()}performHealthCheck(){return E(this,void 0,void 0,function*(){for(let e of this.listSessions())yield this.checkSessionHealth(e)})}checkSessionHealth(e){return E(this,void 0,void 0,function*(){return this.validator.isPtyValid(e)?this.validator.isProcessRunning(e.pid)?!0:(yield this.destroySession(e.id),!1):(yield this.onUnhealthySession(e.id),!1)})}onUnhealthySession(e){return E(this,void 0,void 0,function*(){let r=this.getSession(e);r&&(r.status="terminated",yield this.destroySession(e))})}}});var zM,w0e=p(()=>{ce();rUe();GUe();zUe();YUe();zM=class{constructor(e){this.queryService=new Nge,this.factoryService=new y0e(e,this.queryService),this.ioService=new _0e(this.queryService),this.healthCheckService=new b0e(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(e){return this.factoryService.createSession(e)}destroySession(e){return this.factoryService.destroySession(e)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(e){return this.queryService.getSession(e)}getChildSessions(e){return this.queryService.getChildSessions(e)}getPty(e){return this.factoryService.ptyMap.get(e)}getScrollback(e,r){let n=this.queryService.getSession(e);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(e){let r=this.queryService.getSession(e);return r?this.factoryService.ensureGrid(r):null}attach(e){return this.ioService.attach(e,this.factoryService.ptyMap)}input(e,r){this.ioService.input(e,r,this.factoryService.ptyMap)}resize(e,r,n){this.ioService.resize(e,r,n,this.factoryService.ptyMap)}renameSession(e,r){let n=this.ioService.renameSession(e,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:e,name:r}),n}start(){this.healthCheckService.start()}stop(){return E(this,void 0,void 0,function*(){this.healthCheckService.stop(),yield this.factoryService.destroyAllSessions()})}}});var XXt={};fr(XXt,{readSessionEnvironment:()=>z0});import ori from"os";function z0(){var t,e,r,n,i;return{serverId:(t=process.env.PLANX_SERVER_ID)!==null&&t!==void 0?t:"local",serverName:(e=process.env.PLANX_SERVER_NAME)!==null&&e!==void 0?e:"local",shell:(r=process.env.SHELL)!==null&&r!==void 0?r:ori.platform()==="win32"?"powershell.exe":"/bin/zsh",systemPath:(n=process.env.PATH)!==null&&n!==void 0?n:"",parentEnv:process.env,transportPortFile:(i=process.env.PLANX_TRANSPORT_PORT_FILE)!==null&&i!==void 0?i:null,sessionPort:(()=>{var s;let o=parseInt((s=process.env.PLANX_SESSION_PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)?null:o})(),wtPort:(()=>{var s;let o=parseInt((s=process.env.PLANX_SESSION_WT_PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)||o<=0?null:o})(),port:(()=>{var s;let o=parseInt((s=process.env.PORT)!==null&&s!==void 0?s:"",10);return isNaN(o)||o<=0?null:o})()}}var kO=p(()=>{});var rK,QUe,qc,S0e=p(()=>{ce();de();rK=Ie(at());w0e();kO();de();QUe=new Ve("SESSION_SERVER_CONFIG",{providedIn:"root",factory:()=>()=>{var t;let e=z0();return{serverId:e.serverId,serverName:e.serverName,shell:e.shell,systemPath:e.systemPath,parentEnv:e.parentEnv,transportPortFile:(t=e.transportPortFile)!==null&&t!==void 0?t:void 0}}}),qc=class{constructor(){this.getConfig=q(QUe),this.messageSubscriptions=[],this.message$=new rK.Subject}get manager(){return this._manager||(this._manager=new zM(this.getConfig()),this.messageSubscriptions.push(this._manager.messages$.pipe((0,rK.filter)(e=>e.type==="session:server:pty-manager:session-data")).subscribe(e=>{this.message$.next({type:"[session.server.pty] data",sessionId:e.sessionId,data:e.data})})),this.messageSubscriptions.push(this._manager.messages$.pipe((0,rK.filter)(e=>e.type==="session:server:pty-manager:session-exit")).subscribe(e=>{this.message$.next({type:"[session.server.pty] exit",sessionId:e.sessionId,exitCode:e.exitCode,signal:e.signal})}))),this._manager}start(){return E(this,void 0,void 0,function*(){this.manager.start()})}stop(){return E(this,void 0,void 0,function*(){this._manager&&(yield this._manager.stop());for(let e of this.messageSubscriptions)e.unsubscribe();this.messageSubscriptions=[]})}};qc.\u0275fac=function(e){return new(e||qc)};qc.\u0275prov=le({token:qc,factory:qc.\u0275fac,providedIn:"root"})});function nK(t,e){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),{allowPeersPublicKeys:e.allowPeersPublicKeys}),e.identity?{identity:e.identity}:{}),e.name!==void 0?{name:e.name}:{}),e.roles?{roles:e.roles}:{}),e.allowPeersMode!==void 0?{allowPeersMode:e.allowPeersMode}:{})}function Xw(t,e){return E(this,arguments,void 0,function*(r,n,i=[],s){let o=r.getKeyPair(),a=r.getPeerId(),c=yield n.toUuid(o.publicKey),l={};l[c]=o.publicKey;let u={};for(let d of i){if(!d)continue;let f=yield n.toUuid(d);l[f]=d;let h=s?.[d];h&&(u[f]=h)}return Object.assign({peerId:a,publicKey:o.publicKey,signalingId:c,privateKey:o.privateKey,peers:l},s?{peersMeta:u}:{})})}var eer=p(()=>{ce()});var ter=p(()=>{eer()});var rer=p(()=>{});var JUe=p(()=>{rer()});function RO(t){return E(this,void 0,void 0,function*(){let e=new TextEncoder().encode(t),r=yield crypto.subtle.digest("SHA-256",e),n=new Uint8Array(r).slice(0,16);n[0]=32,n[1]=1,n[2]=0,n[3]=42,n[6]=n[6]&15|128,n[8]=n[8]&63|128;let i=Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("");return[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20,32)].join("-")})}function ZUe(t){let e=t.replace(/-/g,"");if(e.length!==32)throw new Error(`peerIdToBytes: invalid peerId format "${t}" (expected 32 hex chars)`);let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}var ner=p(()=>{ce();JUe()});var ier,ser=p(()=>{ier={maxAgeMs:3e4,now:()=>Date.now()}});var iK=p(()=>{ner();ser();JUe()});var oer=p(()=>{});var aer=p(()=>{oer()});var cer=p(()=>{ter();iK();aer()});var ler=p(()=>{cer()});function uer(t){return new ReadableStream({start(e){e.enqueue(t),e.close()}})}function der(t){return E(this,void 0,void 0,function*(){return new Uint8Array(yield new Response(t).arrayBuffer())})}function fer(t){return E(this,void 0,void 0,function*(){let e=new CompressionStream("deflate-raw");return der(uer(t).pipeThrough(e))})}function per(t){return E(this,void 0,void 0,function*(){let e=new DecompressionStream("deflate-raw");return der(uer(t).pipeThrough(e))})}var her=p(()=>{ce()});var mer=p(()=>{her()});var zl,ger=p(()=>{ce();iK();de();zl=class{getPeerId(e){return E(this,void 0,void 0,function*(){return RO(e.publicKey)})}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};zl.\u0275fac=function(e){return new(e||zl)};zl.\u0275prov=le({token:zl,factory:zl.\u0275fac})});var sK=p(()=>{ger()});var Ex,ver=p(()=>{ce();sK();de();Ex=class extends zl{constructor(){super(...arguments),this.counter=0}generateKeyPair(){return E(this,void 0,void 0,function*(){return this.counter++,{publicKey:`mockPublicKey_${this.counter}_${Date.now()}`,privateKey:`mockPrivateKey_${this.counter}_${Date.now()}`,algorithm:"P-256",createdAt:new Date}})}};Ex.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Ex)))(r||Ex)}})();Ex.\u0275prov=le({token:Ex,factory:Ex.\u0275fac})});var yer=p(()=>{ver()});var E0e=p(()=>{sK();yer()});var Bc,_er=p(()=>{ce();de();Bc=class{encrypt(e,r){return E(this,void 0,void 0,function*(){return this.encryptBytes(new TextEncoder().encode(e),r)})}decrypt(e,r,n){return E(this,void 0,void 0,function*(){return new TextDecoder().decode(yield this.decryptBytes(e,r,n))})}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};Bc.\u0275fac=function(e){return new(e||Bc)};Bc.\u0275prov=le({token:Bc,factory:Bc.\u0275fac})});var KM=p(()=>{_er()});var Ix,ber=p(()=>{ce();KM();de();Ix=class extends Bc{deriveSharedKey(e,r){return E(this,void 0,void 0,function*(){let n=this.base64ToBuffer(e),i=yield crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),s=this.base64ToBuffer(r),o=yield crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]),a=yield crypto.subtle.deriveBits({name:"ECDH",public:o},i,256),c=yield crypto.subtle.digest("SHA-256",a);return crypto.subtle.importKey("raw",c,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])})}encryptBytes(e,r){return E(this,void 0,void 0,function*(){let n=crypto.getRandomValues(new Uint8Array(12)),i=yield crypto.subtle.encrypt({name:"AES-GCM",iv:n},r,e);return{encrypted:this.bufferToBase64(i),iv:this.bufferToBase64(n.buffer)}})}decryptBytes(e,r,n){return E(this,void 0,void 0,function*(){let i=yield crypto.subtle.decrypt({name:"AES-GCM",iv:this.base64ToBuffer(r)},n,this.base64ToBuffer(e));return new Uint8Array(i)})}};Ix.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Ix)))(r||Ix)}})();Ix.\u0275prov=le({token:Ix,factory:Ix.\u0275fac})});var XUe=p(()=>{ber()});var Tx,wer=p(()=>{ce();KM();de();Tx=class extends Bc{deriveSharedKey(e,r){return E(this,void 0,void 0,function*(){return{}})}encryptBytes(e,r){return E(this,void 0,void 0,function*(){let n="";for(let i of e)n+=String.fromCharCode(i);return{encrypted:btoa(n),iv:btoa("mock-iv-12byte")}})}decryptBytes(e,r,n){return E(this,void 0,void 0,function*(){let i=atob(e);return Uint8Array.from(i,s=>s.charCodeAt(0))})}};Tx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Tx)))(r||Tx)}})();Tx.\u0275prov=le({token:Tx,factory:Tx.\u0275fac})});var Ser=p(()=>{wer()});var eHe=p(()=>{KM();XUe();Ser()});function YM(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new Error(`Invalid UUID 8-4-4-4-12: ${t}`);let e=t.replace(/-/g,"");return[0,4,8,12,16,20,24,28].map(r=>e.slice(r,r+4)).join(":")}function Eer(t){if(!/^[0-9a-f]{1,4}(:[0-9a-f]{1,4}){7}$/.test(t))throw new Error(`Invalid IPv6 literal (8 group form required): ${t}`);let r=t.split(":").map(n=>n.padStart(4,"0")).join("");return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")}var yc,Ier=p(()=>{ce();de();yc=class{sha256(e){return E(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")})}toUuid(e){return E(this,void 0,void 0,function*(){let r=new TextEncoder().encode(e),n=yield crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n).slice(0,16);i[0]=32,i[1]=1,i[2]=0,i[3]=42,i[6]=i[6]&15|128,i[8]=i[8]&63|128;let s=Array.from(i).map(o=>o.toString(16).padStart(2,"0")).join("");return[s.slice(0,8),s.slice(8,12),s.slice(12,16),s.slice(16,20),s.slice(20,32)].join("-")})}};yc.\u0275fac=function(e){return new(e||yc)};yc.\u0275prov=le({token:yc,factory:yc.\u0275fac,providedIn:"root"})});var QM=p(()=>{Ier()});var K0,Ter=p(()=>{QM();de();K0=class extends yc{};K0.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(K0)))(r||K0)}})();K0.\u0275prov=le({token:K0,factory:K0.\u0275fac})});var oK=p(()=>{Ter()});var xer=p(()=>{QM();oK()});var nc,Cer=p(()=>{ce();iK();de();nc=class{canonicalStringify(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(i=>this.canonicalStringify(i)).join(",")+"]":"{"+Object.keys(e).sort().filter(i=>e[i]!==void 0).map(i=>JSON.stringify(i)+":"+this.canonicalStringify(e[i])).join(",")+"}"}sign(e,r){return E(this,void 0,void 0,function*(){let n=this.canonicalStringify(e),i=yield this.createSignature(n,r);return{payload:e,signature:i}})}verify(e,r){return E(this,void 0,void 0,function*(){try{let n=this.canonicalStringify(e.payload);return(yield this.verifySignature(n,e.signature,r))?{valid:!0,verifiedBy:r}:{valid:!1,error:"Signature verification failed"}}catch(n){return{valid:!1,error:`Verification error: ${n}`}}})}validateTimestamp(e,r=ier){let i=(r.now?r.now():Date.now())-e;return i>=0&&i<=r.maxAgeMs}base64ToBuffer(e){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}bufferToBase64(e){let r=new Uint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return btoa(n)}};nc.\u0275fac=function(e){return new(e||nc)};nc.\u0275prov=le({token:nc,factory:nc.\u0275fac})});var JM=p(()=>{Cer()});var tHe,xx,Aer=p(()=>{ce();JM();de();tHe="|||",xx=class extends nc{createSignature(e,r){return E(this,void 0,void 0,function*(){return btoa(`mock_sig${tHe}${e}${tHe}${r.substring(0,10)}`)})}verifySignature(e,r,n){return E(this,void 0,void 0,function*(){try{let s=atob(r).split(tHe);return s.length===3&&s[0]==="mock_sig"&&s[1]===e}catch{return!1}})}};xx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(xx)))(r||xx)}})();xx.\u0275prov=le({token:xx,factory:xx.\u0275fac})});var Oer=p(()=>{Aer()});var rHe=p(()=>{JM();Oer()});var Kl,Per=p(()=>{de();Kl=class{};Kl.\u0275fac=function(e){return new(e||Kl)};Kl.\u0275prov=le({token:Kl,factory:Kl.\u0275fac})});var aK=p(()=>{Per()});var Cx,Der=p(()=>{ce();aK();de();Cx=class extends Kl{constructor(){super(...arguments),this.storage=null,this.backups=[]}save(e){return E(this,void 0,void 0,function*(){this.storage=Object.assign({},e)})}load(){return E(this,void 0,void 0,function*(){return this.storage?Object.assign({},this.storage):null})}exists(){return E(this,void 0,void 0,function*(){return this.storage!==null})}delete(){return E(this,void 0,void 0,function*(){this.storage=null})}saveBackup(e,r){return E(this,void 0,void 0,function*(){this.backups.push({keyPair:Object.assign({},e),rotatedAt:r})})}loadBackups(){return E(this,void 0,void 0,function*(){return this.backups.map(e=>({keyPair:Object.assign({},e.keyPair),rotatedAt:e.rotatedAt}))})}cleanupBackups(e){return E(this,void 0,void 0,function*(){let r=Date.now()-e;this.backups=this.backups.filter(n=>n.rotatedAt>r)})}};Cx.\u0275fac=(()=>{let t;return function(r){return(t||(t=Yr(Cx)))(r||Cx)}})();Cx.\u0275prov=le({token:Cx,factory:Cx.\u0275fac})});var Ner=p(()=>{Der()});var I0e=p(()=>{aK();Ner()});var ni,ker=p(()=>{ce();de();iK();I0e();E0e();de();ni=class{constructor(){this.keyGenerator=q(zl),this.storage=q(Kl),this.keyPair=null,this.peerId=null,this._initialized=ps(!1)}initialize(){return E(this,void 0,void 0,function*(){if(this._initialized())return;let e=yield this.storage.load();e?this.keyPair=e:(this.keyPair=yield this.keyGenerator.generateKeyPair(),yield this.storage.save(this.keyPair)),this.peerId=yield RO(this.keyPair.publicKey),this._initialized.set(!0)})}getKeyPair(){if(!this.keyPair)throw new Error("KeyManager not initialized");return this.keyPair}getPeerId(){if(!this.peerId)throw new Error("KeyManager not initialized");return this.peerId}isInitialized(){return this._initialized()}waitForInitialization(){return E(this,arguments,void 0,function*(e=1e4){if(this._initialized())return;let r=Date.now(),n=50;return new Promise((i,s)=>{let o=()=>{if(this._initialized()){i();return}if(Date.now()-r>e){s(new Error("KeyManager initialization timeout"));return}setTimeout(o,n)};o()})})}reset(){return E(this,void 0,void 0,function*(){yield this.storage.delete(),this.keyPair=null,this.peerId=null,this._initialized.set(!1),yield this.initialize()})}rotateKeyPair(){return E(this,void 0,void 0,function*(){if(!this.keyPair)throw new Error("KeyManager not initialized");yield this.storage.saveBackup(this.keyPair,Date.now());let e=yield this.keyGenerator.generateKeyPair();return yield this.storage.save(e),this.keyPair=e,this.peerId=yield RO(e.publicKey),e})}getBackupKeyPairs(){return E(this,void 0,void 0,function*(){return this.storage.loadBackups()})}cleanupOldBackups(){return E(this,arguments,void 0,function*(e=10080*60*1e3){yield this.storage.cleanupBackups(e)})}};ni.\u0275fac=function(e){return new(e||ni)};ni.\u0275prov=le({token:ni,factory:ni.\u0275fac,providedIn:"root"})});var Rer=p(()=>{ker()});var Mer=p(()=>{I0e();E0e();eHe();QM();oK();rHe()});var Ler=p(()=>{Mer()});var nHe=p(()=>{mer();E0e();eHe();xer();rHe();Rer();Ler()});var $er=p(()=>{I0e()});function w1(t){return[{provide:ZM,useFactory:t,multi:!0}]}var ZM,Fer=p(()=>{de();ZM=new Ve("SIGNALING_CHANNELS")});function S1(t){return typeof t=="object"&&t!==null&&"encrypted"in t&&"iv"in t&&typeof t.encrypted=="string"&&typeof t.iv=="string"}var jer=p(()=>{});var qer=p(()=>{});var eS,Ber=p(()=>{de();eS=new Ve("SIGNALING_MESSAGE_SENDER")});function Ver(t){return"lost"in t&&t.lost===!0}var Uer=p(()=>{});var Her=p(()=>{Fer();jer();qer();Ber();Uer()});var Y0,Wer=p(()=>{ce();de();Rt();QM();de();Y0=class{constructor(){this.logger=qe("SignalingIdService"),this.hashAdapter=q(yc)}generateId(e){return E(this,void 0,void 0,function*(){return yield this.hashAdapter.toUuid(e)})}findPublicKeyByHash(e,r){return E(this,void 0,void 0,function*(){for(let n of r)if((yield this.generateId(n))===e)return n;return null})}isHashedId(e){return/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e)}};Y0.\u0275fac=function(e){return new(e||Y0)};Y0.\u0275prov=le({token:Y0,factory:Y0.\u0275fac,providedIn:"root"})});var Ger=p(()=>{Wer()});var T0e,MO,zer=p(()=>{T0e={prod:{hasuraUrl:"https://graphql-prod.machina.at/v1/graphql",apiNextUrl:"https://api.machina.at",signalingUrl:"https://signaling.machina.at",firebaseDatabaseUrl:"https://x-x-machina-default-rtdb.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"},stg:{hasuraUrl:"https://graphql-stg.machina.at/v1/graphql",apiNextUrl:"https://api.stg.machina.at",signalingUrl:"https://signaling-stg.machina.at",firebaseDatabaseUrl:"https://x-x-machina-stg.asia-southeast1.firebasedatabase.app",webServerUrl:"https://server.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable"}},MO={PLANX_GRAPHQL_URL:T0e.prod.hasuraUrl,PLANX_CLOUD_API_URL:T0e.prod.apiNextUrl,PLANX_SIGNALING_URL:T0e.prod.signalingUrl,PLANX_FIREBASE_DATABASE_URL:T0e.prod.firebaseDatabaseUrl,PLANX_SIGNALING_BACKEND:"",PLANX_NOSTR_RELAYS:"wss://nos.lol,wss://relay.snort.social"}});var x0e=p(()=>{zer()});var tS,Ker=p(()=>{de();tS=new Ve("TRPC_CLIENT")});var LO,Yer=p(()=>{LO=class t{static in(e,r){return new t(e,r)}constructor(e,r){var n;this.controller=new AbortController,this.timer=null,this.now=(n=r?.now)!==null&&n!==void 0?n:(()=>Date.now()),this.at=this.now()+Math.max(0,e);let i=()=>this.abort();e<=0?i():this.timer=setTimeout(i,e),r?.parent&&(r.parent.aborted?i():r.parent.addEventListener("abort",i,{once:!0}))}get signal(){return this.controller.signal}remaining(){return Math.max(0,this.at-this.now())}expired(){return this.remaining()===0}child(e){return new t(Math.min(e,this.remaining()),{now:this.now,parent:this.signal})}split(e){let r=Math.min(1,Math.max(0,e));return this.child(Math.floor(this.remaining()*r))}abort(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.controller.signal.aborted||this.controller.abort()}dispose(){this.abort()}}});var Qer=p(()=>{Ker();Yer()});var ari,cri,lri,uri,dri,Pr,Jer=p(()=>{ari={name:"port-forward",prefix:"pf:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`pf:${t}`,parseLabel:t=>t.startsWith("pf:")?t.slice(3):null},cri={name:"heartbeat",prefix:"__heartbeat__",profile:"heartbeat",defaultCap:1,defaultBackpressureProfile:"control",buildLabel:()=>"__heartbeat__",parseLabel:t=>t==="__heartbeat__"?"":null},lri={name:"l7-http",prefix:"l7:http:",profile:"reliable-ordered",defaultCap:1e3,defaultBackpressureProfile:"http",buildLabel:t=>`l7:http:${t}`,parseLabel:t=>t.startsWith("l7:http:")?t.slice(8):null},uri={name:"l7-datagram",prefix:"l7:dg:",profile:"unreliable",defaultCap:8,defaultBackpressureProfile:"terminal",buildLabel:t=>`l7:dg:${t}`,parseLabel:t=>t.startsWith("l7:dg:")?t.slice(6):null},dri={name:"l7-qpack",prefix:"l7:qpack:",profile:"reliable-ordered",defaultCap:8,defaultBackpressureProfile:"control",buildLabel:t=>`l7:qpack:${t}`,parseLabel:t=>t.startsWith("l7:qpack:")?t.slice(9):null},Pr={portForward:ari,heartbeat:cri,l7Http:lri,l7Dg:uri,l7Qpack:dri}});var Zer=p(()=>{Jer()});function sHe(t){return function(e,r,n){let i=Reflect.getMetadata(iHe,e.constructor)||[];return i.push({messageType:t,methodName:r}),Reflect.defineMetadata(iHe,i,e.constructor),n}}function Xer(t){return Reflect.getMetadata(iHe,t.constructor)||[]}var iHe,etr=p(()=>{x8();iHe=Symbol("messageHandlers")});var oHe=p(()=>{etr()});var C0e,XM,ttr=p(()=>{ce();Rt();oHe();C0e=class extends Error{constructor(e){super(`No handler found for message type: ${e}`),this.messageType=e,this.code="HANDLER_NOT_FOUND",this.name="HandlerNotFoundError"}},XM=class{constructor(){this.logger=qe(this.constructor.name)}handle(e,r){return E(this,void 0,void 0,function*(){let i=Xer(e).find(s=>s.messageType===r.type);if(i){let s=e[i.methodName];typeof s=="function"&&(yield s.call(e,r))}else throw this.logger.warn("No handler found for message type:",r.type),new C0e(r.type)})}}});var rtr=p(()=>{oHe();ttr()});function aHe(t){return t.replace(/^http(s?):\/\//,"ws$1://")}var ntr=p(()=>{});function A0e(t,e){let r=YM(t),n=e.replace(/^\//,"");return`https://[${r}]:10/${n}`}var itr=p(()=>{nHe()});var cHe=p(()=>{ntr();itr()});var yr=p(()=>{ler();nHe();$er();Her();Ger();x0e();Qer();Zer();rtr();cHe()});var O0e,str=p(()=>{yr();yr();O0e=class extends XM{}});var otr=p(()=>{str()});import*as Ax from"node:fs";import*as atr from"node:path";var Q0,lHe=p(()=>{Rt();de();Q0=class t{constructor(){this.logger=qe("SessionOutputRecorderService"),this.fd=null,this.buffer=[],this.flushTimer=null,this.enabled=!1}start(e){this.enabled=!0;let r=t.DIR;Ax.mkdirSync(r,{recursive:!0});let n=`${e.slice(0,16)}_${Date.now()}.jsonl`,i=atr.join(r,n);this.fd=Ax.openSync(i,"a"),this.flushTimer=setInterval(()=>this.flush(),t.FLUSH_INTERVAL_MS),this.logger.info("Recording started",{filepath:i})}record(e){if(!this.enabled)return;let r=JSON.stringify(Object.assign({ts:performance.now(),iso:new Date().toISOString()},e));this.buffer.push(r)}flush(){if(this.buffer.length===0||this.fd===null)return;let e=this.buffer.join(`
279
279
  `)+`
280
- `;this.buffer=[];let r=Buffer.from(e);Ax.write(this.fd,r,0,r.length,null,n=>{n&&this.logger.error("Write error",{error:n})})}stop(){this.enabled=!1,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush(),this.fd!==null&&(Ax.closeSync(this.fd),this.fd=null),this.logger.info("Recording stopped")}};Q0.FLUSH_INTERVAL_MS=500;Q0.DIR="/tmp/planx/logs/sessions";Q0.\u0275fac=function(e){return new(e||Q0)};Q0.\u0275prov=le({token:Q0,factory:Q0.\u0275fac,providedIn:"root"})});function fri(){return E(this,void 0,void 0,function*(){return yield import("@fails-components/webtransport")})}var cK,ctr=p(()=>{ce();cK=class t{constructor(e){var r;this.opts=e,this.server=null,this.sessionLoopActive=!1,this.assignedPort=null,this.pathPrefix=(r=e.pathPrefix)!==null&&r!==void 0?r:"/sessions",this.pathPattern=`${this.pathPrefix}/*`}start(){return E(this,void 0,void 0,function*(){var e;if(this.server)return;let r=yield fri(),n=this.opts.port;if(n===0){let{createSocket:s}=yield import("dgram");n=yield new Promise((o,a)=>{let c=s("udp4");c.bind(0,"127.0.0.1",()=>{let l=c.address(),u=typeof l=="object"&&l!==null?l.port:0;c.close(()=>o(u))}),c.on("error",a)}),this.assignedPort=n}let i=new r.Http3Server({port:n,host:t.BIND_HOST,secret:"session-wt-output",cert:this.opts.cert,privKey:this.opts.privKey});(e=i.setRequestCallback)===null||e===void 0||e.call(i,s=>Promise.resolve(t.buildRequestResult(this.pathPrefix,s.header))),i.startServer(),yield i.ready,this.server=i,this.sessionLoopActive=!0,this.runSessionLoop()})}static buildRequestResult(e,r){var n;let i=(n=r[":path"])!==null&&n!==void 0?n:"";return t.parseSessionPath(e,i)!==null?{path:e,status:200}:{path:i,status:404}}stop(){return E(this,void 0,void 0,function*(){this.sessionLoopActive=!1,this.server&&(yield this.server.stopServer(),this.server=null)})}getBindHost(){return t.BIND_HOST}isRunning(){return this.server!==null}getListenPort(){var e,r,n;if(!this.server)return null;if(this.opts.port>0)return this.opts.port;if(this.assignedPort!==null)return this.assignedPort;let i=(r=(e=this.server).address)===null||r===void 0?void 0:r.call(e);return(n=i?.port)!==null&&n!==void 0?n:null}static parseSessionPath(e,r){let n=r.split("?")[0],i=[["output","/output"],["input","/input"]];for(let[s,o]of i){if(!n.startsWith(`${e}/`)||!n.endsWith(o))continue;let a=n.slice(e.length+1,n.length-o.length);if(a.length>0&&!a.includes("/"))return{sessionId:a,direction:s}}return null}static extractSessionId(e,r){let n=t.parseSessionPath(e,r);return n?.direction==="output"?n.sessionId:null}runSessionLoop(){return E(this,void 0,void 0,function*(){if(!this.server)return;let e=this.server.sessionStream(this.pathPrefix).getReader();yield this.consumeSessions(e)})}consumeSessions(e){return E(this,void 0,void 0,function*(){for(var r,n,i,s;this.sessionLoopActive;){let o,a;try{({value:o,done:a}=yield e.read())}catch(c){(n=(r=this.opts).log)===null||n===void 0||n.call(r,"error","session stream read error",t.serializeErr(c));return}if(a)return;if(o)try{this.handleSession(o)}catch(c){(s=(i=this.opts).log)===null||s===void 0||s.call(i,"error","session handler error (isolated)",t.serializeErr(c)),t.safeCloseSession(o)}}})}static serializeErr(e){var r;if(e instanceof Error)return(r=e.stack)!==null&&r!==void 0?r:`${e.name}: ${e.message}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}static safeCloseSession(e){return E(this,void 0,void 0,function*(){var r;try{yield(r=e.close)===null||r===void 0?void 0:r.call(e,{closeCode:404,reason:"session not found"})}catch{}})}handleSession(e){var r,n,i,s,o,a,c,l,u,d,f,h,m,y,g,_;let b=(i=(n=(r=e.header)===null||r===void 0?void 0:r[":path"])!==null&&n!==void 0?n:e.path)!==null&&i!==void 0?i:"";console.error("[wt-output-endpoint] handleSession entered",{":path":(o=(s=e.header)===null||s===void 0?void 0:s[":path"])!==null&&o!==void 0?o:"<no-header>","session.path":(a=e.path)!==null&&a!==void 0?a:"<no-shim>",resolvedPath:b,hasOnOutputSession:!!this.opts.onOutputSession,hasOnInputSession:!!this.opts.onInputSession});let w=t.parseSessionPath(this.pathPrefix,b);if(w===null){(l=(c=this.opts).log)===null||l===void 0||l.call(c,"warn","incoming session with invalid path",{path:b}),console.error("[wt-output-endpoint] SILENT FAIL: parseSessionPath returned null",{pathPrefix:this.pathPrefix,path:b});return}let{sessionId:I,direction:x}=w;if(x==="input"){(d=(u=this.opts).log)===null||d===void 0||d.call(u,"info","incoming input session",{sessionId:I,path:b}),console.error("[wt-output-endpoint] dispatching onInputSession",{sessionId:I,path:b}),(h=(f=this.opts).onInputSession)===null||h===void 0||h.call(f,I,e);return}(y=(m=this.opts).log)===null||y===void 0||y.call(m,"info","incoming output session",{sessionId:I,path:b}),console.error("[wt-output-endpoint] dispatching onOutputSession",{sessionId:I,path:b}),(_=(g=this.opts).onOutputSession)===null||_===void 0||_.call(g,I,e)}};cK.BIND_HOST="127.0.0.1"});var ltr=p(()=>{ctr()});import{createServer as pri}from"http";import{Http2ServerRequest as hri}from"http2";import{Http2ServerRequest as uHe}from"http2";import{Readable as utr}from"stream";import xri from"crypto";async function Eri(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function htr(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(o,i),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function i(a){a&&e.destroy(a)}function s(){t.read().then(o,i)}function o({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(o,i)}catch(l){i(l)}}}function Iri(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:htr(t.getReader(),e)}var $O,mri,gri,lK,vri,ftr,yri,r7,_ri,P0e,D0e,bri,t7,wri,N0e,Sri,dtr,e7,FO,fHe,uK,mtr,Tri,Cri,pHe,Ari,gtr,dHe,vtr,ytr,Ori,Pri,Dri,Nri,E1,n7=p(()=>{$O=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},mri=t=>t instanceof $O?t:new $O(t.message,{cause:t}),gri=global.Request,lK=class extends gri{constructor(t,e){typeof t=="object"&&r7 in t&&(t=t[r7]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},vri=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:i,[n+1]:s}=r;i.charCodeAt(0)!==58&&e.push([i,s])}return new Headers(e)},ftr=Symbol("wrapBodyStream"),yri=(t,e,r,n,i)=>{let s={method:t,headers:r,signal:i.signal};if(t==="TRACE"){s.method="GET";let o=new lK(e,s);return Object.defineProperty(o,"method",{get(){return"TRACE"}}),o}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(o){o.enqueue(n.rawBody),o.close()}});else if(n[ftr]){let o;s.body=new ReadableStream({async pull(a){try{o||=utr.toWeb(n).getReader();let{done:c,value:l}=await o.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=utr.toWeb(n);return new lK(e,s)},r7=Symbol("getRequestCache"),_ri=Symbol("requestCache"),P0e=Symbol("incomingKey"),D0e=Symbol("urlKey"),bri=Symbol("headersKey"),t7=Symbol("abortControllerKey"),wri=Symbol("getAbortController"),N0e={get method(){return this[P0e].method||"GET"},get url(){return this[D0e]},get headers(){return this[bri]||=vri(this[P0e])},[wri](){return this[r7](),this[t7]},[r7](){return this[t7]||=new AbortController,this[_ri]||=yri(this.method,this[D0e],this.headers,this[P0e],this[t7])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(N0e,t,{get(){return this[r7]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(N0e,t,{value:function(){return this[r7]()[t]()}})});Object.setPrototypeOf(N0e,lK.prototype);Sri=(t,e)=>{let r=Object.create(N0e);r[P0e]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof uHe)throw new $O("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[D0e]=a.href}catch(a){throw new $O("Invalid absolute URL",{cause:a})}return r}let i=(t instanceof uHe?t.authority:t.headers.host)||e;if(!i)throw new $O("Missing host header");let s;if(t instanceof uHe){if(s=t.scheme,!(s==="http"||s==="https"))throw new $O("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";let o=new URL(`${s}://${i}${n}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,""))throw new $O("Invalid host header");return r[D0e]=o.href,r},dtr=Symbol("responseCache"),e7=Symbol("getResponseCache"),FO=Symbol("cache"),fHe=global.Response,uK=class ptr{#t;#e;[e7](){return delete this[FO],this[dtr]||=new fHe(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof ptr){let i=r[dtr];if(i){this.#e=i,this[e7]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[FO]=[r?.status||200,e,n])}get headers(){let e=this[FO];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[e7]().headers}get status(){return this[FO]?.[0]??this[e7]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(uK.prototype,t,{get(){return this[e7]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(uK.prototype,t,{value:function(){return this[e7]()[t]()}})});Object.setPrototypeOf(uK,fHe);Object.setPrototypeOf(uK.prototype,fHe.prototype);mtr=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,i]of t)n==="set-cookie"?r.push(i):e[n]=i;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},Tri="x-hono-already-sent",Cri=global.fetch;typeof global.crypto>"u"&&(global.crypto=xri);global.fetch=(t,e)=>(e={compress:!1,...e},Cri(t,e));pHe=Symbol("outgoingEnded"),Ari=()=>new Response(null,{status:400}),gtr=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),dHe=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},vtr=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},ytr=async(t,e)=>{let[r,n,i]=t[FO];i instanceof Headers&&(i=mtr(i)),typeof n=="string"?i["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?i["Content-Length"]=n.byteLength:n instanceof Blob&&(i["Content-Length"]=n.size),e.writeHead(r,i),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(vtr(e),await Iri(n,e)?.catch(s=>dHe(s,e))),e[pHe]?.()},Ori=t=>typeof t.then=="function",Pri=async(t,e,r={})=>{if(Ori(t))if(r.errorHandler)try{t=await t}catch(i){let s=await r.errorHandler(i);if(!s)return;t=s}else t=await t.catch(gtr);if(FO in t)return ytr(t,e);let n=mtr(t.headers);if(t.body){let i=t.body.getReader(),s=[],o=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=i.read();let u=await Eri(a).catch(d=>{console.error(d),o=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){o=!0;break}}o&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),o?e.end():(s.length===0&&vtr(e),await htr(i,e,a))}else n[Tri]||(e.writeHead(t.status,n),e.end());e[pHe]?.()},Dri=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==lK&&(Object.defineProperty(global,"Request",{value:lK}),Object.defineProperty(global,"Response",{value:uK})),async(n,i)=>{let s,o;try{o=Sri(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[ftr]=!0,n.on("end",()=>{a=!0}),n instanceof hri&&(i[pHe]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),i.destroy()})})})),i.on("close",()=>{o[t7]&&(n.errored?o[t7].abort(n.errored.toString()):i.writableFinished||o[t7].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(o,{incoming:n,outgoing:i}),FO in s)return ytr(s,i)}catch(a){if(s)return dHe(a,i);if(e.errorHandler){if(s=await e.errorHandler(o?a:mri(a)),!s)return}else o?s=gtr(a):s=Ari()}try{return await Pri(s,i,e)}catch(a){return dHe(a,i)}}},Nri=t=>{let e=t.fetch,r=Dri(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||pri)(t.serverOptions||{},r)},E1=(t,e)=>{let r=Nri(t);return r.listen(t?.port??3e3,t.hostname,()=>{let n=r.address();e&&e(n)}),r}});var hHe,_tr=p(()=>{hHe=(t,e,r)=>(n,i)=>{let s=-1;return o(0);async function o(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&i||void 0,u)try{c=await u(n,()=>o(a+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}}});var btr=p(()=>{});var wtr,Str=p(()=>{wtr=Symbol()});async function kri(t,e){let r=await t.formData();return r?Rri(r,e):{}}function Rri(t,e){let r=Object.create(null);return t.forEach((n,i)=>{e.all||i.endsWith("[]")?Mri(r,i,n):r[i]=n}),e.dot&&Object.entries(r).forEach(([n,i])=>{n.includes(".")&&(Lri(r,n,i),delete r[n])}),r}var Etr,Mri,Lri,Itr=p(()=>{mHe();Etr=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof k0e?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?kri(t,{all:r,dot:n}):{}};Mri=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Lri=(t,e,r)=>{let n=t,i=e.split(".");i.forEach((s,o)=>{o===i.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})}});var vHe,Ttr,$ri,Fri,R0e,xtr,M0e,jri,yHe,Ctr,jO,L0e,gHe,Atr,Otr,Ptr,_He,i7=p(()=>{vHe=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ttr=t=>{let{groups:e,path:r}=$ri(t),n=vHe(r);return Fri(n,e)},$ri=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let i=`@${n}`;return e.push([i,r]),i}),{groups:e,path:t}},Fri=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let i=t.length-1;i>=0;i--)if(t[i].includes(n)){t[i]=t[i].replace(n,e[r][1]);break}}return t},R0e={},xtr=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return R0e[n]||(r[2]?R0e[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:R0e[n]=[t,r[1],!0]),R0e[n]}return null},M0e=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},jri=t=>M0e(t,decodeURI),yHe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let i=e.charCodeAt(n);if(i===37){let s=e.indexOf("?",n),o=e.slice(r,s===-1?void 0:s);return jri(o.includes("%25")?o.replace(/%25/g,"%2525"):o)}else if(i===63)break}return e.slice(r,n)},Ctr=t=>{let e=yHe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},jO=(t,e,...r)=>(r.length&&(e=jO(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),L0e=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(i=>{if(i!==""&&!/\:/.test(i))n+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){r.length===0&&n===""?r.push("/"):r.push(n);let s=i.replace("?","");n+="/"+s,r.push(n)}else n+="/"+i}),r.filter((i,s,o)=>o.indexOf(i)===s)},gHe=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?M0e(t,_He):t):t,Atr=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let o=t.indexOf(`?${e}`,8);for(o===-1&&(o=t.indexOf(`&${e}`,8));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let c=o+e.length+2,l=t.indexOf("&",c);return gHe(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";o=t.indexOf(`&${e}`,o+1)}if(n=/[%+]/.test(t),!n)return}let i={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let o=t.indexOf("&",s+1),a=t.indexOf("=",s);a>o&&o!==-1&&(a=-1);let c=t.slice(s+1,a===-1?o===-1?void 0:o:a);if(n&&(c=gHe(c)),s=o,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,o===-1?void 0:o),n&&(l=gHe(l))),r?(i[c]&&Array.isArray(i[c])||(i[c]=[]),i[c].push(l)):i[c]??=l}return e?i[e]:i},Otr=Atr,Ptr=(t,e)=>Atr(t,e,!0),_He=decodeURIComponent});var Dtr,k0e,mHe=p(()=>{btr();Str();Itr();i7();Dtr=t=>M0e(t,_He),k0e=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#i(e);return r&&/\%/.test(r)?Dtr(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#i(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?Dtr(n):n)}return t}#i(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Otr(this.url,t)}queries(t){return Ptr(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Etr(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let i=Object.keys(e)[0];return i?e[i].then(s=>(i==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[wtr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}}});var $0e,qri,dK,bHe=p(()=>{$0e={Stringify:1,BeforeStream:2,Stream:3},qri=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r},dK=async(t,e,r,n,i)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);i?i[0]+=t:i=[t];let o=Promise.all(s.map(a=>a({phase:e,buffer:i,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>dK(c,e,!1,n,i))).then(()=>i[0]));return r?qri(await o,s):o}});var Ntr,wHe,ktr,SHe=p(()=>{mHe();bHe();Ntr="text/plain; charset=UTF-8",wHe=(t,e)=>({"Content-Type":t,...e}),ktr=class{#t;#e;env={};#r;finalized=!1;error;#s;#i;#n;#u;#c;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#i=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new k0e(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=new Response(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let i of n)t.headers.append("set-cookie",i)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of s)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a)}if(r)for(let[s,o]of Object.entries(r))if(typeof o=="string")n.set(s,o);else{n.delete(s);for(let a of o)n.append(s,a)}let i=typeof e=="number"?e:e?.status??this.#s;return new Response(t,{status:i,headers:n})}newResponse=(...t)=>this.#o(...t);body=(t,e,r)=>this.#o(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#o(t,e,wHe(Ntr,r));json=(t,e,r)=>this.#o(JSON.stringify(t),e,wHe("application/json",r));html=(t,e,r)=>{let n=i=>this.#o(i,e,wHe("text/html; charset=UTF-8",r));return typeof t=="object"?dK(t,$0e.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))}});var Jo,Rtr,Mtr,F0e,j0e,qO=p(()=>{Jo="ALL",Rtr="all",Mtr=["get","post","put","delete","options","patch"],F0e="Can not add a route since the matcher is already built.",j0e=class extends Error{}});var Ltr,$tr=p(()=>{Ltr="__COMPOSED_HANDLER"});var Bri,Ftr,EHe,jtr=p(()=>{_tr();SHe();qO();$tr();i7();Bri=t=>t.text("404 Not Found",404),Ftr=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},EHe=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Mtr,Rtr].forEach(i=>{this[i]=(s,...o)=>(typeof s=="string"?this.#t=s:this.#s(i,this.#t,s),o.forEach(a=>{this.#s(i,this.#t,a)}),this)}),this.on=(i,s,...o)=>{for(let a of[s].flat()){this.#t=a;for(let c of[i].flat())o.map(l=>{this.#s(c.toUpperCase(),this.#t,l)})}return this},this.use=(i,...s)=>(typeof i=="string"?this.#t=i:(this.#t="*",s.unshift(i)),s.forEach(o=>{this.#s(Jo,this.#t,o)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??yHe:Ctr}#e(){let t=new EHe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Bri;errorHandler=Ftr;route(t,e){let r=this.basePath(t);return e.routes.map(n=>{let i;e.errorHandler===Ftr?i=n.handler:(i=async(s,o)=>(await hHe([],e.errorHandler)(s,()=>n.handler(s,o))).res,i[Ltr]=n.handler),r.#s(n.method,n.path,i)}),this}basePath(t){let e=this.#e();return e._basePath=jO(this._basePath,t),e}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,e,r){let n,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let s=i?a=>{let c=i(a);return Array.isArray(c)?c:[c]}:a=>{let c;try{c=a.executionCtx}catch{}return[a.env,c]};n||=(()=>{let a=jO(this._basePath,t),c=a==="/"?0:a.length;return l=>{let u=new URL(l.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,l)}})();let o=async(a,c)=>{let l=await e(n(a.req.raw),...s(a));if(l)return l;await c()};return this.#s(Jo,jO(t,"*"),o),this}#s(t,e,r){t=t.toUpperCase(),e=jO(this._basePath,e);let n={basePath:this._basePath,path:e,method:t,handler:r};this.router.add(t,e,[r,n]),this.routes.push(n)}#i(t,e){if(t instanceof Error)return this.errorHandler(t,e);throw t}#n(t,e,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,e,r,"GET")))();let i=this.getPath(t,{env:r}),s=this.router.match(n,i),o=new ktr(t,{path:i,matchResult:s,env:r,executionCtx:e,notFoundHandler:this.#r});if(s[0].length===1){let c;try{c=s[0][0][0][0](o,async()=>{o.res=await this.#r(o)})}catch(l){return this.#i(l,o)}return c instanceof Promise?c.then(l=>l||(o.finalized?o.res:this.#r(o))).catch(l=>this.#i(l,o)):c??this.#r(o)}let a=hHe(s[0],this.errorHandler,this.#r);return(async()=>{try{let c=await a(o);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#i(c,o)}})()}fetch=(t,...e)=>this.#n(t,e[1],e[0],t.method);request=(t,e,r,n)=>t instanceof Request?this.fetch(e?new Request(t,e):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${jO("/",t)}`,e),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}}});function IHe(t,e){let r=this.buildAllMatchers(),n=(i,s)=>{let o=r[i]||r[Jo],a=o[2][s];if(a)return a;let c=s.match(o[0]);if(!c)return[[],q0e];let l=c.indexOf("",1);return[o[1][l],c]};return this.match=n,n(t,e)}var q0e,THe=p(()=>{qO();q0e=[]});function Uri(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===fK||t===pK?1:e===fK||e===pK?-1:t===B0e?1:e===B0e?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var B0e,fK,pK,BO,Vri,V0e,xHe=p(()=>{B0e="[^/]+",fK=".*",pK="(?:|/.*)",BO=Symbol(),Vri=new Set(".\\+*[^]$()");V0e=class{#t;#e;#r=Object.create(null);insert(t,e,r,n,i){if(t.length===0){if(this.#t!==void 0)throw BO;if(i)return;this.#t=e;return}let[s,...o]=t,a=s==="*"?o.length===0?["","",fK]:["","",B0e]:s==="/*"?["","",pK]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(a){let l=a[1],u=a[2]||B0e;if(l&&a[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw BO;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(d=>d!==fK&&d!==pK))throw BO;if(i)return;c=this.#r[u]=new V0e,l!==""&&(c.#e=n.varIndex++)}!i&&l!==""&&r.push([l,c.#e])}else if(c=this.#r[s],!c){if(Object.keys(this.#r).some(l=>l.length>1&&l!==fK&&l!==pK))throw BO;if(i)return;c=this.#r[s]=new V0e}c.insert(o,e,r,n,i)}buildRegExpStr(){let e=Object.keys(this.#r).sort(Uri).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:Vri.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}}});var qtr,Btr=p(()=>{xHe();qtr=class{#t={varIndex:0};#e=new V0e;insert(t,e,r){let n=[],i=[];for(let o=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${o}`;return i[o]=[l,c],o++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=i.length-1;o>=0;o--){let[a]=i[o];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,i[o][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,s,o)=>s!==void 0?(r[++e]=Number(s),"$()"):(o!==void 0&&(n[Number(o)]=++e),"")),[new RegExp(`^${t}`),r,n]}}});function Utr(t){return Vtr[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Wri(){Vtr=Object.create(null)}function Gri(t){let e=new qtr,r=[];if(t.length===0)return Hri;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,f])=>l?1:d?-1:u.length-f.length),i=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[f,h,m]=n[l];f?i[h]=[m.map(([g])=>[g,Object.create(null)]),q0e]:u++;let y;try{y=e.insert(h,u,f)}catch(g){throw g===BO?new j0e(h):g}f||(r[u]=m.map(([g,_])=>{let b=Object.create(null);for(_-=1;_>=0;_--){let[w,I]=y[_];b[w]=I}return[g,b]}))}let[s,o,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,f=r[l].length;d<f;d++){let h=r[l][d]?.[1];if(!h)continue;let m=Object.keys(h);for(let y=0,g=m.length;y<g;y++)h[m[y]]=a[h[m[y]]]}let c=[];for(let l in o)c[l]=r[o[l]];return[s,c,i]}function s7(t,e){if(t){for(let r of Object.keys(t).sort((n,i)=>i.length-n.length))if(Utr(r).test(e))return[...t[r]]}}var Hri,Vtr,U0e,CHe=p(()=>{qO();i7();THe();xHe();Btr();Hri=[/^$/,[],Object.create(null)],Vtr=Object.create(null);U0e=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Jo]:Object.create(null)},this.#e={[Jo]:Object.create(null)}}add(t,e,r){let n=this.#t,i=this.#e;if(!n||!i)throw new Error(F0e);n[t]||[n,i].forEach(a=>{a[t]=Object.create(null),Object.keys(a[Jo]).forEach(c=>{a[t][c]=[...a[Jo][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Utr(e);t===Jo?Object.keys(n).forEach(c=>{n[c][e]||=s7(n[c],e)||s7(n[Jo],e)||[]}):n[t][e]||=s7(n[t],e)||s7(n[Jo],e)||[],Object.keys(n).forEach(c=>{(t===Jo||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(i).forEach(c=>{(t===Jo||t===c)&&Object.keys(i[c]).forEach(l=>a.test(l)&&i[c][l].push([r,s]))});return}let o=L0e(e)||[e];for(let a=0,c=o.length;a<c;a++){let l=o[a];Object.keys(i).forEach(u=>{(t===Jo||t===u)&&(i[u][l]||=[...s7(n[u],l)||s7(n[Jo],l)||[]],i[u][l].push([r,s-c+a+1]))})}}match=IHe;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,Wri(),t}#r(t){let e=[],r=t===Jo;return[this.#t,this.#e].forEach(n=>{let i=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];i.length!==0?(r||=!0,e.push(...i)):t!==Jo&&e.push(...Object.keys(n[Jo]).map(s=>[s,n[Jo][s]]))}),r?Gri(e):null}}});var Htr=p(()=>{qO();THe();CHe()});var Wtr=p(()=>{CHe();Htr()});var AHe,Gtr=p(()=>{qO();AHe=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(F0e);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,i=r.length,s=0,o;for(;s<i;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);o=a.match(t,e)}catch(c){if(c instanceof j0e)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}}});var ztr=p(()=>{Gtr()});var hK,OHe,Ktr=p(()=>{qO();i7();hK=Object.create(null),OHe=class{#t;#e;#r;#s=0;#i=hK;constructor(t,e,r){if(this.#e=r||Object.create(null),this.#t=[],t&&e){let n=Object.create(null);n[t]={handler:e,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,e,r){this.#s=++this.#s;let n=this,i=Ttr(e),s=[];for(let o=0,a=i.length;o<a;o++){let c=i[o],l=i[o+1],u=xtr(c,l),d=Array.isArray(u)?u[0]:c;if(d in n.#e){n=n.#e[d],u&&s.push(u[1]);continue}n.#e[d]=new OHe,u&&(n.#r.push(u),s.push(u[1])),n=n.#e[d]}return n.#t.push({[t]:{handler:r,possibleKeys:s.filter((o,a,c)=>c.indexOf(o)===a),score:this.#s}}),n}#n(t,e,r,n){let i=[];for(let s=0,o=t.#t.length;s<o;s++){let a=t.#t[s],c=a[e]||a[Jo],l={};if(c!==void 0&&(c.params=Object.create(null),i.push(c),r!==hK||n&&n!==hK))for(let u=0,d=c.possibleKeys.length;u<d;u++){let f=c.possibleKeys[u],h=l[c.score];c.params[f]=n?.[f]&&!h?n[f]:r[f]??n?.[f],l[c.score]=!0}}return i}search(t,e){let r=[];this.#i=hK;let i=[this],s=vHe(e),o=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=a===c-1,d=[];for(let f=0,h=i.length;f<h;f++){let m=i[f],y=m.#e[l];y&&(y.#i=m.#i,u?(y.#e["*"]&&r.push(...this.#n(y.#e["*"],t,m.#i)),r.push(...this.#n(y,t,m.#i))):d.push(y));for(let g=0,_=m.#r.length;g<_;g++){let b=m.#r[g],w=m.#i===hK?{}:{...m.#i};if(b==="*"){let R=m.#e["*"];R&&(r.push(...this.#n(R,t,m.#i)),R.#i=w,d.push(R));continue}let[I,x,A]=b;if(!l&&!(A instanceof RegExp))continue;let O=m.#e[I],D=s.slice(a).join("/");if(A instanceof RegExp){let R=A.exec(D);if(R){if(w[x]=R[0],r.push(...this.#n(O,t,m.#i,w)),Object.keys(O.#e).length){O.#i=w;let J=R[0].match(/\//)?.length??0;(o[J]||=[]).push(O)}continue}}(A===!0||A.test(l))&&(w[x]=l,u?(r.push(...this.#n(O,t,w,m.#i)),O.#e["*"]&&r.push(...this.#n(O.#e["*"],t,w,m.#i))):(O.#i=w,d.push(O)))}}i=d.concat(o.shift()??[])}return r.length>1&&r.sort((a,c)=>a.score-c.score),[r.map(({handler:a,params:c})=>[a,c])]}}});var PHe,Ytr=p(()=>{i7();Ktr();PHe=class{name="TrieRouter";#t;constructor(){this.#t=new OHe}add(t,e,r){let n=L0e(e);if(n){for(let i=0,s=n.length;i<s;i++)this.#t.insert(t,n[i],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}}});var Qtr=p(()=>{Ytr()});var Po,Jtr=p(()=>{jtr();Wtr();ztr();Qtr();Po=class extends EHe{constructor(t={}){super(t),this.router=t.router??new AHe({routers:[new U0e,new PHe]})}}});var Sp=p(()=>{Jtr()});var I1,o7=p(()=>{I1=t=>{let r={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},n=(s=>typeof s=="string"?s==="*"?()=>s:o=>s===o?o:null:typeof s=="function"?s:o=>s.includes(o)?o:null)(r.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(r.allowMethods);return async function(o,a){function c(u,d){o.res.headers.set(u,d)}let l=await n(o.req.header("origin")||"",o);if(l&&c("Access-Control-Allow-Origin",l),r.credentials&&c("Access-Control-Allow-Credentials","true"),r.exposeHeaders?.length&&c("Access-Control-Expose-Headers",r.exposeHeaders.join(",")),o.req.method==="OPTIONS"){r.origin!=="*"&&c("Vary","Origin"),r.maxAge!=null&&c("Access-Control-Max-Age",r.maxAge.toString());let u=await i(o.req.header("origin")||"",o);u.length&&c("Access-Control-Allow-Methods",u.join(","));let d=r.allowHeaders;if(!d?.length){let f=o.req.header("Access-Control-Request-Headers");f&&(d=f.split(/\s*,\s*/))}return d?.length&&(c("Access-Control-Allow-Headers",d.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),r.origin!=="*"&&o.header("Vary","Origin",{append:!0})}}});var Ztr={};fr(Ztr,{__resetForTesting:()=>Yri,applySessionFps:()=>RHe,getManager:()=>pa,getPendingFpsForSession:()=>MHe,getPendingStreamConfig:()=>$He,getServerConfig:()=>Kri,getWtConfigSnapshot:()=>DHe,initContext:()=>LHe,setSessionFpsApplier:()=>kHe,setWtConfigProvider:()=>zri});function zri(t){W0e=t}function DHe(){return E(this,void 0,void 0,function*(){return W0e?yield W0e():null})}function kHe(t){mK=t}function RHe(t,e){mK?.(t,e)}function MHe(t){let e;for(let[r,n]of NHe)r.endsWith(`\0${t}`)&&(e=n.fps);return e}function LHe(t,e){return Ox||(H0e=t,Ox=e??new zM(t),e||Ox.start(),Ox)}function pa(){if(!Ox)throw new Error("PtyManagerService not initialized. Call initContext() first.");return Ox}function Kri(){if(!H0e)throw new Error("SessionServerConfig not initialized. Call initContext() first.");return H0e}function $He(){return NHe}function Yri(){Ox=null,H0e=null,W0e=null,NHe.clear(),mK=null}var Ox,H0e,W0e,NHe,mK,rS=p(()=>{ce();w0e();Ox=null,H0e=null,W0e=null;NHe=new Map,mK=null});function Xtr(t){let e=t;"keepAliveTimeout"in e&&(e.keepAliveTimeout=3e4),"requestTimeout"in e&&(e.requestTimeout=0),"headersTimeout"in e&&(e.headersTimeout=0),"timeout"in e&&(e.timeout=0)}var err=p(()=>{});function Px(t){var e;return{id:t.id,name:t.name,pid:(e=t.pid)!==null&&e!==void 0?e:null,command:t.command,parentId:t.parentId,createdAt:t.createdAt.toISOString(),lastAccessedAt:t.lastAccessedAt.toISOString(),status:t.status}}var gK=p(()=>{});var Ti,FHe,dr,T1,vK=p(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Ti||(Ti={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(FHe||(FHe={}));dr=Ti.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T1=t=>{switch(typeof t){case"undefined":return dr.undefined;case"string":return dr.string;case"number":return Number.isNaN(t)?dr.nan:dr.number;case"boolean":return dr.boolean;case"function":return dr.function;case"bigint":return dr.bigint;case"symbol":return dr.symbol;case"object":return Array.isArray(t)?dr.array:t===null?dr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?dr.promise:typeof Map<"u"&&t instanceof Map?dr.map:typeof Set<"u"&&t instanceof Set?dr.set:typeof Date<"u"&&t instanceof Date?dr.date:dr.object;default:return dr.unknown}}});var Mt,Qri,uf,G0e=p(()=>{vK();Mt=Ti.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Qri=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),uf=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ti.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};uf.create=t=>new uf(t)});var Jri,nS,jHe=p(()=>{G0e();vK();Jri=(t,e)=>{let r;switch(t.code){case Mt.invalid_type:t.received===dr.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Mt.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ti.jsonStringifyReplacer)}`;break;case Mt.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ti.joinValues(t.keys,", ")}`;break;case Mt.invalid_union:r="Invalid input";break;case Mt.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ti.joinValues(t.options)}`;break;case Mt.invalid_enum_value:r=`Invalid enum value. Expected ${Ti.joinValues(t.options)}, received '${t.received}'`;break;case Mt.invalid_arguments:r="Invalid function arguments";break;case Mt.invalid_return_type:r="Invalid function return type";break;case Mt.invalid_date:r="Invalid date";break;case Mt.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ti.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Mt.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Mt.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Mt.custom:r="Invalid input";break;case Mt.invalid_intersection_types:r="Intersection results could not be merged";break;case Mt.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Mt.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ti.assertNever(t)}return{message:r}},nS=Jri});function Zri(t){trr=t}function a7(){return trr}var trr,z0e=p(()=>{jHe();trr=nS});function nr(t,e){let r=a7(),n=yK({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===nS?void 0:nS].filter(i=>!!i)});t.common.issues.push(n)}var yK,Xri,Yl,un,VO,Au,K0e,Y0e,Dx,c7,qHe=p(()=>{z0e();jHe();yK=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}},Xri=[];Yl=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return un;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return un;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},un=Object.freeze({status:"aborted"}),VO=t=>({status:"dirty",value:t}),Au=t=>({status:"valid",value:t}),K0e=t=>t.status==="aborted",Y0e=t=>t.status==="dirty",Dx=t=>t.status==="valid",c7=t=>typeof Promise<"u"&&t instanceof Promise});var rrr=p(()=>{});var kr,nrr=p(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(kr||(kr={}))});function Qn(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}function arr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function gni(t){return new RegExp(`^${arr(t)}$`)}function crr(t){let e=`${orr}T${arr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vni(t,e){return!!((e==="v4"||!e)&&lni.test(t)||(e==="v6"||!e)&&dni.test(t))}function yni(t,e){if(!sni.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function _ni(t,e){return!!((e==="v4"||!e)&&uni.test(t)||(e==="v6"||!e)&&fni.test(t))}function bni(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function l7(t){if(t instanceof df){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Bh.create(l7(n))}return new df({...t._def,shape:()=>e})}else return t instanceof oS?new oS({...t._def,type:l7(t.element)}):t instanceof Bh?Bh.create(l7(t.unwrap())):t instanceof C1?C1.create(l7(t.unwrap())):t instanceof x1?x1.create(t.items.map(e=>l7(e))):t}function VHe(t,e){let r=T1(t),n=T1(e);if(t===e)return{valid:!0,data:t};if(r===dr.object&&n===dr.object){let i=Ti.objectKeys(e),s=Ti.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=VHe(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===dr.array&&n===dr.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],c=VHe(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===dr.date&&n===dr.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function lrr(t,e){return new XO({values:t,typeName:Lt.ZodEnum,...Qn(e)})}function srr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function urr(t,e={},r){return t?kx.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(o=>{if(!o){let a=srr(e,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=srr(e,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):kx.create()}var Vh,irr,Jn,eni,tni,rni,nni,ini,sni,oni,ani,cni,BHe,lni,uni,dni,fni,pni,hni,orr,mni,Nx,UO,HO,WO,GO,u7,zO,KO,kx,sS,J0,d7,oS,df,YO,iS,Q0e,QO,x1,J0e,f7,p7,Z0e,JO,ZO,XO,eP,Rx,Uh,Bh,C1,tP,rP,h7,wni,_K,bK,nP,Sni,Lt,Eni,drr,frr,Ini,Tni,prr,xni,Cni,Ani,Oni,Pni,Dni,Nni,kni,Rni,Mni,Lni,$ni,Fni,jni,qni,Bni,Vni,Uni,Hni,Wni,Gni,zni,Kni,Yni,Qni,Jni,Zni,Xni,eii,tii,rii,nii,iii,sii,hrr=p(()=>{G0e();z0e();nrr();qHe();vK();Vh=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},irr=(t,e)=>{if(Dx(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new uf(t.common.issues);return this._error=r,this._error}}};Jn=class{get description(){return this._def.description}_getType(e){return T1(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:T1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Yl,ctx:{common:e.parent.common,data:e.data,parsedType:T1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(c7(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)},i=this._parseSync({data:e,path:n.path,parent:n});return irr(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Dx(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Dx(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(c7(i)?i:Promise.resolve(i));return irr(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:Mt.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Uh({schema:this,typeName:Lt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Bh.create(this,this._def)}nullable(){return C1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oS.create(this)}promise(){return Rx.create(this,this._def)}or(e){return YO.create([this,e],this._def)}and(e){return QO.create(this,e,this._def)}transform(e){return new Uh({...Qn(this._def),schema:this,typeName:Lt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new tP({...Qn(this._def),innerType:this,defaultValue:r,typeName:Lt.ZodDefault})}brand(){return new _K({typeName:Lt.ZodBranded,type:this,...Qn(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new rP({...Qn(this._def),innerType:this,catchValue:r,typeName:Lt.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return bK.create(this,e)}readonly(){return nP.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eni=/^c[^\s-]{8,}$/i,tni=/^[0-9a-z]+$/,rni=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nni=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ini=/^[a-z0-9_-]{21}$/i,sni=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oni=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ani=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cni="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lni=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,uni=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dni=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,fni=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pni=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hni=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,orr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",mni=new RegExp(`^${orr}$`);Nx=class t extends Jn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==dr.string){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.string,received:s.parsedType}),un}let n=new Yl,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?nr(i,{code:Mt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&nr(i,{code:Mt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ani.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"email",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")BHe||(BHe=new RegExp(cni,"u")),BHe.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"emoji",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")nni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"uuid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ini.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"nanoid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")eni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cuid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")tni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cuid2",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")rni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"ulid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),nr(i,{validation:"url",code:Mt.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"regex",code:Mt.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?crr(s).test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?mni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?gni(s).test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?oni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"duration",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?vni(e.data,s.version)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"ip",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?yni(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"jwt",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?_ni(e.data,s.version)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cidr",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?pni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"base64",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?hni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"base64url",code:Mt.invalid_string,message:s.message}),n.dirty()):Ti.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Mt.invalid_string,...kr.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...kr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...kr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...kr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...kr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...kr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...kr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...kr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...kr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...kr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...kr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...kr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...kr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...kr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...kr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...kr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...kr.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...kr.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...kr.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...kr.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...kr.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...kr.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...kr.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...kr.errToObj(r)})}nonempty(e){return this.min(1,kr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Nx.create=t=>new Nx({checks:[],typeName:Lt.ZodString,coerce:t?.coerce??!1,...Qn(t)});UO=class t extends Jn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==dr.number){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.number,received:s.parsedType}),un}let n,i=new Yl;for(let s of this._def.checks)s.kind==="int"?Ti.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?bni(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_finite,message:s.message}),i.dirty()):Ti.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,kr.toString(r))}gt(e,r){return this.setLimit("min",e,!1,kr.toString(r))}lte(e,r){return this.setLimit("max",e,!0,kr.toString(r))}lt(e,r){return this.setLimit("max",e,!1,kr.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:kr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:kr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:kr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:kr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:kr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:kr.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:kr.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:kr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:kr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:kr.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ti.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};UO.create=t=>new UO({checks:[],typeName:Lt.ZodNumber,coerce:t?.coerce||!1,...Qn(t)});HO=class t extends Jn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==dr.bigint)return this._getInvalidInput(e);let n,i=new Yl;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Ti.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return nr(r,{code:Mt.invalid_type,expected:dr.bigint,received:r.parsedType}),un}gte(e,r){return this.setLimit("min",e,!0,kr.toString(r))}gt(e,r){return this.setLimit("min",e,!1,kr.toString(r))}lte(e,r){return this.setLimit("max",e,!0,kr.toString(r))}lt(e,r){return this.setLimit("max",e,!1,kr.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:kr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:kr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:kr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:kr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:kr.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:kr.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};HO.create=t=>new HO({checks:[],typeName:Lt.ZodBigInt,coerce:t?.coerce??!1,...Qn(t)});WO=class extends Jn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==dr.boolean){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.boolean,received:n.parsedType}),un}return Au(e.data)}};WO.create=t=>new WO({typeName:Lt.ZodBoolean,coerce:t?.coerce||!1,...Qn(t)});GO=class t extends Jn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==dr.date){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.date,received:s.parsedType}),un}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_date}),un}let n=new Yl,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ti.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:kr.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:kr.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};GO.create=t=>new GO({checks:[],coerce:t?.coerce||!1,typeName:Lt.ZodDate,...Qn(t)});u7=class extends Jn{_parse(e){if(this._getType(e)!==dr.symbol){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.symbol,received:n.parsedType}),un}return Au(e.data)}};u7.create=t=>new u7({typeName:Lt.ZodSymbol,...Qn(t)});zO=class extends Jn{_parse(e){if(this._getType(e)!==dr.undefined){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.undefined,received:n.parsedType}),un}return Au(e.data)}};zO.create=t=>new zO({typeName:Lt.ZodUndefined,...Qn(t)});KO=class extends Jn{_parse(e){if(this._getType(e)!==dr.null){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.null,received:n.parsedType}),un}return Au(e.data)}};KO.create=t=>new KO({typeName:Lt.ZodNull,...Qn(t)});kx=class extends Jn{constructor(){super(...arguments),this._any=!0}_parse(e){return Au(e.data)}};kx.create=t=>new kx({typeName:Lt.ZodAny,...Qn(t)});sS=class extends Jn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Au(e.data)}};sS.create=t=>new sS({typeName:Lt.ZodUnknown,...Qn(t)});J0=class extends Jn{_parse(e){let r=this._getOrReturnCtx(e);return nr(r,{code:Mt.invalid_type,expected:dr.never,received:r.parsedType}),un}};J0.create=t=>new J0({typeName:Lt.ZodNever,...Qn(t)});d7=class extends Jn{_parse(e){if(this._getType(e)!==dr.undefined){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.void,received:n.parsedType}),un}return Au(e.data)}};d7.create=t=>new d7({typeName:Lt.ZodVoid,...Qn(t)});oS=class t extends Jn{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==dr.array)return nr(r,{code:Mt.invalid_type,expected:dr.array,received:r.parsedType}),un;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(nr(r,{code:o?Mt.too_big:Mt.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(nr(r,{code:Mt.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(nr(r,{code:Mt.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Vh(r,o,r.path,a)))).then(o=>Yl.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Vh(r,o,r.path,a)));return Yl.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:kr.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:kr.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:kr.toString(r)}})}nonempty(e){return this.min(1,e)}};oS.create=(t,e)=>new oS({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Lt.ZodArray,...Qn(e)});df=class t extends Jn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Ti.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==dr.object){let l=this._getOrReturnCtx(e);return nr(l,{code:Mt.invalid_type,expected:dr.object,received:l.parsedType}),un}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof J0&&this._def.unknownKeys==="strip"))for(let l in i.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=s[l],d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Vh(i,d,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof J0){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")a.length>0&&(nr(i,{code:Mt.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Vh(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Yl.mergeObjectSync(n,l)):Yl.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return kr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:kr.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Lt.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ti.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ti.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return l7(this)}partial(e){let r={};for(let n of Ti.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ti.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Bh;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return lrr(Ti.objectKeys(this.shape))}};df.create=(t,e)=>new df({shape:()=>t,unknownKeys:"strip",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});df.strictCreate=(t,e)=>new df({shape:()=>t,unknownKeys:"strict",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});df.lazycreate=(t,e)=>new df({shape:t,unknownKeys:"strip",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});YO=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new uf(a.ctx.common.issues));return nr(r,{code:Mt.invalid_union,unionErrors:o}),un}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new uf(c));return nr(r,{code:Mt.invalid_union,unionErrors:a}),un}}get options(){return this._def.options}};YO.create=(t,e)=>new YO({options:t,typeName:Lt.ZodUnion,...Qn(e)});iS=t=>t instanceof JO?iS(t.schema):t instanceof Uh?iS(t.innerType()):t instanceof ZO?[t.value]:t instanceof XO?t.options:t instanceof eP?Ti.objectValues(t.enum):t instanceof tP?iS(t._def.innerType):t instanceof zO?[void 0]:t instanceof KO?[null]:t instanceof Bh?[void 0,...iS(t.unwrap())]:t instanceof C1?[null,...iS(t.unwrap())]:t instanceof _K||t instanceof nP?iS(t.unwrap()):t instanceof rP?iS(t._def.innerType):[],Q0e=class t extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.object)return nr(r,{code:Mt.invalid_type,expected:dr.object,received:r.parsedType}),un;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(nr(r,{code:Mt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),un)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=iS(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:Lt.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Qn(n)})}};QO=class extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(K0e(s)||K0e(o))return un;let a=VHe(s.value,o.value);return a.valid?((Y0e(s)||Y0e(o))&&r.dirty(),{status:r.value,value:a.data}):(nr(n,{code:Mt.invalid_intersection_types}),un)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};QO.create=(t,e,r)=>new QO({left:t,right:e,typeName:Lt.ZodIntersection,...Qn(r)});x1=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.array)return nr(n,{code:Mt.invalid_type,expected:dr.array,received:n.parsedType}),un;if(n.data.length<this._def.items.length)return nr(n,{code:Mt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),un;!this._def.rest&&n.data.length>this._def.items.length&&(nr(n,{code:Mt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Vh(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Yl.mergeArray(r,o)):Yl.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};x1.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new x1({items:t,typeName:Lt.ZodTuple,rest:null,...Qn(e)})};J0e=class t extends Jn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.object)return nr(n,{code:Mt.invalid_type,expected:dr.object,received:n.parsedType}),un;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Vh(n,a,n.path,a)),value:o._parse(new Vh(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Yl.mergeObjectAsync(r,i):Yl.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Jn?new t({keyType:e,valueType:r,typeName:Lt.ZodRecord,...Qn(n)}):new t({keyType:Nx.create(),valueType:e,typeName:Lt.ZodRecord,...Qn(r)})}},f7=class extends Jn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.map)return nr(n,{code:Mt.invalid_type,expected:dr.map,received:n.parsedType}),un;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:i._parse(new Vh(n,a,n.path,[l,"key"])),value:s._parse(new Vh(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return un;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return un;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};f7.create=(t,e,r)=>new f7({valueType:e,keyType:t,typeName:Lt.ZodMap,...Qn(r)});p7=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.set)return nr(n,{code:Mt.invalid_type,expected:dr.set,received:n.parsedType}),un;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(nr(n,{code:Mt.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(nr(n,{code:Mt.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return un;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new Vh(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:kr.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:kr.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};p7.create=(t,e)=>new p7({valueType:t,minSize:null,maxSize:null,typeName:Lt.ZodSet,...Qn(e)});Z0e=class t extends Jn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.function)return nr(r,{code:Mt.invalid_type,expected:dr.function,received:r.parsedType}),un;function n(a,c){return yK({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a7(),nS].filter(l=>!!l),issueData:{code:Mt.invalid_arguments,argumentsError:c}})}function i(a,c){return yK({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a7(),nS].filter(l=>!!l),issueData:{code:Mt.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Rx){let a=this;return Au(async function(...c){let l=new uf([]),u=await a._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw l.addIssue(i(d,h)),l})})}else{let a=this;return Au(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new uf([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new uf([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:x1.create(e).rest(sS.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||x1.create([]).rest(sS.create()),returns:r||sS.create(),typeName:Lt.ZodFunction,...Qn(n)})}},JO=class extends Jn{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};JO.create=(t,e)=>new JO({getter:t,typeName:Lt.ZodLazy,...Qn(e)});ZO=class extends Jn{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return nr(r,{received:r.data,code:Mt.invalid_literal,expected:this._def.value}),un}return{status:"valid",value:e.data}}get value(){return this._def.value}};ZO.create=(t,e)=>new ZO({value:t,typeName:Lt.ZodLiteral,...Qn(e)});XO=class t extends Jn{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return nr(r,{expected:Ti.joinValues(n),received:r.parsedType,code:Mt.invalid_type}),un}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return nr(r,{received:r.data,code:Mt.invalid_enum_value,options:n}),un}return Au(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};XO.create=lrr;eP=class extends Jn{_parse(e){let r=Ti.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==dr.string&&n.parsedType!==dr.number){let i=Ti.objectValues(r);return nr(n,{expected:Ti.joinValues(i),received:n.parsedType,code:Mt.invalid_type}),un}if(this._cache||(this._cache=new Set(Ti.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ti.objectValues(r);return nr(n,{received:n.data,code:Mt.invalid_enum_value,options:i}),un}return Au(e.data)}get enum(){return this._def.values}};eP.create=(t,e)=>new eP({values:t,typeName:Lt.ZodNativeEnum,...Qn(e)});Rx=class extends Jn{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.promise&&r.common.async===!1)return nr(r,{code:Mt.invalid_type,expected:dr.promise,received:r.parsedType}),un;let n=r.parsedType===dr.promise?r.data:Promise.resolve(r.data);return Au(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Rx.create=(t,e)=>new Rx({type:t,typeName:Lt.ZodPromise,...Qn(e)});Uh=class extends Jn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Lt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{nr(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return un;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?un:c.status==="dirty"?VO(c.value):r.value==="dirty"?VO(c.value):c});{if(r.value==="aborted")return un;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?un:a.status==="dirty"?VO(a.value):r.value==="dirty"?VO(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?un:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?un:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Dx(o))return un;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Dx(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):un);Ti.assertNever(i)}};Uh.create=(t,e,r)=>new Uh({schema:t,typeName:Lt.ZodEffects,effect:e,...Qn(r)});Uh.createWithPreprocess=(t,e,r)=>new Uh({schema:e,effect:{type:"preprocess",transform:t},typeName:Lt.ZodEffects,...Qn(r)});Bh=class extends Jn{_parse(e){return this._getType(e)===dr.undefined?Au(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bh.create=(t,e)=>new Bh({innerType:t,typeName:Lt.ZodOptional,...Qn(e)});C1=class extends Jn{_parse(e){return this._getType(e)===dr.null?Au(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C1.create=(t,e)=>new C1({innerType:t,typeName:Lt.ZodNullable,...Qn(e)});tP=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===dr.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};tP.create=(t,e)=>new tP({innerType:t,typeName:Lt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Qn(e)});rP=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return c7(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new uf(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new uf(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};rP.create=(t,e)=>new rP({innerType:t,typeName:Lt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Qn(e)});h7=class extends Jn{_parse(e){if(this._getType(e)!==dr.nan){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.nan,received:n.parsedType}),un}return{status:"valid",value:e.data}}};h7.create=t=>new h7({typeName:Lt.ZodNaN,...Qn(t)});wni=Symbol("zod_brand"),_K=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},bK=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?un:s.status==="dirty"?(r.dirty(),VO(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?un:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Lt.ZodPipeline})}},nP=class extends Jn{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Dx(i)&&(i.value=Object.freeze(i.value)),i);return c7(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};nP.create=(t,e)=>new nP({innerType:t,typeName:Lt.ZodReadonly,...Qn(e)});Sni={object:df.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Lt||(Lt={}));Eni=(t,e={message:`Input not instance of ${t.name}`})=>urr(r=>r instanceof t,e),drr=Nx.create,frr=UO.create,Ini=h7.create,Tni=HO.create,prr=WO.create,xni=GO.create,Cni=u7.create,Ani=zO.create,Oni=KO.create,Pni=kx.create,Dni=sS.create,Nni=J0.create,kni=d7.create,Rni=oS.create,Mni=df.create,Lni=df.strictCreate,$ni=YO.create,Fni=Q0e.create,jni=QO.create,qni=x1.create,Bni=J0e.create,Vni=f7.create,Uni=p7.create,Hni=Z0e.create,Wni=JO.create,Gni=ZO.create,zni=XO.create,Kni=eP.create,Yni=Rx.create,Qni=Uh.create,Jni=Bh.create,Zni=C1.create,Xni=Uh.createWithPreprocess,eii=bK.create,tii=()=>drr().optional(),rii=()=>frr().optional(),nii=()=>prr().optional(),iii={string:(t=>Nx.create({...t,coerce:!0})),number:(t=>UO.create({...t,coerce:!0})),boolean:(t=>WO.create({...t,coerce:!0})),bigint:(t=>HO.create({...t,coerce:!0})),date:(t=>GO.create({...t,coerce:!0}))},sii=un});var B={};fr(B,{BRAND:()=>wni,DIRTY:()=>VO,EMPTY_PATH:()=>Xri,INVALID:()=>un,NEVER:()=>sii,OK:()=>Au,ParseStatus:()=>Yl,Schema:()=>Jn,ZodAny:()=>kx,ZodArray:()=>oS,ZodBigInt:()=>HO,ZodBoolean:()=>WO,ZodBranded:()=>_K,ZodCatch:()=>rP,ZodDate:()=>GO,ZodDefault:()=>tP,ZodDiscriminatedUnion:()=>Q0e,ZodEffects:()=>Uh,ZodEnum:()=>XO,ZodError:()=>uf,ZodFirstPartyTypeKind:()=>Lt,ZodFunction:()=>Z0e,ZodIntersection:()=>QO,ZodIssueCode:()=>Mt,ZodLazy:()=>JO,ZodLiteral:()=>ZO,ZodMap:()=>f7,ZodNaN:()=>h7,ZodNativeEnum:()=>eP,ZodNever:()=>J0,ZodNull:()=>KO,ZodNullable:()=>C1,ZodNumber:()=>UO,ZodObject:()=>df,ZodOptional:()=>Bh,ZodParsedType:()=>dr,ZodPipeline:()=>bK,ZodPromise:()=>Rx,ZodReadonly:()=>nP,ZodRecord:()=>J0e,ZodSchema:()=>Jn,ZodSet:()=>p7,ZodString:()=>Nx,ZodSymbol:()=>u7,ZodTransformer:()=>Uh,ZodTuple:()=>x1,ZodType:()=>Jn,ZodUndefined:()=>zO,ZodUnion:()=>YO,ZodUnknown:()=>sS,ZodVoid:()=>d7,addIssueToContext:()=>nr,any:()=>Pni,array:()=>Rni,bigint:()=>Tni,boolean:()=>prr,coerce:()=>iii,custom:()=>urr,date:()=>xni,datetimeRegex:()=>crr,defaultErrorMap:()=>nS,discriminatedUnion:()=>Fni,effect:()=>Qni,enum:()=>zni,function:()=>Hni,getErrorMap:()=>a7,getParsedType:()=>T1,instanceof:()=>Eni,intersection:()=>jni,isAborted:()=>K0e,isAsync:()=>c7,isDirty:()=>Y0e,isValid:()=>Dx,late:()=>Sni,lazy:()=>Wni,literal:()=>Gni,makeIssue:()=>yK,map:()=>Vni,nan:()=>Ini,nativeEnum:()=>Kni,never:()=>Nni,null:()=>Oni,nullable:()=>Zni,number:()=>frr,object:()=>Mni,objectUtil:()=>FHe,oboolean:()=>nii,onumber:()=>rii,optional:()=>Jni,ostring:()=>tii,pipeline:()=>eii,preprocess:()=>Xni,promise:()=>Yni,quotelessJson:()=>Qri,record:()=>Bni,set:()=>Uni,setErrorMap:()=>Zri,strictObject:()=>Lni,string:()=>drr,symbol:()=>Cni,transformer:()=>Qni,tuple:()=>qni,undefined:()=>Ani,union:()=>$ni,unknown:()=>Dni,util:()=>Ti,void:()=>kni});var UHe=p(()=>{z0e();qHe();rrr();vK();hrr();G0e()});var _c=p(()=>{UHe();UHe()});function grr(t){return oii.includes(t)}function vrr(t){if(/^C-(.+)$/i.test(t)){let e=t.slice(2).toLowerCase();return e.length===1&&e>="a"&&e<="z"?String.fromCharCode(e.charCodeAt(0)-96):e==="space"||e==="@"?"\0":e==="["?"\x1B":e==="\\"?"":e==="]"?"":e==="^"?"":e==="_"?"":t}return/^M-(.+)$/i.test(t)?"\x1B"+t.slice(2):/^[A-Z]/.test(t)&&t.length>1&&mrr[t]?mrr[t]:t}var oii,mrr,yrr=p(()=>{oii=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];mrr={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"}});import{randomUUID as aii}from"crypto";function HHe(t){return E(this,void 0,void 0,function*(){try{return yield t.req.json()}catch{return null}})}function _rr(){let t=new Po;return t.post("/sessions",e=>E(this,void 0,void 0,function*(){var r,n;let i=cii.safeParse(yield HHe(e));if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let s=i.data,o=(r=s.id)!==null&&r!==void 0?r:aii(),a=yield pa().createSession({id:o,name:(n=s.name)!==null&&n!==void 0?n:o.slice(0,8),command:s.command,parentId:s.parentId,cwd:s.cwd,env:s.env});return e.json(Px(a),201)})),t.patch("/sessions/:id",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=lii.safeParse(yield HHe(e));if(!n.success)return e.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=pa().getSession(r);if(!i)return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:s,status:o,cols:a,rows:c}=n.data;a!==void 0&&c!==void 0&&pa().resize(r,a,c),o==="detached"&&(i.status="detached"),s!==void 0&&pa().renameSession(r,s);let l=pa().getSession(r);return e.json(Px(l??i))})),t.delete("/sessions/:id",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id");return yield pa().destroySession(r),e.json({success:!0,id:r})})),t.post("/sessions/:id/input",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=yield HHe(e),i=uii.safeParse(n),s=i.success?null:dii.safeParse(n);if(!i.success&&!s?.success)return e.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!pa().getSession(r))return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return pa().input(r,i.data.data),e.json({success:!0,id:r});let{keys:o,literal:a}=s.success?s.data:{keys:[],literal:!1},c=o.filter(l=>!grr(l)).map(l=>a?l:vrr(l)).join("");return c.length>0&&pa().input(r,c),e.json({success:!0,id:r})})),t}var cii,lii,uii,dii,brr=p(()=>{ce();Sp();_c();rS();gK();yrr();cii=B.object({id:B.string().optional(),name:B.string().optional(),command:B.string().optional(),parentId:B.string().optional(),cwd:B.string().optional(),env:B.record(B.string()).optional()}),lii=B.object({name:B.string().optional(),status:B.literal("detached").optional(),cols:B.number().optional(),rows:B.number().optional()}).refine(t=>t.name!==void 0||t.status!==void 0||t.cols!==void 0&&t.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),uii=B.object({data:B.string()}),dii=B.object({keys:B.array(B.string()),literal:B.boolean().optional()})});function wrr(){let t=new Po;return t.put("/sessions/:id/stream-config",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=null;try{n=yield e.req.json()}catch{}let i=fii.safeParse(n);if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:s,fps:o}=i.data,a=`${s}\0${r}`;return $He().set(a,{fps:o}),RHe(r,o),e.json({success:!0,id:r})})),t.get("/system/wt-config",e=>E(this,void 0,void 0,function*(){return e.json(yield DHe())})),t}var fii,Srr=p(()=>{ce();Sp();_c();rS();fii=B.object({peerId:B.string(),fps:B.number()})});function X0e(t){var e,r;let n=(e=t.intervalMs)!==null&&e!==void 0?e:25e3,i=(r=t.now)!==null&&r!==void 0?r:(()=>Date.now()),s=new TextEncoder,o=!1,a=setInterval(()=>{if(!o)try{t.enqueue(s.encode(`: heartbeat ${i()}
280
+ `;this.buffer=[];let r=Buffer.from(e);Ax.write(this.fd,r,0,r.length,null,n=>{n&&this.logger.error("Write error",{error:n})})}stop(){this.enabled=!1,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush(),this.fd!==null&&(Ax.closeSync(this.fd),this.fd=null),this.logger.info("Recording stopped")}};Q0.FLUSH_INTERVAL_MS=500;Q0.DIR="/tmp/planx/logs/sessions";Q0.\u0275fac=function(e){return new(e||Q0)};Q0.\u0275prov=le({token:Q0,factory:Q0.\u0275fac,providedIn:"root"})});function fri(){return E(this,void 0,void 0,function*(){return yield import("@fails-components/webtransport")})}var cK,ctr=p(()=>{ce();cK=class t{constructor(e){var r;this.opts=e,this.server=null,this.sessionLoopActive=!1,this.assignedPort=null,this.pathPrefix=(r=e.pathPrefix)!==null&&r!==void 0?r:"/sessions",this.pathPattern=`${this.pathPrefix}/*`}start(){return E(this,void 0,void 0,function*(){var e;if(this.server)return;let r=yield fri(),n=this.opts.port;if(n===0){let{createSocket:s}=yield import("dgram");n=yield new Promise((o,a)=>{let c=s("udp4");c.bind(0,"127.0.0.1",()=>{let l=c.address(),u=typeof l=="object"&&l!==null?l.port:0;c.close(()=>o(u))}),c.on("error",a)}),this.assignedPort=n}let i=new r.Http3Server({port:n,host:t.BIND_HOST,secret:"session-wt-output",cert:this.opts.cert,privKey:this.opts.privKey});(e=i.setRequestCallback)===null||e===void 0||e.call(i,s=>Promise.resolve(t.buildRequestResult(this.pathPrefix,s.header))),i.startServer(),yield i.ready,this.server=i,this.sessionLoopActive=!0,this.runSessionLoop()})}static buildRequestResult(e,r){var n;let i=(n=r[":path"])!==null&&n!==void 0?n:"";return t.parseSessionPath(e,i)!==null?{path:e,status:200}:{path:i,status:404}}stop(){return E(this,void 0,void 0,function*(){this.sessionLoopActive=!1,this.server&&(yield this.server.stopServer(),this.server=null)})}getBindHost(){return t.BIND_HOST}isRunning(){return this.server!==null}getListenPort(){var e,r,n;if(!this.server)return null;if(this.opts.port>0)return this.opts.port;if(this.assignedPort!==null)return this.assignedPort;let i=(r=(e=this.server).address)===null||r===void 0?void 0:r.call(e);return(n=i?.port)!==null&&n!==void 0?n:null}static parseSessionPath(e,r){let n=r.split("?")[0],i=[["output","/output"],["input","/input"]];for(let[s,o]of i){if(!n.startsWith(`${e}/`)||!n.endsWith(o))continue;let a=n.slice(e.length+1,n.length-o.length);if(a.length>0&&!a.includes("/"))return{sessionId:a,direction:s}}return null}static extractSessionId(e,r){let n=t.parseSessionPath(e,r);return n?.direction==="output"?n.sessionId:null}runSessionLoop(){return E(this,void 0,void 0,function*(){if(!this.server)return;let e=this.server.sessionStream(this.pathPrefix).getReader();yield this.consumeSessions(e)})}consumeSessions(e){return E(this,void 0,void 0,function*(){for(var r,n,i,s;this.sessionLoopActive;){let o,a;try{({value:o,done:a}=yield e.read())}catch(c){(n=(r=this.opts).log)===null||n===void 0||n.call(r,"error","session stream read error",t.serializeErr(c));return}if(a)return;if(o)try{this.handleSession(o)}catch(c){(s=(i=this.opts).log)===null||s===void 0||s.call(i,"error","session handler error (isolated)",t.serializeErr(c)),t.safeCloseSession(o)}}})}static serializeErr(e){var r;if(e instanceof Error)return(r=e.stack)!==null&&r!==void 0?r:`${e.name}: ${e.message}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}static safeCloseSession(e){return E(this,void 0,void 0,function*(){var r;try{yield(r=e.close)===null||r===void 0?void 0:r.call(e,{closeCode:404,reason:"session not found"})}catch{}})}handleSession(e){var r,n,i,s,o,a,c,l,u,d,f,h,m,y,g,_;let b=(i=(n=(r=e.header)===null||r===void 0?void 0:r[":path"])!==null&&n!==void 0?n:e.path)!==null&&i!==void 0?i:"";console.error("[wt-output-endpoint] handleSession entered",{":path":(o=(s=e.header)===null||s===void 0?void 0:s[":path"])!==null&&o!==void 0?o:"<no-header>","session.path":(a=e.path)!==null&&a!==void 0?a:"<no-shim>",resolvedPath:b,hasOnOutputSession:!!this.opts.onOutputSession,hasOnInputSession:!!this.opts.onInputSession});let w=t.parseSessionPath(this.pathPrefix,b);if(w===null){(l=(c=this.opts).log)===null||l===void 0||l.call(c,"warn","incoming session with invalid path",{path:b}),console.error("[wt-output-endpoint] SILENT FAIL: parseSessionPath returned null",{pathPrefix:this.pathPrefix,path:b});return}let{sessionId:I,direction:x}=w;if(x==="input"){(d=(u=this.opts).log)===null||d===void 0||d.call(u,"info","incoming input session",{sessionId:I,path:b}),console.error("[wt-output-endpoint] dispatching onInputSession",{sessionId:I,path:b}),(h=(f=this.opts).onInputSession)===null||h===void 0||h.call(f,I,e);return}(y=(m=this.opts).log)===null||y===void 0||y.call(m,"info","incoming output session",{sessionId:I,path:b}),console.error("[wt-output-endpoint] dispatching onOutputSession",{sessionId:I,path:b}),(_=(g=this.opts).onOutputSession)===null||_===void 0||_.call(g,I,e)}};cK.BIND_HOST="127.0.0.1"});var ltr=p(()=>{ctr()});import{createServer as pri}from"http";import{Http2ServerRequest as hri}from"http2";import{Http2ServerRequest as uHe}from"http2";import{Readable as utr}from"stream";import xri from"crypto";async function Eri(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function htr(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(o,i),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function i(a){a&&e.destroy(a)}function s(){t.read().then(o,i)}function o({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(o,i)}catch(l){i(l)}}}function Iri(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:htr(t.getReader(),e)}var $O,mri,gri,lK,vri,ftr,yri,r7,_ri,P0e,D0e,bri,t7,wri,N0e,Sri,dtr,e7,FO,fHe,uK,mtr,Tri,Cri,pHe,Ari,gtr,dHe,vtr,ytr,Ori,Pri,Dri,Nri,E1,n7=p(()=>{$O=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},mri=t=>t instanceof $O?t:new $O(t.message,{cause:t}),gri=global.Request,lK=class extends gri{constructor(t,e){typeof t=="object"&&r7 in t&&(t=t[r7]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},vri=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:i,[n+1]:s}=r;i.charCodeAt(0)!==58&&e.push([i,s])}return new Headers(e)},ftr=Symbol("wrapBodyStream"),yri=(t,e,r,n,i)=>{let s={method:t,headers:r,signal:i.signal};if(t==="TRACE"){s.method="GET";let o=new lK(e,s);return Object.defineProperty(o,"method",{get(){return"TRACE"}}),o}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(o){o.enqueue(n.rawBody),o.close()}});else if(n[ftr]){let o;s.body=new ReadableStream({async pull(a){try{o||=utr.toWeb(n).getReader();let{done:c,value:l}=await o.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=utr.toWeb(n);return new lK(e,s)},r7=Symbol("getRequestCache"),_ri=Symbol("requestCache"),P0e=Symbol("incomingKey"),D0e=Symbol("urlKey"),bri=Symbol("headersKey"),t7=Symbol("abortControllerKey"),wri=Symbol("getAbortController"),N0e={get method(){return this[P0e].method||"GET"},get url(){return this[D0e]},get headers(){return this[bri]||=vri(this[P0e])},[wri](){return this[r7](),this[t7]},[r7](){return this[t7]||=new AbortController,this[_ri]||=yri(this.method,this[D0e],this.headers,this[P0e],this[t7])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(N0e,t,{get(){return this[r7]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(N0e,t,{value:function(){return this[r7]()[t]()}})});Object.setPrototypeOf(N0e,lK.prototype);Sri=(t,e)=>{let r=Object.create(N0e);r[P0e]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof uHe)throw new $O("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[D0e]=a.href}catch(a){throw new $O("Invalid absolute URL",{cause:a})}return r}let i=(t instanceof uHe?t.authority:t.headers.host)||e;if(!i)throw new $O("Missing host header");let s;if(t instanceof uHe){if(s=t.scheme,!(s==="http"||s==="https"))throw new $O("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";let o=new URL(`${s}://${i}${n}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,""))throw new $O("Invalid host header");return r[D0e]=o.href,r},dtr=Symbol("responseCache"),e7=Symbol("getResponseCache"),FO=Symbol("cache"),fHe=global.Response,uK=class ptr{#t;#e;[e7](){return delete this[FO],this[dtr]||=new fHe(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof ptr){let i=r[dtr];if(i){this.#e=i,this[e7]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[FO]=[r?.status||200,e,n])}get headers(){let e=this[FO];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[e7]().headers}get status(){return this[FO]?.[0]??this[e7]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(uK.prototype,t,{get(){return this[e7]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(uK.prototype,t,{value:function(){return this[e7]()[t]()}})});Object.setPrototypeOf(uK,fHe);Object.setPrototypeOf(uK.prototype,fHe.prototype);mtr=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,i]of t)n==="set-cookie"?r.push(i):e[n]=i;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},Tri="x-hono-already-sent",Cri=global.fetch;typeof global.crypto>"u"&&(global.crypto=xri);global.fetch=(t,e)=>(e={compress:!1,...e},Cri(t,e));pHe=Symbol("outgoingEnded"),Ari=()=>new Response(null,{status:400}),gtr=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),dHe=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},vtr=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},ytr=async(t,e)=>{let[r,n,i]=t[FO];i instanceof Headers&&(i=mtr(i)),typeof n=="string"?i["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?i["Content-Length"]=n.byteLength:n instanceof Blob&&(i["Content-Length"]=n.size),e.writeHead(r,i),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(vtr(e),await Iri(n,e)?.catch(s=>dHe(s,e))),e[pHe]?.()},Ori=t=>typeof t.then=="function",Pri=async(t,e,r={})=>{if(Ori(t))if(r.errorHandler)try{t=await t}catch(i){let s=await r.errorHandler(i);if(!s)return;t=s}else t=await t.catch(gtr);if(FO in t)return ytr(t,e);let n=mtr(t.headers);if(t.body){let i=t.body.getReader(),s=[],o=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=i.read();let u=await Eri(a).catch(d=>{console.error(d),o=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){o=!0;break}}o&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),o?e.end():(s.length===0&&vtr(e),await htr(i,e,a))}else n[Tri]||(e.writeHead(t.status,n),e.end());e[pHe]?.()},Dri=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==lK&&(Object.defineProperty(global,"Request",{value:lK}),Object.defineProperty(global,"Response",{value:uK})),async(n,i)=>{let s,o;try{o=Sri(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[ftr]=!0,n.on("end",()=>{a=!0}),n instanceof hri&&(i[pHe]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),i.destroy()})})})),i.on("close",()=>{o[t7]&&(n.errored?o[t7].abort(n.errored.toString()):i.writableFinished||o[t7].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(o,{incoming:n,outgoing:i}),FO in s)return ytr(s,i)}catch(a){if(s)return dHe(a,i);if(e.errorHandler){if(s=await e.errorHandler(o?a:mri(a)),!s)return}else o?s=gtr(a):s=Ari()}try{return await Pri(s,i,e)}catch(a){return dHe(a,i)}}},Nri=t=>{let e=t.fetch,r=Dri(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||pri)(t.serverOptions||{},r)},E1=(t,e)=>{let r=Nri(t);return r.listen(t?.port??3e3,t.hostname,()=>{let n=r.address();e&&e(n)}),r}});var hHe,_tr=p(()=>{hHe=(t,e,r)=>(n,i)=>{let s=-1;return o(0);async function o(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&i||void 0,u)try{c=await u(n,()=>o(a+1))}catch(d){if(d instanceof Error&&e)n.error=d,c=await e(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}}});var btr=p(()=>{});var wtr,Str=p(()=>{wtr=Symbol()});async function kri(t,e){let r=await t.formData();return r?Rri(r,e):{}}function Rri(t,e){let r=Object.create(null);return t.forEach((n,i)=>{e.all||i.endsWith("[]")?Mri(r,i,n):r[i]=n}),e.dot&&Object.entries(r).forEach(([n,i])=>{n.includes(".")&&(Lri(r,n,i),delete r[n])}),r}var Etr,Mri,Lri,Itr=p(()=>{mHe();Etr=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,s=(t instanceof k0e?t.raw.headers:t.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?kri(t,{all:r,dot:n}):{}};Mri=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Lri=(t,e,r)=>{let n=t,i=e.split(".");i.forEach((s,o)=>{o===i.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})}});var vHe,Ttr,$ri,Fri,R0e,xtr,M0e,jri,yHe,Ctr,jO,L0e,gHe,Atr,Otr,Ptr,_He,i7=p(()=>{vHe=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ttr=t=>{let{groups:e,path:r}=$ri(t),n=vHe(r);return Fri(n,e)},$ri=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let i=`@${n}`;return e.push([i,r]),i}),{groups:e,path:t}},Fri=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let i=t.length-1;i>=0;i--)if(t[i].includes(n)){t[i]=t[i].replace(n,e[r][1]);break}}return t},R0e={},xtr=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return R0e[n]||(r[2]?R0e[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:R0e[n]=[t,r[1],!0]),R0e[n]}return null},M0e=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},jri=t=>M0e(t,decodeURI),yHe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let i=e.charCodeAt(n);if(i===37){let s=e.indexOf("?",n),o=e.slice(r,s===-1?void 0:s);return jri(o.includes("%25")?o.replace(/%25/g,"%2525"):o)}else if(i===63)break}return e.slice(r,n)},Ctr=t=>{let e=yHe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},jO=(t,e,...r)=>(r.length&&(e=jO(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),L0e=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(i=>{if(i!==""&&!/\:/.test(i))n+="/"+i;else if(/\:/.test(i))if(/\?/.test(i)){r.length===0&&n===""?r.push("/"):r.push(n);let s=i.replace("?","");n+="/"+s,r.push(n)}else n+="/"+i}),r.filter((i,s,o)=>o.indexOf(i)===s)},gHe=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?M0e(t,_He):t):t,Atr=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let o=t.indexOf(`?${e}`,8);for(o===-1&&(o=t.indexOf(`&${e}`,8));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let c=o+e.length+2,l=t.indexOf("&",c);return gHe(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";o=t.indexOf(`&${e}`,o+1)}if(n=/[%+]/.test(t),!n)return}let i={};n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let o=t.indexOf("&",s+1),a=t.indexOf("=",s);a>o&&o!==-1&&(a=-1);let c=t.slice(s+1,a===-1?o===-1?void 0:o:a);if(n&&(c=gHe(c)),s=o,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,o===-1?void 0:o),n&&(l=gHe(l))),r?(i[c]&&Array.isArray(i[c])||(i[c]=[]),i[c].push(l)):i[c]??=l}return e?i[e]:i},Otr=Atr,Ptr=(t,e)=>Atr(t,e,!0),_He=decodeURIComponent});var Dtr,k0e,mHe=p(()=>{btr();Str();Itr();i7();Dtr=t=>M0e(t,_He),k0e=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#i(e);return r&&/\%/.test(r)?Dtr(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#i(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?Dtr(n):n)}return t}#i(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Otr(this.url,t)}queries(t){return Ptr(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Etr(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let i=Object.keys(e)[0];return i?e[i].then(s=>(i==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[wtr](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}}});var $0e,qri,dK,bHe=p(()=>{$0e={Stringify:1,BeforeStream:2,Stream:3},qri=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r},dK=async(t,e,r,n,i)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);i?i[0]+=t:i=[t];let o=Promise.all(s.map(a=>a({phase:e,buffer:i,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>dK(c,e,!1,n,i))).then(()=>i[0]));return r?qri(await o,s):o}});var Ntr,wHe,ktr,SHe=p(()=>{mHe();bHe();Ntr="text/plain; charset=UTF-8",wHe=(t,e)=>({"Content-Type":t,...e}),ktr=class{#t;#e;env={};#r;finalized=!1;error;#s;#i;#n;#u;#c;#l;#a;#d;#f;constructor(t,e){this.#t=t,e&&(this.#i=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#f=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new k0e(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=new Response(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let i of n)t.headers.append("set-cookie",i)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of s)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a)}if(r)for(let[s,o]of Object.entries(r))if(typeof o=="string")n.set(s,o);else{n.delete(s);for(let a of o)n.append(s,a)}let i=typeof e=="number"?e:e?.status??this.#s;return new Response(t,{status:i,headers:n})}newResponse=(...t)=>this.#o(...t);body=(t,e,r)=>this.#o(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#o(t,e,wHe(Ntr,r));json=(t,e,r)=>this.#o(JSON.stringify(t),e,wHe("application/json",r));html=(t,e,r)=>{let n=i=>this.#o(i,e,wHe("text/html; charset=UTF-8",r));return typeof t=="object"?dK(t,$0e.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))}});var Jo,Rtr,Mtr,F0e,j0e,qO=p(()=>{Jo="ALL",Rtr="all",Mtr=["get","post","put","delete","options","patch"],F0e="Can not add a route since the matcher is already built.",j0e=class extends Error{}});var Ltr,$tr=p(()=>{Ltr="__COMPOSED_HANDLER"});var Bri,Ftr,EHe,jtr=p(()=>{_tr();SHe();qO();$tr();i7();Bri=t=>t.text("404 Not Found",404),Ftr=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},EHe=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Mtr,Rtr].forEach(i=>{this[i]=(s,...o)=>(typeof s=="string"?this.#t=s:this.#s(i,this.#t,s),o.forEach(a=>{this.#s(i,this.#t,a)}),this)}),this.on=(i,s,...o)=>{for(let a of[s].flat()){this.#t=a;for(let c of[i].flat())o.map(l=>{this.#s(c.toUpperCase(),this.#t,l)})}return this},this.use=(i,...s)=>(typeof i=="string"?this.#t=i:(this.#t="*",s.unshift(i)),s.forEach(o=>{this.#s(Jo,this.#t,o)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??yHe:Ctr}#e(){let t=new EHe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Bri;errorHandler=Ftr;route(t,e){let r=this.basePath(t);return e.routes.map(n=>{let i;e.errorHandler===Ftr?i=n.handler:(i=async(s,o)=>(await hHe([],e.errorHandler)(s,()=>n.handler(s,o))).res,i[Ltr]=n.handler),r.#s(n.method,n.path,i)}),this}basePath(t){let e=this.#e();return e._basePath=jO(this._basePath,t),e}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,e,r){let n,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let s=i?a=>{let c=i(a);return Array.isArray(c)?c:[c]}:a=>{let c;try{c=a.executionCtx}catch{}return[a.env,c]};n||=(()=>{let a=jO(this._basePath,t),c=a==="/"?0:a.length;return l=>{let u=new URL(l.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,l)}})();let o=async(a,c)=>{let l=await e(n(a.req.raw),...s(a));if(l)return l;await c()};return this.#s(Jo,jO(t,"*"),o),this}#s(t,e,r){t=t.toUpperCase(),e=jO(this._basePath,e);let n={basePath:this._basePath,path:e,method:t,handler:r};this.router.add(t,e,[r,n]),this.routes.push(n)}#i(t,e){if(t instanceof Error)return this.errorHandler(t,e);throw t}#n(t,e,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,e,r,"GET")))();let i=this.getPath(t,{env:r}),s=this.router.match(n,i),o=new ktr(t,{path:i,matchResult:s,env:r,executionCtx:e,notFoundHandler:this.#r});if(s[0].length===1){let c;try{c=s[0][0][0][0](o,async()=>{o.res=await this.#r(o)})}catch(l){return this.#i(l,o)}return c instanceof Promise?c.then(l=>l||(o.finalized?o.res:this.#r(o))).catch(l=>this.#i(l,o)):c??this.#r(o)}let a=hHe(s[0],this.errorHandler,this.#r);return(async()=>{try{let c=await a(o);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#i(c,o)}})()}fetch=(t,...e)=>this.#n(t,e[1],e[0],t.method);request=(t,e,r,n)=>t instanceof Request?this.fetch(e?new Request(t,e):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${jO("/",t)}`,e),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}}});function IHe(t,e){let r=this.buildAllMatchers(),n=(i,s)=>{let o=r[i]||r[Jo],a=o[2][s];if(a)return a;let c=s.match(o[0]);if(!c)return[[],q0e];let l=c.indexOf("",1);return[o[1][l],c]};return this.match=n,n(t,e)}var q0e,THe=p(()=>{qO();q0e=[]});function Uri(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===fK||t===pK?1:e===fK||e===pK?-1:t===B0e?1:e===B0e?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var B0e,fK,pK,BO,Vri,V0e,xHe=p(()=>{B0e="[^/]+",fK=".*",pK="(?:|/.*)",BO=Symbol(),Vri=new Set(".\\+*[^]$()");V0e=class{#t;#e;#r=Object.create(null);insert(t,e,r,n,i){if(t.length===0){if(this.#t!==void 0)throw BO;if(i)return;this.#t=e;return}let[s,...o]=t,a=s==="*"?o.length===0?["","",fK]:["","",B0e]:s==="/*"?["","",pK]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(a){let l=a[1],u=a[2]||B0e;if(l&&a[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw BO;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(d=>d!==fK&&d!==pK))throw BO;if(i)return;c=this.#r[u]=new V0e,l!==""&&(c.#e=n.varIndex++)}!i&&l!==""&&r.push([l,c.#e])}else if(c=this.#r[s],!c){if(Object.keys(this.#r).some(l=>l.length>1&&l!==fK&&l!==pK))throw BO;if(i)return;c=this.#r[s]=new V0e}c.insert(o,e,r,n,i)}buildRegExpStr(){let e=Object.keys(this.#r).sort(Uri).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:Vri.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}}});var qtr,Btr=p(()=>{xHe();qtr=class{#t={varIndex:0};#e=new V0e;insert(t,e,r){let n=[],i=[];for(let o=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${o}`;return i[o]=[l,c],o++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=i.length-1;o>=0;o--){let[a]=i[o];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,i[o][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,s,o)=>s!==void 0?(r[++e]=Number(s),"$()"):(o!==void 0&&(n[Number(o)]=++e),"")),[new RegExp(`^${t}`),r,n]}}});function Utr(t){return Vtr[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Wri(){Vtr=Object.create(null)}function Gri(t){let e=new qtr,r=[];if(t.length===0)return Hri;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,f])=>l?1:d?-1:u.length-f.length),i=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[f,h,m]=n[l];f?i[h]=[m.map(([g])=>[g,Object.create(null)]),q0e]:u++;let y;try{y=e.insert(h,u,f)}catch(g){throw g===BO?new j0e(h):g}f||(r[u]=m.map(([g,_])=>{let b=Object.create(null);for(_-=1;_>=0;_--){let[w,I]=y[_];b[w]=I}return[g,b]}))}let[s,o,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,f=r[l].length;d<f;d++){let h=r[l][d]?.[1];if(!h)continue;let m=Object.keys(h);for(let y=0,g=m.length;y<g;y++)h[m[y]]=a[h[m[y]]]}let c=[];for(let l in o)c[l]=r[o[l]];return[s,c,i]}function s7(t,e){if(t){for(let r of Object.keys(t).sort((n,i)=>i.length-n.length))if(Utr(r).test(e))return[...t[r]]}}var Hri,Vtr,U0e,CHe=p(()=>{qO();i7();THe();xHe();Btr();Hri=[/^$/,[],Object.create(null)],Vtr=Object.create(null);U0e=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Jo]:Object.create(null)},this.#e={[Jo]:Object.create(null)}}add(t,e,r){let n=this.#t,i=this.#e;if(!n||!i)throw new Error(F0e);n[t]||[n,i].forEach(a=>{a[t]=Object.create(null),Object.keys(a[Jo]).forEach(c=>{a[t][c]=[...a[Jo][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Utr(e);t===Jo?Object.keys(n).forEach(c=>{n[c][e]||=s7(n[c],e)||s7(n[Jo],e)||[]}):n[t][e]||=s7(n[t],e)||s7(n[Jo],e)||[],Object.keys(n).forEach(c=>{(t===Jo||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(i).forEach(c=>{(t===Jo||t===c)&&Object.keys(i[c]).forEach(l=>a.test(l)&&i[c][l].push([r,s]))});return}let o=L0e(e)||[e];for(let a=0,c=o.length;a<c;a++){let l=o[a];Object.keys(i).forEach(u=>{(t===Jo||t===u)&&(i[u][l]||=[...s7(n[u],l)||s7(n[Jo],l)||[]],i[u][l].push([r,s-c+a+1]))})}}match=IHe;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,Wri(),t}#r(t){let e=[],r=t===Jo;return[this.#t,this.#e].forEach(n=>{let i=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];i.length!==0?(r||=!0,e.push(...i)):t!==Jo&&e.push(...Object.keys(n[Jo]).map(s=>[s,n[Jo][s]]))}),r?Gri(e):null}}});var Htr=p(()=>{qO();THe();CHe()});var Wtr=p(()=>{CHe();Htr()});var AHe,Gtr=p(()=>{qO();AHe=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(F0e);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,i=r.length,s=0,o;for(;s<i;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);o=a.match(t,e)}catch(c){if(c instanceof j0e)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===i)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}}});var ztr=p(()=>{Gtr()});var hK,OHe,Ktr=p(()=>{qO();i7();hK=Object.create(null),OHe=class{#t;#e;#r;#s=0;#i=hK;constructor(t,e,r){if(this.#e=r||Object.create(null),this.#t=[],t&&e){let n=Object.create(null);n[t]={handler:e,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,e,r){this.#s=++this.#s;let n=this,i=Ttr(e),s=[];for(let o=0,a=i.length;o<a;o++){let c=i[o],l=i[o+1],u=xtr(c,l),d=Array.isArray(u)?u[0]:c;if(d in n.#e){n=n.#e[d],u&&s.push(u[1]);continue}n.#e[d]=new OHe,u&&(n.#r.push(u),s.push(u[1])),n=n.#e[d]}return n.#t.push({[t]:{handler:r,possibleKeys:s.filter((o,a,c)=>c.indexOf(o)===a),score:this.#s}}),n}#n(t,e,r,n){let i=[];for(let s=0,o=t.#t.length;s<o;s++){let a=t.#t[s],c=a[e]||a[Jo],l={};if(c!==void 0&&(c.params=Object.create(null),i.push(c),r!==hK||n&&n!==hK))for(let u=0,d=c.possibleKeys.length;u<d;u++){let f=c.possibleKeys[u],h=l[c.score];c.params[f]=n?.[f]&&!h?n[f]:r[f]??n?.[f],l[c.score]=!0}}return i}search(t,e){let r=[];this.#i=hK;let i=[this],s=vHe(e),o=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=a===c-1,d=[];for(let f=0,h=i.length;f<h;f++){let m=i[f],y=m.#e[l];y&&(y.#i=m.#i,u?(y.#e["*"]&&r.push(...this.#n(y.#e["*"],t,m.#i)),r.push(...this.#n(y,t,m.#i))):d.push(y));for(let g=0,_=m.#r.length;g<_;g++){let b=m.#r[g],w=m.#i===hK?{}:{...m.#i};if(b==="*"){let R=m.#e["*"];R&&(r.push(...this.#n(R,t,m.#i)),R.#i=w,d.push(R));continue}let[I,x,A]=b;if(!l&&!(A instanceof RegExp))continue;let O=m.#e[I],D=s.slice(a).join("/");if(A instanceof RegExp){let R=A.exec(D);if(R){if(w[x]=R[0],r.push(...this.#n(O,t,m.#i,w)),Object.keys(O.#e).length){O.#i=w;let J=R[0].match(/\//)?.length??0;(o[J]||=[]).push(O)}continue}}(A===!0||A.test(l))&&(w[x]=l,u?(r.push(...this.#n(O,t,w,m.#i)),O.#e["*"]&&r.push(...this.#n(O.#e["*"],t,w,m.#i))):(O.#i=w,d.push(O)))}}i=d.concat(o.shift()??[])}return r.length>1&&r.sort((a,c)=>a.score-c.score),[r.map(({handler:a,params:c})=>[a,c])]}}});var PHe,Ytr=p(()=>{i7();Ktr();PHe=class{name="TrieRouter";#t;constructor(){this.#t=new OHe}add(t,e,r){let n=L0e(e);if(n){for(let i=0,s=n.length;i<s;i++)this.#t.insert(t,n[i],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}}});var Qtr=p(()=>{Ytr()});var Po,Jtr=p(()=>{jtr();Wtr();ztr();Qtr();Po=class extends EHe{constructor(t={}){super(t),this.router=t.router??new AHe({routers:[new U0e,new PHe]})}}});var Sp=p(()=>{Jtr()});var I1,o7=p(()=>{I1=t=>{let r={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},n=(s=>typeof s=="string"?s==="*"?()=>s:o=>s===o?o:null:typeof s=="function"?s:o=>s.includes(o)?o:null)(r.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(r.allowMethods);return async function(o,a){function c(u,d){o.res.headers.set(u,d)}let l=await n(o.req.header("origin")||"",o);if(l&&c("Access-Control-Allow-Origin",l),r.credentials&&c("Access-Control-Allow-Credentials","true"),r.exposeHeaders?.length&&c("Access-Control-Expose-Headers",r.exposeHeaders.join(",")),o.req.method==="OPTIONS"){r.origin!=="*"&&c("Vary","Origin"),r.maxAge!=null&&c("Access-Control-Max-Age",r.maxAge.toString());let u=await i(o.req.header("origin")||"",o);u.length&&c("Access-Control-Allow-Methods",u.join(","));let d=r.allowHeaders;if(!d?.length){let f=o.req.header("Access-Control-Request-Headers");f&&(d=f.split(/\s*,\s*/))}return d?.length&&(c("Access-Control-Allow-Headers",d.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),r.origin!=="*"&&o.header("Vary","Origin",{append:!0})}}});var Ztr={};fr(Ztr,{__resetForTesting:()=>Yri,applySessionFps:()=>RHe,getManager:()=>pa,getPendingFpsForSession:()=>MHe,getPendingStreamConfig:()=>$He,getServerConfig:()=>Kri,getWtConfigSnapshot:()=>DHe,initContext:()=>LHe,setSessionFpsApplier:()=>kHe,setWtConfigProvider:()=>zri});function zri(t){W0e=t}function DHe(){return E(this,void 0,void 0,function*(){return W0e?yield W0e():null})}function kHe(t){mK=t}function RHe(t,e){mK?.(t,e)}function MHe(t){let e;for(let[r,n]of NHe)r.endsWith(`\0${t}`)&&(e=n.fps);return e}function LHe(t,e){return Ox||(H0e=t,Ox=e??new zM(t),e||Ox.start(),Ox)}function pa(){if(!Ox)throw new Error("PtyManagerService not initialized. Call initContext() first.");return Ox}function Kri(){if(!H0e)throw new Error("SessionServerConfig not initialized. Call initContext() first.");return H0e}function $He(){return NHe}function Yri(){Ox=null,H0e=null,W0e=null,NHe.clear(),mK=null}var Ox,H0e,W0e,NHe,mK,rS=p(()=>{ce();w0e();Ox=null,H0e=null,W0e=null;NHe=new Map,mK=null});function Xtr(t){let e=t;"keepAliveTimeout"in e&&(e.keepAliveTimeout=3e4),"requestTimeout"in e&&(e.requestTimeout=0),"headersTimeout"in e&&(e.headersTimeout=0),"timeout"in e&&(e.timeout=0)}var err=p(()=>{});function Px(t){var e;return{id:t.id,name:t.name,pid:(e=t.pid)!==null&&e!==void 0?e:null,command:t.command,parentId:t.parentId,createdAt:t.createdAt.toISOString(),lastAccessedAt:t.lastAccessedAt.toISOString(),status:t.status}}var gK=p(()=>{});var Ti,FHe,dr,T1,vK=p(()=>{(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Ti||(Ti={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(FHe||(FHe={}));dr=Ti.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T1=t=>{switch(typeof t){case"undefined":return dr.undefined;case"string":return dr.string;case"number":return Number.isNaN(t)?dr.nan:dr.number;case"boolean":return dr.boolean;case"function":return dr.function;case"bigint":return dr.bigint;case"symbol":return dr.symbol;case"object":return Array.isArray(t)?dr.array:t===null?dr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?dr.promise:typeof Map<"u"&&t instanceof Map?dr.map:typeof Set<"u"&&t instanceof Set?dr.set:typeof Date<"u"&&t instanceof Date?dr.date:dr.object;default:return dr.unknown}}});var Mt,Qri,uf,G0e=p(()=>{vK();Mt=Ti.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Qri=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),uf=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ti.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};uf.create=t=>new uf(t)});var Jri,nS,jHe=p(()=>{G0e();vK();Jri=(t,e)=>{let r;switch(t.code){case Mt.invalid_type:t.received===dr.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Mt.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ti.jsonStringifyReplacer)}`;break;case Mt.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ti.joinValues(t.keys,", ")}`;break;case Mt.invalid_union:r="Invalid input";break;case Mt.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ti.joinValues(t.options)}`;break;case Mt.invalid_enum_value:r=`Invalid enum value. Expected ${Ti.joinValues(t.options)}, received '${t.received}'`;break;case Mt.invalid_arguments:r="Invalid function arguments";break;case Mt.invalid_return_type:r="Invalid function return type";break;case Mt.invalid_date:r="Invalid date";break;case Mt.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ti.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Mt.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Mt.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Mt.custom:r="Invalid input";break;case Mt.invalid_intersection_types:r="Intersection results could not be merged";break;case Mt.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Mt.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ti.assertNever(t)}return{message:r}},nS=Jri});function Zri(t){trr=t}function a7(){return trr}var trr,z0e=p(()=>{jHe();trr=nS});function nr(t,e){let r=a7(),n=yK({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===nS?void 0:nS].filter(i=>!!i)});t.common.issues.push(n)}var yK,Xri,Yl,un,VO,Au,K0e,Y0e,Dx,c7,qHe=p(()=>{z0e();jHe();yK=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}},Xri=[];Yl=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return un;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return un;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},un=Object.freeze({status:"aborted"}),VO=t=>({status:"dirty",value:t}),Au=t=>({status:"valid",value:t}),K0e=t=>t.status==="aborted",Y0e=t=>t.status==="dirty",Dx=t=>t.status==="valid",c7=t=>typeof Promise<"u"&&t instanceof Promise});var rrr=p(()=>{});var kr,nrr=p(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(kr||(kr={}))});function Qn(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}function arr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function gni(t){return new RegExp(`^${arr(t)}$`)}function crr(t){let e=`${orr}T${arr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vni(t,e){return!!((e==="v4"||!e)&&lni.test(t)||(e==="v6"||!e)&&dni.test(t))}function yni(t,e){if(!sni.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function _ni(t,e){return!!((e==="v4"||!e)&&uni.test(t)||(e==="v6"||!e)&&fni.test(t))}function bni(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function l7(t){if(t instanceof df){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Bh.create(l7(n))}return new df({...t._def,shape:()=>e})}else return t instanceof oS?new oS({...t._def,type:l7(t.element)}):t instanceof Bh?Bh.create(l7(t.unwrap())):t instanceof C1?C1.create(l7(t.unwrap())):t instanceof x1?x1.create(t.items.map(e=>l7(e))):t}function VHe(t,e){let r=T1(t),n=T1(e);if(t===e)return{valid:!0,data:t};if(r===dr.object&&n===dr.object){let i=Ti.objectKeys(e),s=Ti.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=VHe(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===dr.array&&n===dr.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let o=t[s],a=e[s],c=VHe(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===dr.date&&n===dr.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function lrr(t,e){return new XO({values:t,typeName:Lt.ZodEnum,...Qn(e)})}function srr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function urr(t,e={},r){return t?kx.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(o=>{if(!o){let a=srr(e,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=srr(e,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):kx.create()}var Vh,irr,Jn,eni,tni,rni,nni,ini,sni,oni,ani,cni,BHe,lni,uni,dni,fni,pni,hni,orr,mni,Nx,UO,HO,WO,GO,u7,zO,KO,kx,sS,J0,d7,oS,df,YO,iS,Q0e,QO,x1,J0e,f7,p7,Z0e,JO,ZO,XO,eP,Rx,Uh,Bh,C1,tP,rP,h7,wni,_K,bK,nP,Sni,Lt,Eni,drr,frr,Ini,Tni,prr,xni,Cni,Ani,Oni,Pni,Dni,Nni,kni,Rni,Mni,Lni,$ni,Fni,jni,qni,Bni,Vni,Uni,Hni,Wni,Gni,zni,Kni,Yni,Qni,Jni,Zni,Xni,eii,tii,rii,nii,iii,sii,hrr=p(()=>{G0e();z0e();nrr();qHe();vK();Vh=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},irr=(t,e)=>{if(Dx(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new uf(t.common.issues);return this._error=r,this._error}}};Jn=class{get description(){return this._def.description}_getType(e){return T1(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:T1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Yl,ctx:{common:e.parent.common,data:e.data,parsedType:T1(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(c7(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)},i=this._parseSync({data:e,path:n.path,parent:n});return irr(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Dx(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Dx(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T1(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(c7(i)?i:Promise.resolve(i));return irr(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:Mt.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Uh({schema:this,typeName:Lt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Bh.create(this,this._def)}nullable(){return C1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oS.create(this)}promise(){return Rx.create(this,this._def)}or(e){return YO.create([this,e],this._def)}and(e){return QO.create(this,e,this._def)}transform(e){return new Uh({...Qn(this._def),schema:this,typeName:Lt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new tP({...Qn(this._def),innerType:this,defaultValue:r,typeName:Lt.ZodDefault})}brand(){return new _K({typeName:Lt.ZodBranded,type:this,...Qn(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new rP({...Qn(this._def),innerType:this,catchValue:r,typeName:Lt.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return bK.create(this,e)}readonly(){return nP.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eni=/^c[^\s-]{8,}$/i,tni=/^[0-9a-z]+$/,rni=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nni=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ini=/^[a-z0-9_-]{21}$/i,sni=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oni=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ani=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cni="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lni=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,uni=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,dni=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,fni=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pni=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hni=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,orr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",mni=new RegExp(`^${orr}$`);Nx=class t extends Jn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==dr.string){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.string,received:s.parsedType}),un}let n=new Yl,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(e,i),o?nr(i,{code:Mt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&nr(i,{code:Mt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")ani.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"email",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")BHe||(BHe=new RegExp(cni,"u")),BHe.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"emoji",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")nni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"uuid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ini.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"nanoid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")eni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cuid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")tni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cuid2",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")rni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"ulid",code:Mt.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),nr(i,{validation:"url",code:Mt.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"regex",code:Mt.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?crr(s).test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?mni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?gni(s).test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?oni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"duration",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?vni(e.data,s.version)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"ip",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?yni(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"jwt",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?_ni(e.data,s.version)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"cidr",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?pni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"base64",code:Mt.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?hni.test(e.data)||(i=this._getOrReturnCtx(e,i),nr(i,{validation:"base64url",code:Mt.invalid_string,message:s.message}),n.dirty()):Ti.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Mt.invalid_string,...kr.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...kr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...kr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...kr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...kr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...kr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...kr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...kr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...kr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...kr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...kr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...kr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...kr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...kr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...kr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...kr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...kr.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...kr.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...kr.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...kr.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...kr.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...kr.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...kr.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...kr.errToObj(r)})}nonempty(e){return this.min(1,kr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Nx.create=t=>new Nx({checks:[],typeName:Lt.ZodString,coerce:t?.coerce??!1,...Qn(t)});UO=class t extends Jn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==dr.number){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.number,received:s.parsedType}),un}let n,i=new Yl;for(let s of this._def.checks)s.kind==="int"?Ti.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?bni(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_finite,message:s.message}),i.dirty()):Ti.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,kr.toString(r))}gt(e,r){return this.setLimit("min",e,!1,kr.toString(r))}lte(e,r){return this.setLimit("max",e,!0,kr.toString(r))}lt(e,r){return this.setLimit("max",e,!1,kr.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:kr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:kr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:kr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:kr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:kr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:kr.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:kr.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:kr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:kr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:kr.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ti.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};UO.create=t=>new UO({checks:[],typeName:Lt.ZodNumber,coerce:t?.coerce||!1,...Qn(t)});HO=class t extends Jn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==dr.bigint)return this._getInvalidInput(e);let n,i=new Yl;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:Mt.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Ti.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return nr(r,{code:Mt.invalid_type,expected:dr.bigint,received:r.parsedType}),un}gte(e,r){return this.setLimit("min",e,!0,kr.toString(r))}gt(e,r){return this.setLimit("min",e,!1,kr.toString(r))}lte(e,r){return this.setLimit("max",e,!0,kr.toString(r))}lt(e,r){return this.setLimit("max",e,!1,kr.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:kr.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:kr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:kr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:kr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:kr.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:kr.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};HO.create=t=>new HO({checks:[],typeName:Lt.ZodBigInt,coerce:t?.coerce??!1,...Qn(t)});WO=class extends Jn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==dr.boolean){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.boolean,received:n.parsedType}),un}return Au(e.data)}};WO.create=t=>new WO({typeName:Lt.ZodBoolean,coerce:t?.coerce||!1,...Qn(t)});GO=class t extends Jn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==dr.date){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_type,expected:dr.date,received:s.parsedType}),un}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return nr(s,{code:Mt.invalid_date}),un}let n=new Yl,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),nr(i,{code:Mt.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ti.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:kr.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:kr.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};GO.create=t=>new GO({checks:[],coerce:t?.coerce||!1,typeName:Lt.ZodDate,...Qn(t)});u7=class extends Jn{_parse(e){if(this._getType(e)!==dr.symbol){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.symbol,received:n.parsedType}),un}return Au(e.data)}};u7.create=t=>new u7({typeName:Lt.ZodSymbol,...Qn(t)});zO=class extends Jn{_parse(e){if(this._getType(e)!==dr.undefined){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.undefined,received:n.parsedType}),un}return Au(e.data)}};zO.create=t=>new zO({typeName:Lt.ZodUndefined,...Qn(t)});KO=class extends Jn{_parse(e){if(this._getType(e)!==dr.null){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.null,received:n.parsedType}),un}return Au(e.data)}};KO.create=t=>new KO({typeName:Lt.ZodNull,...Qn(t)});kx=class extends Jn{constructor(){super(...arguments),this._any=!0}_parse(e){return Au(e.data)}};kx.create=t=>new kx({typeName:Lt.ZodAny,...Qn(t)});sS=class extends Jn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Au(e.data)}};sS.create=t=>new sS({typeName:Lt.ZodUnknown,...Qn(t)});J0=class extends Jn{_parse(e){let r=this._getOrReturnCtx(e);return nr(r,{code:Mt.invalid_type,expected:dr.never,received:r.parsedType}),un}};J0.create=t=>new J0({typeName:Lt.ZodNever,...Qn(t)});d7=class extends Jn{_parse(e){if(this._getType(e)!==dr.undefined){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.void,received:n.parsedType}),un}return Au(e.data)}};d7.create=t=>new d7({typeName:Lt.ZodVoid,...Qn(t)});oS=class t extends Jn{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==dr.array)return nr(r,{code:Mt.invalid_type,expected:dr.array,received:r.parsedType}),un;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(nr(r,{code:o?Mt.too_big:Mt.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(nr(r,{code:Mt.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(nr(r,{code:Mt.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Vh(r,o,r.path,a)))).then(o=>Yl.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Vh(r,o,r.path,a)));return Yl.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:kr.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:kr.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:kr.toString(r)}})}nonempty(e){return this.min(1,e)}};oS.create=(t,e)=>new oS({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Lt.ZodArray,...Qn(e)});df=class t extends Jn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Ti.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==dr.object){let l=this._getOrReturnCtx(e);return nr(l,{code:Mt.invalid_type,expected:dr.object,received:l.parsedType}),un}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof J0&&this._def.unknownKeys==="strip"))for(let l in i.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=s[l],d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Vh(i,d,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof J0){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")a.length>0&&(nr(i,{code:Mt.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Vh(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Yl.mergeObjectSync(n,l)):Yl.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return kr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:kr.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Lt.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ti.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ti.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return l7(this)}partial(e){let r={};for(let n of Ti.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ti.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Bh;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return lrr(Ti.objectKeys(this.shape))}};df.create=(t,e)=>new df({shape:()=>t,unknownKeys:"strip",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});df.strictCreate=(t,e)=>new df({shape:()=>t,unknownKeys:"strict",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});df.lazycreate=(t,e)=>new df({shape:t,unknownKeys:"strip",catchall:J0.create(),typeName:Lt.ZodObject,...Qn(e)});YO=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new uf(a.ctx.common.issues));return nr(r,{code:Mt.invalid_union,unionErrors:o}),un}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new uf(c));return nr(r,{code:Mt.invalid_union,unionErrors:a}),un}}get options(){return this._def.options}};YO.create=(t,e)=>new YO({options:t,typeName:Lt.ZodUnion,...Qn(e)});iS=t=>t instanceof JO?iS(t.schema):t instanceof Uh?iS(t.innerType()):t instanceof ZO?[t.value]:t instanceof XO?t.options:t instanceof eP?Ti.objectValues(t.enum):t instanceof tP?iS(t._def.innerType):t instanceof zO?[void 0]:t instanceof KO?[null]:t instanceof Bh?[void 0,...iS(t.unwrap())]:t instanceof C1?[null,...iS(t.unwrap())]:t instanceof _K||t instanceof nP?iS(t.unwrap()):t instanceof rP?iS(t._def.innerType):[],Q0e=class t extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.object)return nr(r,{code:Mt.invalid_type,expected:dr.object,received:r.parsedType}),un;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(nr(r,{code:Mt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),un)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=iS(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:Lt.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Qn(n)})}};QO=class extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,o)=>{if(K0e(s)||K0e(o))return un;let a=VHe(s.value,o.value);return a.valid?((Y0e(s)||Y0e(o))&&r.dirty(),{status:r.value,value:a.data}):(nr(n,{code:Mt.invalid_intersection_types}),un)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};QO.create=(t,e,r)=>new QO({left:t,right:e,typeName:Lt.ZodIntersection,...Qn(r)});x1=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.array)return nr(n,{code:Mt.invalid_type,expected:dr.array,received:n.parsedType}),un;if(n.data.length<this._def.items.length)return nr(n,{code:Mt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),un;!this._def.rest&&n.data.length>this._def.items.length&&(nr(n,{code:Mt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Vh(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Yl.mergeArray(r,o)):Yl.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};x1.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new x1({items:t,typeName:Lt.ZodTuple,rest:null,...Qn(e)})};J0e=class t extends Jn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.object)return nr(n,{code:Mt.invalid_type,expected:dr.object,received:n.parsedType}),un;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Vh(n,a,n.path,a)),value:o._parse(new Vh(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Yl.mergeObjectAsync(r,i):Yl.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Jn?new t({keyType:e,valueType:r,typeName:Lt.ZodRecord,...Qn(n)}):new t({keyType:Nx.create(),valueType:e,typeName:Lt.ZodRecord,...Qn(r)})}},f7=class extends Jn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.map)return nr(n,{code:Mt.invalid_type,expected:dr.map,received:n.parsedType}),un;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:i._parse(new Vh(n,a,n.path,[l,"key"])),value:s._parse(new Vh(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return un;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return un;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};f7.create=(t,e,r)=>new f7({valueType:e,keyType:t,typeName:Lt.ZodMap,...Qn(r)});p7=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==dr.set)return nr(n,{code:Mt.invalid_type,expected:dr.set,received:n.parsedType}),un;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(nr(n,{code:Mt.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(nr(n,{code:Mt.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return un;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new Vh(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:kr.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:kr.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};p7.create=(t,e)=>new p7({valueType:t,minSize:null,maxSize:null,typeName:Lt.ZodSet,...Qn(e)});Z0e=class t extends Jn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.function)return nr(r,{code:Mt.invalid_type,expected:dr.function,received:r.parsedType}),un;function n(a,c){return yK({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a7(),nS].filter(l=>!!l),issueData:{code:Mt.invalid_arguments,argumentsError:c}})}function i(a,c){return yK({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,a7(),nS].filter(l=>!!l),issueData:{code:Mt.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Rx){let a=this;return Au(async function(...c){let l=new uf([]),u=await a._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw l.addIssue(i(d,h)),l})})}else{let a=this;return Au(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new uf([n(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new uf([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:x1.create(e).rest(sS.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||x1.create([]).rest(sS.create()),returns:r||sS.create(),typeName:Lt.ZodFunction,...Qn(n)})}},JO=class extends Jn{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};JO.create=(t,e)=>new JO({getter:t,typeName:Lt.ZodLazy,...Qn(e)});ZO=class extends Jn{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return nr(r,{received:r.data,code:Mt.invalid_literal,expected:this._def.value}),un}return{status:"valid",value:e.data}}get value(){return this._def.value}};ZO.create=(t,e)=>new ZO({value:t,typeName:Lt.ZodLiteral,...Qn(e)});XO=class t extends Jn{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return nr(r,{expected:Ti.joinValues(n),received:r.parsedType,code:Mt.invalid_type}),un}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return nr(r,{received:r.data,code:Mt.invalid_enum_value,options:n}),un}return Au(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};XO.create=lrr;eP=class extends Jn{_parse(e){let r=Ti.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==dr.string&&n.parsedType!==dr.number){let i=Ti.objectValues(r);return nr(n,{expected:Ti.joinValues(i),received:n.parsedType,code:Mt.invalid_type}),un}if(this._cache||(this._cache=new Set(Ti.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ti.objectValues(r);return nr(n,{received:n.data,code:Mt.invalid_enum_value,options:i}),un}return Au(e.data)}get enum(){return this._def.values}};eP.create=(t,e)=>new eP({values:t,typeName:Lt.ZodNativeEnum,...Qn(e)});Rx=class extends Jn{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==dr.promise&&r.common.async===!1)return nr(r,{code:Mt.invalid_type,expected:dr.promise,received:r.parsedType}),un;let n=r.parsedType===dr.promise?r.data:Promise.resolve(r.data);return Au(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Rx.create=(t,e)=>new Rx({type:t,typeName:Lt.ZodPromise,...Qn(e)});Uh=class extends Jn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Lt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{nr(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return un;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?un:c.status==="dirty"?VO(c.value):r.value==="dirty"?VO(c.value):c});{if(r.value==="aborted")return un;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?un:a.status==="dirty"?VO(a.value):r.value==="dirty"?VO(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?un:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?un:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Dx(o))return un;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Dx(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):un);Ti.assertNever(i)}};Uh.create=(t,e,r)=>new Uh({schema:t,typeName:Lt.ZodEffects,effect:e,...Qn(r)});Uh.createWithPreprocess=(t,e,r)=>new Uh({schema:e,effect:{type:"preprocess",transform:t},typeName:Lt.ZodEffects,...Qn(r)});Bh=class extends Jn{_parse(e){return this._getType(e)===dr.undefined?Au(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bh.create=(t,e)=>new Bh({innerType:t,typeName:Lt.ZodOptional,...Qn(e)});C1=class extends Jn{_parse(e){return this._getType(e)===dr.null?Au(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C1.create=(t,e)=>new C1({innerType:t,typeName:Lt.ZodNullable,...Qn(e)});tP=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===dr.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};tP.create=(t,e)=>new tP({innerType:t,typeName:Lt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Qn(e)});rP=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return c7(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new uf(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new uf(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};rP.create=(t,e)=>new rP({innerType:t,typeName:Lt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Qn(e)});h7=class extends Jn{_parse(e){if(this._getType(e)!==dr.nan){let n=this._getOrReturnCtx(e);return nr(n,{code:Mt.invalid_type,expected:dr.nan,received:n.parsedType}),un}return{status:"valid",value:e.data}}};h7.create=t=>new h7({typeName:Lt.ZodNaN,...Qn(t)});wni=Symbol("zod_brand"),_K=class extends Jn{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},bK=class t extends Jn{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?un:s.status==="dirty"?(r.dirty(),VO(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?un:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Lt.ZodPipeline})}},nP=class extends Jn{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Dx(i)&&(i.value=Object.freeze(i.value)),i);return c7(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};nP.create=(t,e)=>new nP({innerType:t,typeName:Lt.ZodReadonly,...Qn(e)});Sni={object:df.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Lt||(Lt={}));Eni=(t,e={message:`Input not instance of ${t.name}`})=>urr(r=>r instanceof t,e),drr=Nx.create,frr=UO.create,Ini=h7.create,Tni=HO.create,prr=WO.create,xni=GO.create,Cni=u7.create,Ani=zO.create,Oni=KO.create,Pni=kx.create,Dni=sS.create,Nni=J0.create,kni=d7.create,Rni=oS.create,Mni=df.create,Lni=df.strictCreate,$ni=YO.create,Fni=Q0e.create,jni=QO.create,qni=x1.create,Bni=J0e.create,Vni=f7.create,Uni=p7.create,Hni=Z0e.create,Wni=JO.create,Gni=ZO.create,zni=XO.create,Kni=eP.create,Yni=Rx.create,Qni=Uh.create,Jni=Bh.create,Zni=C1.create,Xni=Uh.createWithPreprocess,eii=bK.create,tii=()=>drr().optional(),rii=()=>frr().optional(),nii=()=>prr().optional(),iii={string:(t=>Nx.create({...t,coerce:!0})),number:(t=>UO.create({...t,coerce:!0})),boolean:(t=>WO.create({...t,coerce:!0})),bigint:(t=>HO.create({...t,coerce:!0})),date:(t=>GO.create({...t,coerce:!0}))},sii=un});var B={};fr(B,{BRAND:()=>wni,DIRTY:()=>VO,EMPTY_PATH:()=>Xri,INVALID:()=>un,NEVER:()=>sii,OK:()=>Au,ParseStatus:()=>Yl,Schema:()=>Jn,ZodAny:()=>kx,ZodArray:()=>oS,ZodBigInt:()=>HO,ZodBoolean:()=>WO,ZodBranded:()=>_K,ZodCatch:()=>rP,ZodDate:()=>GO,ZodDefault:()=>tP,ZodDiscriminatedUnion:()=>Q0e,ZodEffects:()=>Uh,ZodEnum:()=>XO,ZodError:()=>uf,ZodFirstPartyTypeKind:()=>Lt,ZodFunction:()=>Z0e,ZodIntersection:()=>QO,ZodIssueCode:()=>Mt,ZodLazy:()=>JO,ZodLiteral:()=>ZO,ZodMap:()=>f7,ZodNaN:()=>h7,ZodNativeEnum:()=>eP,ZodNever:()=>J0,ZodNull:()=>KO,ZodNullable:()=>C1,ZodNumber:()=>UO,ZodObject:()=>df,ZodOptional:()=>Bh,ZodParsedType:()=>dr,ZodPipeline:()=>bK,ZodPromise:()=>Rx,ZodReadonly:()=>nP,ZodRecord:()=>J0e,ZodSchema:()=>Jn,ZodSet:()=>p7,ZodString:()=>Nx,ZodSymbol:()=>u7,ZodTransformer:()=>Uh,ZodTuple:()=>x1,ZodType:()=>Jn,ZodUndefined:()=>zO,ZodUnion:()=>YO,ZodUnknown:()=>sS,ZodVoid:()=>d7,addIssueToContext:()=>nr,any:()=>Pni,array:()=>Rni,bigint:()=>Tni,boolean:()=>prr,coerce:()=>iii,custom:()=>urr,date:()=>xni,datetimeRegex:()=>crr,defaultErrorMap:()=>nS,discriminatedUnion:()=>Fni,effect:()=>Qni,enum:()=>zni,function:()=>Hni,getErrorMap:()=>a7,getParsedType:()=>T1,instanceof:()=>Eni,intersection:()=>jni,isAborted:()=>K0e,isAsync:()=>c7,isDirty:()=>Y0e,isValid:()=>Dx,late:()=>Sni,lazy:()=>Wni,literal:()=>Gni,makeIssue:()=>yK,map:()=>Vni,nan:()=>Ini,nativeEnum:()=>Kni,never:()=>Nni,null:()=>Oni,nullable:()=>Zni,number:()=>frr,object:()=>Mni,objectUtil:()=>FHe,oboolean:()=>nii,onumber:()=>rii,optional:()=>Jni,ostring:()=>tii,pipeline:()=>eii,preprocess:()=>Xni,promise:()=>Yni,quotelessJson:()=>Qri,record:()=>Bni,set:()=>Uni,setErrorMap:()=>Zri,strictObject:()=>Lni,string:()=>drr,symbol:()=>Cni,transformer:()=>Qni,tuple:()=>qni,undefined:()=>Ani,union:()=>$ni,unknown:()=>Dni,util:()=>Ti,void:()=>kni});var UHe=p(()=>{z0e();qHe();rrr();vK();hrr();G0e()});var _c=p(()=>{UHe();UHe()});function grr(t){return oii.includes(t)}function vrr(t){if(/^C-(.+)$/i.test(t)){let e=t.slice(2).toLowerCase();return e.length===1&&e>="a"&&e<="z"?String.fromCharCode(e.charCodeAt(0)-96):e==="space"||e==="@"?"\0":e==="["?"\x1B":e==="\\"?"":e==="]"?"":e==="^"?"":e==="_"?"":t}return/^M-(.+)$/i.test(t)?"\x1B"+t.slice(2):/^[A-Z]/.test(t)&&t.length>1&&mrr[t]?mrr[t]:t}var oii,mrr,yrr=p(()=>{oii=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];mrr={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"}});import{randomUUID as aii}from"crypto";function HHe(t){return E(this,void 0,void 0,function*(){try{return yield t.req.json()}catch{return null}})}function _rr(){let t=new Po;return t.post("/sessions",e=>E(this,void 0,void 0,function*(){var r,n;let i=cii.safeParse(yield HHe(e));if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let s=i.data,o=(r=s.id)!==null&&r!==void 0?r:aii(),a=yield pa().createSession({id:o,name:(n=s.name)!==null&&n!==void 0?n:o.slice(0,8),command:s.command,parentId:s.parentId,cwd:s.cwd,env:s.env});return e.json(Px(a),201)})),t.patch("/sessions/:id",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=lii.safeParse(yield HHe(e));if(!n.success)return e.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=pa().getSession(r);if(!i)return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:s,status:o,cols:a,rows:c}=n.data;a!==void 0&&c!==void 0&&pa().resize(r,a,c),o==="detached"&&(i.status="detached"),s!==void 0&&pa().renameSession(r,s);let l=pa().getSession(r);return e.json(Px(l??i))})),t.delete("/sessions/:id",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id");return yield pa().destroySession(r),e.json({success:!0,id:r})})),t.post("/sessions/:id/input",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=yield HHe(e),i=uii.safeParse(n),s=i.success?null:dii.safeParse(n);if(!i.success&&!s?.success)return e.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!pa().getSession(r))return e.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return pa().input(r,i.data.data),e.json({success:!0,id:r});let{keys:o,literal:a}=s.success?s.data:{keys:[],literal:!1},c=o.filter(l=>!grr(l)).map(l=>a?l:vrr(l)).join("");return c.length>0&&pa().input(r,c),e.json({success:!0,id:r})})),t}var cii,lii,uii,dii,brr=p(()=>{ce();Sp();_c();rS();gK();yrr();cii=B.object({id:B.string().optional(),name:B.string().optional(),command:B.string().optional(),parentId:B.string().optional(),cwd:B.string().optional(),env:B.record(B.string(),B.string()).optional()}),lii=B.object({name:B.string().optional(),status:B.literal("detached").optional(),cols:B.number().optional(),rows:B.number().optional()}).refine(t=>t.name!==void 0||t.status!==void 0||t.cols!==void 0&&t.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),uii=B.object({data:B.string()}),dii=B.object({keys:B.array(B.string()),literal:B.boolean().optional()})});function wrr(){let t=new Po;return t.put("/sessions/:id/stream-config",e=>E(this,void 0,void 0,function*(){let r=e.req.param("id"),n=null;try{n=yield e.req.json()}catch{}let i=fii.safeParse(n);if(!i.success)return e.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:s,fps:o}=i.data,a=`${s}\0${r}`;return $He().set(a,{fps:o}),RHe(r,o),e.json({success:!0,id:r})})),t.get("/system/wt-config",e=>E(this,void 0,void 0,function*(){return e.json(yield DHe())})),t}var fii,Srr=p(()=>{ce();Sp();_c();rS();fii=B.object({peerId:B.string(),fps:B.number()})});function X0e(t){var e,r;let n=(e=t.intervalMs)!==null&&e!==void 0?e:25e3,i=(r=t.now)!==null&&r!==void 0?r:(()=>Date.now()),s=new TextEncoder,o=!1,a=setInterval(()=>{if(!o)try{t.enqueue(s.encode(`: heartbeat ${i()}
281
281
 
282
282
  `))}catch{c()}},n),c=()=>{o||(o=!0,clearInterval(a))};return t.signal&&(t.signal.aborted?c():t.signal.addEventListener("abort",c,{once:!0})),c}var WHe=p(()=>{});function Err(t){let e=new TextEncoder,r;try{r=t.req.raw.signal}catch{r=void 0}let n=!1,i=null,s=null,o=()=>{n=!0;try{i?.unsubscribe()}catch{}try{s?.()}catch{}},a=new ReadableStream({start(c){c.enqueue(e.encode(`: sse-init
283
283
 
@@ -950,7 +950,7 @@ Error: ${d}
950
950
  To fix: Run "planx server restart" in your terminal.`)}return Xp(`Server Status: CONNECTED
951
951
  Transport Port File: ${u.transportPortFile}
952
952
  Transport Port Exists: ${u.transportPortExists}`)})),t.tool("list_sessions",{serverId:B.string().optional().describe("Server ID or name to filter sessions"),parentId:B.string().optional().describe("Parent session ID to filter child sessions")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=h7r(u.serverId,d),h=Bat(u.parentId,d),m=o.listSessions(f,{timeout:8e3});m.catch(()=>{});let y=yield Promise.race([m,new Promise((g,_)=>setTimeout(()=>_(new Error("list_sessions timed out after 9s (server unreachable)")),9e3))]);return y=g7r(y,d),h&&!Hf(d)&&(y=y.filter(g=>g.parentId===h)),Xp(`Found ${y.length} sessions
953
- ${JSON.stringify(y,null,2)}`)}catch(d){return aE(d)}})),t.tool("create_session",{serverId:B.string().optional().describe("Target server ID or name to create session on"),name:B.string().describe("Session name"),command:B.string().optional().describe("Command to run (default: ~/.planx/config.json `defaultCommand` or /bin/bash)"),parentId:B.string().optional().describe("Parent session ID for hierarchical sessions"),cwd:B.string().optional().describe("Working directory for the session"),env:B.record(B.string()).optional().describe("Environment variables for the session")},u=>E(this,void 0,void 0,function*(){let d=Date.now();console.error(`[MCP create_session] START serverId=${u.serverId} name=${u.name} parentId=${u.parentId||"none"}`);try{let f=Zp(),h=r.getServers?yield r.getServers():[],m=yield m8(u.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");let y=Bat(u.parentId,f),g=yield n.createSession({id:$p(),serverId:m,name:u.name,command:u.command||l||"/bin/bash",parentId:y,cwd:u.cwd,env:u.env});return console.error(`[MCP create_session] SUCCESS elapsed=${Date.now()-d}ms`),Xp(`Session created successfully
953
+ ${JSON.stringify(y,null,2)}`)}catch(d){return aE(d)}})),t.tool("create_session",{serverId:B.string().optional().describe("Target server ID or name to create session on"),name:B.string().describe("Session name"),command:B.string().optional().describe("Command to run (default: ~/.planx/config.json `defaultCommand` or /bin/bash)"),parentId:B.string().optional().describe("Parent session ID for hierarchical sessions"),cwd:B.string().optional().describe("Working directory for the session"),env:B.record(B.string(),B.string()).optional().describe("Environment variables for the session")},u=>E(this,void 0,void 0,function*(){let d=Date.now();console.error(`[MCP create_session] START serverId=${u.serverId} name=${u.name} parentId=${u.parentId||"none"}`);try{let f=Zp(),h=r.getServers?yield r.getServers():[],m=yield m8(u.serverId,f,h);if(!m)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");let y=Bat(u.parentId,f),g=yield n.createSession({id:$p(),serverId:m,name:u.name,command:u.command||l||"/bin/bash",parentId:y,cwd:u.cwd,env:u.env});return console.error(`[MCP create_session] SUCCESS elapsed=${Date.now()-d}ms`),Xp(`Session created successfully
954
954
  ${JSON.stringify(g,null,2)}`)}catch(f){return console.error(`[MCP create_session] ERROR elapsed=${Date.now()-d}ms error=${f?.message}`),aE(f)}})),t.tool("rename_session",{serverId:B.string().optional().describe("Server ID or name where the session exists"),sessionId:B.string().describe("Session ID to rename"),newName:B.string().describe("New name for the session")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=r.getServers?yield r.getServers():[],h=yield m8(u.serverId,d,f);if(!h)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield mq(h,u.sessionId,d,o),yield s.renameSession({serverId:h,sessionId:u.sessionId,newName:u.newName}),Xp(`Session renamed to "${u.newName}" successfully`)}catch(d){return aE(d)}})),t.tool("delete_session",{serverId:B.string().optional().describe("Server ID or name where the session exists"),sessionId:B.string().describe("Session ID to delete")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=r.getServers?yield r.getServers():[],h=yield m8(u.serverId,d,f);if(!h)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield mq(h,u.sessionId,d,o),yield i.deleteSession({serverId:h,sessionId:u.sessionId}),Xp(`Session ${u.sessionId} deleted successfully`)}catch(d){return aE(d)}})),t.tool("send_keys",{serverId:B.string().optional().describe("Server ID or name where the session exists"),sessionId:B.string().describe("Session ID to send keys to"),keys:B.array(B.string()).describe("Keys to send (e.g., ['ls -la', 'Enter'], ['C-c'] for Ctrl+C)"),literal:B.boolean().optional().describe("If true, send keys literally without interpretation")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=r.getServers?yield r.getServers():[],h=yield m8(u.serverId,d,f);if(!h)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");return yield mq(h,u.sessionId,d,o),yield c.sendKeysToSession(h,u.sessionId,u.keys,{literal:u.literal}),Xp(`Keys sent successfully to session ${u.sessionId}`)}catch(d){return aE(d)}})),t.tool("get_session_output",{serverId:B.string().optional().describe("Server ID or name where the session exists"),sessionId:B.string().describe("Session ID to get output from"),lines:B.number().optional().describe("Number of lines to retrieve (default: all)")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=r.getServers?yield r.getServers():[],h=yield m8(u.serverId,d,f);if(!h)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");yield mq(h,u.sessionId,d,o);let m=yield a.getOutput({serverId:h,sessionId:u.sessionId,lines:u.lines});return Xp(m.output||"(no output)")}catch(d){return aE(d)}})),t.tool("resize_session",{serverId:B.string().optional().describe("Server ID or name where the session exists"),sessionId:B.string().describe("Session ID to resize"),cols:B.number().describe("Number of columns"),rows:B.number().describe("Number of rows")},u=>E(this,void 0,void 0,function*(){try{let d=Zp(),f=r.getServers?yield r.getServers():[],h=yield m8(u.serverId,d,f);if(!h)throw new Error("serverId is required. Provide it as a parameter or set PLANX_SERVER_ID environment variable.");yield mq(h,u.sessionId,d,o);let m=yield r.resolveServerPeerId(h);return yield r.resize(m,u.sessionId,{cols:u.cols,rows:u.rows}),Xp(`Session ${u.sessionId} resized to ${u.cols}x${u.rows}`)}catch(d){return aE(d)}}))}var _7r=p(()=>{ce();_c();im();STe()});var b7r=p(()=>{});import{readFile as _ki}from"fs/promises";import{homedir as bki}from"os";import{join as wki}from"path";function S7r(){return E(this,void 0,void 0,function*(){var t,e,r;try{let n=yield _ki(w7r,"utf-8"),i=JSON.parse(n);if(!(!((t=i.env)===null||t===void 0)&&t.ANTHROPIC_AUTH_TOKEN))throw new Error("ANTHROPIC_AUTH_TOKEN is required in settings.zai.json");if(!(!((e=i.env)===null||e===void 0)&&e.ANTHROPIC_BASE_URL))throw new Error("ANTHROPIC_BASE_URL is required in settings.zai.json");if(!(!((r=i.env)===null||r===void 0)&&r.ANTHROPIC_DEFAULT_SONNET_MODEL))throw new Error("ANTHROPIC_DEFAULT_SONNET_MODEL is required in settings.zai.json");return i}catch(n){throw n.code==="ENOENT"?new Error(`z.ai settings file not found at ${w7r}. Please create it with the following format:
955
955
  `+JSON.stringify({env:{ANTHROPIC_AUTH_TOKEN:"your-zai-api-key",ANTHROPIC_BASE_URL:"https://api.z.ai/api/anthropic",ANTHROPIC_DEFAULT_SONNET_MODEL:"glm-4.7"}},null,2)):n}})}var w7r,E7r=p(()=>{ce();w7r=wki(bki(),".claude","settings.zai.json")});function gq(t){return new Promise(e=>setTimeout(e,t))}function T7r(){return`subagent-${Date.now()}`}function x7r(t){return[[`export ANTHROPIC_AUTH_TOKEN='${t.env.ANTHROPIC_AUTH_TOKEN}'`,"Enter"],[`export ANTHROPIC_BASE_URL='${t.env.ANTHROPIC_BASE_URL}'`,"Enter"],[`export ANTHROPIC_DEFAULT_SONNET_MODEL='${t.env.ANTHROPIC_DEFAULT_SONNET_MODEL}'`,"Enter"]]}function C7r(t){switch(t){case"machina":return["machina agent --json","Enter"];case"claude":return["claude --dangerously-skip-permissions","Enter"]}}function Vat(t,e){switch(e){case"machina":return t.includes('"status"')&&(t.includes('"running"')||t.includes('"completed"'));case"claude":return t.includes(">")||t.includes("\u276F")}}function A7r(t,e){switch(e){case"machina":return t.includes('"status": "success"')||t.includes('"status": "error"')||t.includes('"status":"success"')||t.includes('"status":"error"');case"claude":let n=t.trim().split(`
956
956
  `).slice(-5).join(`
@@ -958,7 +958,7 @@ ${JSON.stringify(g,null,2)}`)}catch(f){return console.error(`[MCP create_session
958
958
  ${y.output}`);return vq.info("[Subagent] Agent started successfully"),d})}var vq,P7r=p(()=>{ce();im();Rt();ETe();vq=qe("Subagent")});function N7r(t,e){return E(this,void 0,void 0,function*(){let{serverId:r,sessionId:n,sessionName:i,agentType:s,startTime:o,timeoutMs:a}=t,c=s==="machina"?50:20;for(;Date.now()-o<a;){yield gq(5e3);let u=yield e.getOutput({serverId:r,sessionId:n,lines:c});if(A7r(u.output||"",s)){D7r.info("[Subagent] Task completed");let d=yield e.getOutput({serverId:r,sessionId:n,lines:100});return{sessionId:n,sessionName:i,status:"completed",output:d.output||"",duration:Math.round((Date.now()-o)/1e3),agentType:s}}}D7r.warn("[Subagent] Task timed out");let l=yield e.getOutput({serverId:r,sessionId:n,lines:100});return{sessionId:n,sessionName:i,status:"timeout",output:l.output||"",duration:Math.round((Date.now()-o)/1e3),agentType:s,error:`Task timed out after ${Math.round(a/1e3)} seconds`}})}var D7r,k7r=p(()=>{ce();Rt();ETe();D7r=qe("Subagent")});function R7r(t,e,r,n){return E(this,void 0,void 0,function*(){let{task:i,agentType:s,timeout:o,sessionName:a}=t,{serverId:c,parentId:l}=e,{sessionCreateService:u,sessionLogService:d,sendKeyUsecase:f}=n,h=Date.now(),m=a||T7r(),y;try{return y=yield O7r({serverId:c,parentId:l,sessionName:m,agentType:s,settings:r},{sessionCreateService:u,sessionLogService:d,sendKeyUsecase:f}),console.error("[Subagent] Sending task"),yield f.sendKeysToSession(c,y,[i,"Enter"]),console.error("[Subagent] Waiting for task completion"),yield N7r({serverId:c,sessionId:y,sessionName:m,agentType:s,startTime:h,timeoutMs:o*1e3},d)}catch(g){return console.error(`[Subagent] Error: ${g.message}`),{sessionId:y||"",sessionName:m,status:"error",output:"",duration:Math.round((Date.now()-h)/1e3),agentType:s,error:g.message}}})}var M7r=p(()=>{ce();ETe();P7r();k7r()});var L7r=p(()=>{b7r();E7r();M7r()});function Eki(t){return{content:[{type:"text",text:t}]}}function Uat(t){let e=t?.message||String(t);return console.error(`[Subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Iki(t){let e=["## Subagent Result","",`**Status**: ${t.status}`,`**Agent Type**: ${t.agentType}`,`**Duration**: ${t.duration}s`,`**Session ID**: ${t.sessionId}`,`**Session Name**: ${t.sessionName}`,""];return t.error&&e.push(`**Error**: ${t.error}`,""),e.push("### Output","```",t.output,"```"),e.join(`
959
959
  `)}function $7r(t,e){t.tool("run_subagent",{task:B.string().describe("Task to execute"),agentType:B.enum(["machina","claude"]).default("machina").describe("Agent type (machina: lightweight, claude: full-featured)"),timeout:B.number().optional().default(300).describe("Timeout in seconds (default: 300)"),sessionName:B.string().optional().describe("Session name (default: subagent-{timestamp})")},r=>E(this,void 0,void 0,function*(){var n;let i=Date.now();console.error(`[MCP run_subagent] START task="${r.task.substring(0,50)}..." agentType=${r.agentType}`);try{let s=Zp();if(!Hf(s))return Uat(new Error("run_subagent requires restricted mode. Please set PLANX_SERVER_ID and PLANX_SESSION_ID environment variables."));if(!s.serverId||!s.sessionId)return Uat(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let o=yield S7r(),a={task:r.task,agentType:r.agentType,timeout:(n=r.timeout)!==null&&n!==void 0?n:300,sessionName:r.sessionName},c={serverId:s.serverId,parentId:s.sessionId},l=yield R7r(a,c,o,e);return console.error(`[MCP run_subagent] DONE status=${l.status} elapsed=${Date.now()-i}ms`),Eki(Iki(l))}catch(s){return console.error(`[MCP run_subagent] ERROR elapsed=${Date.now()-i}ms error=${s?.message}`),Uat(s)}}))}var F7r=p(()=>{ce();_c();STe();L7r()});import{existsSync as Tki,readFileSync as xki,writeFileSync as j7r}from"fs";import{homedir as Cki}from"os";import{join as Aki}from"path";function q7r(t,e,r){let n=Aki(Cki(),".claude","teams",t,"config.json");if(!Tki(n))throw new Error(`Team config not found: ${n}. TeamCreate must be called before create_subagent.`);let i=JSON.parse(xki(n,"utf-8")),s=`${e}@${t}`,o=i.members.find(a=>a.agentId===s);return o?(o.isActive=!0,o.cwd=r,j7r(n,JSON.stringify(i,null,2)+`
960
960
  `),{agentId:s,created:!1}):(i.members.push({agentId:s,name:e,agentType:"worker",model:"claude-opus-4-6",joinedAt:Date.now(),tmuxPaneId:"",cwd:r,subscriptions:[],isActive:!0}),j7r(n,JSON.stringify(i,null,2)+`
961
- `),{agentId:s,created:!0})}var B7r=p(()=>{});function Oki(t,e){return[["CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1","claude","--dangerously-skip-permissions",`--agent-name ${t}`,`--agent-id ${t}@${e}`,`--team-name ${e}`,"--session-id $(uuidgen)"].join(" "),"Enter"]}function Hat(t,e,r){return E(this,void 0,void 0,function*(){let{teamName:n,workerName:i,cwd:s}=t,{serverId:o,parentId:a,parentName:c}=e,{sessionCreateService:l,sendKeyUsecase:u}=r,d=s||process.cwd();Bte.info(`[create_subagent] Adding worker ${i} to team ${n}`);let{agentId:f,created:h}=q7r(n,i,d);Bte.info(`[create_subagent] Worker ${h?"created":"updated"}: ${f}`);let m=`${n}-${i}`;Bte.info(`[create_subagent] Creating session: ${m}`);let y=yield l.createSession({id:$p(),serverId:o,name:m,command:"/bin/zsh",parentId:a,cwd:d,env:{PLANX_IS_SUBAGENT:"1",PLANX_AGENT_NAME:i,PLANX_AGENT_ROLES:"worker",PLANX_AGENT_TEAM_NAME:n,PLANX_AGENT_PARENT_NAME:c,PLANX_SERVER_ID:o}});Bte.info(`[create_subagent] Session created: ${y.id}`),Bte.info("[create_subagent] Sending claude startup command");let g=Oki(i,n);return yield u.sendKeysToSession(o,y.id,g),{sessionId:y.id,sessionName:m,agentId:f,teamName:n,workerName:i}})}var Bte,V7r=p(()=>{ce();im();Rt();B7r();Bte=qe("create_subagent")});var U7r=p(()=>{V7r()});function Pki(t){return{content:[{type:"text",text:t}]}}function Wat(t){let e=t?.message||String(t);return console.error(`[create_subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function H7r(t,e){t.tool("create_subagent",{teamName:B.string().describe("Team name (from TeamCreate)"),workerName:B.string().describe("Worker name (e.g. worker-1)"),cwd:B.string().optional().describe("Working directory for the worker session")},r=>E(this,void 0,void 0,function*(){console.error(`[MCP create_subagent] START team=${r.teamName} worker=${r.workerName}`);try{let n=Zp();if(!Hf(n))return Wat(new Error("create_subagent requires restricted mode. Set PLANX_SERVER_ID and PLANX_SESSION_ID."));if(!n.serverId||!n.sessionId)return Wat(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let i={serverId:n.serverId,parentId:n.sessionId,parentName:process.env.PLANX_AGENT_NAME||"team-lead"},s=yield Hat({teamName:r.teamName,workerName:r.workerName,cwd:r.cwd},i,e);return console.error(`[MCP create_subagent] DONE session=${s.sessionId}`),Pki(JSON.stringify(s,null,2))}catch(n){return console.error(`[MCP create_subagent] ERROR: ${n?.message}`),Wat(n)}}))}var W7r=p(()=>{ce();_c();STe();U7r()});function G7r(t,e,r,n){var i;if(r===e)return!0;let s=n.find(o=>{var a;return((a=o.env)===null||a===void 0?void 0:a.PLANX_AGENT_NAME)===r});return((i=s?.env)===null||i===void 0?void 0:i.PLANX_AGENT_PARENT_NAME)===t}var z7r=p(()=>{});import*as cE from"fs";import*as Gat from"path";import*as zat from"os";function Dki(t,e){return Gat.join(zat.homedir(),".claude","teams",t,"inboxes",`${e}.json`)}function Nki(t){let e=Gat.join(zat.homedir(),".claude","teams",t,"inboxes");cE.existsSync(e)||cE.mkdirSync(e,{recursive:!0})}function kki(t){if(!cE.existsSync(t))return[];let e=cE.readFileSync(t,"utf-8");return JSON.parse(e)}function K7r(t,e,r){Nki(t);let n=Dki(t,e),i=kki(n);i.push(r),cE.writeFileSync(n,JSON.stringify(i,null,2),"utf-8")}var Y7r=p(()=>{});function Kat(t,e,r){return E(this,void 0,void 0,function*(){let{recipient:n,content:i,summary:s}=t,{agentName:o,teamName:a,parentName:c,serverId:l}=e,{sessionListService:u}=r,d=yield u.listSessions(l,{timeout:3e4});if(!G7r(o,c,n,d))throw new Error(`Access denied: '${o}' cannot send messages to '${n}'. Only parent ('${c}') or child agents are allowed.`);let f=new Date().toISOString(),h=Object.assign(Object.assign({from:o,text:i},s?{summary:s}:{}),{timestamp:f,read:!1});return K7r(a,n,h),{success:!0,recipient:n,timestamp:f}})}var Q7r=p(()=>{ce();z7r();Y7r()});var J7r=p(()=>{Q7r()});function Rki(t){return{content:[{type:"text",text:t}]}}function Z7r(t){let e=t?.message||String(t);return console.error(`[send_message Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Mki(){return process.env.PLANX_SERVER_ID}function X7r(t,e){t.tool("agent_send_message",{recipient:B.string().describe("Recipient name (e.g. team-lead, worker-1)"),content:B.string().describe("Message content"),summary:B.string().optional().describe("Brief summary of the message"),sender_name:B.string().describe("Sender agent name"),team_name:B.string().describe("Team name")},r=>E(this,void 0,void 0,function*(){var n;console.error(`[MCP agent_send_message] START from=${r.sender_name} to=${r.recipient}`);try{let i=Mki();if(!i)return Z7r(new Error("PLANX_SERVER_ID not set in server process."));let o=(yield e.sessionListService.listSessions(i,{timeout:3e4})).find(u=>{var d;return((d=u.env)===null||d===void 0?void 0:d.PLANX_AGENT_NAME)===r.sender_name}),a=((n=o?.env)===null||n===void 0?void 0:n.PLANX_AGENT_PARENT_NAME)||"",c={agentName:r.sender_name,teamName:r.team_name,parentName:a,serverId:i},l=yield Kat({recipient:r.recipient,content:r.content,summary:r.summary},c,e);return console.error(`[MCP agent_send_message] DONE to=${l.recipient}`),Rki(JSON.stringify(l,null,2))}catch(i){return console.error(`[MCP agent_send_message] ERROR: ${i?.message}`),Z7r(i)}}))}var eLr=p(()=>{ce();_c();J7r()});function Vte(t){return{content:[{type:"text",text:t}]}}function yq(t){return{content:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Ute(t,e){let r=t.agent_name||e.defaultAgentName;if(!r)throw new Error("agent_name is required. Either pass it as parameter or set PLANX_AGENT_NAME env var.");return r}function tLr(t){return Sd({links:[tu({url:`${t.stateServerUrl}/trpc`})]})}var rLr=p(()=>{e_()});function g8(t,e="root"){let r=[];if(!t||typeof t!="object")return r.push(`${e}: schema must be an object`),r;let n=t,i=n.type;if(i==="object")if(!n.properties||typeof n.properties!="object")r.push(`${e}: type 'object' requires 'properties' to be defined`);else for(let[s,o]of Object.entries(n.properties))r.push(...g8(o,`${e}.${s}`));else i==="array"&&(!n.items||typeof n.items!="object"?r.push(`${e}: type 'array' requires 'items' to be defined`):r.push(...g8(n.items,`${e}[items]`)));return r}var Yat=p(()=>{});function nLr(t,e){console.error("[State Tools] Starting registration"),console.error("[State Tools] State server URL:",e.stateServerUrl),console.error("[State Tools] Default agent name:",e.defaultAgentName||"(not set)");let r=tLr(e),n=B.lazy(()=>B.object({type:B.enum(["string","number","boolean","array","object"]),default:B.any().optional(),items:n.optional(),properties:B.record(n).optional()}));t.tool("init_state",{agent_name:B.string().optional().describe("Unique state identifier (defaults to PLANX_AGENT_NAME env var)"),schema:B.object({type:B.literal("object"),properties:B.record(n)}).describe("JSON Schema for state structure")},i=>E(this,void 0,void 0,function*(){try{let s=Ute(i,e),{schema:o}=i,a=g8(o);if(a.length>0)return yq(`Schema validation failed:
961
+ `),{agentId:s,created:!0})}var B7r=p(()=>{});function Oki(t,e){return[["CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1","claude","--dangerously-skip-permissions",`--agent-name ${t}`,`--agent-id ${t}@${e}`,`--team-name ${e}`,"--session-id $(uuidgen)"].join(" "),"Enter"]}function Hat(t,e,r){return E(this,void 0,void 0,function*(){let{teamName:n,workerName:i,cwd:s}=t,{serverId:o,parentId:a,parentName:c}=e,{sessionCreateService:l,sendKeyUsecase:u}=r,d=s||process.cwd();Bte.info(`[create_subagent] Adding worker ${i} to team ${n}`);let{agentId:f,created:h}=q7r(n,i,d);Bte.info(`[create_subagent] Worker ${h?"created":"updated"}: ${f}`);let m=`${n}-${i}`;Bte.info(`[create_subagent] Creating session: ${m}`);let y=yield l.createSession({id:$p(),serverId:o,name:m,command:"/bin/zsh",parentId:a,cwd:d,env:{PLANX_IS_SUBAGENT:"1",PLANX_AGENT_NAME:i,PLANX_AGENT_ROLES:"worker",PLANX_AGENT_TEAM_NAME:n,PLANX_AGENT_PARENT_NAME:c,PLANX_SERVER_ID:o}});Bte.info(`[create_subagent] Session created: ${y.id}`),Bte.info("[create_subagent] Sending claude startup command");let g=Oki(i,n);return yield u.sendKeysToSession(o,y.id,g),{sessionId:y.id,sessionName:m,agentId:f,teamName:n,workerName:i}})}var Bte,V7r=p(()=>{ce();im();Rt();B7r();Bte=qe("create_subagent")});var U7r=p(()=>{V7r()});function Pki(t){return{content:[{type:"text",text:t}]}}function Wat(t){let e=t?.message||String(t);return console.error(`[create_subagent Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function H7r(t,e){t.tool("create_subagent",{teamName:B.string().describe("Team name (from TeamCreate)"),workerName:B.string().describe("Worker name (e.g. worker-1)"),cwd:B.string().optional().describe("Working directory for the worker session")},r=>E(this,void 0,void 0,function*(){console.error(`[MCP create_subagent] START team=${r.teamName} worker=${r.workerName}`);try{let n=Zp();if(!Hf(n))return Wat(new Error("create_subagent requires restricted mode. Set PLANX_SERVER_ID and PLANX_SESSION_ID."));if(!n.serverId||!n.sessionId)return Wat(new Error("PLANX_SERVER_ID and PLANX_SESSION_ID are required."));let i={serverId:n.serverId,parentId:n.sessionId,parentName:process.env.PLANX_AGENT_NAME||"team-lead"},s=yield Hat({teamName:r.teamName,workerName:r.workerName,cwd:r.cwd},i,e);return console.error(`[MCP create_subagent] DONE session=${s.sessionId}`),Pki(JSON.stringify(s,null,2))}catch(n){return console.error(`[MCP create_subagent] ERROR: ${n?.message}`),Wat(n)}}))}var W7r=p(()=>{ce();_c();STe();U7r()});function G7r(t,e,r,n){var i;if(r===e)return!0;let s=n.find(o=>{var a;return((a=o.env)===null||a===void 0?void 0:a.PLANX_AGENT_NAME)===r});return((i=s?.env)===null||i===void 0?void 0:i.PLANX_AGENT_PARENT_NAME)===t}var z7r=p(()=>{});import*as cE from"fs";import*as Gat from"path";import*as zat from"os";function Dki(t,e){return Gat.join(zat.homedir(),".claude","teams",t,"inboxes",`${e}.json`)}function Nki(t){let e=Gat.join(zat.homedir(),".claude","teams",t,"inboxes");cE.existsSync(e)||cE.mkdirSync(e,{recursive:!0})}function kki(t){if(!cE.existsSync(t))return[];let e=cE.readFileSync(t,"utf-8");return JSON.parse(e)}function K7r(t,e,r){Nki(t);let n=Dki(t,e),i=kki(n);i.push(r),cE.writeFileSync(n,JSON.stringify(i,null,2),"utf-8")}var Y7r=p(()=>{});function Kat(t,e,r){return E(this,void 0,void 0,function*(){let{recipient:n,content:i,summary:s}=t,{agentName:o,teamName:a,parentName:c,serverId:l}=e,{sessionListService:u}=r,d=yield u.listSessions(l,{timeout:3e4});if(!G7r(o,c,n,d))throw new Error(`Access denied: '${o}' cannot send messages to '${n}'. Only parent ('${c}') or child agents are allowed.`);let f=new Date().toISOString(),h=Object.assign(Object.assign({from:o,text:i},s?{summary:s}:{}),{timestamp:f,read:!1});return K7r(a,n,h),{success:!0,recipient:n,timestamp:f}})}var Q7r=p(()=>{ce();z7r();Y7r()});var J7r=p(()=>{Q7r()});function Rki(t){return{content:[{type:"text",text:t}]}}function Z7r(t){let e=t?.message||String(t);return console.error(`[send_message Error] ${e}`),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}function Mki(){return process.env.PLANX_SERVER_ID}function X7r(t,e){t.tool("agent_send_message",{recipient:B.string().describe("Recipient name (e.g. team-lead, worker-1)"),content:B.string().describe("Message content"),summary:B.string().optional().describe("Brief summary of the message"),sender_name:B.string().describe("Sender agent name"),team_name:B.string().describe("Team name")},r=>E(this,void 0,void 0,function*(){var n;console.error(`[MCP agent_send_message] START from=${r.sender_name} to=${r.recipient}`);try{let i=Mki();if(!i)return Z7r(new Error("PLANX_SERVER_ID not set in server process."));let o=(yield e.sessionListService.listSessions(i,{timeout:3e4})).find(u=>{var d;return((d=u.env)===null||d===void 0?void 0:d.PLANX_AGENT_NAME)===r.sender_name}),a=((n=o?.env)===null||n===void 0?void 0:n.PLANX_AGENT_PARENT_NAME)||"",c={agentName:r.sender_name,teamName:r.team_name,parentName:a,serverId:i},l=yield Kat({recipient:r.recipient,content:r.content,summary:r.summary},c,e);return console.error(`[MCP agent_send_message] DONE to=${l.recipient}`),Rki(JSON.stringify(l,null,2))}catch(i){return console.error(`[MCP agent_send_message] ERROR: ${i?.message}`),Z7r(i)}}))}var eLr=p(()=>{ce();_c();J7r()});function Vte(t){return{content:[{type:"text",text:t}]}}function yq(t){return{content:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Ute(t,e){let r=t.agent_name||e.defaultAgentName;if(!r)throw new Error("agent_name is required. Either pass it as parameter or set PLANX_AGENT_NAME env var.");return r}function tLr(t){return Sd({links:[tu({url:`${t.stateServerUrl}/trpc`})]})}var rLr=p(()=>{e_()});function g8(t,e="root"){let r=[];if(!t||typeof t!="object")return r.push(`${e}: schema must be an object`),r;let n=t,i=n.type;if(i==="object")if(!n.properties||typeof n.properties!="object")r.push(`${e}: type 'object' requires 'properties' to be defined`);else for(let[s,o]of Object.entries(n.properties))r.push(...g8(o,`${e}.${s}`));else i==="array"&&(!n.items||typeof n.items!="object"?r.push(`${e}: type 'array' requires 'items' to be defined`):r.push(...g8(n.items,`${e}[items]`)));return r}var Yat=p(()=>{});function nLr(t,e){console.error("[State Tools] Starting registration"),console.error("[State Tools] State server URL:",e.stateServerUrl),console.error("[State Tools] Default agent name:",e.defaultAgentName||"(not set)");let r=tLr(e),n=B.lazy(()=>B.object({type:B.enum(["string","number","boolean","array","object"]),default:B.any().optional(),items:n.optional(),properties:B.record(B.string(),n).optional()}));t.tool("init_state",{agent_name:B.string().optional().describe("Unique state identifier (defaults to PLANX_AGENT_NAME env var)"),schema:B.object({type:B.literal("object"),properties:B.record(B.string(),n)}).describe("JSON Schema for state structure")},i=>E(this,void 0,void 0,function*(){try{let s=Ute(i,e),{schema:o}=i,a=g8(o);if(a.length>0)return yq(`Schema validation failed:
962
962
  ${a.join(`
963
963
  `)}`);let c=yield r.state.initState.mutate({stateId:s,schema:o});return Vte(`State initialized: ${s}
964
964
  ${JSON.stringify(c,null,2)}`)}catch(s){return yq(s)}})),t.tool("get_state",{agent_name:B.string().optional().describe("State identifier (defaults to PLANX_AGENT_NAME env var)")},i=>E(this,void 0,void 0,function*(){try{let s=Ute(i,e),o=yield r.state.getState.query({stateId:s});return Vte(JSON.stringify(o,null,2))}catch(s){return yq(s)}})),t.tool("update_state",{agent_name:B.string().optional().describe("State identifier (defaults to PLANX_AGENT_NAME env var)"),operation:B.enum(["set","push","remove","updateAt"]).describe("CRDT operation type"),path:B.string().describe('Dot-separated path (e.g., "tasks" or "config.theme")'),value:B.any().describe("Value for the operation")},i=>E(this,void 0,void 0,function*(){try{let s=Ute(i,e),{operation:o,path:a,value:c}=i,l=yield r.state.updateState.mutate({stateId:s,operation:o,path:a,value:c});return Vte(`State updated (${o} at ${a})