@kabmo-labs/kabmo 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -65,7 +65,7 @@
65
65
  by `scripts/build-client.ts`. A page that ships an external font must
66
66
  name it somewhere; this one did not. -->
67
67
  <!--app-head-->
68
- <link rel="stylesheet" crossorigin href="./static/js/index-naa91727.css"><script type="module" crossorigin src="./static/js/index-43z47ngg.js"></script></head>
68
+ <link rel="stylesheet" crossorigin href="./static/js/index-naa91727.css"><script type="module" crossorigin src="./static/js/index-5vjbp04s.js"></script></head>
69
69
  <body>
70
70
  <div id="app"></div>
71
71
  <!--app-bootstrap-->
@@ -663,7 +663,7 @@ return u.substring(s,qi)
663
663
  `:`c.headers={}
664
664
  for(const [k,v] of c.request.headers.entries())c.headers[k]=v
665
665
  `},listen(e){return(t,r)=>{if(typeof Bun>"u")throw Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(e.compile(),typeof t=="string"){if(!$b(t))throw Error("Port must be a numeric value");t=parseInt(t)}let n=(s,{withAsync:a=!1}={})=>{let c={},l=[];if(e.event.request?.length||e.event.trace?.length||e.extender.higherOrderFunctions.length)return a?Promise.resolve(c):c;for(let[u,d]of Object.entries(s))if(u=encodeURI(u),qb){if(!d)continue;for(let[f,p]of Object.entries(d))if(!(!p||!(f in C6))){if(p instanceof Promise){a&&(c[u]||(c[u]={}),l.push(p.then((h)=>{h instanceof Response&&(c[u][f]=h),Ug(h)&&(c[u][f]=h)})));continue}!(p instanceof Response)&&!Ug(p)||(c[u]||(c[u]={}),c[u][f]=p)}}else{if(!d)continue;if(d instanceof Promise){a&&(c[u]||(c[u]={}),l.push(d.then((f)=>{f instanceof Response&&(c[u]=f)})));continue}if(!(d instanceof Response))continue;c[u]=d}return a?Promise.all(l).then(()=>c):c},o=P6(Rw(Rw(n(e.router.response),R6(e)),e.config.serve?.routes)),i=typeof t=="object"?{development:!qs,reusePort:!0,idleTimeout:30,...e.config.serve||{},...t||{},routes:o,websocket:{...e.config.websocket||{},...xE||{},...t.websocket||{}},fetch:e.fetch}:{development:!qs,reusePort:!0,idleTimeout:30,...e.config.serve||{},routes:o,websocket:{...e.config.websocket||{},...xE||{}},port:t,fetch:e.fetch};if(e.server=Bun.serve(i),e.event.start)for(let s=0;s<e.event.start.length;s++)e.event.start[s].fn(e);r&&r(e.server),process.on("beforeExit",async()=>{if(e.server&&(await e.server.stop?.(),e.server=null,e.event.stop))for(let s=0;s<e.event.stop.length;s++)e.event.stop[s].fn(e)}),e.promisedModules.then(async()=>{e.config.aot,e.compile();let s=P6(Rw(Rw(await n(e.router.response,{withAsync:!0}),R6(e)),e.config.serve?.routes));e.server?.reload({...i,fetch:e.fetch,routes:s}),Bun?.gc(!1)})}},async stop(e,t){if(e.server){if(await e.server.stop(t),e.server=null,e.event.stop?.length)for(let r=0;r<e.event.stop.length;r++)e.event.stop[r].fn(e)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",Error().stack)},ws(e,t,r){let{parse:n,body:o,response:i,...s}=r,a=Ut(o,{modules:e.definitions.typebox,models:e.definitions.type,normalize:e.config.normalize}),c=a?a.provider==="standard"?(u)=>a.schema["~standard"].validate(u).issues:(u)=>a.Check(u)===!1:void 0,l=Ut(i,{modules:e.definitions.typebox,models:e.definitions.type,normalize:e.config.normalize});e.route("WS",t,async(u)=>{let d=u.server??e.server,{set:f,path:p,qi:h,headers:g,query:y,params:b}=u;if(u.validator=l,r.upgrade)if(typeof r.upgrade=="function"){let R=r.upgrade(u);R instanceof Promise&&await R}else r.upgrade&&Object.assign(f.headers,r.upgrade);if(f.cookie&&Fe(f.cookie)){let R=Rg(f.cookie);R&&(f.headers["set-cookie"]=R)}f.headers["set-cookie"]&&Array.isArray(f.headers["set-cookie"])&&(f.headers=cE(new Headers(f.headers),f.headers["set-cookie"]));let w=E6(l),E=T6(n),S;if(typeof r.beforeHandle=="function"){let R=r.beforeHandle(u);R instanceof Promise&&await R}let A=[...r.error?Array.isArray(r.error)?r.error:[r.error]:[],...(e.event.error??[]).map((R)=>typeof R=="function"?R:R.fn)].filter((R)=>R),T=A.length>0,I=T?async(R,F)=>{for(let U of A){let P=U(Object.assign(u,{error:F}));if(P instanceof Promise&&(P=await P),await w(R,P),P)break}}:()=>{};if(!d?.upgrade(u.request,{headers:Fe(f.headers)?f.headers:void 0,data:{...u,get id(){return S||(S=$s())},validator:l,ping(R,F){r.ping?.(R,F)},pong(R,F){r.pong?.(R,F)},open:async(R)=>{try{await w(R,r.open?.(new bp(R,u)))}catch(F){I(R,F)}},message:async(R,F)=>{let U=await E(R,F);if(c&&c(U)){let P=new le("message",a,U);return T?I(R,P):void R.send(P.message)}try{await w(R,r.message?.(new bp(R,u,U),U))}catch(P){I(R,P)}},drain:async(R)=>{try{await w(R,r.drain?.(new bp(R,u)))}catch(F){I(R,F)}},close:async(R,F,U)=>{try{await w(R,r.close?.(new bp(R,u),F,U))}catch(P){I(R,P)}}}}))return Xi(400,"Expected a websocket connection")},{...s,websocket:r})}};var Pw=uo?Bun.env:typeof process<"u"&&process?.env?process.env:{};var D6=/^(.+)\[(\d+)\]$/,M6=new Set(["__proto__","constructor","prototype"]),N6=(e)=>{if(M6.has(e))return!0;let t=e.match(D6);return t?M6.has(t[1]):!1},L6=(e)=>{let t=e.match(D6);return t?{name:t[1],index:parseInt(t[2],10)}:null},R0e=(e)=>{if(!(typeof e!="string"||e.charCodeAt(0)!==123))try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return}},kE=(e,t,r)=>{let n=t.split("."),o=n.pop();if(N6(o)||n.some(N6))return;let i=e;for(let a of n){let c=L6(a);if(c){Array.isArray(i[c.name])||(i[c.name]=[]);let l=i[c.name][c.index],u=typeof File<"u"&&l instanceof File;(!l||typeof l!="object"||Array.isArray(l)||u)&&(i[c.name][c.index]=R0e(l)??{}),i=i[c.name][c.index]}else(!i[a]||typeof i[a]!="object")&&(i[a]={}),i=i[a]}let s=L6(o);s?(Array.isArray(i[s.name])||(i[s.name]=[]),i[s.name][s.index]=r):i[o]=r},vE=(e)=>{if(e.length===1){let o=e[0];if(typeof o=="string"&&(o.charCodeAt(0)===123||o.charCodeAt(0)===91))try{let i=JSON.parse(o);if(i&&typeof i=="object")return i}catch{}return e[0]}let t=e.find((o)=>typeof o=="string");if(!t||typeof File>"u")return e;let r=e.filter((o)=>o instanceof File);if(!r.length||t.charCodeAt(0)!==123)return e;let n;try{n=JSON.parse(t)}catch{return e}return typeof n!="object"||n===null?e:(!("file"in n)&&r.length===1?n.file=r[0]:!("files"in n)&&r.length>1&&(n.files=r),n)},AE=(e,t)=>{let r=e.schema;if(!r)return;r.$defs?.[r.$ref]&&(r=r.$defs[r.$ref]);let n=es(r);if(n)for(let[o,i]of Object.entries(n))t[o]??=i.default};async function eu(e,t,r){let n=await t.Validate(r);if(n.issues)throw new le(e,t,r,!1,n.issues);return n.value}var TE=(e)=>{let{mapResponse:t,mapEarlyResponse:r}=e["~adapter"].handler,n=e.setHeaders;return async(o)=>{let i=o.url,s=i.indexOf("/",11),a=i.indexOf("?",s+1),c=a===-1?i.substring(s):i.substring(s,a),l={cookie:{},status:200,headers:n?{...n}:{}},u=Object.assign({},e.singleton.decorator,{set:l,store:e.singleton.store,request:o,path:c,qi:a,error:Xi,status:Xi,redirect:Fl}),d;try{if(e.event.request)for(let F=0;F<e.event.request.length;F++){let U=e.event.request[F].fn,P=U(u);if(P instanceof Promise&&(P=await P),P=r(P,l),P)return u.response=P}let f=o.method==="GET"&&o.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":o.method,p=e.router.dynamic.find(o.method,c)??e.router.dynamic.find(f,c)??e.router.dynamic.find("ALL",c);if(!p)throw u.query=a===-1?{}:Xa(i.substring(a+1)),new np;let{handle:h,validator:g,content:y,route:b}=p.store;if(d=p.store.hooks,d.config?.mount)return await d.config.mount(o);let w;if(o.method!=="GET"&&o.method!=="HEAD")if(y)switch(y){case"application/json":w=await o.json();break;case"text/plain":w=await o.text();break;case"application/x-www-form-urlencoded":w=Xa(await o.text());break;case"application/octet-stream":w=await o.arrayBuffer();break;case"multipart/form-data":{w={};let F=await o.formData(),U=new Map;F.forEach((P,B)=>{let D=U.get(B);D?D.push(P):U.set(B,[P])});for(let[P,B]of U){if(w[P])continue;let D=vE(B);P.includes(".")||P.includes("[")?kE(w,P,D):w[P]=D}break}}else{let F;if(o.body&&(F=o.headers.get("content-type")),F){let U=F.indexOf(";");if(U!==-1&&(F=F.slice(0,U)),u.contentType=F,d.parse)for(let P=0;P<d.parse.length;P++){let B=d.parse[P].fn;if(typeof B=="string")switch(B){case"json":case"application/json":w=await o.json();break;case"text":case"text/plain":w=await o.text();break;case"urlencoded":case"application/x-www-form-urlencoded":w=Xa(await o.text());break;case"arrayBuffer":case"application/octet-stream":w=await o.arrayBuffer();break;case"formdata":case"multipart/form-data":{w={};let D=await o.formData(),J=new Map;D.forEach((Z,ie)=>{let oe=J.get(ie);oe?oe.push(Z):J.set(ie,[Z])});for(let[Z,ie]of J){if(w[Z])continue;let oe=vE(ie);Z.includes(".")||Z.includes("[")?kE(w,Z,oe):w[Z]=oe}break}default:{let D=e["~parser"][B];if(D){let J=D(u,F);if(J instanceof Promise&&(J=await J),J){w=J;break}}break}}else{let D=B(u,F);if(D instanceof Promise&&(D=await D),D){w=D;break}}}if(delete u.contentType,w===void 0)switch(F){case"application/json":w=await o.json();break;case"text/plain":w=await o.text();break;case"application/x-www-form-urlencoded":w=Xa(await o.text());break;case"application/octet-stream":w=await o.arrayBuffer();break;case"multipart/form-data":{w={};let P=await o.formData(),B=new Map;P.forEach((D,J)=>{let Z=B.get(J);Z?Z.push(D):B.set(J,[D])});for(let[D,J]of B){if(w[D])continue;let Z=vE(J);D.includes(".")||D.includes("[")?kE(w,D,Z):w[D]=Z}break}}}}u.route=b,u.body=w,u.params=p?.params||void 0,u.query=a===-1?{}:Xa(i.substring(a+1)),u.headers={};for(let[F,U]of o.headers.entries())u.headers[F]=U;let E={domain:e.config.cookie?.domain??g?.cookie?.config.domain,expires:e.config.cookie?.expires??g?.cookie?.config.expires,httpOnly:e.config.cookie?.httpOnly??g?.cookie?.config.httpOnly,maxAge:e.config.cookie?.maxAge??g?.cookie?.config.maxAge,path:e.config.cookie?.path??g?.cookie?.config.path,priority:e.config.cookie?.priority??g?.cookie?.config.priority,partitioned:e.config.cookie?.partitioned??g?.cookie?.config.partitioned,sameSite:e.config.cookie?.sameSite??g?.cookie?.config.sameSite,secure:e.config.cookie?.secure??g?.cookie?.config.secure,secrets:e.config.cookie?.secrets??g?.cookie?.config.secrets,sign:e.config.cookie?.sign??g?.cookie?.config.sign},S=o.headers.get("cookie");u.cookie=await fw(u.set,S,E);let A=g?.createHeaders?.();A&&AE(A,u.headers);let T=g?.createParams?.();T&&AE(T,u.params);let I=g?.createQuery?.();if(I&&AE(I,u.query),d.transform)for(let F=0;F<d.transform.length;F++){let U=d.transform[F],P=U.fn(u);if(P instanceof Promise&&(P=await P),P instanceof Dt){let B=r(P,u.set);if(B)return u.response=B}U.subType==="derive"&&Object.assign(u,P)}if(g){if(A){let U=structuredClone(u.headers);for(let[P,B]of o.headers)U[P]=B;if(A.provider==="standard")u.headers=await eu("header",A,U);else if(g.headers.Check(U)===!1)throw new le("header",g.headers,U)}else g.headers?.Decode&&(u.headers=g.headers.Decode(u.headers));if(T?.provider==="standard")u.params=await eu("params",T,u.params);else{if(T?.Check(u.params)===!1)throw new le("params",g.params,u.params);g.params?.Decode&&(u.params=g.params.Decode(u.params))}if(g.query?.schema){let U=g.query.schema;U.$defs?.[U.$ref]&&(U=U.$defs[U.$ref]);let P=es(U);if(P)for(let B of Object.keys(P)){let D=P[B];(D.type==="array"||D.items?.type==="string")&&typeof u.query[B]=="string"&&u.query[B]&&(u.query[B]=u.query[B].split(","))}}if(I?.provider==="standard")u.query=await eu("query",I,u.query);else{if(I?.Check(u.query)===!1)throw new le("query",g.query,u.query);g.query?.Decode&&(u.query=g.query.Decode(u.query))}if(g.createCookie?.()){let U={};for(let[P,B]of Object.entries(u.cookie))U[P]=B.value;if(g.cookie.provider==="standard"){U=await eu("cookie",g.cookie,U);for(let P of Object.keys(U))u.cookie[P].value=U[P]}else{if(g.cookie.Check(U)===!1)throw new le("cookie",g.cookie,U);g.cookie?.Decode&&(U=g.cookie.Decode(U))}}let F=g.createBody?.();if(F?.provider==="standard")u.body=await eu("body",F,w);else{if(F?.Check(w)===!1)throw new le("body",g.body,w);if(g.body?.Decode){let U=g.body.Decode(w);U instanceof Promise&&(U=await U),u.body=U?.value??U}}}if(d.beforeHandle)for(let F=0;F<d.beforeHandle.length;F++){let U=d.beforeHandle[F],P=U.fn(u);if(P instanceof Promise&&(P=await P),P instanceof Dt){let B=r(P,u.set);if(B)return u.response=B}if(U.subType==="resolve"){Object.assign(u,P);continue}if(P!==void 0){if(u.response=P,d.afterHandle)for(let D=0;D<d.afterHandle.length;D++){let J=d.afterHandle[D].fn(u);J instanceof Promise&&(J=await J),J&&(P=J)}let B=r(P,u.set);if(B)return u.response=B}}let R=typeof h=="function"?h(u):h;if(R instanceof Promise&&(R=await R),d.afterHandle?.length){u.response=R;for(let F=0;F<d.afterHandle.length;F++){let U=d.afterHandle[F].fn(u);U instanceof Promise&&(U=await U);let P=U instanceof Dt,B=P?U.code:l.status?typeof l.status=="string"?Ji[l.status]:l.status:200;P&&(l.status=B,U=U.response);let D=g?.createResponse?.()?.[B];if(D?.provider==="standard")U=await eu("response",D,U);else if(D?.Check(U)===!1)if(D?.Clean)try{let Z=D.Clean(U);if(D?.Check(Z)===!1)throw new le("response",D,U);U=Z}catch(Z){throw Z instanceof le?Z:new le("response",D,U)}else throw new le("response",D,U);if(D?.Encode&&(u.response=U=D.Encode(U)),D?.Clean)try{u.response=U=D.Clean(U)}catch{}let J=r(U,u.set);if(J!==void 0)return u.response=J}}else{let F=R instanceof Dt,U=F?R.code:l.status?typeof l.status=="string"?Ji[l.status]:l.status:200;F&&(l.status=U,R=R.response);let P=g?.createResponse?.()?.[U];if(P?.provider==="standard")R=await eu("response",P,R);else if(P?.Check(R)===!1)if(P?.Clean)try{let B=P.Clean(R);if(P?.Check(B)===!1)throw new le("response",P,R);R=B}catch(B){throw B instanceof le?B:new le("response",P,R)}else throw new le("response",P,R);if(P?.Encode&&(R=P.Encode(R)),P?.Clean)try{R=P.Clean(R)}catch{}}if(u.set.cookie&&E?.sign){let F=E.secrets?typeof E.secrets=="string"?E.secrets:E.secrets[0]:void 0;if(E.sign===!0){if(F)for(let[U,P]of Object.entries(u.set.cookie))u.set.cookie[U].value=await tp(P.value,F)}else{let U=es(g?.cookie?.schema);if(F)for(let P of E.sign)!U||!(P in U)||u.set.cookie[P]?.value&&(u.set.cookie[P].value=await tp(u.set.cookie[P].value,F))}}return t(u.response=R,u.set)}catch(f){let p=f instanceof Nl&&f.error?f.error:f;return e.handleError(u,p)}finally{let f=d?d.afterResponse:e.event.afterResponse;f&&(Hb?setImmediate(async()=>{for(let p of f)await p.fn(u)}):Promise.resolve().then(async()=>{for(let p of f)await p.fn(u)}))}}},F6=(e)=>{let{mapResponse:t}=e["~adapter"].handler;return async(r,n)=>{let o=Object.assign(r,{error:n,code:n.code});if(o.set=r.set,typeof n?.toResponse=="function"&&!(n instanceof le)&&!(n instanceof Nl))try{let i=n.toResponse();typeof i?.then=="function"&&(i=await i),i instanceof Response&&(r.set.status=i.status),r.response=i}catch{}if(!r.response&&e.event.error)for(let i=0;i<e.event.error.length;i++){let s=e.event.error[i].fn(o);if(s instanceof Promise&&(s=await s),s!=null)return r.response=t(s,r.set)}if(r.response){if(e.event.mapResponse)for(let i=0;i<e.event.mapResponse.length;i++){let s=e.event.mapResponse[i].fn(o);s instanceof Promise&&(s=await s),s!=null&&(r.response=s)}return t(r.response,r.set)}return r.set.status=n.status??500,t(typeof n.cause=="string"?n.cause:n.message,r.set)}};var U6;U6=Symbol.dispose;var P0e=class e{constructor(t={}){this.server=null,this.dependencies={},this["~Prefix"]="",this["~Singleton"]=null,this["~Definitions"]=null,this["~Metadata"]=null,this["~Ephemeral"]=null,this["~Volatile"]=null,this["~Routes"]=null,this.singleton={decorator:{},store:{},derive:{},resolve:{}},this.definitions={typebox:z.Module({}),type:{},error:{}},this.extender={macro:{},higherOrderFunctions:[]},this.validator={global:null,scoped:null,local:null,getCandidate(){return!this.global&&!this.scoped&&!this.local?{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0}:ep(ep(this.global,this.scoped),this.local)}},this.standaloneValidator={global:null,scoped:null,local:null},this.event={},this.router={"~http":void 0,get http(){return this["~http"]||(this["~http"]=new gl({lazy:!0,onParam:EE.default})),this["~http"]},"~dynamic":void 0,get dynamic(){return this["~dynamic"]||(this["~dynamic"]=new gl({onParam:EE.default})),this["~dynamic"]},static:{},response:{},history:[]},this.routeTree={},this.inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1},this["~parser"]={},this.handle=async(r)=>this.fetch(r),this.handleError=async(r,n)=>(this.handleError=this.config.aot?SE(this):F6(this))(r,n),this.listen=(r,n)=>(this["~adapter"].listen(this)(r,n),this),this.stop=async(r)=>(await this["~adapter"].stop?.(this,r),this),this[U6]=()=>{this.server&&this.stop()},t.tags&&(t.detail?t.detail.tags=t.tags:t.detail={tags:t.tags}),this.config={aot:Pw.ELYSIA_AOT!=="false",nativeStaticResponse:!0,encodeSchema:!0,normalize:!0,...t,prefix:t.prefix?t.prefix.charCodeAt(0)===47?t.prefix:`/${t.prefix}`:void 0,cookie:{path:"/",...t?.cookie},experimental:t?.experimental??{},seed:t?.seed===void 0?"":t?.seed},this["~adapter"]=t.adapter??(typeof Bun<"u"?O6:Cg),t?.analytic&&(t?.name||t?.seed!==void 0)&&(this.telemetry={stack:Error().stack})}get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}getServer(){return this.server}getParent(){return null}get promisedModules(){return this._promisedModules||(this._promisedModules=new CT(console.error,()=>{})),this._promisedModules}env(t,r=Pw){if(Ut(t,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(r)===!1){let n=new le("env",t,r);throw Error(n.all.map((o)=>o.summary).join(`
666
- `))}return this}wrap(t){return this.extender.higherOrderFunctions.push({checksum:Hs(JSON.stringify({name:this.config.name,seed:this.config.seed,content:t.toString()})),fn:t}),this}get models(){let t={};for(let r of Object.keys(this.definitions.type))t[r]=Ut(this.definitions.typebox.Import(r),{models:this.definitions.type});return t.modules=this.definitions.typebox,t}add(t,r,n,o,i){let s=i?.skipPrefix??!1,a=i?.allowMeta??!1;o??={},this.applyMacro(o);let c=[];if(o.standaloneValidator&&(c=c.concat(o.standaloneValidator)),this.standaloneValidator.local&&(c=c.concat(this.standaloneValidator.local)),this.standaloneValidator.scoped&&(c=c.concat(this.standaloneValidator.scoped)),this.standaloneValidator.global&&(c=c.concat(this.standaloneValidator.global)),r!==""&&r.charCodeAt(0)!==47&&(r="/"+r),this.config.prefix&&!s&&(r=this.config.prefix+r),o?.type)switch(o.type){case"text":o.type="text/plain";break;case"json":o.type="application/json";break;case"formdata":o.type="multipart/form-data";break;case"urlencoded":o.type="application/x-www-form-urlencoded";break;case"arrayBuffer":o.type="application/octet-stream";break;default:break}let l=this.validator.getCandidate(),u={body:o?.body??l?.body,headers:o?.headers??l?.headers,params:o?.params??l?.params,query:o?.query??l?.query,cookie:o?.cookie??l?.cookie,response:o?.response??l?.response},d=this.config.precompile===!0||typeof this.config.precompile=="object"&&this.config.precompile.compose===!0,f=()=>{let P=this.definitions.type,B=!this.config.aot,D=this.config.normalize,J=this.definitions.typebox,Z=()=>this.config.sanitize,ie=()=>{if(u.cookie||c.find((oe)=>oe.cookie))return S6({modules:J,validator:u.cookie,defaultConfig:this.config.cookie,normalize:D,config:u.cookie?.config??{},dynamic:B,models:P,validators:c.map((oe)=>oe.cookie),sanitize:Z})};return d?{body:Ut(u.body,{modules:J,dynamic:B,models:P,normalize:D,additionalCoerce:(()=>{let oe=yE(u.body,P,J);return oe&&N in oe&&(Ir("File",oe)||Ir("Files",oe))?gE():Ng()})(),validators:c.map((oe)=>oe.body),sanitize:Z}),headers:Ut(u.headers,{modules:J,dynamic:B,models:P,additionalProperties:!0,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.headers),sanitize:Z}),params:Ut(u.params,{modules:J,dynamic:B,models:P,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.params),sanitize:Z}),query:Ut(u.query,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:fE(),validators:c.map((oe)=>oe.query),sanitize:Z}),cookie:ie(),response:kw(u.response,{modules:J,dynamic:B,models:P,normalize:D,validators:c.map((oe)=>oe.response),sanitize:Z})}:{createBody(){return this.body?this.body:this.body=Ut(u.body,{modules:J,dynamic:B,models:P,normalize:D,additionalCoerce:(()=>{let oe=yE(u.body,P,J);return oe&&N in oe&&(Ir("File",oe)||Ir("Files",oe))?gE():Ng()})(),validators:c.map((oe)=>oe.body),sanitize:Z})},createHeaders(){return this.headers?this.headers:this.headers=Ut(u.headers,{modules:J,dynamic:B,models:P,normalize:D,additionalProperties:!D,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.headers),sanitize:Z})},createParams(){return this.params?this.params:this.params=Ut(u.params,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.params),sanitize:Z})},createQuery(){return this.query?this.query:this.query=Ut(u.query,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:fE(),validators:c.map((oe)=>oe.query),sanitize:Z})},createCookie(){return this.cookie?this.cookie:this.cookie=ie()},createResponse(){return this.response?this.response:this.response=kw(u.response,{modules:J,dynamic:B,models:P,normalize:D,validators:c.map((oe)=>oe.response),sanitize:Z})}}};(l.body||l.cookie||l.headers||l.params||l.query||l.response)&&(o=Yi(o,l)),o.tags&&(o.detail?o.detail.tags=o.tags:o.detail={tags:o.tags}),Fe(this.config.detail)&&(o.detail=cr(Object.assign({},this.config.detail),o.detail));let p=Fe(this.event)?Yi(this.event,OT(o)):{...bD(OT(o))};if(c.length&&Object.assign(p,{standaloneValidator:c}),this.config.aot===!1){let P=f();this.router.dynamic.add(t,r,{validator:P,hooks:p,content:o?.type,handle:n,route:r});let B=Bl(r,{dynamic:!0});if(r!==B&&this.router.dynamic.add(t,B,{validator:P,hooks:p,content:o?.type,handle:n,route:r}),!this.config.strictPath){let D=Ul(r);this.router.dynamic.add(t,D,{validator:P,hooks:p,content:o?.type,handle:n,route:r});let J=Bl(D);D!==J&&this.router.dynamic.add(t,D,{validator:P,hooks:p,content:o?.type,handle:n,route:r})}this.router.history.push({method:t,path:r,composed:null,handler:n,compile:void 0,hooks:p});return}let h=this["~adapter"].handler,g=typeof n!="function"?()=>{let P=h.createNativeStaticHandler?.(n,p,{headers:Object.assign({},this.setHeaders)});return P instanceof Promise?P.then((B)=>{if(B)return B}):P?.()}:void 0,y=this.config.nativeStaticResponse===!0,b=(P)=>{!y||!g||(qb?this.router.response[P]?this.router.response[P][t]=g():this.router.response[P]={[t]:g()}:this.router.response[P]=g())};b(r);let w,E=()=>{if(w)return w;let P=k6({app:this,path:r,method:t,hooks:p,validator:f(),handler:typeof n!="function"&&typeof h.createStaticHandler!="function"?()=>n:n,allowMeta:a,inference:this.inference});return this.router.history[A]&&(w=this.router.history[A].composed=P),P},S;if(`${t}_${r}`in this.routeTree)for(let P=0;P<this.router.history.length;P++){let B=this.router.history[P];if(B.path===r&&B.method===t){S=P;break}}else this.routeTree[`${t}_${r}`]=this.router.history.length;let A=S??this.router.history.length,T=this.router.history,I=d?E():(P)=>w?w(P):(T[A].composed=E())(P);S!==void 0?this.router.history[S]=Object.assign({method:t,path:r,composed:I,compile:E,handler:n,hooks:p},c.length?{standaloneValidators:c}:void 0,o.webSocket?{websocket:o.websocket}:void 0):this.router.history.push(Object.assign({method:t,path:r,composed:I,compile:E,handler:n,hooks:p},o.webSocket?{websocket:o.websocket}:void 0));let R={handler:d?T[A].composed:void 0,compile(){return this.handler=E()}},F=this.router.static,U=r.indexOf(":")===-1&&r.indexOf("*")===-1;if(t==="WS"){if(U){r in F?F[r][t]=A:F[r]={[t]:A};return}this.router.http.add("WS",r,R),this.config.strictPath||this.router.http.add("WS",Ul(r),R);let P=Bl(r,{dynamic:!0});r!==P&&this.router.http.add("WS",P,R);return}if(U)r in F?F[r][t]=A:F[r]={[t]:A},this.config.strictPath||b(Ul(r));else{if(this.router.http.add(t,r,R),!this.config.strictPath){let B=Ul(r);b(B),this.router.http.add(t,B,R)}let P=Bl(r,{dynamic:!0});r!==P&&(this.router.http.add(t,P,R),b(P))}}headers(t){return t?(this.setHeaders||(this.setHeaders={}),this.setHeaders=cr(this.setHeaders,t),this):this}onStart(t){return this.on("start",t),this}onRequest(t){return this.on("request",t),this}onParse(t,r){return r?this.on(t,"parse",r):typeof t=="string"?this.on("parse",this["~parser"][t]):this.on("parse",t)}parser(t,r){return this["~parser"][t]=r,this}onTransform(t,r){return r?this.on(t,"transform",r):this.on("transform",t)}resolve(t,r){r||(r=t,t={as:"local"});let n={subType:"resolve",fn:r};return this.onBeforeHandle(t,n)}mapResolve(t,r){r||(r=t,t={as:"local"});let n={subType:"mapResolve",fn:r};return this.onBeforeHandle(t,n)}onBeforeHandle(t,r){return r?this.on(t,"beforeHandle",r):this.on("beforeHandle",t)}onAfterHandle(t,r){return r?this.on(t,"afterHandle",r):this.on("afterHandle",t)}mapResponse(t,r){return r?this.on(t,"mapResponse",r):this.on("mapResponse",t)}onAfterResponse(t,r){return r?this.on(t,"afterResponse",r):this.on("afterResponse",t)}trace(t,r){r||(r=t,t={as:"local"}),Array.isArray(r)||(r=[r]);for(let n of r)this.on(t,"trace",m6(n));return this}error(t,r){switch(typeof t){case"string":return r.prototype[jl]=t,this.definitions.error[t]=r,this;case"function":return this.definitions.error=t(this.definitions.error),this}for(let[n,o]of Object.entries(t))o.prototype[jl]=n,this.definitions.error[n]=o;return this}onError(t,r){return r?this.on(t,"error",r):this.on("error",t)}onStop(t){return this.on("stop",t),this}on(t,r,n){let o;switch(typeof t){case"string":o=t,n=r;break;case"object":o=r,!Array.isArray(r)&&typeof r=="object"&&(n=r);break}Array.isArray(n)?n=ar(n):typeof n=="function"?n=[{fn:n}]:n=[n];let i=n;for(let s of i)s.scope=typeof t=="string"?"local":t?.as??"local",(o==="resolve"||o==="derive")&&(s.subType=o);o!=="trace"&&(this.inference=Yl({[o]:i.map((s)=>s.fn)},this.inference,this.config.sucrose));for(let s of i){let a=wD(s,"global",{skipIfHasType:!0});switch((this.config.name||this.config.seed)&&(a.checksum=Hs(this.config.name+JSON.stringify(this.config.seed))),o){case"start":this.event.start??=[],this.event.start.push(a);break;case"request":this.event.request??=[],this.event.request.push(a);break;case"parse":this.event.parse??=[],this.event.parse.push(a);break;case"transform":this.event.transform??=[],this.event.transform.push(a);break;case"derive":this.event.transform??=[],this.event.transform.push(ar(a,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(a);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(ar(a,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(a);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(a);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(a);break;case"trace":this.event.trace??=[],this.event.trace.push(a);break;case"error":this.event.error??=[],this.event.error.push(a);break;case"stop":this.event.stop??=[],this.event.stop.push(a);break}}return this}as(t){return Ks(this.event.parse,t),Ks(this.event.transform,t),Ks(this.event.beforeHandle,t),Ks(this.event.afterHandle,t),Ks(this.event.mapResponse,t),Ks(this.event.afterResponse,t),Ks(this.event.trace,t),Ks(this.event.error,t),t==="scoped"?(this.validator.scoped=ep(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null)):t==="global"&&(this.validator.global=ep(this.validator.global,ep(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null),this.standaloneValidator.scoped!==null&&(this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null)),this}group(t,r,n){let o=new e({...this.config,prefix:""});o.singleton={...this.singleton},o.definitions={...this.definitions},o.getServer=()=>this.getServer(),o.inference=Kb(this.inference),o.extender={...this.extender},o["~parser"]=this["~parser"],o.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let i=typeof r=="object",s=(i?n:r)(o);return this.singleton=cr(this.singleton,o.singleton),this.definitions=cr(this.definitions,o.definitions),s.event.request?.length&&(this.event.request=[...this.event.request||[],...s.event.request||[]]),s.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...s.event.mapResponse||[]]),this.model(s.definitions.type),Object.values(o.router.history).forEach(({method:a,path:c,handler:l,hooks:u})=>{if(c=(i?"":this.config.prefix??"")+t+c,i){let{body:d,headers:f,query:p,params:h,cookie:g,response:y,...b}=r,w=u;this.applyMacro(b);let E=d||f||p||h||g||y;this.add(a,c,l,Yi(b,{...w||{},error:w.error?Array.isArray(w.error)?[...w.error??[],...s.event.error??[]]:[w.error,...s.event.error??[]]:s.event.error,standaloneValidator:b.standaloneValidator||w.standaloneValidator||E?[...b.standaloneValidator??[],...w.standaloneValidator??[],...E?[{body:d,headers:f,query:p,params:h,cookie:g,response:y}]:[]]:void 0}),void 0)}else this.add(a,c,l,Yi(u,{error:s.event.error}),{skipPrefix:!0})}),this}guard(t,r){if(!r){if(typeof t=="object"){this.applyMacro(t),t.detail&&(this.config.detail?this.config.detail=cr(Object.assign({},this.config.detail),t.detail):this.config.detail=t.detail),t.tags&&(this.config.detail?this.config.detail.tags=t.tags:this.config.detail={tags:t.tags});let i=t.as??"local";if(t.schema==="standalone"){this.standaloneValidator[i]||(this.standaloneValidator[i]=[]);let s=t?.response?typeof t.response=="string"||N in t.response||"~standard"in t.response?{200:t.response}:t?.response:void 0;this.standaloneValidator[i].push({body:t.body,headers:t.headers,params:t.params,query:t.query,response:s,cookie:t.cookie})}else this.validator[i]={body:t.body??this.validator[i]?.body,headers:t.headers??this.validator[i]?.headers,params:t.params??this.validator[i]?.params,query:t.query??this.validator[i]?.query,response:t.response??this.validator[i]?.response,cookie:t.cookie??this.validator[i]?.cookie};return t.parse&&this.on({as:i},"parse",t.parse),t.transform&&this.on({as:i},"transform",t.transform),t.derive&&this.on({as:i},"derive",t.derive),t.beforeHandle&&this.on({as:i},"beforeHandle",t.beforeHandle),t.resolve&&this.on({as:i},"resolve",t.resolve),t.afterHandle&&this.on({as:i},"afterHandle",t.afterHandle),t.mapResponse&&this.on({as:i},"mapResponse",t.mapResponse),t.afterResponse&&this.on({as:i},"afterResponse",t.afterResponse),t.error&&this.on({as:i},"error",t.error),this}return this.guard({},t)}let n=new e({...this.config,prefix:""});n.singleton={...this.singleton},n.definitions={...this.definitions},n.inference=Kb(this.inference),n.extender={...this.extender},n.getServer=()=>this.getServer();let o=r(n);if(this.singleton=cr(this.singleton,n.singleton),this.definitions=cr(this.definitions,n.definitions),o.getServer=()=>this.server,o.event.request?.length&&(this.event.request=[...this.event.request||[],...o.event.request||[]]),o.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...o.event.mapResponse||[]]),this.model(o.definitions.type),Object.values(n.router.history).forEach(({method:i,path:s,handler:a,hooks:c})=>{let{body:l,headers:u,query:d,params:f,cookie:p,response:h,...g}=t,y=l||u||d||f||p||h;this.add(i,s,a,Yi(g,{...c||{},error:c.error?Array.isArray(c.error)?[...c.error??[],...o.event.error??[]]:[c.error,...o.event.error??[]]:o.event.error,standaloneValidator:y?[...c.standaloneValidator??[],{body:l,headers:u,query:d,params:f,cookie:p,response:h}]:c.standaloneValidator}))}),n.promisedModules.size>0){let i=n.router.history.length;for(let s of n.promisedModules.promises)this.promisedModules.add(s.then(()=>{let{body:a,headers:c,query:l,params:u,cookie:d,response:f,...p}=t,h=a||c||l||u||d||f,g=i;i=n.router.history.length;for(let y=g;y<n.router.history.length;y++){let{method:b,path:w,handler:E,hooks:S}=n.router.history[y];this.add(b,w,E,Yi(p,{...S||{},error:S.error?Array.isArray(S.error)?[...S.error??[],...o.event.error??[]]:[S.error,...o.event.error??[]]:o.event.error,standaloneValidator:h?[...S.standaloneValidator??[],{body:a,headers:c,query:l,params:u,cookie:d,response:f}]:S.standaloneValidator}))}}))}return this}use(t){if(!t)return this;if(Array.isArray(t)){let r=this;for(let n of t)r=r.use(n);return r}return t instanceof Promise?(this.promisedModules.add(t.then((r)=>{if(typeof r=="function")return r(this);if(r instanceof e)return this._use(r).compile();if(r.constructor?.name==="Elysia")return this._use(r).compile();if(typeof r.default=="function")return r.default(this);if(r.default instanceof e)return this._use(r.default);if(r.constructor?.name==="Elysia")return this._use(r.default);if(r.constructor?.name==="_Elysia")return this._use(r.default);try{return this._use(r.default)}catch(n){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),n}}).then((r)=>(r&&typeof r.compile=="function"&&r.compile(),r))),this):this._use(t)}propagatePromiseModules(t){if(t.promisedModules.size<=0)return this;for(let r of t.promisedModules.promises)this.promisedModules.add(r.then((n)=>{if(!n)return;let o=this._use(n);return o instanceof Promise?o.then((i)=>{i?i.compile():n.compile()}):n.compile()}));return this}_use(t){if(typeof t=="function"){let o=t(this);return o instanceof Promise?(this.promisedModules.add(o.then((i)=>{if(i instanceof e){i.getServer=()=>this.getServer(),i.getGlobalRoutes=()=>this.getGlobalRoutes(),i.getGlobalDefinitions=()=>this.getGlobalDefinitions(),i.model(this.definitions.type),i.error(this.definitions.error);for(let{method:s,path:a,handler:c,hooks:l}of Object.values(i.router.history))this.add(s,a,c,l,void 0);return i===this?void 0:(this.propagatePromiseModules(i),i)}return typeof i=="function"?i(this):typeof i.default=="function"?i.default(this):this._use(i)}).then((i)=>(i&&typeof i.compile=="function"&&i.compile(),i))),this):o}this.propagatePromiseModules(t);let r=t.config.name,n=t.config.seed;if(t.getParent=()=>this,t.getServer=()=>this.getServer(),t.getGlobalRoutes=()=>this.getGlobalRoutes(),t.getGlobalDefinitions=()=>this.getGlobalDefinitions(),t.standaloneValidator?.scoped&&(this.standaloneValidator.local?this.standaloneValidator.local=this.standaloneValidator.local.concat(t.standaloneValidator.scoped):this.standaloneValidator.local=t.standaloneValidator.scoped),t.standaloneValidator?.global&&(this.standaloneValidator.global?this.standaloneValidator.global=this.standaloneValidator.global.concat(t.standaloneValidator.global):this.standaloneValidator.global=t.standaloneValidator.global),Fe(t["~parser"])&&(this["~parser"]={...t["~parser"],...this["~parser"]}),t.setHeaders&&this.headers(t.setHeaders),r){r in this.dependencies||(this.dependencies[r]=[]);let o=n!==void 0?Hs(r+JSON.stringify(n)):0;this.dependencies[r].some(({checksum:i})=>o===i)||(this.extender.macro={...this.extender.macro,...t.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions))}else Fe(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro}),t.extender.higherOrderFunctions.length&&(this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions));if(t.extender.higherOrderFunctions.length){LT(this.extender.higherOrderFunctions);let o=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let s=this.extender.higherOrderFunctions[i];s.checksum&&(o.includes(s.checksum)&&(this.extender.higherOrderFunctions.splice(i,1),i--),o.push(s.checksum))}o.length=0}this.inference=dw(this.inference,t.inference),Fe(t.singleton.decorator)&&this.decorate(t.singleton.decorator),Fe(t.singleton.store)&&this.state(t.singleton.store),Fe(t.definitions.type)&&this.model(t.definitions.type),Fe(t.definitions.error)&&this.error(t.definitions.error),Fe(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro});for(let{method:o,path:i,handler:s,hooks:a}of Object.values(t.router.history))this.add(o,i,s,a);if(r){r in this.dependencies||(this.dependencies[r]=[]);let o=n!==void 0?Hs(r+JSON.stringify(n)):0;if(this.dependencies[r].some(({checksum:i})=>o===i))return this;this.dependencies[r].push(this.config?.analytic?{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies,stack:t.telemetry?.stack,routes:t.router.history,decorators:t.singleton,store:t.singleton.store,error:t.definitions.error,derive:t.event.transform?.filter((i)=>i?.subType==="derive").map((i)=>({fn:i.toString(),stack:Error().stack??""})),resolve:t.event.transform?.filter((i)=>i?.subType==="resolve").map((i)=>({fn:i.toString(),stack:Error().stack??""}))}:{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies}),Fe(t.event)&&(this.event=RT(this.event,PT(t.event),o))}else Fe(t.event)&&(this.event=RT(this.event,PT(t.event)));return t.validator.global&&(this.validator.global=Yi(this.validator.global,{...t.validator.global})),t.validator.scoped&&(this.validator.local=Yi(this.validator.local,{...t.validator.scoped})),this}macro(t,r){if(typeof t=="string"&&!r)throw Error("Macro function is required");return typeof t=="string"?this.extender.macro[t]=r:this.extender.macro={...this.extender.macro,...t},this}applyMacro(t,r=t,{iteration:n=0,applied:o={}}={}){if(n>=16)return;let i=this.extender.macro;for(let[s,a]of Object.entries(r)){if(!(s in i))continue;let c=typeof i[s]=="function"?i[s](a):i[s];if(!c||typeof i[s]=="object"&&a===!1)return;let l=Hs(s+JSON.stringify(c.seed??a));if(!(l in o)){o[l]=!0;for(let[u,d]of Object.entries(c))if(u!=="seed"){if(u in kD){SD(t,u,d),delete t[s];continue}if(u==="introspect"){d?.(t),delete t[s];continue}if(u==="detail"){t.detail||(t.detail={}),t.detail=cr(t.detail,d,{mergeArray:!0}),delete t[s];continue}if(u in i){this.applyMacro(t,{[u]:d},{applied:o,iteration:n+1}),delete t[s];continue}switch((u==="derive"||u==="resolve")&&typeof d=="function"&&(d={fn:d,subType:u}),typeof t[u]){case"function":t[u]=[t[u],d];break;case"object":Array.isArray(t[u])?t[u].push(d):t[u]=[t[u],d];break;case"undefined":t[u]=d;break}delete t[s]}}}}mount(t,r,n){if(t instanceof e||typeof t=="function"||t.length===0||t==="/"){let a=typeof t=="function"?t:t instanceof e?t.compile().fetch:r instanceof e?r.compile().fetch:typeof r=="function"?r:(()=>{throw Error("Invalid handler")})(),c=({request:l,path:u})=>a(new Request(jb(l.url,u),l));return this.route("ALL","/*",c,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:a}}),this}let o=r instanceof e?r.compile().fetch:typeof r=="function"?r:(()=>{throw Error("Invalid handler")})(),i=(typeof t=="string"&&this.config.prefix?this.config.prefix+t:t).length-(t.endsWith("*")?1:0),s=({request:a,path:c})=>o(new Request(jb(a.url,c.slice(i)||"/"),a));return this.route("ALL",t,s,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:o}}),this.route("ALL",t+(t.endsWith("/")?"*":"/*"),s,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:o}}),this}get(t,r,n){return this.add("GET",t,r,n),this}post(t,r,n){return this.add("POST",t,r,n),this}put(t,r,n){return this.add("PUT",t,r,n),this}patch(t,r,n){return this.add("PATCH",t,r,n),this}delete(t,r,n){return this.add("DELETE",t,r,n),this}options(t,r,n){return this.add("OPTIONS",t,r,n),this}all(t,r,n){return this.add("ALL",t,r,n),this}head(t,r,n){return this.add("HEAD",t,r,n),this}connect(t,r,n){return this.add("CONNECT",t,r,n),this}route(t,r,n,o){return this.add(t.toUpperCase(),r,n,o,o?.config),this}ws(t,r){return this["~adapter"].ws?this["~adapter"].ws(this,t,r):console.warn("Current adapter doesn't support WebSocket"),this}state(t,r,n){r===void 0?(n=t,t={as:"append"},r=""):n===void 0&&(typeof t=="string"?(n=r,r=t,t={as:"append"}):typeof t=="object"&&(n=r,r=""));let{as:o}=t;if(typeof r!="string")return this;switch(typeof n){case"object":return!n||!Fe(n)?this:r?((r in this.singleton.store)?this.singleton.store[r]=cr(this.singleton.store[r],n,{override:o==="override"}):this.singleton.store[r]=n,this):n===null?this:(this.singleton.store=cr(this.singleton.store,n,{override:o==="override"}),this);case"function":return r?(o==="override"||!(r in this.singleton.store))&&(this.singleton.store[r]=n):this.singleton.store=n(this.singleton.store),this;default:return(o==="override"||!(r in this.singleton.store))&&(this.singleton.store[r]=n),this}}decorate(t,r,n){r===void 0?(n=t,t={as:"append"},r=""):n===void 0&&(typeof t=="string"?(n=r,r=t,t={as:"append"}):typeof t=="object"&&(n=r,r=""));let{as:o}=t;if(typeof r!="string")return this;switch(typeof n){case"object":return r?((r in this.singleton.decorator)?this.singleton.decorator[r]=cr(this.singleton.decorator[r],n,{override:o==="override"}):this.singleton.decorator[r]=n,this):n===null?this:(this.singleton.decorator=cr(this.singleton.decorator,n,{override:o==="override"}),this);case"function":return r?(o==="override"||!(r in this.singleton.decorator))&&(this.singleton.decorator[r]=n):this.singleton.decorator=n(this.singleton.decorator),this;default:return(o==="override"||!(r in this.singleton.decorator))&&(this.singleton.decorator[r]=n),this}}derive(t,r){r||(r=t,t={as:"local"});let n={subType:"derive",fn:r};return this.onTransform(t,n)}model(t,r){let n=(o)=>{let i={};for(let s in o)"~standard"in o[s]||(i[s]=o[s]);return i};switch(typeof t){case"object":let o={},i=Object.entries(t);if(!i.length)return this;for(let[c,l]of i)c in this.definitions.type||("~standard"in l?this.definitions.type[c]=l:(o[c]=this.definitions.type[c]=l,o[c].$id??=`#/components/schemas/${c}`));return this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,...o}),this;case"function":let s=t(this.definitions.type);return this.definitions.type=s,this.definitions.typebox=z.Module(n(s)),this;case"string":if(!r)break;if(this.definitions.type[t]=r,"~standard"in r)return this;let a={...r,id:r.$id??`#/components/schemas/${t}`};return this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,...a}),this}return r?(this.definitions.type[t]=r,("~standard"in r)?this:(this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,[t]:r}),this)):this}Ref(t){return z.Ref(t)}mapDerive(t,r){r||(r=t,t={as:"local"});let n={subType:"mapDerive",fn:r};return this.onTransform(t,n)}affix(t,r,n){if(n==="")return this;let o=["_","-"," "],i=(l)=>l[0].toUpperCase()+l.slice(1),s=t==="prefix"?(l,u)=>o.includes(l.at(-1)??"")?l+u:l+i(u):o.includes(n.at(-1)??"")?(l,u)=>u+l:(l,u)=>u+i(l),a=(l)=>{let u={};switch(l){case"decorator":for(let d in this.singleton.decorator)u[s(n,d)]=this.singleton.decorator[d];this.singleton.decorator=u;break;case"state":for(let d in this.singleton.store)u[s(n,d)]=this.singleton.store[d];this.singleton.store=u;break;case"model":for(let d in this.definitions.type)u[s(n,d)]=this.definitions.type[d];this.definitions.type=u;break;case"error":for(let d in this.definitions.error)u[s(n,d)]=this.definitions.error[d];this.definitions.error=u;break}},c=Array.isArray(r)?r:[r];for(let l of c.some((u)=>u==="all")?["decorator","state","model","error"]:c)a(l);return this}prefix(t,r){return this.affix("prefix",t,r)}suffix(t,r){return this.affix("suffix",t,r)}compile(){return this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard?(this._handle=this.config.aot?Tw(this):TE(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload=="function"&&this.server.reload({...this.server||{},fetch:this.fetch}),this):(typeof this.server?.reload=="function"&&this.server.reload(this.server||{}),this._handle=Tw(this),this)}get fetch(){let t=this.config.aot?Tw(this):TE(this);return Object.defineProperty(this,"fetch",{value:t,configurable:!0,writable:!0}),t}get modules(){return this.promisedModules}},Bo=P0e;var Iw={name:"@kabmo-labs/kabmo",version:"0.29.0",description:"Web console and diagnostic workbench for AI coding agents: Elysia + Preact on Bun.",license:"MIT",author:"Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",type:"module",engines:{bun:">=1.4.0"},publishConfig:{access:"public"},bin:{kabmo:"./src/cli/kabmo.js"},repository:{type:"git",url:"git+https://github.com/kabmo-labs/kabmo.git"},homepage:"https://github.com/kabmo-labs/kabmo#readme",bugs:{url:"https://github.com/kabmo-labs/kabmo/issues"},keywords:["kabmo","coding-agent","agent","console","elysia","preact","bun"],files:["src","extensions","index.html","bunfig.toml","public","tsconfig.json","marketplace","dist/client"],scripts:{dev:"bun run --hot src/server/index.ts --kabmo-server","dev:lan":"HOST=0.0.0.0 bun run --hot src/server/index.ts --kabmo-server",build:"bun run scripts/build-client.ts","editor:themes":"bun run scripts/editor-themes.mjs","icons:tints":"bun run scripts/icon-tints.mjs","icons:tints:check":"bun run scripts/icon-tints.mjs --check","editor:themes:check":"bun run scripts/editor-themes.mjs --check","omp:schema":"bun run scripts/omp-schema.mjs","omp:schema:check":"bun run scripts/omp-schema.mjs --check",start:"NODE_ENV=production bun run src/server/index.ts --kabmo-server",typecheck:"tsc",clean:"rm -rf dist",lint:"tsc --noEmit","check:fast":"bun check --no-script",test:"bun test","test:e2e":"playwright test --config tests/e2e/playwright.config.ts","readme:media":"bun run scripts/readme-media.ts","shell:wordmark":"bun run scripts/shell-wordmark.mjs","shell:docs":"bun run scripts/shell-document-types.mjs --write","shell:docs:check":"bun run scripts/shell-document-types.mjs --check","typecheck:e2e":"tsc --noEmit -p tests/e2e","typecheck:consumer":"tsc --noEmit -p tsconfig.consumer.json","publish:plugins":"bash .github/scripts/publish-plugin-packages.sh packages/kabmo-sdk packages/kabmo-ui"},dependencies:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/language":"6.13.1","@codemirror/legacy-modes":"^6.5.5","@codemirror/lint":"^6.9.7","@codemirror/merge":"6.12.3","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@dskripchenko/drawio":"^0.1.0","@fontsource/fira-code":"^5.3.0","@kabmo-labs/kabmo-sdk":"workspace:*","@kabmo-labs/kabmo-ui":"workspace:*","@shikijs/langs":"^4.4.3","@shikijs/themes":"^4.4.3","@tailwindcss/postcss":"^4.1.14",dompurify:"^3.4.15",elysia:"^1.4.30","ghostty-web":"0.4.0-next.21.g640db46","jsonc-parser":"^3.3.1",katex:"^0.18.7","lucide-preact":"^1.47.0",mammoth:"^1.13.0",marked:"^18.0.11","marked-linkify-it":"^4.0.2",mermaid:"^12.0.0",postcss:"^8.5.16",preact:"^10.29.8",remend:"^1.3.1",ripgrep:"^0.3.1",shiki:"^4.4.3","smol-toml":"^1.9.1",tailwindcss:"^4.1.14",xlsx:"https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",yaml:"^2.9.1"},devDependencies:{"@playwright/test":"^1.64.0","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/bun":"1.4.4","@types/node":"^22.14.0","bun-types":"1.4.4","conventional-changelog-conventionalcommits":"^9.3.1","happy-dom":"^20.14.5","semantic-release":"^25.0.9",typescript:"~5.8.2"},workspaces:["packages/*"]};var B6=tN("{\"index\":\"./dist/client/index.html\",\"files\":[{\"input\":\"../../index.html\",\"path\":\"./dist/client/static/js/index-43z47ngg.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"RIPfZCc1UDA\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../index.html\",\"path\":\"./dist/client/index.html\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"Q8E-fS32T8U\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../index.html\",\"path\":\"./dist/client/static/js/index-naa91727.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"1eoKiYFHIic\",\"content-type\":\"text/css;charset=utf-8\"}},{\"input\":\"../../public/manifest.webmanifest\",\"path\":\"./dist/client/static/manifest-vdvdqpre.webmanifest\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"Wy1bbZc2uM4\",\"content-type\":\"application/manifest+json\"}},{\"input\":\"../../public/icon.svg\",\"path\":\"./dist/client/static/icon-8h6v1jcy.svg\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"yFEme-ESbP4\",\"content-type\":\"image/svg+xml\"}},{\"input\":\"../../public/icon-192x192.png\",\"path\":\"./dist/client/static/icon-192x192-kz5bvz85.png\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"819lS3sfyKU\",\"content-type\":\"image/png\"}},{\"input\":\"../../public/apple-touch-icon.png\",\"path\":\"./dist/client/static/apple-touch-icon-bbhgf3mq.png\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"K8vRUA9jdJc\",\"content-type\":\"image/png\"}}]}");function m(e,t={}){let r=new Headers(t.headers);if(!r.has("content-type"))r.set("content-type","application/json; charset=utf-8");return new Response(JSON.stringify(e),{status:t.status??200,headers:r})}var re={"cache-control":"no-store"};import{brotliCompressSync as O0e,constants as M0e}from"zlib";function fo(e){if(e.buffer instanceof ArrayBuffer)return e;return new Uint8Array(e)}var RE=1024,j6=/^(text\/|application\/(json|javascript|xml|wasm|svg))/,N0e=["zstd","br","gzip"];function H6(e){return j6.test(e)}function PE(e){if(!e)return null;for(let t of N0e)if(e.includes(t))return t;return null}function IE(e,t){if(t==="zstd")return fo(Bun.zstdCompressSync(e,{level:3}));if(t==="br")return fo(O0e(e,{params:{[M0e.BROTLI_PARAM_QUALITY]:4}}));return fo(Bun.gzipSync(e,{level:6}))}async function _a(e,t){if(!t)return e;let r=e.headers.get("content-type")??"";if(r.includes("text/event-stream"))return e;if(!j6.test(r))return e;if(e.status===204||e.status===304)return e;let n=PE(t);if(!n)return e;let o=fo(new Uint8Array(await e.arrayBuffer()));if(o.byteLength<RE)return L0e(e,o);let i=IE(o,n),s=new Headers(e.headers);return s.set("content-encoding",n),s.set("content-length",String(i.byteLength)),s.append("vary","accept-encoding"),new Response(i,{status:e.status,headers:s})}function L0e(e,t){return new Response(t,{status:e.status,headers:e.headers})}function G(e,t,r={}){let n=[];if(e.loader)n.push({method:"GET",path:t,handler:e.loader});else if(e.action)n.push({method:"GET",path:t,handler:V});if(e.action)for(let o of r.mutating??["POST","PUT","PATCH","DELETE"])n.push({method:o,path:t,handler:e.action});return n}var V=()=>tu();function tu(){return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:{"content-type":"application/json; charset=utf-8"}})}async function $t(e){try{return{ok:!0,body:await e.json()}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}function br(e,t){let r=e[t];return r?r:null}function go(e,t=500){return m({error:e instanceof Error?e.message:String(e)},{status:t})}async function D0e(e){if(e instanceof Response)return e;if(e instanceof ReadableStream)return new Response(e,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}});return new Response(JSON.stringify(e??null),{status:200,headers:{"content-type":"application/json; charset=utf-8"}})}function F0e(e){return async({request:t,params:r})=>{try{let n=await D0e(await e({request:t,params:r}));return await _a(n,t.headers.get("accept-encoding"))}catch(n){let o=n instanceof Error?n.message:String(n);return new Response(JSON.stringify({error:o}),{status:500,headers:{"content-type":"application/json; charset=utf-8"}})}}}function W6(e,t){let r=e;for(let{method:n,path:o,handler:i}of t){let s=F0e(i);if(n==="GET")r=r.get(o,s);else if(n==="POST")r=r.post(o,s);else if(n==="PUT")r=r.put(o,s);else if(n==="PATCH")r=r.patch(o,s);else r=r.delete(o,s)}return r}function nt(e,t,r){return[{method:"GET",path:t,handler:r??V},...["POST","PUT","PATCH","DELETE"].map((n)=>({method:n,path:t,handler:e}))]}import{existsSync as CE,realpathSync as U0e}from"fs";import{homedir as $6,tmpdir as zct}from"os";import*as _t from"path";var K6="omp",B0e=".omp";function q6(){return Bun.env.PI_CONFIG_DIR||B0e}function ho(){return _t.join($6(),q6())}function ce(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return _t.resolve(e);return _t.join(ho(),"agent")}function V6(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return _t.resolve(e)===_t.join(ho(),"agent");return!0}function j0e(){if(process.platform!=="linux"&&process.platform!=="darwin")return;if(!V6())return;let e=Bun.env.XDG_DATA_HOME;if(!e)return;try{let t=_t.join(e,K6);return CE(t)?t:void 0}catch{return}}function H0e(e){let t=j0e();return _t.join(t??ce(),e)}function jo(){return H0e("sessions")}function G6(){return _t.join(ce(),"projects.json")}function z6(){if(process.platform!=="linux"&&process.platform!=="darwin")return ho();if(!V6())return ho();let e=Bun.env.XDG_DATA_HOME;if(!e)return ho();try{let t=_t.join(e,K6);return CE(t)?t:ho()}catch{return ho()}}function Y6(){return _t.join(z6(),"plugins")}function OE(){return _t.join(z6(),"marketplaces.json")}function J6(e){let t=$6(),r=q6(),n=_t.resolve(e);for(let o of[r,".git"]){let i=n;while(i!==t){if(CE(_t.join(i,o)))return _t.join(i,r,"plugins");let s=_t.dirname(i);if(s===i)break;i=s}}return _t.join(n,r,"plugins")}function ru(e){try{return U0e.native(e)}catch{return e}}async function X(e){try{return await Bun.file(e).stat(),!0}catch{return!1}}function yo(e){let t=ru(e);return t.replace(/\/+$/,"")||t}import NE from"fs";import*as Ow from"path";function x(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Or(e){let t=[];for(let r of e.split(`
666
+ `))}return this}wrap(t){return this.extender.higherOrderFunctions.push({checksum:Hs(JSON.stringify({name:this.config.name,seed:this.config.seed,content:t.toString()})),fn:t}),this}get models(){let t={};for(let r of Object.keys(this.definitions.type))t[r]=Ut(this.definitions.typebox.Import(r),{models:this.definitions.type});return t.modules=this.definitions.typebox,t}add(t,r,n,o,i){let s=i?.skipPrefix??!1,a=i?.allowMeta??!1;o??={},this.applyMacro(o);let c=[];if(o.standaloneValidator&&(c=c.concat(o.standaloneValidator)),this.standaloneValidator.local&&(c=c.concat(this.standaloneValidator.local)),this.standaloneValidator.scoped&&(c=c.concat(this.standaloneValidator.scoped)),this.standaloneValidator.global&&(c=c.concat(this.standaloneValidator.global)),r!==""&&r.charCodeAt(0)!==47&&(r="/"+r),this.config.prefix&&!s&&(r=this.config.prefix+r),o?.type)switch(o.type){case"text":o.type="text/plain";break;case"json":o.type="application/json";break;case"formdata":o.type="multipart/form-data";break;case"urlencoded":o.type="application/x-www-form-urlencoded";break;case"arrayBuffer":o.type="application/octet-stream";break;default:break}let l=this.validator.getCandidate(),u={body:o?.body??l?.body,headers:o?.headers??l?.headers,params:o?.params??l?.params,query:o?.query??l?.query,cookie:o?.cookie??l?.cookie,response:o?.response??l?.response},d=this.config.precompile===!0||typeof this.config.precompile=="object"&&this.config.precompile.compose===!0,f=()=>{let P=this.definitions.type,B=!this.config.aot,D=this.config.normalize,J=this.definitions.typebox,Z=()=>this.config.sanitize,ie=()=>{if(u.cookie||c.find((oe)=>oe.cookie))return S6({modules:J,validator:u.cookie,defaultConfig:this.config.cookie,normalize:D,config:u.cookie?.config??{},dynamic:B,models:P,validators:c.map((oe)=>oe.cookie),sanitize:Z})};return d?{body:Ut(u.body,{modules:J,dynamic:B,models:P,normalize:D,additionalCoerce:(()=>{let oe=yE(u.body,P,J);return oe&&N in oe&&(Ir("File",oe)||Ir("Files",oe))?gE():Ng()})(),validators:c.map((oe)=>oe.body),sanitize:Z}),headers:Ut(u.headers,{modules:J,dynamic:B,models:P,additionalProperties:!0,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.headers),sanitize:Z}),params:Ut(u.params,{modules:J,dynamic:B,models:P,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.params),sanitize:Z}),query:Ut(u.query,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:fE(),validators:c.map((oe)=>oe.query),sanitize:Z}),cookie:ie(),response:kw(u.response,{modules:J,dynamic:B,models:P,normalize:D,validators:c.map((oe)=>oe.response),sanitize:Z})}:{createBody(){return this.body?this.body:this.body=Ut(u.body,{modules:J,dynamic:B,models:P,normalize:D,additionalCoerce:(()=>{let oe=yE(u.body,P,J);return oe&&N in oe&&(Ir("File",oe)||Ir("Files",oe))?gE():Ng()})(),validators:c.map((oe)=>oe.body),sanitize:Z})},createHeaders(){return this.headers?this.headers:this.headers=Ut(u.headers,{modules:J,dynamic:B,models:P,normalize:D,additionalProperties:!D,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.headers),sanitize:Z})},createParams(){return this.params?this.params:this.params=Ut(u.params,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:Zl(),validators:c.map((oe)=>oe.params),sanitize:Z})},createQuery(){return this.query?this.query:this.query=Ut(u.query,{modules:J,dynamic:B,models:P,normalize:D,coerce:!0,additionalCoerce:fE(),validators:c.map((oe)=>oe.query),sanitize:Z})},createCookie(){return this.cookie?this.cookie:this.cookie=ie()},createResponse(){return this.response?this.response:this.response=kw(u.response,{modules:J,dynamic:B,models:P,normalize:D,validators:c.map((oe)=>oe.response),sanitize:Z})}}};(l.body||l.cookie||l.headers||l.params||l.query||l.response)&&(o=Yi(o,l)),o.tags&&(o.detail?o.detail.tags=o.tags:o.detail={tags:o.tags}),Fe(this.config.detail)&&(o.detail=cr(Object.assign({},this.config.detail),o.detail));let p=Fe(this.event)?Yi(this.event,OT(o)):{...bD(OT(o))};if(c.length&&Object.assign(p,{standaloneValidator:c}),this.config.aot===!1){let P=f();this.router.dynamic.add(t,r,{validator:P,hooks:p,content:o?.type,handle:n,route:r});let B=Bl(r,{dynamic:!0});if(r!==B&&this.router.dynamic.add(t,B,{validator:P,hooks:p,content:o?.type,handle:n,route:r}),!this.config.strictPath){let D=Ul(r);this.router.dynamic.add(t,D,{validator:P,hooks:p,content:o?.type,handle:n,route:r});let J=Bl(D);D!==J&&this.router.dynamic.add(t,D,{validator:P,hooks:p,content:o?.type,handle:n,route:r})}this.router.history.push({method:t,path:r,composed:null,handler:n,compile:void 0,hooks:p});return}let h=this["~adapter"].handler,g=typeof n!="function"?()=>{let P=h.createNativeStaticHandler?.(n,p,{headers:Object.assign({},this.setHeaders)});return P instanceof Promise?P.then((B)=>{if(B)return B}):P?.()}:void 0,y=this.config.nativeStaticResponse===!0,b=(P)=>{!y||!g||(qb?this.router.response[P]?this.router.response[P][t]=g():this.router.response[P]={[t]:g()}:this.router.response[P]=g())};b(r);let w,E=()=>{if(w)return w;let P=k6({app:this,path:r,method:t,hooks:p,validator:f(),handler:typeof n!="function"&&typeof h.createStaticHandler!="function"?()=>n:n,allowMeta:a,inference:this.inference});return this.router.history[A]&&(w=this.router.history[A].composed=P),P},S;if(`${t}_${r}`in this.routeTree)for(let P=0;P<this.router.history.length;P++){let B=this.router.history[P];if(B.path===r&&B.method===t){S=P;break}}else this.routeTree[`${t}_${r}`]=this.router.history.length;let A=S??this.router.history.length,T=this.router.history,I=d?E():(P)=>w?w(P):(T[A].composed=E())(P);S!==void 0?this.router.history[S]=Object.assign({method:t,path:r,composed:I,compile:E,handler:n,hooks:p},c.length?{standaloneValidators:c}:void 0,o.webSocket?{websocket:o.websocket}:void 0):this.router.history.push(Object.assign({method:t,path:r,composed:I,compile:E,handler:n,hooks:p},o.webSocket?{websocket:o.websocket}:void 0));let R={handler:d?T[A].composed:void 0,compile(){return this.handler=E()}},F=this.router.static,U=r.indexOf(":")===-1&&r.indexOf("*")===-1;if(t==="WS"){if(U){r in F?F[r][t]=A:F[r]={[t]:A};return}this.router.http.add("WS",r,R),this.config.strictPath||this.router.http.add("WS",Ul(r),R);let P=Bl(r,{dynamic:!0});r!==P&&this.router.http.add("WS",P,R);return}if(U)r in F?F[r][t]=A:F[r]={[t]:A},this.config.strictPath||b(Ul(r));else{if(this.router.http.add(t,r,R),!this.config.strictPath){let B=Ul(r);b(B),this.router.http.add(t,B,R)}let P=Bl(r,{dynamic:!0});r!==P&&(this.router.http.add(t,P,R),b(P))}}headers(t){return t?(this.setHeaders||(this.setHeaders={}),this.setHeaders=cr(this.setHeaders,t),this):this}onStart(t){return this.on("start",t),this}onRequest(t){return this.on("request",t),this}onParse(t,r){return r?this.on(t,"parse",r):typeof t=="string"?this.on("parse",this["~parser"][t]):this.on("parse",t)}parser(t,r){return this["~parser"][t]=r,this}onTransform(t,r){return r?this.on(t,"transform",r):this.on("transform",t)}resolve(t,r){r||(r=t,t={as:"local"});let n={subType:"resolve",fn:r};return this.onBeforeHandle(t,n)}mapResolve(t,r){r||(r=t,t={as:"local"});let n={subType:"mapResolve",fn:r};return this.onBeforeHandle(t,n)}onBeforeHandle(t,r){return r?this.on(t,"beforeHandle",r):this.on("beforeHandle",t)}onAfterHandle(t,r){return r?this.on(t,"afterHandle",r):this.on("afterHandle",t)}mapResponse(t,r){return r?this.on(t,"mapResponse",r):this.on("mapResponse",t)}onAfterResponse(t,r){return r?this.on(t,"afterResponse",r):this.on("afterResponse",t)}trace(t,r){r||(r=t,t={as:"local"}),Array.isArray(r)||(r=[r]);for(let n of r)this.on(t,"trace",m6(n));return this}error(t,r){switch(typeof t){case"string":return r.prototype[jl]=t,this.definitions.error[t]=r,this;case"function":return this.definitions.error=t(this.definitions.error),this}for(let[n,o]of Object.entries(t))o.prototype[jl]=n,this.definitions.error[n]=o;return this}onError(t,r){return r?this.on(t,"error",r):this.on("error",t)}onStop(t){return this.on("stop",t),this}on(t,r,n){let o;switch(typeof t){case"string":o=t,n=r;break;case"object":o=r,!Array.isArray(r)&&typeof r=="object"&&(n=r);break}Array.isArray(n)?n=ar(n):typeof n=="function"?n=[{fn:n}]:n=[n];let i=n;for(let s of i)s.scope=typeof t=="string"?"local":t?.as??"local",(o==="resolve"||o==="derive")&&(s.subType=o);o!=="trace"&&(this.inference=Yl({[o]:i.map((s)=>s.fn)},this.inference,this.config.sucrose));for(let s of i){let a=wD(s,"global",{skipIfHasType:!0});switch((this.config.name||this.config.seed)&&(a.checksum=Hs(this.config.name+JSON.stringify(this.config.seed))),o){case"start":this.event.start??=[],this.event.start.push(a);break;case"request":this.event.request??=[],this.event.request.push(a);break;case"parse":this.event.parse??=[],this.event.parse.push(a);break;case"transform":this.event.transform??=[],this.event.transform.push(a);break;case"derive":this.event.transform??=[],this.event.transform.push(ar(a,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(a);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(ar(a,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(a);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(a);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(a);break;case"trace":this.event.trace??=[],this.event.trace.push(a);break;case"error":this.event.error??=[],this.event.error.push(a);break;case"stop":this.event.stop??=[],this.event.stop.push(a);break}}return this}as(t){return Ks(this.event.parse,t),Ks(this.event.transform,t),Ks(this.event.beforeHandle,t),Ks(this.event.afterHandle,t),Ks(this.event.mapResponse,t),Ks(this.event.afterResponse,t),Ks(this.event.trace,t),Ks(this.event.error,t),t==="scoped"?(this.validator.scoped=ep(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null)):t==="global"&&(this.validator.global=ep(this.validator.global,ep(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null&&(this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null),this.standaloneValidator.scoped!==null&&(this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null)),this}group(t,r,n){let o=new e({...this.config,prefix:""});o.singleton={...this.singleton},o.definitions={...this.definitions},o.getServer=()=>this.getServer(),o.inference=Kb(this.inference),o.extender={...this.extender},o["~parser"]=this["~parser"],o.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let i=typeof r=="object",s=(i?n:r)(o);return this.singleton=cr(this.singleton,o.singleton),this.definitions=cr(this.definitions,o.definitions),s.event.request?.length&&(this.event.request=[...this.event.request||[],...s.event.request||[]]),s.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...s.event.mapResponse||[]]),this.model(s.definitions.type),Object.values(o.router.history).forEach(({method:a,path:c,handler:l,hooks:u})=>{if(c=(i?"":this.config.prefix??"")+t+c,i){let{body:d,headers:f,query:p,params:h,cookie:g,response:y,...b}=r,w=u;this.applyMacro(b);let E=d||f||p||h||g||y;this.add(a,c,l,Yi(b,{...w||{},error:w.error?Array.isArray(w.error)?[...w.error??[],...s.event.error??[]]:[w.error,...s.event.error??[]]:s.event.error,standaloneValidator:b.standaloneValidator||w.standaloneValidator||E?[...b.standaloneValidator??[],...w.standaloneValidator??[],...E?[{body:d,headers:f,query:p,params:h,cookie:g,response:y}]:[]]:void 0}),void 0)}else this.add(a,c,l,Yi(u,{error:s.event.error}),{skipPrefix:!0})}),this}guard(t,r){if(!r){if(typeof t=="object"){this.applyMacro(t),t.detail&&(this.config.detail?this.config.detail=cr(Object.assign({},this.config.detail),t.detail):this.config.detail=t.detail),t.tags&&(this.config.detail?this.config.detail.tags=t.tags:this.config.detail={tags:t.tags});let i=t.as??"local";if(t.schema==="standalone"){this.standaloneValidator[i]||(this.standaloneValidator[i]=[]);let s=t?.response?typeof t.response=="string"||N in t.response||"~standard"in t.response?{200:t.response}:t?.response:void 0;this.standaloneValidator[i].push({body:t.body,headers:t.headers,params:t.params,query:t.query,response:s,cookie:t.cookie})}else this.validator[i]={body:t.body??this.validator[i]?.body,headers:t.headers??this.validator[i]?.headers,params:t.params??this.validator[i]?.params,query:t.query??this.validator[i]?.query,response:t.response??this.validator[i]?.response,cookie:t.cookie??this.validator[i]?.cookie};return t.parse&&this.on({as:i},"parse",t.parse),t.transform&&this.on({as:i},"transform",t.transform),t.derive&&this.on({as:i},"derive",t.derive),t.beforeHandle&&this.on({as:i},"beforeHandle",t.beforeHandle),t.resolve&&this.on({as:i},"resolve",t.resolve),t.afterHandle&&this.on({as:i},"afterHandle",t.afterHandle),t.mapResponse&&this.on({as:i},"mapResponse",t.mapResponse),t.afterResponse&&this.on({as:i},"afterResponse",t.afterResponse),t.error&&this.on({as:i},"error",t.error),this}return this.guard({},t)}let n=new e({...this.config,prefix:""});n.singleton={...this.singleton},n.definitions={...this.definitions},n.inference=Kb(this.inference),n.extender={...this.extender},n.getServer=()=>this.getServer();let o=r(n);if(this.singleton=cr(this.singleton,n.singleton),this.definitions=cr(this.definitions,n.definitions),o.getServer=()=>this.server,o.event.request?.length&&(this.event.request=[...this.event.request||[],...o.event.request||[]]),o.event.mapResponse?.length&&(this.event.mapResponse=[...this.event.mapResponse||[],...o.event.mapResponse||[]]),this.model(o.definitions.type),Object.values(n.router.history).forEach(({method:i,path:s,handler:a,hooks:c})=>{let{body:l,headers:u,query:d,params:f,cookie:p,response:h,...g}=t,y=l||u||d||f||p||h;this.add(i,s,a,Yi(g,{...c||{},error:c.error?Array.isArray(c.error)?[...c.error??[],...o.event.error??[]]:[c.error,...o.event.error??[]]:o.event.error,standaloneValidator:y?[...c.standaloneValidator??[],{body:l,headers:u,query:d,params:f,cookie:p,response:h}]:c.standaloneValidator}))}),n.promisedModules.size>0){let i=n.router.history.length;for(let s of n.promisedModules.promises)this.promisedModules.add(s.then(()=>{let{body:a,headers:c,query:l,params:u,cookie:d,response:f,...p}=t,h=a||c||l||u||d||f,g=i;i=n.router.history.length;for(let y=g;y<n.router.history.length;y++){let{method:b,path:w,handler:E,hooks:S}=n.router.history[y];this.add(b,w,E,Yi(p,{...S||{},error:S.error?Array.isArray(S.error)?[...S.error??[],...o.event.error??[]]:[S.error,...o.event.error??[]]:o.event.error,standaloneValidator:h?[...S.standaloneValidator??[],{body:a,headers:c,query:l,params:u,cookie:d,response:f}]:S.standaloneValidator}))}}))}return this}use(t){if(!t)return this;if(Array.isArray(t)){let r=this;for(let n of t)r=r.use(n);return r}return t instanceof Promise?(this.promisedModules.add(t.then((r)=>{if(typeof r=="function")return r(this);if(r instanceof e)return this._use(r).compile();if(r.constructor?.name==="Elysia")return this._use(r).compile();if(typeof r.default=="function")return r.default(this);if(r.default instanceof e)return this._use(r.default);if(r.constructor?.name==="Elysia")return this._use(r.default);if(r.constructor?.name==="_Elysia")return this._use(r.default);try{return this._use(r.default)}catch(n){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),n}}).then((r)=>(r&&typeof r.compile=="function"&&r.compile(),r))),this):this._use(t)}propagatePromiseModules(t){if(t.promisedModules.size<=0)return this;for(let r of t.promisedModules.promises)this.promisedModules.add(r.then((n)=>{if(!n)return;let o=this._use(n);return o instanceof Promise?o.then((i)=>{i?i.compile():n.compile()}):n.compile()}));return this}_use(t){if(typeof t=="function"){let o=t(this);return o instanceof Promise?(this.promisedModules.add(o.then((i)=>{if(i instanceof e){i.getServer=()=>this.getServer(),i.getGlobalRoutes=()=>this.getGlobalRoutes(),i.getGlobalDefinitions=()=>this.getGlobalDefinitions(),i.model(this.definitions.type),i.error(this.definitions.error);for(let{method:s,path:a,handler:c,hooks:l}of Object.values(i.router.history))this.add(s,a,c,l,void 0);return i===this?void 0:(this.propagatePromiseModules(i),i)}return typeof i=="function"?i(this):typeof i.default=="function"?i.default(this):this._use(i)}).then((i)=>(i&&typeof i.compile=="function"&&i.compile(),i))),this):o}this.propagatePromiseModules(t);let r=t.config.name,n=t.config.seed;if(t.getParent=()=>this,t.getServer=()=>this.getServer(),t.getGlobalRoutes=()=>this.getGlobalRoutes(),t.getGlobalDefinitions=()=>this.getGlobalDefinitions(),t.standaloneValidator?.scoped&&(this.standaloneValidator.local?this.standaloneValidator.local=this.standaloneValidator.local.concat(t.standaloneValidator.scoped):this.standaloneValidator.local=t.standaloneValidator.scoped),t.standaloneValidator?.global&&(this.standaloneValidator.global?this.standaloneValidator.global=this.standaloneValidator.global.concat(t.standaloneValidator.global):this.standaloneValidator.global=t.standaloneValidator.global),Fe(t["~parser"])&&(this["~parser"]={...t["~parser"],...this["~parser"]}),t.setHeaders&&this.headers(t.setHeaders),r){r in this.dependencies||(this.dependencies[r]=[]);let o=n!==void 0?Hs(r+JSON.stringify(n)):0;this.dependencies[r].some(({checksum:i})=>o===i)||(this.extender.macro={...this.extender.macro,...t.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions))}else Fe(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro}),t.extender.higherOrderFunctions.length&&(this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(t.extender.higherOrderFunctions));if(t.extender.higherOrderFunctions.length){LT(this.extender.higherOrderFunctions);let o=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let s=this.extender.higherOrderFunctions[i];s.checksum&&(o.includes(s.checksum)&&(this.extender.higherOrderFunctions.splice(i,1),i--),o.push(s.checksum))}o.length=0}this.inference=dw(this.inference,t.inference),Fe(t.singleton.decorator)&&this.decorate(t.singleton.decorator),Fe(t.singleton.store)&&this.state(t.singleton.store),Fe(t.definitions.type)&&this.model(t.definitions.type),Fe(t.definitions.error)&&this.error(t.definitions.error),Fe(t.extender.macro)&&(this.extender.macro={...this.extender.macro,...t.extender.macro});for(let{method:o,path:i,handler:s,hooks:a}of Object.values(t.router.history))this.add(o,i,s,a);if(r){r in this.dependencies||(this.dependencies[r]=[]);let o=n!==void 0?Hs(r+JSON.stringify(n)):0;if(this.dependencies[r].some(({checksum:i})=>o===i))return this;this.dependencies[r].push(this.config?.analytic?{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies,stack:t.telemetry?.stack,routes:t.router.history,decorators:t.singleton,store:t.singleton.store,error:t.definitions.error,derive:t.event.transform?.filter((i)=>i?.subType==="derive").map((i)=>({fn:i.toString(),stack:Error().stack??""})),resolve:t.event.transform?.filter((i)=>i?.subType==="resolve").map((i)=>({fn:i.toString(),stack:Error().stack??""}))}:{name:t.config.name,seed:t.config.seed,checksum:o,dependencies:t.dependencies}),Fe(t.event)&&(this.event=RT(this.event,PT(t.event),o))}else Fe(t.event)&&(this.event=RT(this.event,PT(t.event)));return t.validator.global&&(this.validator.global=Yi(this.validator.global,{...t.validator.global})),t.validator.scoped&&(this.validator.local=Yi(this.validator.local,{...t.validator.scoped})),this}macro(t,r){if(typeof t=="string"&&!r)throw Error("Macro function is required");return typeof t=="string"?this.extender.macro[t]=r:this.extender.macro={...this.extender.macro,...t},this}applyMacro(t,r=t,{iteration:n=0,applied:o={}}={}){if(n>=16)return;let i=this.extender.macro;for(let[s,a]of Object.entries(r)){if(!(s in i))continue;let c=typeof i[s]=="function"?i[s](a):i[s];if(!c||typeof i[s]=="object"&&a===!1)return;let l=Hs(s+JSON.stringify(c.seed??a));if(!(l in o)){o[l]=!0;for(let[u,d]of Object.entries(c))if(u!=="seed"){if(u in kD){SD(t,u,d),delete t[s];continue}if(u==="introspect"){d?.(t),delete t[s];continue}if(u==="detail"){t.detail||(t.detail={}),t.detail=cr(t.detail,d,{mergeArray:!0}),delete t[s];continue}if(u in i){this.applyMacro(t,{[u]:d},{applied:o,iteration:n+1}),delete t[s];continue}switch((u==="derive"||u==="resolve")&&typeof d=="function"&&(d={fn:d,subType:u}),typeof t[u]){case"function":t[u]=[t[u],d];break;case"object":Array.isArray(t[u])?t[u].push(d):t[u]=[t[u],d];break;case"undefined":t[u]=d;break}delete t[s]}}}}mount(t,r,n){if(t instanceof e||typeof t=="function"||t.length===0||t==="/"){let a=typeof t=="function"?t:t instanceof e?t.compile().fetch:r instanceof e?r.compile().fetch:typeof r=="function"?r:(()=>{throw Error("Invalid handler")})(),c=({request:l,path:u})=>a(new Request(jb(l.url,u),l));return this.route("ALL","/*",c,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:a}}),this}let o=r instanceof e?r.compile().fetch:typeof r=="function"?r:(()=>{throw Error("Invalid handler")})(),i=(typeof t=="string"&&this.config.prefix?this.config.prefix+t:t).length-(t.endsWith("*")?1:0),s=({request:a,path:c})=>o(new Request(jb(a.url,c.slice(i)||"/"),a));return this.route("ALL",t,s,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:o}}),this.route("ALL",t+(t.endsWith("/")?"*":"/*"),s,{parse:"none",...n,detail:{...n?.detail,hide:!0},config:{mount:o}}),this}get(t,r,n){return this.add("GET",t,r,n),this}post(t,r,n){return this.add("POST",t,r,n),this}put(t,r,n){return this.add("PUT",t,r,n),this}patch(t,r,n){return this.add("PATCH",t,r,n),this}delete(t,r,n){return this.add("DELETE",t,r,n),this}options(t,r,n){return this.add("OPTIONS",t,r,n),this}all(t,r,n){return this.add("ALL",t,r,n),this}head(t,r,n){return this.add("HEAD",t,r,n),this}connect(t,r,n){return this.add("CONNECT",t,r,n),this}route(t,r,n,o){return this.add(t.toUpperCase(),r,n,o,o?.config),this}ws(t,r){return this["~adapter"].ws?this["~adapter"].ws(this,t,r):console.warn("Current adapter doesn't support WebSocket"),this}state(t,r,n){r===void 0?(n=t,t={as:"append"},r=""):n===void 0&&(typeof t=="string"?(n=r,r=t,t={as:"append"}):typeof t=="object"&&(n=r,r=""));let{as:o}=t;if(typeof r!="string")return this;switch(typeof n){case"object":return!n||!Fe(n)?this:r?((r in this.singleton.store)?this.singleton.store[r]=cr(this.singleton.store[r],n,{override:o==="override"}):this.singleton.store[r]=n,this):n===null?this:(this.singleton.store=cr(this.singleton.store,n,{override:o==="override"}),this);case"function":return r?(o==="override"||!(r in this.singleton.store))&&(this.singleton.store[r]=n):this.singleton.store=n(this.singleton.store),this;default:return(o==="override"||!(r in this.singleton.store))&&(this.singleton.store[r]=n),this}}decorate(t,r,n){r===void 0?(n=t,t={as:"append"},r=""):n===void 0&&(typeof t=="string"?(n=r,r=t,t={as:"append"}):typeof t=="object"&&(n=r,r=""));let{as:o}=t;if(typeof r!="string")return this;switch(typeof n){case"object":return r?((r in this.singleton.decorator)?this.singleton.decorator[r]=cr(this.singleton.decorator[r],n,{override:o==="override"}):this.singleton.decorator[r]=n,this):n===null?this:(this.singleton.decorator=cr(this.singleton.decorator,n,{override:o==="override"}),this);case"function":return r?(o==="override"||!(r in this.singleton.decorator))&&(this.singleton.decorator[r]=n):this.singleton.decorator=n(this.singleton.decorator),this;default:return(o==="override"||!(r in this.singleton.decorator))&&(this.singleton.decorator[r]=n),this}}derive(t,r){r||(r=t,t={as:"local"});let n={subType:"derive",fn:r};return this.onTransform(t,n)}model(t,r){let n=(o)=>{let i={};for(let s in o)"~standard"in o[s]||(i[s]=o[s]);return i};switch(typeof t){case"object":let o={},i=Object.entries(t);if(!i.length)return this;for(let[c,l]of i)c in this.definitions.type||("~standard"in l?this.definitions.type[c]=l:(o[c]=this.definitions.type[c]=l,o[c].$id??=`#/components/schemas/${c}`));return this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,...o}),this;case"function":let s=t(this.definitions.type);return this.definitions.type=s,this.definitions.typebox=z.Module(n(s)),this;case"string":if(!r)break;if(this.definitions.type[t]=r,"~standard"in r)return this;let a={...r,id:r.$id??`#/components/schemas/${t}`};return this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,...a}),this}return r?(this.definitions.type[t]=r,("~standard"in r)?this:(this.definitions.typebox=z.Module({...this.definitions.typebox.$defs,[t]:r}),this)):this}Ref(t){return z.Ref(t)}mapDerive(t,r){r||(r=t,t={as:"local"});let n={subType:"mapDerive",fn:r};return this.onTransform(t,n)}affix(t,r,n){if(n==="")return this;let o=["_","-"," "],i=(l)=>l[0].toUpperCase()+l.slice(1),s=t==="prefix"?(l,u)=>o.includes(l.at(-1)??"")?l+u:l+i(u):o.includes(n.at(-1)??"")?(l,u)=>u+l:(l,u)=>u+i(l),a=(l)=>{let u={};switch(l){case"decorator":for(let d in this.singleton.decorator)u[s(n,d)]=this.singleton.decorator[d];this.singleton.decorator=u;break;case"state":for(let d in this.singleton.store)u[s(n,d)]=this.singleton.store[d];this.singleton.store=u;break;case"model":for(let d in this.definitions.type)u[s(n,d)]=this.definitions.type[d];this.definitions.type=u;break;case"error":for(let d in this.definitions.error)u[s(n,d)]=this.definitions.error[d];this.definitions.error=u;break}},c=Array.isArray(r)?r:[r];for(let l of c.some((u)=>u==="all")?["decorator","state","model","error"]:c)a(l);return this}prefix(t,r){return this.affix("prefix",t,r)}suffix(t,r){return this.affix("suffix",t,r)}compile(){return this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard?(this._handle=this.config.aot?Tw(this):TE(this),Object.defineProperty(this,"fetch",{value:this._handle,configurable:!0,writable:!0}),typeof this.server?.reload=="function"&&this.server.reload({...this.server||{},fetch:this.fetch}),this):(typeof this.server?.reload=="function"&&this.server.reload(this.server||{}),this._handle=Tw(this),this)}get fetch(){let t=this.config.aot?Tw(this):TE(this);return Object.defineProperty(this,"fetch",{value:t,configurable:!0,writable:!0}),t}get modules(){return this.promisedModules}},Bo=P0e;var Iw={name:"@kabmo-labs/kabmo",version:"0.30.0",description:"Web console and diagnostic workbench for AI coding agents: Elysia + Preact on Bun.",license:"MIT",author:"Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",type:"module",engines:{bun:">=1.4.0"},publishConfig:{access:"public"},bin:{kabmo:"./src/cli/kabmo.js"},repository:{type:"git",url:"git+https://github.com/kabmo-labs/kabmo.git"},homepage:"https://github.com/kabmo-labs/kabmo#readme",bugs:{url:"https://github.com/kabmo-labs/kabmo/issues"},keywords:["kabmo","coding-agent","agent","console","elysia","preact","bun"],files:["src","extensions","index.html","bunfig.toml","public","tsconfig.json","marketplace","dist/client"],scripts:{dev:"bun run --hot src/server/index.ts --kabmo-server","dev:lan":"HOST=0.0.0.0 bun run --hot src/server/index.ts --kabmo-server",build:"bun run scripts/build-client.ts","editor:themes":"bun run scripts/editor-themes.mjs","icons:tints":"bun run scripts/icon-tints.mjs","icons:tints:check":"bun run scripts/icon-tints.mjs --check","editor:themes:check":"bun run scripts/editor-themes.mjs --check","omp:schema":"bun run scripts/omp-schema.mjs","omp:schema:check":"bun run scripts/omp-schema.mjs --check",start:"NODE_ENV=production bun run src/server/index.ts --kabmo-server",typecheck:"tsc",clean:"rm -rf dist",lint:"tsc --noEmit","check:fast":"bun check --no-script",test:"bun test","test:e2e":"playwright test --config tests/e2e/playwright.config.ts","readme:media":"bun run scripts/readme-media.ts","shell:wordmark":"bun run scripts/shell-wordmark.mjs","shell:docs":"bun run scripts/shell-document-types.mjs --write","shell:docs:check":"bun run scripts/shell-document-types.mjs --check","typecheck:e2e":"tsc --noEmit -p tests/e2e","typecheck:consumer":"tsc --noEmit -p tsconfig.consumer.json","publish:plugins":"bash .github/scripts/publish-plugin-packages.sh packages/kabmo-sdk packages/kabmo-ui"},dependencies:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/language":"6.13.1","@codemirror/legacy-modes":"^6.5.5","@codemirror/lint":"^6.9.7","@codemirror/merge":"6.12.3","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@dskripchenko/drawio":"^0.1.0","@fontsource/fira-code":"^5.3.0","@kabmo-labs/kabmo-sdk":"workspace:*","@kabmo-labs/kabmo-ui":"workspace:*","@shikijs/langs":"^4.4.3","@shikijs/themes":"^4.4.3","@tailwindcss/postcss":"^4.1.14",dompurify:"^3.4.15",elysia:"^1.4.30","ghostty-web":"0.4.0-next.21.g640db46","jsonc-parser":"^3.3.1",katex:"^0.18.7","lucide-preact":"^1.47.0",mammoth:"^1.13.0",marked:"^18.0.11","marked-linkify-it":"^4.0.2",mermaid:"^12.0.0",postcss:"^8.5.16",preact:"^10.29.8",remend:"^1.3.1",ripgrep:"^0.3.1",shiki:"^4.4.3","smol-toml":"^1.9.1",tailwindcss:"^4.1.14",xlsx:"https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",yaml:"^2.9.1"},devDependencies:{"@playwright/test":"^1.64.0","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/bun":"1.4.4","@types/node":"^22.14.0","bun-types":"1.4.4","conventional-changelog-conventionalcommits":"^9.3.1","happy-dom":"^20.14.5","semantic-release":"^25.0.9",typescript:"~5.8.2"},workspaces:["packages/*"]};var B6=tN("{\"index\":\"./dist/client/index.html\",\"files\":[{\"input\":\"../../index.html\",\"path\":\"./dist/client/static/js/index-5vjbp04s.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"JXuSy1ZgpDk\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../index.html\",\"path\":\"./dist/client/index.html\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"N1KVX8uT2Uo\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../index.html\",\"path\":\"./dist/client/static/js/index-naa91727.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"1eoKiYFHIic\",\"content-type\":\"text/css;charset=utf-8\"}},{\"input\":\"../../public/manifest.webmanifest\",\"path\":\"./dist/client/static/manifest-vdvdqpre.webmanifest\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"Wy1bbZc2uM4\",\"content-type\":\"application/manifest+json\"}},{\"input\":\"../../public/icon.svg\",\"path\":\"./dist/client/static/icon-8h6v1jcy.svg\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"yFEme-ESbP4\",\"content-type\":\"image/svg+xml\"}},{\"input\":\"../../public/icon-192x192.png\",\"path\":\"./dist/client/static/icon-192x192-kz5bvz85.png\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"819lS3sfyKU\",\"content-type\":\"image/png\"}},{\"input\":\"../../public/apple-touch-icon.png\",\"path\":\"./dist/client/static/apple-touch-icon-bbhgf3mq.png\",\"loader\":\"file\",\"isEntry\":false,\"headers\":{\"etag\":\"K8vRUA9jdJc\",\"content-type\":\"image/png\"}}]}");function m(e,t={}){let r=new Headers(t.headers);if(!r.has("content-type"))r.set("content-type","application/json; charset=utf-8");return new Response(JSON.stringify(e),{status:t.status??200,headers:r})}var re={"cache-control":"no-store"};import{brotliCompressSync as O0e,constants as M0e}from"zlib";function fo(e){if(e.buffer instanceof ArrayBuffer)return e;return new Uint8Array(e)}var RE=1024,j6=/^(text\/|application\/(json|javascript|xml|wasm|svg))/,N0e=["zstd","br","gzip"];function H6(e){return j6.test(e)}function PE(e){if(!e)return null;for(let t of N0e)if(e.includes(t))return t;return null}function IE(e,t){if(t==="zstd")return fo(Bun.zstdCompressSync(e,{level:3}));if(t==="br")return fo(O0e(e,{params:{[M0e.BROTLI_PARAM_QUALITY]:4}}));return fo(Bun.gzipSync(e,{level:6}))}async function _a(e,t){if(!t)return e;let r=e.headers.get("content-type")??"";if(r.includes("text/event-stream"))return e;if(!j6.test(r))return e;if(e.status===204||e.status===304)return e;let n=PE(t);if(!n)return e;let o=fo(new Uint8Array(await e.arrayBuffer()));if(o.byteLength<RE)return L0e(e,o);let i=IE(o,n),s=new Headers(e.headers);return s.set("content-encoding",n),s.set("content-length",String(i.byteLength)),s.append("vary","accept-encoding"),new Response(i,{status:e.status,headers:s})}function L0e(e,t){return new Response(t,{status:e.status,headers:e.headers})}function G(e,t,r={}){let n=[];if(e.loader)n.push({method:"GET",path:t,handler:e.loader});else if(e.action)n.push({method:"GET",path:t,handler:V});if(e.action)for(let o of r.mutating??["POST","PUT","PATCH","DELETE"])n.push({method:o,path:t,handler:e.action});return n}var V=()=>tu();function tu(){return new Response(JSON.stringify({error:"Method not allowed"}),{status:405,headers:{"content-type":"application/json; charset=utf-8"}})}async function $t(e){try{return{ok:!0,body:await e.json()}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}function br(e,t){let r=e[t];return r?r:null}function go(e,t=500){return m({error:e instanceof Error?e.message:String(e)},{status:t})}async function D0e(e){if(e instanceof Response)return e;if(e instanceof ReadableStream)return new Response(e,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}});return new Response(JSON.stringify(e??null),{status:200,headers:{"content-type":"application/json; charset=utf-8"}})}function F0e(e){return async({request:t,params:r})=>{try{let n=await D0e(await e({request:t,params:r}));return await _a(n,t.headers.get("accept-encoding"))}catch(n){let o=n instanceof Error?n.message:String(n);return new Response(JSON.stringify({error:o}),{status:500,headers:{"content-type":"application/json; charset=utf-8"}})}}}function W6(e,t){let r=e;for(let{method:n,path:o,handler:i}of t){let s=F0e(i);if(n==="GET")r=r.get(o,s);else if(n==="POST")r=r.post(o,s);else if(n==="PUT")r=r.put(o,s);else if(n==="PATCH")r=r.patch(o,s);else r=r.delete(o,s)}return r}function nt(e,t,r){return[{method:"GET",path:t,handler:r??V},...["POST","PUT","PATCH","DELETE"].map((n)=>({method:n,path:t,handler:e}))]}import{existsSync as CE,realpathSync as U0e}from"fs";import{homedir as $6,tmpdir as zct}from"os";import*as _t from"path";var K6="omp",B0e=".omp";function q6(){return Bun.env.PI_CONFIG_DIR||B0e}function ho(){return _t.join($6(),q6())}function ce(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return _t.resolve(e);return _t.join(ho(),"agent")}function V6(){let e=Bun.env.PI_CODING_AGENT_DIR;if(e)return _t.resolve(e)===_t.join(ho(),"agent");return!0}function j0e(){if(process.platform!=="linux"&&process.platform!=="darwin")return;if(!V6())return;let e=Bun.env.XDG_DATA_HOME;if(!e)return;try{let t=_t.join(e,K6);return CE(t)?t:void 0}catch{return}}function H0e(e){let t=j0e();return _t.join(t??ce(),e)}function jo(){return H0e("sessions")}function G6(){return _t.join(ce(),"projects.json")}function z6(){if(process.platform!=="linux"&&process.platform!=="darwin")return ho();if(!V6())return ho();let e=Bun.env.XDG_DATA_HOME;if(!e)return ho();try{let t=_t.join(e,K6);return CE(t)?t:ho()}catch{return ho()}}function Y6(){return _t.join(z6(),"plugins")}function OE(){return _t.join(z6(),"marketplaces.json")}function J6(e){let t=$6(),r=q6(),n=_t.resolve(e);for(let o of[r,".git"]){let i=n;while(i!==t){if(CE(_t.join(i,o)))return _t.join(i,r,"plugins");let s=_t.dirname(i);if(s===i)break;i=s}}return _t.join(n,r,"plugins")}function ru(e){try{return U0e.native(e)}catch{return e}}async function X(e){try{return await Bun.file(e).stat(),!0}catch{return!1}}function yo(e){let t=ru(e);return t.replace(/\/+$/,"")||t}import NE from"fs";import*as Ow from"path";function x(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Or(e){let t=[];for(let r of e.split(`
667
667
  `)){let n=r.trim();if(!n)continue;try{t.push(JSON.parse(n))}catch{}}return t}function X6(e){let t=e.endsWith("\\")?e.slice(0,-1):e;try{return JSON.parse(`"${t}"`)}catch{return t.replace(/\\n/g,`
668
668
  `).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}}function Cr(e,t,r=0){let n=e.indexOf(`"${t}"`,r);if(n===-1)return;let o=e.indexOf(":",n+t.length+2);if(o===-1)return;let i=o+1;while(i<e.length){let c=e.charCodeAt(i);if(c!==32&&c!==9&&c!==10&&c!==13)break;i++}if(e.charCodeAt(i)!==34)return;let s=i+1,a=!1;for(let c=s;c<e.length;c++){let l=e.charCodeAt(c);if(a){a=!1;continue}if(l===92){a=!0;continue}if(l===34)return X6(e.slice(s,c))}return X6(e.slice(s))}function Z6(e){let t=0,r=0;while(r<e.length){let n=e.indexOf('"type"',r);if(n===-1)break;let o=e.indexOf(":",n+6);if(o===-1)break;if(Cr(e,"type",n)==="message")t++;r=o+1}return t}function Q6(e){if(e===void 0)return;return e.trim()?e:null}function W0e(e,t){if(e?.type!=="session"||typeof e.id!=="string")return;return{id:e.id,cwd:typeof e.cwd==="string"?e.cwd:void 0,title:t===null?void 0:t??(typeof e.title==="string"?e.title:void 0),parentSession:typeof e.parentSession==="string"?e.parentSession:void 0,timestamp:typeof e.timestamp==="string"?e.timestamp:void 0}}function $0e(e,t){if(Cr(e,"type")!=="session")return;let r=Cr(e,"id");if(!r)return;return{id:r,cwd:Cr(e,"cwd"),title:t===null?void 0:t??Cr(e,"title"),parentSession:Cr(e,"parentSession"),timestamp:Cr(e,"timestamp")}}function _6(e,t){let r=t[0],n=Q6(r?.type==="title"&&typeof r.title==="string"?r.title:void 0),o=W0e(t[r?.type==="title"?1:0],n);if(o)return o;let i,s=!0;for(let a of e.split(/\r?\n/)){let c=a.trim();if(!c)continue;if(s&&Cr(c,"type")==="title"){i=Q6(Cr(c,"title")),s=!1;continue}return $0e(c,i)}return}var ME=4096,K0e=16384,e5=1048576;async function t5(e,t){let r=Bun.file(e),n=await r.stat(),o=Math.min(t,n.size);return{text:o>0?await r.slice(0,o).text():"",size:n.size,mtime:new Date(n.mtimeMs),mtimeMs:n.mtimeMs}}var q0e={session_exit:!0};function V0e(e){let t,r,n,o=!1;try{let a=JSON.parse(e);if(x(a))o=!0,t=a.type,r=a.customType,n=a.timestamp}catch{}if(!o)n=Cr(e,"timestamp"),t=Cr(e,"type"),r=Cr(e,"customType");let i;if(typeof n==="number"&&Number.isFinite(n))i=new Date(n);else if(typeof n==="string"){let a=new Date(n);if(!Number.isNaN(a.getTime()))i=a}if(!i)return;let s=t==="custom"&&typeof r==="string"&&q0e[r]===!0;return{at:i,lifecycle:s}}async function r5(e,t,r){if(t<=0)return;let n=K0e;for(;;){let o=Math.max(0,t-n),i;if(t<=ME)i=r;else if(o===0)try{i=await Bun.file(e).text()}catch{return}else try{i=await Bun.file(e).slice(o-1).text()}catch{return}let s=i.split(`
669
669
  `);if(o>0)s.shift();for(let a=s.length-1;a>=0;a--){let c=s[a].trim();if(!c.includes('"timestamp"'))continue;let l=V0e(c);if(l&&!l.lifecycle)return l.at}if(o===0||n>=e5)return;n=Math.min(n*4,e5)}}var o5=/User invoked the \\?"([^"\\]+)\\?" skill/,Cw="skill-prompt";function n5(e){if(typeof e==="string")return e;if(!Array.isArray(e))return"";return e.map((t)=>x(t)&&typeof t.text==="string"?t.text:"").join("")}function i5(e,t){let r=e.trim();if(!r)return"";let n=t?.trim();return n?`/skill:${r} ${n}`:`/skill:${r}`}function jg(e){if(e.type==="custom_message"&&e.customType===Cw){if(e.attribution!==void 0&&e.attribution!=="user")return;let r=x(e.details)?e.details:void 0,n=typeof r?.name==="string"?r.name:o5.exec(n5(e.content))?.[1];if(!n)return;let o=typeof r?.args==="string"?r.args:void 0;return i5(n,o)||void 0}if(e.type!=="message")return;let t=x(e.message)?e.message:void 0;if(!t||t.role!=="user")return;return n5(t.content).trim()||void 0}function s5(e){let t,r=e.indexOf('"role"');while(r!==-1){let o=Cr(e,"role",r),i=Cr(e,"content",r)??Cr(e,"text",r);if(i){if(o==="user")return i;if(!t&&(o==="developer"||o==="assistant"))t=i}r=e.indexOf('"role"',r+6)}let n=e.indexOf('"customType"');while(n!==-1){if(Cr(e,"customType",n)===Cw){let o=o5.exec(e.slice(n))?.[1];if(o)return i5(o)}n=e.indexOf('"customType"',n+12)}return t}var nu=256;async function a5(e){try{let{text:t,size:r,mtime:n,mtimeMs:o}=await t5(e,ME),i=await r5(e,r,t),s=Or(t),a=_6(t,s);if(!a)return;let c=0,l="",u;for(let d=1;d<s.length;d++){let f=s[d];if(f.type==="compaction"&&typeof f.shortSummary==="string")u=f.shortSummary;if(f.type==="message"&&f.message)c++;if(!l){let p=jg(f);if(p)l=p}}return l||=s5(t)??"",{path:e,id:a.id,cwd:a.cwd??"",title:a.title??u,parentSessionPath:a.parentSession,created:new Date(a.timestamp??""),modified:i??n,fileMtime:n,fileMtimeMs:o,messageCount:Math.max(c,Z6(t)),size:r,firstMessage:l||"(no messages)"}}catch{return}}var c5=3,G0e=2048;async function LE(e=jo()){try{await Bun.file(e).stat()}catch{return[]}if(!globalThis.__kabmoSessionFileListCache)globalThis.__kabmoSessionFileListCache=new Map;let t=globalThis.__kabmoSessionFileListCache,r=t.get(e);if(r){let s=!0;for(let a of await NE.promises.readdir(e,{withFileTypes:!0})){if(!a.isDirectory())continue;try{let c=await Bun.file(Ow.join(e,a.name)).stat();if(r.dirMtimes.get(a.name)!==c.mtimeMs){s=!1;break}}catch{s=!1;break}}if(s&&r.dirMtimes.size>0)return r.files}let n=[],o=new Map,i=[];try{i=await NE.promises.readdir(e,{withFileTypes:!0})}catch{}for(let s of i){if(!s.isDirectory())continue;let a=Ow.join(e,s.name);try{o.set(s.name,(await Bun.file(a).stat()).mtimeMs)}catch{continue}let c=[];try{c=await NE.promises.readdir(a,{withFileTypes:!0})}catch{continue}for(let l of c){if(!l.isFile()||!l.name.endsWith(".jsonl"))continue;n.push(Ow.join(a,l.name))}}return t.set(e,{dirMtimes:o,files:n}),globalThis.__kabmoSessionIdIndex?.delete(e),n}function z0e(){let e=globalThis.__kabmoSessionScanCache;if(e&&e.version===c5)return e.entries;let t={version:c5,entries:new Map};return globalThis.__kabmoSessionScanCache=t,t.entries}async function Hg(e){let t;try{t=await Bun.file(e).stat()}catch{return}let r=z0e(),n=r.get(e);if(n){let i=n;if(i.size===t.size&&i.fileMtimeMs===t.mtimeMs)return r.delete(e),r.set(e,i),i;r.delete(e)}let o=await a5(e);if(o){r.set(e,o);while(r.size>G0e){let i=r.keys().next().value;if(i===void 0)break;r.delete(i)}}return o}async function Y0e(e,t,r){let n=Array(e.length),o=0,i=Array(Math.min(t,e.length)).fill(null).map(async()=>{for(;;){let s=o++;if(s>=e.length)return;n[s]=await r(e[s])}});return await Promise.all(i),n}var J0e=32;async function DE(e=jo()){let t=await LE(e),r=await Y0e(t,J0e,(o)=>Hg(o)),n=[];for(let o of r)if(o)n.push(o);return n.sort((o,i)=>i.modified.getTime()-o.modified.getTime()),n}async function FE(e=jo()){let t=globalThis.__kabmoSessionIdIndex??=new Map,r=t.get(e);if(r)return r.entries;let n=new Map;for(let o of await DE(e))if(!n.has(o.id))n.set(o.id,o.path);return t.set(e,{entries:n}),n}function St(){globalThis.__kabmoSessionFileListCache?.clear(),globalThis.__kabmoSessionScanCache?.entries.clear(),globalThis.__kabmoSessionIdIndex?.clear()}async function ec(e){try{let r=(await Bun.file(e).slice(0,nu+4096).text()).split(`
@@ -2063,7 +2063,7 @@ ${o}
2063
2063
 
2064
2064
  ${n}`;if(i===n)return!1;return await Kt(e,i),cd(),!0}catch{return!1}}var $5e=Bun.env.SKILLS_API_URL||"https://skills.sh",K5e=15000,q5e=180000;async function s0(e,t=24){if(O())return[];let r=`${$5e}/api/search?q=${encodeURIComponent(e)}&limit=${Math.min(50,Math.max(1,t))}`;try{let n=await fetch(r,{signal:AbortSignal.timeout(K5e)});if(!n.ok)return[];return((await n.json()).skills??[]).filter((i)=>typeof i.id==="string"&&i.id.length>0).map((i)=>({package:i.id,name:typeof i.name==="string"?i.name:i.id,source:typeof i.source==="string"?i.source:"",installs:typeof i.installs==="number"?i.installs:0}))}catch{return[]}}function g1(e,t){return e.map((r)=>({id:`catalog-${r.package}`,sourceId:t,name:r.name,description:r.source?`From ${r.source}`:"",repoTag:r.package,githubUrl:r.source?`https://github.com/${r.source}`:void 0,instructions:r.package}))}async function JQ(e){let t=Bun.spawn({env:Ue(),cmd:["bunx","skills",...e],stdout:"pipe",stderr:"pipe",timeout:q5e,maxBuffer:4194304,windowsHide:!0}),[r,n]=await Promise.all([new Response(t.stdout).text(),new Response(t.stderr).text()]),o=await t.exited;if(o!==0)throw Error(n.trim()||`bunx skills ${e[0]} exited with code ${o}`);return r}async function h1(e,t){if(!/^[\w.\-]+\/[\w.\-@:]+$/.test(e))throw Error("Invalid skill package");if(O())throw Error("Skill install is unavailable in mock mode");let r=t?.trim();if(r&&!/^[\w.\-]+$/.test(r))throw Error("Invalid skill name");return{output:(await JQ(["add",e,"--agent","universal",...r?["--skill",r]:[],"-g","-y"])).slice(-4000)}}async function XQ(e){if(!/^[\w.\-@/]+$/.test(e))throw Error("Invalid skill name");if(O())throw Error("Skill uninstall is unavailable in mock mode");return{output:(await JQ(["remove",e,"-g","-y"])).slice(-4000)}}import Sa from"fs";import{tmpdir as V5e}from"os";import{dirname as ZO,join as mf,relative as ZQ,resolve as QQ,sep as QO}from"path";var G5e=120000,nl=60,b1=5242880,z5e=4,Y5e=524288;function ff(e){let t=e.trim().replace(/\/+$/,"");if(!t||/\s/.test(t))return null;if(/^(https?|ssh|file):\/\/\S+$/i.test(t)||/^git@[^:/\s]+:\S+$/.test(t))return{url:t,slug:J5e(t)};if(t.startsWith("/")||t.startsWith("~")||/^[a-z]:[\\/]/i.test(t))return{url:t,slug:t};let r=t.replace(/^github\.com\//i,"");if(/^[\w.-]+\/[\w.-]+$/.test(r))return{url:`https://github.com/${r}.git`,slug:r.replace(/\.git$/i,"")};return null}function J5e(e){let n=e.replace(/^[a-z]+:\/\//i,"").replace(/^git@[^:]+:/i,"").split("/").filter(Boolean).slice(-2).map((o)=>o.replace(/\.git$/i,""));if(n.length===2&&!n[0].includes(":"))return`${n[0]}/${n[1]}`;return Hu(e)||e}function _O(e,t){let r=ZQ(QQ(e),QQ(t));return r!==""&&!r.startsWith("..")&&!r.startsWith(QO)&&!r.startsWith("/")}var X5e={node_modules:!0,".git":!0,dist:!0,build:!0,out:!0,coverage:!0,vendor:!0,".next":!0,target:!0};async function Q5e(e,t){let r=ZO(t);if(!_O(e,r))return null;let n;try{n=await Sa.promises.stat(t)}catch{return null}if(!n.isFile()||n.size>Y5e)return null;let o;try{o=await Sa.promises.readFile(t,"utf8")}catch{return null}let{data:i}=jp(o),s=(i.name||r.split(QO).pop()||"").trim();if(!s)return null;let a=(i.description||"").replace(/\s+/g," ").trim();return{path:ZQ(e,r).split(QO).join("/"),name:s,description:a,loadable:a.length>0}}async function Z5e(e){let t=[],r=new Set,n=(a)=>{let c=ZO(a);if(r.has(c)||t.length>=nl*3)return;r.add(c),t.push(a)},o=async(a)=>{try{return await Sa.promises.readdir(a,{withFileTypes:!0})}catch{return[]}},i=await o(e);for(let a of i)if(a.isFile()&&a.name==="SKILL.md")n(mf(e,a.name));for(let a of["skills","plugins","agents"]){let c=mf(e,a);if(!await Sa.promises.stat(c).then((l)=>l.isDirectory()).catch(()=>!1))continue;for(let l of await o(c)){if(!l.isDirectory())continue;let u=mf(c,l.name,"SKILL.md");if(await Sa.promises.stat(u).then((d)=>d.isFile()).catch(()=>!1))n(u)}}let s=async(a,c)=>{if(c>z5e||t.length>=nl*3)return;for(let l of await o(a)){if(t.length>=nl*3)return;if(!l.isDirectory()||l.name.startsWith(".")||Object.hasOwn(X5e,l.name))continue;let u=mf(a,l.name),d=mf(u,"SKILL.md");if(await Sa.promises.stat(d).then((f)=>f.isFile()).catch(()=>!1))n(d);await s(u,c+1)}};return await s(e,1),t}async function y1(e){let t=await Z5e(e),r=[],n=new Set;for(let o of t){let i=await Q5e(e,o);if(!i)continue;let s=`${i.path}::${i.name}`;if(n.has(s))continue;if(n.add(s),r.push(i),r.length>=nl)break}return r.sort((o,i)=>Number(i.loadable)-Number(o.loadable))}async function eM(e,t){let r=Hu(e)||"repo",n=mf(t,`kabmo-skill-stage-${r}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);await Sa.promises.rm(n,{recursive:!0,force:!0}),await Sa.promises.mkdir(ZO(n),{recursive:!0});let o=await xt(["clone","--depth","1","--quiet",e,n],{timeoutMs:G5e}),i=async()=>{await Sa.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})};if(o.failed||o.exitCode!==0){await i();let s=ko(o.stderr);if(/could not read Username|authentication failed|Permission denied/i.test(o.stderr))throw Error(`${s||"git clone failed"} \u2014 the repository needs credentials Kabmo cannot supply`);throw Error(s||"git clone failed")}return{dir:n,cleanup:i}}async function _Q(e,t={}){let r=ff(e);if(!r)throw Error("Expected a git URL or an owner/repo pair");if(t.sourceDir){let i=await y1(t.sourceDir);return{repo:r.slug,skills:i,notes:[...i.length>=nl?[`Only the first ${nl} skills are listed.`]:[]]}}let n=t.stagingParent??V5e(),o=await eM(r.url,n);try{let i=await y1(o.dir),s=[];if(i.length===0)s.push("No SKILL.md found in this repository.");if(i.length>=nl)s.push(`Only the first ${nl} skills are listed.`);let a=i.filter((c)=>!c.loadable).length;if(a>0)s.push(`${a} SKILL.md file(s) have no description, so omp would not load them.`);return{repo:r.slug,skills:i,notes:s}}finally{await o.cleanup()}}import gf from"fs";import{tmpdir as _5e}from"os";import{join as tM}from"path";function e8e(e){let t=e.trim();if(!t)throw Error("A skill has no name");if(/[\\/]/.test(t)||t==="."||t==="..")throw Error(`Skill name refuses a path separator: ${t}`);return t}async function eZ(e){let t=0,r=await gf.promises.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let n of r){let o=tM(e,n.name);if(n.isDirectory())t+=await eZ(o);else if(n.isFile())t+=await gf.promises.stat(o).then((i)=>i.size).catch(()=>0);if(t>b1)return t}return t}async function tZ(e,t,r){let n=ff(e);if(!n)throw Error("Expected a git URL or an owner/repo pair");if(r.scope==="project"&&!r.projectDir)throw Error("A workspace root is required to install a project skill");let o=r.stagingParent??_5e(),i=r.sourceDir?{dir:r.sourceDir,cleanup:async()=>{}}:await eM(n.url,o),s=[],a=[],c=new Set(t);try{let l=(await y1(i.dir)).filter((f)=>c.has(f.path));if(l.length===0)throw Error("None of the selected skills are in that repository");let u=o0(r.projectDir??null),d=r.scope==="project"?u[1]:u[0];if(!d)throw Error("A workspace root is required to install a project skill");for(let f of l){let p=tM(i.dir,...f.path.split("/"));if(!_O(i.dir,p)){a.push({name:f.name,reason:"path is outside the repository"});continue}let h;try{h=e8e(f.name)}catch(w){a.push({name:f.name,reason:w instanceof Error?w.message:String(w)});continue}if(!f.loadable){a.push({name:f.name,reason:"SKILL.md has no description, so omp will not load it"});continue}let g=tM(d,h),y=await gf.promises.stat(g).then((w)=>w.isDirectory()).catch(()=>!1);if(y&&!r.overwrite){a.push({name:f.name,reason:"already installed \u2014 enable overwrite to replace it"});continue}let b=await eZ(p);if(b>b1){a.push({name:f.name,reason:`skill directory is ${Math.round(b/1024)} KB (limit ${b1/1024} KB)`});continue}if(y)await gf.promises.rm(g,{recursive:!0,force:!0});await gf.promises.mkdir(d,{recursive:!0}),await gf.promises.cp(p,g,{recursive:!0,force:!0}),s.push(f.name)}if(s.length>0)cd();return{installed:s,skipped:a}}finally{await i.cleanup()}}function t8e(e){return e instanceof Error?e.message:String(e)}async function rZ(e,t){let r=O(),{db:n,scope:o}=t,i=typeof e.type==="string"?e.type:"";if(i==="add_source"){let s=ff(typeof e.repo==="string"?e.repo:"");if(!s)return m({error:"Expected a git URL or an owner/repo pair"},{status:400});let a=await ad(n);if(a.some((u)=>u.repo===s.slug))return m({error:`${s.slug} is already a source`},{status:409});let c={id:`custom-${Date.now().toString(36)}`,name:typeof e.name==="string"&&e.name.trim()?e.name.trim():s.slug,repo:s.slug,skillCount:null,scannedAt:null,isCustom:!0},l=[...a,c];return await f1(n,l),m({success:!0,catalogSources:l,source:c})}if(i==="remove_source"){let s=typeof e.id==="string"?e.id:"";if(!s)return m({error:"id is required"},{status:400});let a=await ad(n),c=a.filter((l)=>l.id!==s);if(c.length===a.length)return m({error:"Source not found"},{status:404});return await f1(n,c),m({success:!0,catalogSources:c})}if(i==="search_catalog"){let s=typeof e.q==="string"?e.q.trim():"";if(!s)return m({query:s,catalogSkills:[]});if(r){let l=s.toLowerCase();return m({query:s,catalogSkills:n0.filter((u)=>`${u.name} ${u.description} ${u.repoTag}`.toLowerCase().includes(l))})}let a=new Set,c=g1(await s0(s,24),"skills-sh").filter((l)=>a.has(l.repoTag)?!1:(a.add(l.repoTag),!0));return m({query:s,catalogSkills:c})}if(i==="inspect_git_repo"||i==="scan_source"){if(r)return m({error:"Repository inspection is unavailable in mock mode"},{status:409});let s,a=[],c=null;if(i==="scan_source"){let p=typeof e.id==="string"?e.id:"";a=await ad(n);let h=a.find((g)=>g.id===p);if(!h)return m({error:"Source not found"},{status:404});s=h.repo,c=p}else s=typeof e.url==="string"?e.url:"";let l=await _Q(s),u=new Set((await t.listSkills(o)).map((p)=>p.name)),d=l.skills.map((p)=>({...p,installed:u.has(p.name)}));if(!c)return m({...l,skills:d});let f=a.map((p)=>p.id===c?{...p,skillCount:d.filter((h)=>h.loadable).length,scannedAt:Date.now()}:p);return await f1(n,f),m({...l,skills:d,sourceId:c,catalogSources:f})}if(i==="install_git_skills"){if(r)return m({error:"Skill install is unavailable in mock mode"},{status:409});let s=typeof e.url==="string"?e.url:"",a=Array.isArray(e.paths)?e.paths.filter((u)=>typeof u==="string"):[];if(a.length===0)return m({error:"Select at least one skill to install"},{status:400});if(e.mode==="registry"){let u=[],d=[];for(let f of a){let p=f.split("/").pop()??"";try{await h1(ff(s)?.slug??s.trim(),p),u.push(p)}catch(h){d.push({name:p,reason:t8e(h)})}}return await on(),m({repo:s,mode:"registry",installed:u,skipped:d,skills:await t.listSkills(o)})}let c=e.location==="project"?"project":"user";if(c==="project"&&!t.hasWorkspace)return m({error:"Select a workspace to install a project skill"},{status:400});let l=await tZ(s,a,{scope:c,projectDir:c==="project"?o.workspace:null,overwrite:e.overwrite===!0});if(l.installed.length>0)await on();return m({repo:s,mode:"managed_copy",...l,skills:await t.listSkills(o)})}return null}var r8e={"native:user":"User / omp agent","native:project":"Project / .omp/skills","agents:user":"User / .agents","agents:project":"Project / .agents","claude:user":"User / .claude","claude:project":"Project / .claude","codex:user":"User / .codex","codex:project":"Project / .codex","github:project":"Project / .github/skills","opencode:user":"User / opencode","opencode:project":"Project / .opencode"};async function n8e(e){let t=r8e[e.source]??e.source,r=e.filePath;if(e.managed){let n=await VQ(e.filePath);if(n)r=n.body}return{id:e.id,name:e.name,description:e.description,location:e.sourceRoot,locationLabel:t,instructions:r,project:"omp",filePath:e.filePath,source:e.source,managed:e.managed,hidden:e.hidden}}async function hf(e){let t=await i0(e.cwd,e.workspace);return Promise.all(t.map((r)=>n8e(r)))}function nZ(e){return e instanceof Error?e.message:String(e)}async function o8e({request:e}){let t=O();try{if(t){let f=await k();return m({skills:t0,catalogSources:await ad(f),catalogSkills:n0,root:null,isMock:!0})}let r=await k(),n=new URL(e.url),o=n.searchParams.get("sessionId");if(o){let f=Be(o);if(f?.isAlive()&&tr(f)!=="omp-rpc")return m({skills:[],catalogSources:[],catalogSkills:[],root:null,isMock:!1})}let i=await Bi(n.searchParams.get("root"),n.searchParams.get("scope")),s=await ad(r),[a,c,l]=await Promise.all([hf(i),s0("popular",18),s0("code review",8)]),u=new Set,d=g1([...c,...l],"skills-sh").filter((f)=>u.has(f.repoTag)?!1:(u.add(f.repoTag),!0));return m({skills:a,catalogSources:s,catalogSkills:d,root:i.workspace,isMock:!1})}catch(r){return m({error:nZ(r),skills:[],catalogSources:r0,catalogSkills:n0,root:null,isMock:t},{status:500})}}async function i8e({request:e,params:t}){let r=O();try{let n=await k(),o=new URL(e.url);if(e.method==="DELETE"){let c=await Bi(o.searchParams.get("root"),o.searchParams.get("scope")),l=o.searchParams.get("id");if(!l)return m({error:"id is required"},{status:400});if(r)return m({success:!0,skills:t0});if(!await zQ(l,c.workspace))return m({error:"Skill not found"},{status:404});return await on(),m({success:!0,skills:await hf(c)})}if(e.method!=="POST"&&e.method!=="PUT")return V({request:e,params:t});let i=await e.json(),s=await Bi(o.searchParams.get("root")??(typeof i.root==="string"?i.root:null),o.searchParams.get("scope")??(typeof i.scope==="string"?i.scope:null));if(i.type==="toggle_model_invocation"){if(r)return m({success:!1});let c=(await i0(s.cwd,s.workspace)).find((u)=>u.id===i.skillId);if(!c)return m({error:"Skill not found"},{status:404});let l=await YQ(c.filePath,i.disable===!0);if(l)await on();return m({success:l,skills:await hf(s)})}if(i.type==="reload"){if(r)return m({success:!0,reloaded:[]});let c=await on();return m({success:!0,reloaded:c})}let a=await rZ(i,{db:n,scope:s,hasWorkspace:Boolean(o.searchParams.get("root")??(typeof i.root==="string"?i.root:null))&&(o.searchParams.get("scope")??i.scope)!=="user",listSkills:async(c)=>hf(c)});if(a)return a;if(i.type==="install_toggle"){let{skill:c,install:l}=i;if(r)return m({success:!0,skills:t0});if(l){if(typeof c.repoTag==="string"&&/^[\w.\-]+\/[\w.\-@:]+$/.test(c.repoTag))await h1(c.repoTag,typeof c.name==="string"?c.name:null)}else if(typeof c.name==="string"&&c.name.trim())await XQ(c.name.trim());return await on(),m({success:!0,skills:await hf(s)})}if(i.skill){if(r)return m({success:!0,skills:t0});let c=i.skill,l=c.location==="project"?"project":"user",u=typeof c.id==="string"?(await i0(s.cwd,s.workspace)).find((d)=>d.id===c.id):void 0;if(u&&!u.managed)return m({error:`"${u.name}" is managed by ${u.source} and cannot be edited here`},{status:403});return await GQ({scope:l,projectDir:s.workspace,previousDir:u?.baseDir??null,name:c.name??"",description:c.description??"",hidden:c.hidden===!0,body:typeof c.instructions==="string"?c.instructions:""}),await on(),m({success:!0,skills:await hf(s)})}return m({error:"Unsupported skill action"},{status:400})}catch(n){return m({error:nZ(n)},{status:500})}}var oZ={"Cache-Control":"no-store"};async function s8e({request:e,params:t}){if(e.method!=="GET")return V({request:e,params:t});try{let r=new URL(e.url).searchParams.get("refresh")==="1";return m(await Rk({force:r}),{headers:oZ})}catch(r){return m({error:r instanceof Error?r.message:"Failed to load usage"},{status:500,headers:oZ})}}var a8e=30000,c8e=30000,l8e=8388608;function To(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Vt(e){return typeof e==="string"&&e.trim().length>0?e:void 0}function u8e(e){if(!x(e)||typeof e.id!=="string"||!e.id)return null;let t=Array.isArray(e.clears)?e.clears.filter((n)=>typeof n==="string"):void 0,r=Array.isArray(e.usedFractions)?e.usedFractions.filter((n)=>typeof n==="number"):void 0;return{id:e.id,...Vt(e.title)?{title:Vt(e.title)}:{},...Vt(e.program)?{program:Vt(e.program)}:{},...Vt(e.status)?{status:Vt(e.status)}:{},...To(e.remainingCount)!==void 0?{remainingCount:To(e.remainingCount)}:{},...typeof e.usable==="boolean"?{usable:e.usable}:{},...typeof e.requiresLimit==="boolean"?{requiresLimit:e.requiresLimit}:{},...t&&t.length>0?{clears:t}:{},...typeof e.blocking==="boolean"?{blocking:e.blocking}:{},...r&&r.length>0?{usedFractions:r}:{},...To(e.grantedAt)!==void 0?{grantedAt:To(e.grantedAt)}:{},...To(e.expiresAt)!==void 0?{expiresAt:To(e.expiresAt)}:{}}}function d8e(e){let t=x(e)?To(e.generatedAt)??Date.now():Date.now(),r=x(e)&&Array.isArray(e.accounts)?e.accounts:[],n=[];for(let o of r){if(!x(o))continue;let i=Vt(o.provider),s=Vt(o.credentialId);if(!i||!s)continue;let a=Array.isArray(o.credits)?o.credits.map(u8e).filter((c)=>c!==null):[];n.push({provider:i,credentialId:s,...Vt(o.email)?{email:Vt(o.email)}:{},...Vt(o.accountId)?{accountId:Vt(o.accountId)}:{},...Vt(o.orgId)?{orgId:Vt(o.orgId)}:{},...Vt(o.orgName)?{orgName:Vt(o.orgName)}:{},...To(o.availableCount)!==void 0?{availableCount:To(o.availableCount)}:{},...To(o.redeemableCount)!==void 0?{redeemableCount:To(o.redeemableCount)}:{},...Vt(o.nextCreditId)?{nextCreditId:Vt(o.nextCreditId)}:{},...To(o.soonestExpiry)!==void 0?{soonestExpiry:To(o.soonestExpiry)}:{},...Vt(o.unavailableReason)?{unavailableReason:Vt(o.unavailableReason)}:{},...Vt(o.error)?{error:Vt(o.error)}:{},credits:a})}return{generatedAt:t,accounts:n}}async function iZ(e,t){let r=Me();if(!r)return{ok:!1,stdout:"",stderr:"omp binary not found"};try{let n=Bun.spawn({env:Ue(),cmd:[r,"usage",...e],stdout:"pipe",stderr:"pipe",timeout:t,maxBuffer:l8e,windowsHide:!0}),[o,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{ok:await n.exited===0,stdout:o,stderr:i}}catch(n){return{ok:!1,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}function w1(e){return(e.trim().split(`
2065
2065
  `).map((n)=>n.trim()).find(Boolean)??"").replace(/^[^\w@/]*/,"").trim()}async function sZ(){if(O())return p8e();let e=await iZ(["reset","--json"],a8e);if(!e.ok)throw Error(w1(e.stderr)||w1(e.stdout)||"omp usage reset failed");try{return d8e(JSON.parse(e.stdout))}catch{throw Error("omp usage reset returned unexpected JSON")}}async function aZ(e){if(O())return{ok:!1,message:"Saved resets are unavailable in demo mode."};let t=await iZ(["reset",e],c8e),r=w1(t.ok?t.stdout:t.stderr)||w1(t.stdout);return{ok:t.ok,message:r||"omp usage reset produced no result"}}function p8e(){return{generatedAt:Date.now(),accounts:[{provider:"openai-codex",credentialId:"demo-codex-1",email:"demo@example.com",availableCount:2,redeemableCount:1,nextCreditId:"credit-demo-1",soonestExpiry:Date.now()+259200000,credits:[{id:"credit-demo-1",title:"Rate-limit reset",status:"available",remainingCount:1,usable:!0,clears:["openai-codex:5h"]}]},{provider:"anthropic",credentialId:"demo-claude-1",email:"demo@example.com",availableCount:1,redeemableCount:0,unavailableReason:"the provider did not identify a grant that can be safely spent",credits:[{id:"credit-demo-2",title:"Weekly limit reset",status:"available",remainingCount:1}]}]}}var a0={"Cache-Control":"no-store"};async function m8e({request:e,params:t}){if(e.method!=="GET")return V({request:e,params:t});try{return m(await sZ(),{headers:a0})}catch(r){return m({accounts:[],generatedAt:Date.now(),error:r instanceof Error?r.message:"Failed to list saved resets"},{headers:a0})}}async function f8e({request:e,params:t}){if(e.method!=="POST")return V({request:e,params:t});try{let r=await e.json(),n=typeof r.target==="string"?r.target.trim():"",o=n.split("/");if(o.length!==2||!o[0]||!o[1])return m({ok:!1,message:"A target must be `<provider>/<credential id>`, as the list reports it."},{status:400,headers:a0});return m(await aZ(n),{headers:a0})}catch(r){return m({ok:!1,message:r instanceof Error?r.message:"Failed to spend the saved reset"},{status:500,headers:a0})}}var cZ=[...G(V2,"/api/settings"),...G(J2,"/api/settings/agents"),...G(Z2,"/api/settings/behavior"),...G(nO,"/api/settings/commands"),...G(iO,"/api/settings/mcp"),...G(yO,"/api/settings/model-override"),...G(bO,"/api/settings/mcp-test"),...G(kO,"/api/settings/omp-config"),...G(OO,"/api/settings/projects"),...G(NO,"/api/settings/provider-entry"),...G(LO,"/api/provider-icon"),...G(BO,"/api/settings/provider-models"),...G(jO,"/api/settings/providers/refresh"),...G(HO,"/api/settings/provider-model"),...G(WO,"/api/settings/providers"),{method:"POST",path:"/api/settings/providers/logout",handler:yQ},...G(JO,"/api/settings/plugins"),...G(rM,"/api/settings/skills"),...G(nM,"/api/settings/usage"),...G(oM,"/api/settings/usage/reset")];function _n(e){return Math.round(e)}async function iM(e,t,r){if(typeof t!=="number")return{write:!0,diskMtimeMs:null};let n=await r(e);if(!n)return{write:!0,diskMtimeMs:null};let o=_n(n.mtimeMs);return{write:o===_n(t),diskMtimeMs:o}}function sM(e){if(typeof e!=="string"||e==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}async function yf(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t),(r)=>r.toString(16).padStart(2,"0")).join("")}import{homedir as g8e}from"os";import{dirname as h8e,isAbsolute as y8e,join as lZ,resolve as b8e}from"path";import uZ from"fs";import c0 from"path";async function dZ(e,t,r){let n=wm({path:t,size:r});if(n!=="text")return n;let o=await Bun.file(e).slice(0,gk).bytes();return wm({path:t,size:r,head:o})}var w8e=[".","node_modules","Library"];async function pZ({request:e}){let r=new URL(e.url).searchParams.get("path"),n=g8e(),o;if(r){let c=r.startsWith("~/")?lZ(n,r.slice(2)):r==="~"?n:r;if(!y8e(c))return m({error:"Path must be absolute",code:"not_absolute"},{status:400});o=b8e(c)}else o=n;let i=[];try{i=(await uZ.promises.readdir(o,{withFileTypes:!0})).filter((c)=>c.isDirectory()&&!w8e.some((l)=>c.name.startsWith(l))).map((c)=>c.name)}catch{return m({error:`Cannot read directory: ${o}`,code:"unreadable"},{status:400})}let s=i.map((c)=>({name:c,path:lZ(o,c)})).sort((c,l)=>c.name.localeCompare(l.name)),a=o===n?null:h8e(o);return m({path:o,parentPath:a===o?null:a,directories:s})}async function mZ({request:e}){let t=new URL(e.url),r=O(),n=await ge(t.searchParams.get("root"),await er(r)),o=t.searchParams.get("repo");if(o&&o!=="."){let a=Oe(n,o);if(!a)return m({error:"Invalid repo path"},{status:403});n=a}let i=t.searchParams.get("path")||".",s=Oe(n,i);if(!s)return m({error:"Invalid path"},{status:403});try{let a=await Kk(s,n);return m({files:a,isMock:r,root:n,path:i})}catch(a){return console.error(a),m({error:"Failed to read directory",isMock:r},{status:500})}}var aM=3000,S8e={node_modules:!0,".git":!0,dist:!0,build:!0,".next":!0,".cache":!0,coverage:!0};async function fZ(e,t,r){if(r.length>=aM)return;let n;try{n=await uZ.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let o of n){if(r.length>=aM)return;if(o.name.startsWith("."))continue;if(o.isDirectory()){if(S8e[o.name])continue;await fZ(c0.join(e,o.name),t,r);continue}if(!o.isFile())continue;let i=c0.relative(t,c0.join(e,o.name)).split(c0.sep).join("/");r.push({name:o.name,path:i})}}async function gZ({request:e}){let t=new URL(e.url),r=O(),n=await ge(t.searchParams.get("root"),await er(r));try{let o=[];return await fZ(n,n,o),o.sort((i,s)=>i.path.localeCompare(s.path)),m({files:o,root:n,truncated:o.length>=aM})}catch(o){return console.error(o),m({error:"Failed to list files"},{status:500})}}async function hZ({request:e}){let t=new URL(e.url),r=t.searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});let n=await ge(t.searchParams.get("root"),await er(O())),o=t.searchParams.get("repo");if(o&&o!=="."){let a=Oe(n,o);if(a)n=a}let i=r.replace(/^\/+/,""),s=Oe(n,i);if(!s)return m({error:"Invalid path"},{status:403});try{let a=Bun.file(s);if(!await a.exists())return m({error:"File not found"},{status:404});let c=await a.stat();if(c.isDirectory())return m({error:"Cannot read a directory"},{status:400});let l=await dZ(s,i,c.size);if(l==="image"||l==="document")return m({error:"This file is served by /api/fs/raw"},{status:400});if(l!=="text")return m({error:Lu(l,c.size,i),kind:l},{status:415});let u=await a.text();return m({content:u,mtimeMs:_n(c.mtimeMs),hash:await yf(u)})}catch(a){return go(a)}}async function yZ({request:e}){let r=new URL(e.url).searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});if(/^https?:\/\//i.test(r))return m({error:"Remote references are not supported"},{status:400});let n=await T8(r.replace(/^file:\/\//,""));if(!n)return m({error:"File not found"},{status:404});try{let o=Bun.file(n),i=await o.stat();if(i.isDirectory())return m({error:"Cannot read a directory"},{status:400});let s=await dZ(n,n,i.size);if(s==="image"||s==="document")return m({error:"This file is served by /api/fs/raw"},{status:400});if(s!=="text")return m({error:Lu(s,i.size,n),kind:s},{status:415});return m({content:await o.text(),name:c0.basename(n)})}catch(o){return go(o)}}function bZ(e){if(!/^file:\/\//i.test(e))return null;try{let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:[\\/]/.test(t)?t.slice(1):t}catch{return null}}import x8e from"fs";import wZ from"path";function cM(e){if(!/^file:\/\//i.test(e))return e;return bZ(e)}var k8e="That file is outside every workspace this console can read.";async function lM(e){let t=await E8(e);if(!t)return m({error:k8e,code:"outside_workspace"},{status:403});let r=wZ.resolve(t.root,t.path),n=await x8e.promises.stat(r).catch(()=>null);if(!n)return m({error:"File not found"},{status:404});if(n.isDirectory())return m({error:"That is a folder, not a file."},{status:400});let o=Bun.file(r),i=wm({path:t.path,size:n.size}),s=i==="text"?wm({path:t.path,size:n.size,head:await o.slice(0,gk).bytes()}):i;return m({root:t.root,path:t.path,name:wZ.basename(t.path),kind:s,size:n.size,...s==="binary"||s==="too-large"?{error:Lu(s,n.size,t.path)}:{}})}async function SZ({request:e}){let r=new URL(e.url).searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});let n=cM(r);if(!n)return m({error:"Malformed file URL"},{status:400});return lM(n)}async function xZ({request:e}){let t=new URL(e.url),r=t.searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});let n=await ge(t.searchParams.get("root"),await er(O())),o=t.searchParams.get("repo");if(o&&o!=="."){let c=Oe(n,o);if(c)n=c}let i=Oe(n,r.replace(/^\/+/,""));if(!i)return m({error:"Invalid path"},{status:403});let s=await Bun.file(i).stat().catch(()=>null),a=s!==null&&!s.isDirectory();return m({exists:a,mtimeMs:a?_n(s.mtimeMs):null})}var v8e=64,bf=new Map;function A8e(e,t){bf.delete(e),bf.set(e,t);while(bf.size>v8e){let r=bf.keys().next().value;if(r===void 0)break;bf.delete(r)}}async function kZ({request:e}){let t=new URL(e.url),r=t.searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});let n=await ge(t.searchParams.get("root"),await er(O())),o=t.searchParams.get("repo");if(o&&o!=="."){let c=Oe(n,o);if(c)n=c}let i=Oe(n,r.replace(/^\/+/,""));if(!i)return m({error:"Invalid path"},{status:403});let s=await Bun.file(i).stat().catch(()=>null);if(!s||s.isDirectory())return m({exists:!1,mtimeMs:null,hash:null});if(s.size>mk)return m({exists:!0,mtimeMs:_n(s.mtimeMs),hash:null});let a=bf.get(i);if(a&&a.mtimeMs===s.mtimeMs&&a.size===s.size)return m({exists:!0,mtimeMs:_n(s.mtimeMs),hash:a.hash});try{let c=await yf(await Bun.file(i).text());return A8e(i,{mtimeMs:s.mtimeMs,size:s.size,hash:c}),m({exists:!0,mtimeMs:_n(s.mtimeMs),hash:c})}catch{return m({exists:!0,mtimeMs:_n(s.mtimeMs),hash:null})}}async function vZ({request:e}){let t=new URL(e.url),r=t.searchParams.get("path");if(!r)return m({error:"Missing path"},{status:400});let n=await ge(t.searchParams.get("root"),await er(O())),o=t.searchParams.get("repo");if(o&&o!=="."){let a=Oe(n,o);if(a)n=a}let i=r.replace(/^\/+/,""),s=Oe(n,i);if(!s)return m({error:"Invalid path"},{status:403});try{let a=Bun.file(s);if(!await a.exists())return m({error:"File not found"},{status:404});let c=await a.stat();if(c.isDirectory())return m({error:"Cannot read a directory"},{status:400});let l=fk[Nu(i)];if(l!==void 0&&c.size>l)return m({error:Lu("too-large",c.size,i),kind:"too-large"},{status:415});return new Response(a.stream(),{headers:{"content-type":EW(i)??"application/octet-stream","content-length":String(c.size),"content-disposition":`inline; filename="${T8e(i)}"`,"cache-control":"no-store"}})}catch(a){return go(a)}}function T8e(e){return(e.split("/").pop()??"file").replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file"}import sl from"fs";import xa from"path";import E8e from"path";var AZ=5000,R8e={darwin:["open"],win32:["explorer"],linux:["xdg-open","gio"]},P8e=["xdg-open"];async function S1(e){let t=E8e.resolve(e),r=await Bun.file(t).stat().catch(()=>null);if(!r)return{ok:!1,error:`Directory does not exist: ${t}`};if(!r.isDirectory())return{ok:!1,error:`Not a directory: ${t}`};let n=R8e[process.platform]??P8e,o=n.find((c)=>Bun.which(c)!==null);if(!o)return{ok:!1,error:`No file manager opener on PATH (tried ${n.join(", ")})`};let i;try{i=Bun.spawn({env:Ue(),cmd:[o,t],stdin:"ignore",stdout:"ignore",stderr:"pipe",detached:!0,timeout:AZ})}catch(c){return{ok:!1,error:c instanceof Error?c.message:String(c)}}let s=(await new Response(i.stderr).text()).trim(),a=await i.exited;if(process.platform==="win32"&&!i.killed)return{ok:!0,opener:o};if(i.killed&&i.signalCode==="SIGTERM")return{ok:!1,error:`${o} did not return within ${AZ}ms`};if(a!==0)return{ok:!1,error:s||`${o} exited with code ${a}`};return{ok:!0,opener:o}}import wf from"fs";import Qo from"path";function TZ(e,t){if(e.path===""||e.path===".")return"The workspace root cannot be moved or copied";if(e.kind==="folder"&&(t===e.path||t.startsWith(`${e.path}/`)))return"Cannot paste a folder into itself";return null}function uM(e,t){if(!t(e))return e;let r=e.lastIndexOf("."),n=r>0?e.slice(0,r):e,o=r>0?e.slice(r):"",i=`${n} copy${o}`;if(!t(i))return i;for(let s=2;s<1000;s+=1){let a=`${n} copy ${s}${o}`;if(!t(a))return a}return`${n} copy ${Date.now()}${o}`}function EZ(e,t,r){if(t==="file")return uM(e,r);if(!r(`${e} copy`))return`${e} copy`;for(let n=2;n<1000;n+=1){let o=`${e} copy ${n}`;if(!r(o))return o}return`${e} copy ${Date.now()}`}function ol(e,t){return Qo.relative(e,t).split(Qo.sep).join("/")}async function RZ(e){try{return new Set(await wf.promises.readdir(e))}catch{return new Set}}async function dM(e,t){await wf.promises.cp(e,t,{recursive:!0,errorOnExist:!0,force:!1})}async function I8e(e,t){try{await wf.promises.rename(e,t);return}catch(r){if(r.code!=="EXDEV")throw r}await dM(e,t),await wf.promises.rm(e,{recursive:!0,force:!0})}async function PZ(e){let{scopedRoot:t,sourcePath:r,destinationDir:n,mode:o}=e,i=Qo.dirname(r),s=await RZ(n);if(o==="cut"&&i===n)s.delete(Qo.basename(r));let a=uM(Qo.basename(r),(f)=>s.has(f)),c=Qo.join(n,a);if(o==="cut"&&c===r)return{error:"Already in this folder",status:409};let l=await wf.promises.realpath(r).catch(()=>r),u=await wf.promises.realpath(n).catch(()=>n),d=Qo.join(u,a);if(d===l||d.startsWith(l+Qo.sep))return{error:"Cannot paste an entry into itself",status:409};if(o==="cut")await I8e(r,c);else await dM(r,c);return{path:ol(t,c)}}async function IZ(e){let{scopedRoot:t,sourcePath:r,destinationName:n}=e,o=Qo.dirname(r),i=Qo.join(o,n);return await dM(r,i),{path:ol(t,i)}}async function CZ(e,t){let r=await RZ(Qo.dirname(e));return EZ(Qo.basename(e),t,(n)=>r.has(n))}import M8e from"fs";import ld from"path";import O8e from"fs";var x1=[{id:"zip",label:"ZIP",extension:"zip"},{id:"7z",label:"7Z",extension:"7z"},{id:"rar",label:"RAR",extension:"rar"},{id:"tar",label:"TAR",extension:"tar"},{id:"tar.gz",label:"TAR.GZ",extension:"tar.gz"}],C8e=[[".tar.gz","tar.gz"],[".tar.bz2","tar.bz2"],[".tar.xz","tar.xz"],[".tgz","tar.gz"],[".tbz2","tar.bz2"],[".txz","tar.xz"],[".tar","tar"],[".zip","zip"],[".7z","7z"],[".rar","rar"],[".gz","gz"],[".bz2","bz2"],[".xz","xz"]];function OZ(e){let t=e.toLowerCase();for(let[r,n]of C8e)if(t.endsWith(r))return n;return null}var Zo={zip:["zip"],unzip:["unzip"],sevenZip:["7z","7zz","7za"],rar:["rar"],unrar:["unrar"],tar:["tar"],bsdtar:["bsdtar"],gzip:["gzip"],bzip2:["bzip2"],xz:["xz"]};function _o(e){for(let t of e)if(Bun.which(t))return t;return null}function MZ(){return x1.map((e)=>{let t=NZ(e.id);return{...e,available:t!==null,tool:t??LZ(e.id)}})}function NZ(e){switch(e){case"zip":return _o(Zo.zip);case"7z":return _o(Zo.sevenZip);case"rar":return _o(Zo.rar);case"tar":case"tar.gz":return _o(Zo.tar)}}function LZ(e){switch(e){case"zip":return"zip";case"7z":return"7z";case"rar":return"rar";case"tar":case"tar.gz":return"tar"}}function il(e){return`'${e.replaceAll("'","'\\''")}'`}function DZ(e,t){let r=(e.stderr.trim()||e.stdout.trim()).split(`
2066
- `)[0]?.trim();return r?r.slice(0,300):t}async function FZ(e){let{destinationDir:t,name:r,format:n,sources:o}=e,i=NZ(n);if(!i)return{ok:!1,status:501,error:`${LZ(n)} is not installed on this machine`};if(o.length===0)return{ok:!1,status:400,error:"Nothing to compress"};let s=ld.join(t,r);if(await Bun.file(s).exists())return{ok:!1,status:409,error:`${r} already exists`};let a=[];for(let d of o){let f=ld.relative(t,d).split(ld.sep).join("/");if(f===""||f.startsWith("../")||ld.isAbsolute(f))return{ok:!1,status:400,error:"Compress into a folder that contains every selected item"};a.push(f)}let c=a.map((d)=>`./${d}`).join(" "),l=(()=>{switch(n){case"zip":return`${i} -r -q ${il(r)} ${c}`;case"7z":return`${i} a -y -- ${il(r)} ${c}`;case"rar":return`${i} a -r -ep1 ${il(r)} ${c}`;case"tar":return`${i} -cf ${il(r)} ${c}`;case"tar.gz":return`${i} -czf ${il(r)} ${c}`}})(),u=await Pt(l,{cwd:t,timeout:120000});if(!Di(u))return{ok:!1,status:500,error:DZ(u,`Could not write ${r}`)};return{ok:!0,path:s}}async function UZ(e){let{archivePath:t,destinationDir:r}=e,n=OZ(ld.basename(t));if(!n)return{ok:!1,status:400,error:"That file is not a recognised archive"};let o=await Bun.file(t).stat().catch(()=>null);if(!o||o.isDirectory())return{ok:!1,status:404,error:"That archive no longer exists"};await O8e.promises.mkdir(r,{recursive:!0});let i=il(t),s=il(r),a=(f)=>Pt(f,{timeout:300000}),c=i,l=s,u=_o(Zo.sevenZip),d=_o(Zo.bsdtar);switch(n){case"zip":{let f=_o(Zo.unzip);if(f)return Hi(await a(`${f} -o -q ${c} -d ${l}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("unzip")}case"7z":{if(u)return Hi(await a(`${u} x -y -o${l} ${c}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("7z")}case"rar":{let f=_o(Zo.unrar);if(f)return Hi(await a(`${f} x -o+ ${c} ${l}`),t);if(u)return Hi(await a(`${u} x -y -o${l} ${c}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("unrar or 7z")}case"tar":case"tar.gz":case"tar.bz2":case"tar.xz":{let f=_o(Zo.tar);if(f)return Hi(await a(`${f} -xf ${c} -C ${l}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("tar")}case"gz":case"bz2":case"xz":{let f=n==="gz"?_o(Zo.gzip):n==="bz2"?_o(Zo.bzip2):_o(Zo.xz),p=ld.basename(t).replace(/\.(gz|bz2|xz)$/i,""),h=il(ld.join(r,p));if(f)return Hi(await a(`${f} -dc ${c} > ${h}`),p);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0(n)}}}function Hi(e,t){if(Di(e))return{ok:!0,path:t};return{ok:!1,status:500,error:DZ(e,"The archive could not be extracted")}}function l0(e){return{ok:!1,status:501,error:`No tool available to extract this archive (install ${e})`}}async function BZ(e){let{formData:t,scopedRoot:r}=e,n;try{n=JSON.parse(t.get("paths")??"[]")}catch{return m({error:"Invalid delete list"},{status:400})}if(!Array.isArray(n)||n.length===0||n.some((s)=>typeof s!=="string"))return m({error:"Invalid delete list"},{status:400});let o=[];for(let s of n){let a=Oe(r,s);if(!a)return m({error:"Invalid path"},{status:403});o.push({rel:s,full:a})}let i=[];for(let s of o)await M8e.promises.rm(s.full,{recursive:!0,force:!0}),i.push(s.rel);return m({success:!0,removed:i})}async function jZ(e){let{actionType:t,formData:r,scopedRoot:n}=e;if(t==="extract"){let f=(r.get("path")??"").trim(),p=Oe(n,f);if(!p)return m({error:"Invalid path"},{status:403});let h=(r.get("destination")??"").trim()||".",g=Oe(n,h);if(!g)return m({error:"Invalid destination"},{status:403});let y=await UZ({archivePath:p,destinationDir:g});if(!y.ok)return m({error:y.error},{status:y.status});return m({success:!0,path:ol(n,g)})}let o=r.get("format")??"zip",i=x1.find((f)=>f.id===o)?.id;if(!i)return m({error:"Unknown archive format"},{status:400});let s=(r.get("name")??"").trim();if(!fr(s))return m({error:"Enter an archive name without a path separator"},{status:400});let a=(r.get("destination")??"").trim()||".",c=Oe(n,a);if(!c)return m({error:"Invalid destination"},{status:403});let l;try{l=JSON.parse(r.get("paths")??"[]")}catch{return m({error:"Invalid selection"},{status:400})}if(!Array.isArray(l)||l.length===0||l.some((f)=>typeof f!=="string"))return m({error:"Select something to compress"},{status:400});let u=[];for(let f of l){let p=Oe(n,f);if(!p)return m({error:"Invalid path"},{status:403});u.push(p)}let d=await FZ({destinationDir:c,name:s,format:i,sources:u});if(!d.ok)return m({error:d.error},{status:d.status});return m({success:!0,path:ol(n,d.path)})}function u0(e){let t=e.trim().replace(/\\/g,"/");if(!t||t.includes("\x00"))return null;if(t.startsWith("/")||/^[a-zA-Z]:/.test(t))return null;let r=[];for(let n of t.split("/")){if(n===""||n===".")continue;if(n==="..")return null;r.push(n)}return r.length>0?r.join("/"):null}function N8e(e){return e.includes("\r")?e.replace(/\r\n?/g,`
2066
+ `)[0]?.trim();return r?r.slice(0,300):t}async function FZ(e){let{destinationDir:t,name:r,format:n,sources:o}=e;if(o.length===0)return{ok:!1,status:400,error:"Nothing to compress"};let i=ld.join(t,r);if(await Bun.file(i).exists())return{ok:!1,status:409,error:`${r} already exists`};let s=[];for(let d of o){let f=ld.relative(t,d).split(ld.sep).join("/");if(f===""||f.startsWith("../")||ld.isAbsolute(f))return{ok:!1,status:400,error:"Compress into a folder that contains every selected item"};s.push(f)}let a=NZ(n);if(!a)return{ok:!1,status:501,error:`${LZ(n)} is not installed on this machine`};let c=s.map((d)=>`./${d}`).join(" "),l=(()=>{switch(n){case"zip":return`${a} -r -q ${il(r)} ${c}`;case"7z":return`${a} a -y -- ${il(r)} ${c}`;case"rar":return`${a} a -r -ep1 ${il(r)} ${c}`;case"tar":return`${a} -cf ${il(r)} ${c}`;case"tar.gz":return`${a} -czf ${il(r)} ${c}`}})(),u=await Pt(l,{cwd:t,timeout:120000});if(!Di(u))return{ok:!1,status:500,error:DZ(u,`Could not write ${r}`)};return{ok:!0,path:i}}async function UZ(e){let{archivePath:t,destinationDir:r}=e,n=OZ(ld.basename(t));if(!n)return{ok:!1,status:400,error:"That file is not a recognised archive"};let o=await Bun.file(t).stat().catch(()=>null);if(!o||o.isDirectory())return{ok:!1,status:404,error:"That archive no longer exists"};await O8e.promises.mkdir(r,{recursive:!0});let i=il(t),s=il(r),a=(f)=>Pt(f,{timeout:300000}),c=i,l=s,u=_o(Zo.sevenZip),d=_o(Zo.bsdtar);switch(n){case"zip":{let f=_o(Zo.unzip);if(f)return Hi(await a(`${f} -o -q ${c} -d ${l}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("unzip")}case"7z":{if(u)return Hi(await a(`${u} x -y -o${l} ${c}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("7z")}case"rar":{let f=_o(Zo.unrar);if(f)return Hi(await a(`${f} x -o+ ${c} ${l}`),t);if(u)return Hi(await a(`${u} x -y -o${l} ${c}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("unrar or 7z")}case"tar":case"tar.gz":case"tar.bz2":case"tar.xz":{let f=_o(Zo.tar),p=n==="tar.gz"?"z":n==="tar.bz2"?"j":n==="tar.xz"?"J":"";if(f)return Hi(await a(`${f} -x${p}f - -C ${l} < ${c}`),t);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0("tar")}case"gz":case"bz2":case"xz":{let f=n==="gz"?_o(Zo.gzip):n==="bz2"?_o(Zo.bzip2):_o(Zo.xz),p=ld.basename(t).replace(/\.(gz|bz2|xz)$/i,""),h=il(ld.join(r,p));if(f)return Hi(await a(`${f} -dc ${c} > ${h}`),p);if(d)return Hi(await a(`${d} -xf ${c} -C ${l}`),t);return l0(n)}}}function Hi(e,t){if(Di(e))return{ok:!0,path:t};return{ok:!1,status:500,error:DZ(e,"The archive could not be extracted")}}function l0(e){return{ok:!1,status:501,error:`No tool available to extract this archive (install ${e})`}}async function BZ(e){let{formData:t,scopedRoot:r}=e,n;try{n=JSON.parse(t.get("paths")??"[]")}catch{return m({error:"Invalid delete list"},{status:400})}if(!Array.isArray(n)||n.length===0||n.some((s)=>typeof s!=="string"))return m({error:"Invalid delete list"},{status:400});let o=[];for(let s of n){let a=Oe(r,s);if(!a)return m({error:"Invalid path"},{status:403});o.push({rel:s,full:a})}let i=[];for(let s of o)await M8e.promises.rm(s.full,{recursive:!0,force:!0}),i.push(s.rel);return m({success:!0,removed:i})}async function jZ(e){let{actionType:t,formData:r,scopedRoot:n}=e;if(t==="extract"){let f=(r.get("path")??"").trim(),p=Oe(n,f);if(!p)return m({error:"Invalid path"},{status:403});let h=(r.get("destination")??"").trim()||".",g=Oe(n,h);if(!g)return m({error:"Invalid destination"},{status:403});let y=await UZ({archivePath:p,destinationDir:g});if(!y.ok)return m({error:y.error},{status:y.status});return m({success:!0,path:ol(n,g)})}let o=r.get("format")??"zip",i=x1.find((f)=>f.id===o)?.id;if(!i)return m({error:"Unknown archive format"},{status:400});let s=(r.get("name")??"").trim();if(!fr(s))return m({error:"Enter an archive name without a path separator"},{status:400});let a=(r.get("destination")??"").trim()||".",c=Oe(n,a);if(!c)return m({error:"Invalid destination"},{status:403});let l;try{l=JSON.parse(r.get("paths")??"[]")}catch{return m({error:"Invalid selection"},{status:400})}if(!Array.isArray(l)||l.length===0||l.some((f)=>typeof f!=="string"))return m({error:"Select something to compress"},{status:400});let u=[];for(let f of l){let p=Oe(n,f);if(!p)return m({error:"Invalid path"},{status:403});u.push(p)}let d=await FZ({destinationDir:c,name:s,format:i,sources:u});if(!d.ok)return m({error:d.error},{status:d.status});return m({success:!0,path:ol(n,d.path)})}function u0(e){let t=e.trim().replace(/\\/g,"/");if(!t||t.includes("\x00"))return null;if(t.startsWith("/")||/^[a-zA-Z]:/.test(t))return null;let r=[];for(let n of t.split("/")){if(n===""||n===".")continue;if(n==="..")return null;r.push(n)}return r.length>0?r.join("/"):null}function N8e(e){return e.includes("\r")?e.replace(/\r\n?/g,`
2067
2067
  `):e}function pM(e,t){let r=N8e(e);return t==="crlf"?r.replace(/\n/g,`\r
2068
2068
  `):r}function L8e(e){if(e.error)return m({error:e.error},{status:e.status??400});return m({success:!0,path:e.path})}async function D8e(e){let{filePath:t,scopedRoot:r}=e,n=Oe(r,t);if(!n)return m({error:"Invalid path"},{status:403});let o=(await Bun.file(n).stat().catch(()=>null))?.isDirectory()?"folder":"file",i=await CZ(n,o);return L8e(await IZ({scopedRoot:r,sourcePath:n,destinationName:i}))}async function F8e(e){let{formData:t,scopedRoot:r}=e,n=t.get("mode")==="cut"?"cut":"copy",o=t.getAll("sourcePath").map((f)=>String(f).trim()).filter(Boolean);if(o.length===0)return m({error:"Nothing to paste"},{status:400});let i=(t.get("targetPath")??"").trim()||".",a=(t.get("targetKind")==="folder"?"folder":"file")==="folder"?i:xa.dirname(i),c=Oe(r,a);if(!c)return m({error:"Invalid path"},{status:403});let l=[],u=[];for(let f of o){let p=Oe(r,f);if(!p)return m({error:"Invalid path"},{status:403});let h=await Bun.file(p).stat().catch(()=>null);if(!h){u.push({path:f,error:"The entry on the clipboard no longer exists"});continue}let g=TZ({path:f,kind:h.isDirectory()?"folder":"file"},a);if(g)return m({error:g},{status:409});l.push({rel:f,full:p})}let d=[];for(let f of l){let p=await PZ({scopedRoot:r,sourcePath:f.full,destinationDir:c,mode:n});if(p.error)u.push({path:f.rel,error:p.error});else if(p.path)d.push(p.path)}if(d.length===0&&u.length>0){let f=u.every((p)=>p.error.includes("no longer exists"));return m({error:u[0].error},{status:f?404:400})}if(o.length===1)return m({success:!0,path:d[0]});return m(u.length>0?{success:!0,paths:d,failures:u}:{success:!0,paths:d})}async function U8e({request:e}){let t=await e.formData(),r=t.get("actionType"),n=t.get("path"),o=await ge(t.get("root"),await er(O())),i=t.get("repo")||".",s=i==="."?o:Oe(o,i);if(!s)return m({error:"Invalid repo path"},{status:403});try{if(r==="duplicate")return await D8e({filePath:n,scopedRoot:s});if(r==="paste")return await F8e({formData:t,scopedRoot:s});if(r==="extract"||r==="compress")return await jZ({actionType:r,formData:t,scopedRoot:s});if(r==="delete"&&typeof t.get("paths")==="string")return await BZ({formData:t,scopedRoot:s});let a=Oe(s,n);if(!a)return m({error:"Invalid path"},{status:403});if(r==="save"){let c=t.get("content")??"",l=t.get("eol"),u=l==="crlf"||l==="lf"?pM(c,l):c,d=await iM(a,sM(t.get("baseMtime")),async(p)=>{let h=await Bun.file(p).stat().catch(()=>null);return h&&!h.isDirectory()?{mtimeMs:h.mtimeMs}:null});if(!d.write)return m({error:"This file changed on disk since it was opened.",conflict:!0,mtimeMs:d.diskMtimeMs},{status:409});await sl.promises.mkdir(xa.dirname(a),{recursive:!0}),await Bun.write(a,u);let f=await Bun.file(a).stat().catch(()=>null);return m({success:!0,mtimeMs:f?_n(f.mtimeMs):null,hash:await yf(u)})}else if(r==="saveBytes"){let c=t.get("bytes");if(!(c instanceof Blob))return m({error:"No file bytes"},{status:400});if(c.size>ym)return m({error:"The edited file is larger than the editor writes."},{status:413});let l=await iM(a,sM(t.get("baseMtime")),async(d)=>{let f=await Bun.file(d).stat().catch(()=>null);return f&&!f.isDirectory()?{mtimeMs:f.mtimeMs}:null});if(!l.write)return m({error:"This file changed on disk since it was opened.",conflict:!0,mtimeMs:l.diskMtimeMs},{status:409});await sl.promises.mkdir(xa.dirname(a),{recursive:!0}),await Bun.write(a,c);let u=await Bun.file(a).stat().catch(()=>null);return m({success:!0,mtimeMs:u?_n(u.mtimeMs):null,hash:null})}else if(r==="saveAs"){let c=t.get("path")??"",l=(t.get("name")??"").trim();if(!fr(l))return m({error:"Enter a file name without a path separator"},{status:400});let u=Oe(s,xa.join(c||".",l));if(!u)return m({error:"Invalid path"},{status:403});if(await Bun.file(u).stat().catch(()=>null)!==null)return m({error:`${l} already exists`},{status:409});let d=t.get("content")??"",f=t.get("eol"),p=f==="crlf"||f==="lf"?pM(d,f):d;return await sl.promises.mkdir(xa.dirname(u),{recursive:!0}),await Bun.write(u,p),m({success:!0,path:ol(s,u)})}else if(r==="create"){let c=t.get("kind")==="folder"?"folder":"file",l=u0(t.get("name")??"");if(!l)return m({error:"Enter a name without .. or a leading slash"},{status:400});let u=Oe(s,xa.join(n||".",l));if(!u)return m({error:"Invalid path"},{status:403});if(await Bun.file(u).stat().catch(()=>null)!==null)return m({error:`${l} already exists`},{status:409});if(c==="folder")await sl.promises.mkdir(u,{recursive:!0});else await sl.promises.mkdir(xa.dirname(u),{recursive:!0}),await Bun.write(u,"");return m({success:!0,kind:c,path:ol(s,u)})}else if(r==="delete")return await sl.promises.rm(a,{recursive:!0,force:!0}),m({success:!0});else if(r==="rename"){let c=u0(t.get("newPath")??"");if(!c)return m({error:"Enter a name without .. or a leading slash"},{status:400});let l=Oe(s,c);if(!l)return m({error:"Invalid new path"},{status:403});if(l===a)return m({success:!0,path:c,previousPath:n});let u=await Bun.file(a).stat().catch(()=>null);if(!u)return m({error:"That entry no longer exists"},{status:404});if(u.isDirectory()&&Ei(a,l))return m({error:"A folder cannot be moved inside itself"},{status:400});if(await Bun.file(l).stat().catch(()=>null)!==null)return m({error:`${c} already exists`},{status:409});return await sl.promises.mkdir(xa.dirname(l),{recursive:!0}),await sl.promises.rename(a,l),m({success:!0,path:c,previousPath:n})}else if(r==="open_explorer"){let c=(await Bun.file(a).stat().catch(()=>null))?.isDirectory()??!1,l=await S1(c?a:xa.dirname(a));return l.ok?m({success:!0}):m({error:l.error},{status:500})}else if(r==="git_history"){let c=s,l=await Pt(`git log -n 50 --date-order --pretty=format:"|~|%h|~|%an|~|%ar|~|%s" -- "${n}"`,{cwd:c,maxBuffer:1048576});if(l.exitCode!==0&&l.stderr.includes("not a git repository"))return m({error:"Not a git repository"},{status:200});let u=l.stdout.split(`
2069
2069
  `).filter(Boolean).map((d)=>{let f=d.split("|~|");if(f.length===1)return{graph:"",message:f[0]};return{graph:f[0],hash:f[1],author:f[2],time:f[3],message:f[4]}});return m({success:!0,type:"history",data:u})}return m({error:"Unknown action"},{status:400})}catch(a){return go(a)}}async function B8e(){return m({formats:MZ()})}import T1 from"path";var Sf=50;import WZ from"path";function HZ(e){let t={branch:"",detached:!1,hasCommits:!0,upstream:"",ahead:0,behind:0,gone:!1,changed:0,untracked:0,conflicts:0},r="",n=!1,o=e.split("\x00");for(let i=0;i<o.length;i+=1){let s=o[i];if(!s)continue;if(s.startsWith("# ")){let[c,...l]=s.slice(2).split(" "),u=l.join(" ");if(c==="branch.oid")r=u;else if(c==="branch.head")if(u==="(detached)")t.detached=!0;else t.branch=u;else if(c==="branch.upstream")t.upstream=u;else if(c==="branch.ab"){n=!0;let d=/\+(\d+)/.exec(u),f=/-(\d+)/.exec(u);t.ahead=d?Number(d[1]):0,t.behind=f?Number(f[1]):0}continue}let a=s[0];if(a==="1"){t.changed+=1;continue}if(a==="2"){t.changed+=1,i+=1;continue}if(a==="u"){t.conflicts+=1;continue}if(a==="?"){t.untracked+=1;continue}}if(t.detached)t.branch=r.slice(0,7);return t.hasCommits=r!==""&&r!=="(initial)",t.gone=t.upstream!==""&&!n,t}import{existsSync as j8e}from"fs";var H8e=8;async function W8e(e,t){let r={path:t,isRepo:!1,branch:"",detached:!1,changed:0,untracked:0,ahead:0,behind:0,upstream:"",gone:!1,operation:null,conflicts:0,subject:"",date:""},n=t==="."?e:WZ.resolve(e,t);if(!Ei(e,n))return{...r,error:"Invalid repo path"};let o=await ne(["status","--porcelain=v2","--branch","-z","-uall"],{cwd:n,timeout:15000,maxBuffer:8388608});if(o.exitCode!==0)return{...r,error:o.stderr.trim()||"Not a git repository"};let i=HZ(o.stdout),s={...r,isRepo:!0,branch:i.branch,detached:i.detached,changed:i.changed,untracked:i.untracked,ahead:i.ahead,behind:i.behind,upstream:i.upstream,gone:i.gone,conflicts:i.conflicts},[a,c]=await Promise.all([i.hasCommits?$8e(n):Promise.resolve({subject:"",date:""}),K8e(n,i.conflicts)]);return{...s,...a,operation:c}}async function $8e(e){let t=await ne(["log","-1","--format=%s%x00%cr"],{cwd:e,timeout:8000});if(t.exitCode!==0)return{subject:"",date:""};let[r,n]=t.stdout.split("\x00");return{subject:(r??"").trim(),date:(n??"").trim()}}async function K8e(e,t){let r=await ne(["rev-parse","--absolute-git-dir"],{cwd:e,timeout:8000});if(r.exitCode!==0)return null;let n=r.stdout.trim();if(!n)return null;for(let{name:o,operation:i}of eC)if(j8e(WZ.join(n,o)))return i;return t>0?"stash-pop":null}async function $Z(e,t){let r=Array(t.length),n=0,o=Array.from({length:Math.min(H8e,t.length)},async()=>{for(;;){let i=n;if(n+=1,i>=t.length)return;r[i]=await W8e(e,t[i])}});return await Promise.all(o),r}import q8e from"path";var d0=[{hash:"8f8ca583e7162b190f898394e1e3ad81472a1290",shortHash:"8f8ca583",author:"Wijarnako Putra Rajeb",date:"Sep 10, 2026, 12:40 PM",message:"feat(chat): persist composer draft and attachments per session",body:`inputValue and inputAttachments are now session-scoped so each session keeps its own pending draft; send-success clearing and steer-failure restore flow through the persisted setter unchanged.
@@ -2244,7 +2244,7 @@ The client bundle does not build:
2244
2244
 
2245
2245
  ${e.detail}`;return`The shell route answered with markup that is not the shell, and the client bundle builds cleanly.
2246
2246
 
2247
- In production Bun caches the HTML route's output, so a build failure on the first request is cached as an empty page. Restart the server to rebuild it.`}async function kie(e,t=!1){let r=Mp(),n=await fie();return bKe({status:e,markupInvalid:t,detail:n,pressure:r})}var D3="<!--app-bootstrap-->";async function vie(){let e=TA();if(!e)return{ok:!1,reason:"The HTTP listener is not up yet."};let t=yKe(Mp());if(t)return{ok:!1,reason:t};try{let r=await fetch(new URL(AA,e),EA());if(!r.ok)return{ok:!1,reason:await kie(r.status)};let n=await r.text();if(!n.includes(D3))return{ok:!1,reason:await kie(r.status,!0)};return{ok:!0,html:n}}catch(r){return{ok:!1,reason:r instanceof Error?r.message:String(r)}}}import{resolve as wKe}from"path";var Aie="omp-first-frame";function F3(e){return`html,body{background-color:${r1(Xo(e.canvas)??{r:0,g:0,b:0,a:1})};}`}var U3="/manifest.webmanifest",RA=null;async function Tie(){if(RA!==null)return RA;try{return RA=await Bun.file(wKe(mt(),"public","manifest.webmanifest")).text(),RA}catch{return null}}function Eie(e){return e.replace(/<link rel="manifest" href="[^"]*"/,`<link rel="manifest" href="${U3}"`)}function SKe(e){return{background:e.canvas,theme:e.canvas}}function Rie(e,t){let r;try{r=JSON.parse(e)}catch{return e}let n=SKe(t);return r.background_color=n.background,r.theme_color=n.theme,JSON.stringify(r,null,2)}var Pie="monochrome",Iie="data-icon-style",Cie="iconStyle";function xKe(e){return e==="monochrome"||e==="color"}function Oie(e){return xKe(e)?e:"monochrome"}var Mie={Activity:240,AlignJustify:100,AlignLeft:150,Archive:50,ArchiveRestore:90,ArrowDown:100,ArrowDownToLine:330,ArrowLeft:350,ArrowRight:80,ArrowUp:150,ArrowUpDown:310,ArrowUpRight:70,BarChart3:150,BellRing:260,Blocks:110,Bot:220,Box:260,Boxes:220,Brain:350,BrainCircuit:300,Briefcase:310,Camera:60,CaseSensitive:110,ChevronDown:120,ChevronLeft:250,ChevronRight:300,ChevronUp:250,ChevronsUpDown:80,Circle:50,CircleCheck:350,CircleDashed:120,CircleDot:240,ClipboardCopy:280,ClipboardList:290,ClipboardPaste:200,Cloud:340,CloudDownload:300,Code:200,Code2:260,Coins:210,Columns:280,Columns2:20,Command:100,Component:200,Copy:320,CopyPlus:40,CornerDownLeft:10,Cpu:250,Database:280,Dice5:50,Diff:300,DollarSign:220,Download:210,DownloadCloud:180,Edit2:210,Ellipsis:100,ExternalLink:60,Eye:20,EyeOff:350,File:310,FileCode:260,FileCog:340,FileEdit:270,FileImage:40,FilePlus:350,FilePlus2:350,FileSearch:310,FileText:80,Files:320,Flag:350,FlaskConical:170,Folder:290,FolderGit:190,FolderGit2:190,FolderInput:310,FolderOpen:330,FolderPlus:250,FolderSearch:10,FolderTree:10,Gamepad2:300,GitBranch:30,GitCommitVertical:240,GitCompare:340,GitFork:30,GitMerge:90,GitPullRequest:10,Globe:340,GraduationCap:190,GripVertical:350,Hammer:310,Hand:200,HardDrive:0,Hash:330,Heading:250,Heart:270,History:110,Home:20,Image:140,Key:240,KeyRound:240,Keyboard:120,Laptop:170,Layers:30,LayoutTemplate:170,Leaf:50,Library:160,Lightbulb:0,List:170,ListChecks:320,ListFilter:230,ListOrdered:220,ListTodo:210,ListTree:330,Loader2:40,Lock:220,LockKeyhole:270,LockOpen:180,LogIn:140,LogOut:190,Maximize:310,Maximize2:270,Menu:100,MessageSquare:150,MessageSquareOff:40,MessageSquarePlus:350,MessagesSquare:220,Mic:160,MicOff:170,Minimize:290,Minimize2:130,Minus:110,Monitor:250,Moon:80,MoreHorizontal:160,MousePointerClick:70,MoveVertical:300,Music:280,Package:270,Paintbrush:250,Palette:320,PanelLeft:280,PanelLeftClose:160,PanelRight:330,PanelRightClose:350,Paperclip:310,Pause:10,Pencil:0,PencilLine:260,Pin:0,PinOff:50,Pipette:120,Play:310,Plug:50,Plus:210,Power:340,Puzzle:50,Quote:110,Radio:320,Ratio:160,RefreshCw:180,Regex:280,Replace:190,ReplaceAll:140,Rocket:210,RotateCcw:330,RotateCw:0,Rows:160,Rows3:250,Save:40,SaveAll:190,Scissors:260,Search:250,Send:110,Server:300,ServerCog:50,Settings:240,Settings2:20,Shield:160,Shrink:160,Sliders:290,SlidersHorizontal:50,Smartphone:20,Space:290,Sparkles:180,Square:60,SquareFunction:220,SquarePen:10,Star:170,StickyNote:100,Store:340,Sun:90,Tablet:290,Tag:310,Target:200,Terminal:210,TextSelect:220,Ticket:170,TriangleAlert:210,Type:170,Undo2:310,Upload:0,UploadCloud:50,User:140,Variable:330,Volume2:270,VolumeX:50,Wand2:270,WandSparkles:40,Waypoints:30,WholeWord:240,WrapText:340,Wrench:0,X:230,Zap:120,ZoomIn:250,ZoomOut:340},B3={deepest:{0:"#ea3037",10:"#e9350b",20:"#cf5500",30:"#b46800",40:"#a17400",50:"#8e7a00",60:"#808000",70:"#738400",80:"#618600",90:"#518a00",100:"#3c8d00",110:"#229000",120:"#00910a",130:"#008d29",140:"#009040",150:"#008e55",160:"#008d67",170:"#008b79",180:"#008989",190:"#00899f",200:"#0085b7",210:"#007fdd",220:"#2e71fd",230:"#506fff",240:"#5c6bff",250:"#7363fd",260:"#8b5ef9",270:"#9f55ed",280:"#ae4ee0",290:"#bb47d2",300:"#c442c4",310:"#cd3cb5",320:"#d637a3",330:"#de318c",340:"#e52c71",350:"#e92c54"},deeper:{0:"#f53d40",10:"#f4421d",20:"#dd5c00",30:"#c07000",40:"#ac7d00",50:"#988300",60:"#898900",70:"#7b8e00",80:"#698f00",90:"#579400",100:"#419700",110:"#269a00",120:"#00980b",130:"#00982d",140:"#009a45",150:"#00995c",160:"#00976f",170:"#009582",180:"#009393",190:"#0090a6",200:"#008ec4",210:"#0085e7",220:"#3e7dff",230:"#5777ff",240:"#6678ff",250:"#7b70ff",260:"#9065ff",270:"#a85ff8",280:"#b858ea",290:"#c452dc",300:"#cf4cce",310:"#d847bf",320:"#e042ac",330:"#e93d95",340:"#f0397a",350:"#f4395d"},deep:{0:"#f94143",10:"#f84522",20:"#e25e00",30:"#c47200",40:"#b08000",50:"#9b8600",60:"#8d8c00",70:"#7e9100",80:"#6b9300",90:"#599700",100:"#429b00",110:"#269a00",120:"#009f0d",130:"#009b2e",140:"#009a45",150:"#009c5e",160:"#009b72",170:"#009985",180:"#009696",190:"#0093aa",200:"#0091c8",210:"#008bf1",220:"#4381ff",230:"#5b7bff",240:"#6a7cff",250:"#7e75ff",260:"#936aff",270:"#ab62fb",280:"#bb5bee",290:"#c855df",300:"#d250d1",310:"#db4bc2",320:"#e446af",330:"#ec4199",340:"#f43d7c",350:"#f83d60"},mid:{0:"#fc4546",10:"#fc4926",20:"#e66000",30:"#c97500",40:"#b08000",50:"#9f8900",60:"#908f00",70:"#7e9100",80:"#6e9600",90:"#5b9a00",100:"#429b00",110:"#279e00",120:"#009f0d",130:"#009f2f",140:"#009e47",150:"#009c5e",160:"#009b72",170:"#009c88",180:"#009a9a",190:"#0096ae",200:"#0091c8",210:"#008bf1",220:"#4985ff",230:"#5f80ff",240:"#6a7cff",250:"#8179ff",260:"#956fff",270:"#ab62fb",280:"#be5ff1",290:"#cb58e3",300:"#d553d4",310:"#df4ec5",320:"#e849b2",330:"#f0449c",340:"#f7417f",350:"#fb4163"},light:{0:"#ff4a4a",10:"#fc4926",20:"#eb6200",30:"#cd7700",40:"#b48200",50:"#a28c00",60:"#908f00",70:"#819400",80:"#709900",90:"#5b9a00",100:"#449e00",110:"#28a100",120:"#00a30d",130:"#00a230",140:"#00a149",150:"#00a060",160:"#009e74",170:"#009f8b",180:"#009d9d",190:"#009ab2",200:"#0095cc",210:"#008ef6",220:"#4985ff",230:"#6384ff",240:"#6e80ff",250:"#8179ff",260:"#9874ff",270:"#ae66ff",280:"#c162f4",290:"#ce5ce6",300:"#d957d8",310:"#e252c8",320:"#eb4db6",330:"#f4489f",340:"#fb4582",350:"#ff4566"},bright:{0:"#ff5351",10:"#ff5636",20:"#f06400",30:"#d17a00",40:"#bc8800",50:"#a68f00",60:"#969500",70:"#849800",80:"#739d00",90:"#5fa100",100:"#47a500",110:"#29a500",120:"#00a70e",130:"#00a632",140:"#00a54b",150:"#00a362",160:"#00a57a",170:"#00a38e",180:"#00a0a1",190:"#009db5",200:"#009bd5",210:"#0091fb",220:"#548dff",230:"#6788ff",240:"#7185ff",250:"#847eff",260:"#9a79ff",270:"#b270ff",280:"#c565f8",290:"#d25fe9",300:"#dc5adb",310:"#e655cc",320:"#ef50b9",330:"#f74ca2",340:"#ff4985",350:"#ff4f6b"}},Nie={0:"#ff7d7f",10:"#ff8069",20:"#ff843d",30:"#ff9e07",40:"#f7b900",50:"#e1c400",60:"#cfcc00",70:"#bed200",80:"#a9d900",90:"#92de0b",100:"#7ce239",110:"#68e54e",120:"#55e75b",130:"#38e96a",140:"#00e980",150:"#00e79c",160:"#00e5b4",170:"#00e2cc",180:"#00e0e1",190:"#00dcf8",200:"#09c1ff",210:"#5cb1ff",220:"#7fa9ff",230:"#91a3ff",240:"#9d9fff",250:"#a99aff",260:"#b793ff",270:"#c68bff",280:"#d680ff",290:"#e772fd",300:"#fe7cff",310:"#fc6ee8",320:"#ff69d2",330:"#ff70bd",340:"#ff76a7",350:"#ff7a93"};var Xsr=Array.from({length:61},(e,t)=>0.9-t*0.01),kKe=[0.8503,0.8888,0.9137,0.9433,1],Lie=["deepest","deeper","deep","mid","light","bright"];var Qsr=Array.from({length:36},(e,t)=>t*10);function PA(e){let t=Xo(e);if(!t)return"deep";let r=(i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4},n=0.2126*r(t.r)+0.7152*r(t.g)+0.0722*r(t.b),o=kKe.findIndex((i)=>n<i);return Lie[o===-1?Lie.length-1:o]}var Die={error:"var(--theme-error)",success:"var(--theme-success)",warning:"var(--theme-warning)",info:"var(--theme-info)"},j3={light:{saturation:60,lightness:30},dark:{saturation:65,lightness:70}},q0=210;function vKe(e){return(Math.round(e/10)*10%360+360)%360}function Fie(e,t="light",r){let n=t==="dark"?Nie:B3[r?PA(r):"deepest"];return n[vKe(e)]??n[0]}var IA={deepest:"--icon-tone",deeper:"--icon-tone-deeper",deep:"--icon-tone-deep",mid:"--icon-tone-mid",light:"--icon-tone-light",bright:"--icon-tone-bright",dark:"--icon-tone-dark"};var xd="data-icon-paper",H3=Object.entries(B3);function V0(e){let{saturation:t,lightness:r}=j3[e],n=`hsl(var(--icon-hue, ${q0}) ${t}% ${r}%)`;return e==="light"?`var(--icon-tone, ${n})`:`var(--icon-tone-dark, ${n})`}var AKe={AlertCircle:"error",AlertTriangle:"error",Ban:"error",Bug:"error",BugOff:"error",CircleAlert:"error",CircleSlash:"error",FileWarning:"error",FileX:"error",OctagonAlert:"error",OctagonX:"error",PackageX:"error",ShieldAlert:"error",Trash2:"error",XCircle:"error",Check:"success",CheckCheck:"success",CheckCircle2:"success",CheckSquare:"success",PackageCheck:"success",ShieldCheck:"success",Braces:"warning",FileArchive:"warning",FileSpreadsheet:"success",FileType:"warning",Bell:"warning",Calendar:"warning",CalendarRange:"warning",Clock:"warning",Clock3:"warning",Hourglass:"warning",BookOpen:"info",CircleQuestionMark:"info",Compass:"info",HelpCircle:"info",Info:"info"};function TKe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-zA-Z])([0-9])/g,"$1-$2").toLowerCase()}function Uie(e){return`lucide-${TKe(e)}`}var Bie=Object.entries(AKe).map(([e,t])=>({className:Uie(e),role:t})),jie=Object.entries(Mie).map(([e,t])=>({className:Uie(e),hue:t}));var Hie="classic",Wie="data-surface",$ie="surfaceStyle";function EKe(e){return e==="classic"||e==="glass"}function Kie(e){return EKe(e)?e:"classic"}var RKe='data-theme="paper"',PKe='data-theme-variant="light"',IKe='<meta name="theme-color" content="#faf8f3" />';function CKe(e,t,r){let n=Kie(e),o=Oie(t),i=[];if(n!==Hie)i.push(`${Wie}="${n}"`);if(o!==Pie)i.push(`${Iie}="${o}"`);if(r&&r.variant==="light")i.push(`${xd}="${PA(r.paper)}"`);return i.length>0?` ${i.join(" ")}`:""}function qie(e,t){return e.replace(RKe,`data-theme="${t.palette.id}"${CKe(t.surfaceStyle,t.iconStyle,t.palette)}`).replace(PKe,`data-theme-variant="${t.palette.variant}"`).replace(IKe,`<meta name="theme-color" content="${t.chromeColor}" />`)}function Vie(e,t){return t.authRequired||t.isMobile?e.canvas:e.paper}var $3=[20,25,30,35,40,45,50,55,60,65,70,75,80,85,90];var OKe=8,G0=4.5,CA=0.005;function OA(e,t){let[r,n]=[cf(e),cf(t)].sort((o,i)=>i-o);return(r+0.05)/(n+0.05)}function W3(e,t){let r=Math.min(OA(e,t.paper),OA(e,t.canvas));return Number.isFinite(r)?r:0}var Gie=new WeakMap;function zie(e){let t=Gie.get(e);if(t)return t;let r=$3.map((i)=>id(e.paper,e.ink,i/100)),n=r.find((i)=>W3(i,e)>=G0)??e.ink,o={ink:e.ink,ladder:r,muted:n,codeFill:id(e.paper,e.ink,OKe/100)};return Gie.set(e,o),o}function Yie(e){if(!Xo(e.canvas))return e.canvas;if(OA(e.canvas,e.ink)>=G0)return e.canvas;for(let t=CA;t<=1;t+=CA){let r=e.variant==="dark"?"#000000":"#ffffff",n=id(e.canvas,r,t);if(OA(n,e.ink)>=G0)return n}return e.canvas}var Jie=["error","success","info","warning","meta"];function Xie(e,t){let r=e[t];if(!Xo(r))return r;if(W3(r,e)>=G0)return r;let n=e.variant==="dark"?"#ffffff":"#000000";for(let o=CA;o<=1;o+=CA){let i=id(r,n,o);if(W3(i,e)>=G0)return i}return n}var Zie="omp-theme-palettes",MKe=[["--theme-info-hover","--theme-info"],["--theme-warning-hover","--theme-warning"]];function NKe(e){let t=zie(e),r=[` --theme-paper: ${e.paper};`,` --theme-canvas: ${e.canvas};`,` --theme-ink: ${e.ink};`,...t.ladder.map((n,o)=>` --theme-ink-${$3[o]}: ${n};`),` --theme-code-fill: ${t.codeFill};`,` --theme-on-ink-muted: ${Yie(e)};`,` --theme-muted: ${t.muted};`,` --theme-error: ${e.error};`,` --theme-success: ${e.success};`,` --theme-info: ${e.info};`,` --theme-warning: ${e.warning};`,` --theme-meta: ${e.meta};`];for(let n of Jie)r.push(` --theme-${n}-text: ${Xie(e,n)};`);for(let[n,o]of MKe)r.push(` ${n}: color-mix(in srgb, var(${o}) 85%, var(--theme-ink));`);return r.push(` color-scheme: ${e.variant};`),`html[data-theme="${e.id}"] {
2247
+ In production Bun caches the HTML route's output, so a build failure on the first request is cached as an empty page. Restart the server to rebuild it.`}async function kie(e,t=!1){let r=Mp(),n=await fie();return bKe({status:e,markupInvalid:t,detail:n,pressure:r})}var D3="<!--app-bootstrap-->";async function vie(){let e=TA();if(!e)return{ok:!1,reason:"The HTTP listener is not up yet."};let t=yKe(Mp());if(t)return{ok:!1,reason:t};try{let r=await fetch(new URL(AA,e),EA());if(!r.ok)return{ok:!1,reason:await kie(r.status)};let n=await r.text();if(!n.includes(D3))return{ok:!1,reason:await kie(r.status,!0)};return{ok:!0,html:n}}catch(r){return{ok:!1,reason:r instanceof Error?r.message:String(r)}}}import{resolve as wKe}from"path";var Aie="omp-first-frame";function F3(e){return`html,body{background-color:${r1(Xo(e.canvas)??{r:0,g:0,b:0,a:1})};}`}var U3="/manifest.webmanifest",RA=null;async function Tie(){if(RA!==null)return RA;try{return RA=await Bun.file(wKe(mt(),"public","manifest.webmanifest")).text(),RA}catch{return null}}function Eie(e){return e.replace(/<link rel="manifest" href="[^"]*"/,`<link rel="manifest" href="${U3}"`)}function SKe(e){return{background:e.canvas,theme:e.canvas}}function Rie(e,t){let r;try{r=JSON.parse(e)}catch{return e}let n=SKe(t);return r.background_color=n.background,r.theme_color=n.theme,JSON.stringify(r,null,2)}var Pie="monochrome",Iie="data-icon-style",Cie="iconStyle";function xKe(e){return e==="monochrome"||e==="color"}function Oie(e){return xKe(e)?e:"monochrome"}var Mie={Activity:240,AlignJustify:100,AlignLeft:150,Archive:50,ArchiveRestore:90,ArrowDown:100,ArrowDownToLine:330,ArrowLeft:350,ArrowRight:80,ArrowUp:150,ArrowUpDown:310,ArrowUpRight:70,BarChart3:150,BellRing:260,Blocks:110,Bot:220,Box:260,Boxes:220,Brain:350,BrainCircuit:300,Briefcase:310,Camera:60,CaseSensitive:110,ChevronDown:120,ChevronLeft:250,ChevronRight:300,ChevronUp:250,ChevronsUpDown:80,Circle:50,CircleCheck:350,CircleDashed:120,CircleDot:240,ClipboardCopy:280,ClipboardList:290,ClipboardPaste:200,Cloud:340,CloudDownload:300,Code:200,Code2:260,Coins:210,Columns:280,Columns2:20,Command:100,Component:200,Copy:320,CopyPlus:40,CornerDownLeft:10,Cpu:250,Database:280,Dice5:50,Diff:300,DollarSign:220,Download:210,DownloadCloud:180,Edit2:210,Ellipsis:100,ExternalLink:60,Eye:20,EyeOff:350,File:310,FileCode:260,FileCog:340,FileEdit:270,FileImage:40,FilePlus:350,FilePlus2:350,FileSearch:310,FileText:80,Files:320,Flag:350,FlaskConical:170,Folder:290,FolderGit:190,FolderGit2:190,FolderInput:310,FolderOpen:330,FolderPlus:250,FolderSearch:10,FolderTree:10,Gamepad2:300,GitBranch:30,GitCommitVertical:240,GitCompare:340,GitFork:30,GitMerge:90,GitPullRequest:10,Globe:340,GraduationCap:190,GripVertical:350,Hammer:310,Hand:200,HardDrive:0,Hash:330,Heading:250,Heart:270,History:110,Home:20,Image:140,Key:240,KeyRound:240,Keyboard:120,Laptop:170,Layers:30,LayoutTemplate:170,Leaf:50,Library:160,Lightbulb:0,List:170,ListChecks:320,ListFilter:230,ListOrdered:220,ListTodo:210,ListTree:330,Loader2:40,Lock:220,LockKeyhole:270,LockOpen:180,LogIn:140,LogOut:190,Maximize:310,Maximize2:270,Menu:100,MessageSquare:150,MessageSquareOff:40,MessageSquarePlus:350,MessagesSquare:220,Mic:160,MicOff:170,Minimize:290,Minimize2:130,Minus:110,Monitor:250,Moon:80,MoreHorizontal:160,MousePointerClick:70,MoveVertical:300,Music:280,Package:270,PackageOpen:230,Paintbrush:250,Palette:320,PanelLeft:280,PanelLeftClose:160,PanelRight:330,PanelRightClose:350,Paperclip:310,Pause:10,Pencil:0,PencilLine:260,Pin:0,PinOff:50,Pipette:120,Play:310,Plug:50,Plus:210,Power:340,Puzzle:50,Quote:110,Radio:320,Ratio:160,RefreshCw:180,Regex:280,Replace:190,ReplaceAll:140,Rocket:210,RotateCcw:330,RotateCw:0,Rows:160,Rows3:250,Save:40,SaveAll:190,Scissors:260,Search:250,Send:110,Server:300,ServerCog:50,Settings:240,Settings2:20,Shield:160,Shrink:160,Sliders:290,SlidersHorizontal:50,Smartphone:20,Space:290,Sparkles:180,Square:60,SquareFunction:220,SquarePen:10,Star:170,StickyNote:100,Store:340,Sun:90,Tablet:290,Tag:310,Target:200,Terminal:210,TextSelect:220,Ticket:170,TriangleAlert:210,Type:170,Undo2:310,Upload:0,UploadCloud:50,User:140,Variable:330,Volume2:270,VolumeX:50,Wand2:270,WandSparkles:40,Waypoints:30,WholeWord:240,WrapText:340,Wrench:0,X:230,Zap:120,ZoomIn:250,ZoomOut:340},B3={deepest:{0:"#ea3037",10:"#e9350b",20:"#cf5500",30:"#b46800",40:"#a17400",50:"#8e7a00",60:"#808000",70:"#738400",80:"#618600",90:"#518a00",100:"#3c8d00",110:"#229000",120:"#00910a",130:"#008d29",140:"#009040",150:"#008e55",160:"#008d67",170:"#008b79",180:"#008989",190:"#00899f",200:"#0085b7",210:"#007fdd",220:"#2e71fd",230:"#506fff",240:"#5c6bff",250:"#7363fd",260:"#8b5ef9",270:"#9f55ed",280:"#ae4ee0",290:"#bb47d2",300:"#c442c4",310:"#cd3cb5",320:"#d637a3",330:"#de318c",340:"#e52c71",350:"#e92c54"},deeper:{0:"#f53d40",10:"#f4421d",20:"#dd5c00",30:"#c07000",40:"#ac7d00",50:"#988300",60:"#898900",70:"#7b8e00",80:"#698f00",90:"#579400",100:"#419700",110:"#269a00",120:"#00980b",130:"#00982d",140:"#009a45",150:"#00995c",160:"#00976f",170:"#009582",180:"#009393",190:"#0090a6",200:"#008ec4",210:"#0085e7",220:"#3e7dff",230:"#5777ff",240:"#6678ff",250:"#7b70ff",260:"#9065ff",270:"#a85ff8",280:"#b858ea",290:"#c452dc",300:"#cf4cce",310:"#d847bf",320:"#e042ac",330:"#e93d95",340:"#f0397a",350:"#f4395d"},deep:{0:"#f94143",10:"#f84522",20:"#e25e00",30:"#c47200",40:"#b08000",50:"#9b8600",60:"#8d8c00",70:"#7e9100",80:"#6b9300",90:"#599700",100:"#429b00",110:"#269a00",120:"#009f0d",130:"#009b2e",140:"#009a45",150:"#009c5e",160:"#009b72",170:"#009985",180:"#009696",190:"#0093aa",200:"#0091c8",210:"#008bf1",220:"#4381ff",230:"#5b7bff",240:"#6a7cff",250:"#7e75ff",260:"#936aff",270:"#ab62fb",280:"#bb5bee",290:"#c855df",300:"#d250d1",310:"#db4bc2",320:"#e446af",330:"#ec4199",340:"#f43d7c",350:"#f83d60"},mid:{0:"#fc4546",10:"#fc4926",20:"#e66000",30:"#c97500",40:"#b08000",50:"#9f8900",60:"#908f00",70:"#7e9100",80:"#6e9600",90:"#5b9a00",100:"#429b00",110:"#279e00",120:"#009f0d",130:"#009f2f",140:"#009e47",150:"#009c5e",160:"#009b72",170:"#009c88",180:"#009a9a",190:"#0096ae",200:"#0091c8",210:"#008bf1",220:"#4985ff",230:"#5f80ff",240:"#6a7cff",250:"#8179ff",260:"#956fff",270:"#ab62fb",280:"#be5ff1",290:"#cb58e3",300:"#d553d4",310:"#df4ec5",320:"#e849b2",330:"#f0449c",340:"#f7417f",350:"#fb4163"},light:{0:"#ff4a4a",10:"#fc4926",20:"#eb6200",30:"#cd7700",40:"#b48200",50:"#a28c00",60:"#908f00",70:"#819400",80:"#709900",90:"#5b9a00",100:"#449e00",110:"#28a100",120:"#00a30d",130:"#00a230",140:"#00a149",150:"#00a060",160:"#009e74",170:"#009f8b",180:"#009d9d",190:"#009ab2",200:"#0095cc",210:"#008ef6",220:"#4985ff",230:"#6384ff",240:"#6e80ff",250:"#8179ff",260:"#9874ff",270:"#ae66ff",280:"#c162f4",290:"#ce5ce6",300:"#d957d8",310:"#e252c8",320:"#eb4db6",330:"#f4489f",340:"#fb4582",350:"#ff4566"},bright:{0:"#ff5351",10:"#ff5636",20:"#f06400",30:"#d17a00",40:"#bc8800",50:"#a68f00",60:"#969500",70:"#849800",80:"#739d00",90:"#5fa100",100:"#47a500",110:"#29a500",120:"#00a70e",130:"#00a632",140:"#00a54b",150:"#00a362",160:"#00a57a",170:"#00a38e",180:"#00a0a1",190:"#009db5",200:"#009bd5",210:"#0091fb",220:"#548dff",230:"#6788ff",240:"#7185ff",250:"#847eff",260:"#9a79ff",270:"#b270ff",280:"#c565f8",290:"#d25fe9",300:"#dc5adb",310:"#e655cc",320:"#ef50b9",330:"#f74ca2",340:"#ff4985",350:"#ff4f6b"}},Nie={0:"#ff7d7f",10:"#ff8069",20:"#ff843d",30:"#ff9e07",40:"#f7b900",50:"#e1c400",60:"#cfcc00",70:"#bed200",80:"#a9d900",90:"#92de0b",100:"#7ce239",110:"#68e54e",120:"#55e75b",130:"#38e96a",140:"#00e980",150:"#00e79c",160:"#00e5b4",170:"#00e2cc",180:"#00e0e1",190:"#00dcf8",200:"#09c1ff",210:"#5cb1ff",220:"#7fa9ff",230:"#91a3ff",240:"#9d9fff",250:"#a99aff",260:"#b793ff",270:"#c68bff",280:"#d680ff",290:"#e772fd",300:"#fe7cff",310:"#fc6ee8",320:"#ff69d2",330:"#ff70bd",340:"#ff76a7",350:"#ff7a93"};var Xsr=Array.from({length:61},(e,t)=>0.9-t*0.01),kKe=[0.8503,0.8888,0.9137,0.9433,1],Lie=["deepest","deeper","deep","mid","light","bright"];var Qsr=Array.from({length:36},(e,t)=>t*10);function PA(e){let t=Xo(e);if(!t)return"deep";let r=(i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4},n=0.2126*r(t.r)+0.7152*r(t.g)+0.0722*r(t.b),o=kKe.findIndex((i)=>n<i);return Lie[o===-1?Lie.length-1:o]}var Die={error:"var(--theme-error)",success:"var(--theme-success)",warning:"var(--theme-warning)",info:"var(--theme-info)"},j3={light:{saturation:60,lightness:30},dark:{saturation:65,lightness:70}},q0=210;function vKe(e){return(Math.round(e/10)*10%360+360)%360}function Fie(e,t="light",r){let n=t==="dark"?Nie:B3[r?PA(r):"deepest"];return n[vKe(e)]??n[0]}var IA={deepest:"--icon-tone",deeper:"--icon-tone-deeper",deep:"--icon-tone-deep",mid:"--icon-tone-mid",light:"--icon-tone-light",bright:"--icon-tone-bright",dark:"--icon-tone-dark"};var xd="data-icon-paper",H3=Object.entries(B3);function V0(e){let{saturation:t,lightness:r}=j3[e],n=`hsl(var(--icon-hue, ${q0}) ${t}% ${r}%)`;return e==="light"?`var(--icon-tone, ${n})`:`var(--icon-tone-dark, ${n})`}var AKe={AlertCircle:"error",AlertTriangle:"error",Ban:"error",Bug:"error",BugOff:"error",CircleAlert:"error",CircleSlash:"error",FileWarning:"error",FileX:"error",OctagonAlert:"error",OctagonX:"error",PackageX:"error",ShieldAlert:"error",Trash2:"error",XCircle:"error",Check:"success",CheckCheck:"success",CheckCircle2:"success",CheckSquare:"success",PackageCheck:"success",ShieldCheck:"success",Braces:"warning",FileArchive:"warning",FileSpreadsheet:"success",FileType:"warning",Bell:"warning",Calendar:"warning",CalendarRange:"warning",Clock:"warning",Clock3:"warning",Hourglass:"warning",BookOpen:"info",CircleQuestionMark:"info",Compass:"info",HelpCircle:"info",Info:"info"};function TKe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-zA-Z])([0-9])/g,"$1-$2").toLowerCase()}function Uie(e){return`lucide-${TKe(e)}`}var Bie=Object.entries(AKe).map(([e,t])=>({className:Uie(e),role:t})),jie=Object.entries(Mie).map(([e,t])=>({className:Uie(e),hue:t}));var Hie="classic",Wie="data-surface",$ie="surfaceStyle";function EKe(e){return e==="classic"||e==="glass"}function Kie(e){return EKe(e)?e:"classic"}var RKe='data-theme="paper"',PKe='data-theme-variant="light"',IKe='<meta name="theme-color" content="#faf8f3" />';function CKe(e,t,r){let n=Kie(e),o=Oie(t),i=[];if(n!==Hie)i.push(`${Wie}="${n}"`);if(o!==Pie)i.push(`${Iie}="${o}"`);if(r&&r.variant==="light")i.push(`${xd}="${PA(r.paper)}"`);return i.length>0?` ${i.join(" ")}`:""}function qie(e,t){return e.replace(RKe,`data-theme="${t.palette.id}"${CKe(t.surfaceStyle,t.iconStyle,t.palette)}`).replace(PKe,`data-theme-variant="${t.palette.variant}"`).replace(IKe,`<meta name="theme-color" content="${t.chromeColor}" />`)}function Vie(e,t){return t.authRequired||t.isMobile?e.canvas:e.paper}var $3=[20,25,30,35,40,45,50,55,60,65,70,75,80,85,90];var OKe=8,G0=4.5,CA=0.005;function OA(e,t){let[r,n]=[cf(e),cf(t)].sort((o,i)=>i-o);return(r+0.05)/(n+0.05)}function W3(e,t){let r=Math.min(OA(e,t.paper),OA(e,t.canvas));return Number.isFinite(r)?r:0}var Gie=new WeakMap;function zie(e){let t=Gie.get(e);if(t)return t;let r=$3.map((i)=>id(e.paper,e.ink,i/100)),n=r.find((i)=>W3(i,e)>=G0)??e.ink,o={ink:e.ink,ladder:r,muted:n,codeFill:id(e.paper,e.ink,OKe/100)};return Gie.set(e,o),o}function Yie(e){if(!Xo(e.canvas))return e.canvas;if(OA(e.canvas,e.ink)>=G0)return e.canvas;for(let t=CA;t<=1;t+=CA){let r=e.variant==="dark"?"#000000":"#ffffff",n=id(e.canvas,r,t);if(OA(n,e.ink)>=G0)return n}return e.canvas}var Jie=["error","success","info","warning","meta"];function Xie(e,t){let r=e[t];if(!Xo(r))return r;if(W3(r,e)>=G0)return r;let n=e.variant==="dark"?"#ffffff":"#000000";for(let o=CA;o<=1;o+=CA){let i=id(r,n,o);if(W3(i,e)>=G0)return i}return n}var Zie="omp-theme-palettes",MKe=[["--theme-info-hover","--theme-info"],["--theme-warning-hover","--theme-warning"]];function NKe(e){let t=zie(e),r=[` --theme-paper: ${e.paper};`,` --theme-canvas: ${e.canvas};`,` --theme-ink: ${e.ink};`,...t.ladder.map((n,o)=>` --theme-ink-${$3[o]}: ${n};`),` --theme-code-fill: ${t.codeFill};`,` --theme-on-ink-muted: ${Yie(e)};`,` --theme-muted: ${t.muted};`,` --theme-error: ${e.error};`,` --theme-success: ${e.success};`,` --theme-info: ${e.info};`,` --theme-warning: ${e.warning};`,` --theme-meta: ${e.meta};`];for(let n of Jie)r.push(` --theme-${n}-text: ${Xie(e,n)};`);for(let[n,o]of MKe)r.push(` ${n}: color-mix(in srgb, var(${o}) 85%, var(--theme-ink));`);return r.push(` color-scheme: ${e.variant};`),`html[data-theme="${e.id}"] {
2248
2248
  ${r.join(`
2249
2249
  `)}
2250
2250
  }`}var Qie=null;function _ie(){return Qie??=`/* Generated from src/shared/lib/theme/palettes \u2014 do not edit by hand. */