planx 20.53.1 → 20.53.2

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.
@@ -11932,7 +11932,7 @@ spurious results.`);
11932
11932
  }
11933
11933
  };
11934
11934
 
11935
- // packages/@planx.machina.at/explorer/src/do-store/do-store.ts
11935
+ // packages/@10p.io/explorer/src/do-store/do-store.ts
11936
11936
  var EXPLORER_FIELDS = "id, location, location_etag, filter, listing_collection, refresh_requested_at, refreshed_at, view";
11937
11937
  var DEFAULT_VIEW = "all";
11938
11938
  var SESSION_TABLES = ["explorers", "entries", "explorer_home"];
@@ -12067,7 +12067,7 @@ spurious results.`);
12067
12067
  }
12068
12068
  };
12069
12069
 
12070
- // packages/@planx.machina.at/explorer/src/do-store-threads/do-store-threads.ts
12070
+ // packages/@10p.io/explorer/src/do-store-threads/do-store-threads.ts
12071
12071
  var THREAD_FIELDS = "id, url, selector, etag, status, created_at, created_by";
12072
12072
  function text2(value) {
12073
12073
  return String(value != null ? value : "");
@@ -12149,7 +12149,7 @@ spurious results.`);
12149
12149
  }
12150
12150
  };
12151
12151
 
12152
- // packages/@planx.machina.at/explorer/src/do-snapshot/do-snapshot.ts
12152
+ // packages/@10p.io/explorer/src/do-snapshot/do-snapshot.ts
12153
12153
  var EXPLORER_FIELDS2 = "session_id, id, location, location_etag, filter, listing_collection, refresh_requested_at, refreshed_at, view";
12154
12154
  var DEFAULT_VIEW2 = "all";
12155
12155
  function text3(value) {
@@ -26928,7 +26928,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
26928
26928
  // node_modules/zod/v4/classic/external.js
26929
26929
  config(en_default());
26930
26930
 
26931
- // packages/@planx.machina.at/explorer/src/explorer-logic/explorer-logic.ts
26931
+ // packages/@10p.io/explorer/src/explorer-logic/explorer-logic.ts
26932
26932
  function pathOf(url2) {
26933
26933
  try {
26934
26934
  return new URL(url2).pathname;
@@ -26970,7 +26970,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
26970
26970
  var FS_PLANE_ORIGIN = `http://127.0.0.1:${FS_PLANE_PORT}`;
26971
26971
  var SESSION_ID_HEADER = "x-planx-session-id";
26972
26972
 
26973
- // packages/@planx.machina.at/explorer/src/do-command/do-command.ts
26973
+ // packages/@10p.io/explorer/src/do-command/do-command.ts
26974
26974
  function defineCommand(def) {
26975
26975
  return def;
26976
26976
  }
@@ -27019,7 +27019,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
27019
27019
  return app;
27020
27020
  }
27021
27021
 
27022
- // packages/@planx.machina.at/explorer/src/do-commands/do-commands.ts
27022
+ // packages/@10p.io/explorer/src/do-commands/do-commands.ts
27023
27023
  var DEFAULT_EXPLORER = "main";
27024
27024
  var entrySchema = external_exports.object({
27025
27025
  url: external_exports.string(),
@@ -27127,7 +27127,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
27127
27127
  ];
27128
27128
  }
27129
27129
 
27130
- // packages/@planx.machina.at/explorer/src/do-commands-session/do-commands-session.ts
27130
+ // packages/@10p.io/explorer/src/do-commands-session/do-commands-session.ts
27131
27131
  var DEFAULT_LEASE_MS = 15e3;
27132
27132
  var DEFAULT_EXPLORER2 = "main";
27133
27133
  function buildSessionCommands(deps) {
@@ -27191,7 +27191,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
27191
27191
  ];
27192
27192
  }
27193
27193
 
27194
- // packages/@planx.machina.at/explorer/src/do-commands-threads/do-commands-threads.ts
27194
+ // packages/@10p.io/explorer/src/do-commands-threads/do-commands-threads.ts
27195
27195
  var authorSchema = external_exports.object({ kind: external_exports.enum(["human", "agent"]), name: external_exports.string().min(1) });
27196
27196
  var selectorSchema = external_exports.object({
27197
27197
  exact: external_exports.string().min(1),
@@ -27264,7 +27264,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
27264
27264
  ];
27265
27265
  }
27266
27266
 
27267
- // packages/@planx.machina.at/explorer/src/explorer-session-view/explorer-session-view.ts
27267
+ // packages/@10p.io/explorer/src/explorer-session-view/explorer-session-view.ts
27268
27268
  var EXPLORER_SESSION_VIEW_SDL = [
27269
27269
  "scalar LocalUrl",
27270
27270
  "enum EntryType { DIR FILE SYMLINK }",
@@ -27298,7 +27298,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
27298
27298
  };
27299
27299
  }
27300
27300
 
27301
- // packages/@planx.machina.at/explorer/src/explorer-graphql-view/explorer-graphql-view.ts
27301
+ // packages/@10p.io/explorer/src/explorer-graphql-view/explorer-graphql-view.ts
27302
27302
  var COMMENT_THREADS_SDL = [
27303
27303
  "type TextQuoteSelector { exact: String! prefix: String! suffix: String! line: Int }",
27304
27304
  "type CommentAuthor { kind: String! name: String! }",
package/explorer.main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- globalThis.__PLANX_SERVICE_VERSION__="20.53.1";
1
+ globalThis.__PLANX_SERVICE_VERSION__="20.53.2";
2
2
  import*as Ce from"fs";import{dirname as Tt,join as Lt}from"path";function re(e,t){let n=e[t];if(!n)throw new Error(`explorer child \u306E\u8D77\u52D5\u306B ${t} \u304C\u5FC5\u8981\u3067\u3059`);return n}function Fe(e=process.env){let t=Number(e.PLANX_EXPLORER_LEASE_MS??"");return{port:Number(e.PORT??0),portFile:e.PLANX_EXPLORER_PORT_FILE,pidFile:e.PLANX_EXPLORER_PID_FILE,sessionPortFile:re(e,"PLANX_SESSION_PORT_FILE"),domainPortFile:e.PLANX_DOMAIN_PORT_FILE??Lt(Tt(re(e,"PLANX_SESSION_PORT_FILE")),"domain.port"),filesystemPortFile:re(e,"PLANX_FILESYSTEM_PORT_FILE"),...Number.isInteger(t)&&t>0?{leaseMs:t}:{}}}import{existsSync as It,readFileSync as Ft}from"fs";function j(e,t){if(!It(e))throw new Error(`${t} \u304C\u8D77\u52D5\u3057\u3066\u3044\u307E\u305B\u3093: ${e} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);let n=Number(Ft(e,"utf-8").trim());if(!Number.isInteger(n)||n<=0)throw new Error(`${t} \u306E port file \u304C\u4E0D\u6B63\u3067\u3059: ${e}`);return n}import{readFileSync as Mt}from"fs";var kt=250,Ht=e=>new Promise(t=>setTimeout(t,e)),ne=class extends Error{constructor(n,r){super(n);this.status=r;this.name="DoRequestError"}};async function $t(e,t){if(!e.ok)throw new ne(`${t} \u306B\u5931\u6557\u3057\u307E\u3057\u305F (${e.status}): ${await e.text()}`,e.status)}async function Me(e){let t=e.sleep??Ht,n=Mt(e.bundlePath,"utf-8"),r=null;for(let s=1;s<=(e.attempts??30);s+=1)try{let o=e.deployUrl(),i=await fetch(o,{method:"POST",headers:e.headers,body:n});await $t(i,"explorer plugin \u306E install");return}catch(o){r=o,await t(kt*4)}throw r}function se(e){try{return new URL(e).pathname}catch{return""}}function N(e){let t=se(e);return t?t.endsWith("/")?t:t.slice(0,t.lastIndexOf("/")+1):""}var ke=10,oe=`http://127.0.0.1:${ke}`,He="x-planx-session-id";function U(e){try{return new URL(e).port===String(ke)}catch{return!1}}function ie(e,t){return!t||!e.startsWith(t)?e:oe+e.slice(t.length)}function Dt(e){if(e)return`${oe}${e.endsWith("/")?e:`${e}/`}`}async function jt(e,t){let n=new Set(e.map(i=>i.id)),r=new Set(t.sessionIds()),s=[...r].filter(i=>!n.has(i)).map(i=>t.detach(i)),o=e.filter(i=>!r.has(i.id)).map(i=>t.attach(i.id,{home:Dt(i.cwd)}));await Promise.all([...s,...o].map(i=>i.catch(a=>t.onError?.(a))))}async function*Nt(e){let t=e.getReader(),n=new TextDecoder,r="";for(;;){let{done:s,value:o}=await t.read();if(s)return;r+=n.decode(o,{stream:!0});let i=r.indexOf(`
3
3
 
4
4
  `);for(;i>=0;){let a=r.slice(0,i).split(`
@@ -9,6 +9,6 @@ import*as Ce from"fs";import{dirname as Tt,join as Lt}from"path";function re(e,t
9
9
 
10
10
  `),n=t.pop()??"";return{events:t.filter(r=>r.length>0),rest:n}}function je(e){let t=e.split(`
11
11
  `).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));return t.length>0?t.join(`
12
- `):void 0}var Ne="explorer",Ut=1e4,Wt="{ explorers { session_id id location listing_collection refresh_requested_at refreshed_at } }";function A(e){return e==null?"":String(e)}function Ue(e){let t=()=>`http://127.0.0.1:${e.domainPort()}/domain`,n=()=>AbortSignal.timeout(e.timeoutMs??Ut),r=async(s,o,i)=>{let a=await fetch(`${t()}/plugins/${Ne}/api${s}`,{method:"POST",headers:{"content-type":"application/json",...i?{[He]:i}:{}},body:JSON.stringify(o),signal:n()});if(!a.ok)throw new Error(`explorer ${s} \u306B\u5931\u6557\u3057\u307E\u3057\u305F (${a.status}): ${await a.text()}`);return await a.json()};return{command:(s,o,i)=>r(`/${s}`,o,i),async explorers(){let s=await r("/graphql",{query:Wt});if(s.errors?.length)throw new Error(`explorer \u306E explorers query \u304C error \u3092\u8FD4\u3057\u307E\u3057\u305F: ${JSON.stringify(s.errors)}`);return(s.data?.explorers??[]).map(o=>({sessionId:A(o.session_id),id:A(o.id),location:A(o.location),locationEtag:"",filter:"",listingCollection:A(o.listing_collection),refreshRequestedAt:A(o.refresh_requested_at),refreshedAt:A(o.refreshed_at),entries:[]}))},async objectId(){let s=await fetch(`${t()}/plugins`,{signal:n()});if(!s.ok)throw new Error(`domain \u306E plugin \u4E00\u89A7\u3092\u53D6\u308C\u307E\u305B\u3093 (${s.status})`);let{plugins:o}=await s.json();return o.find(i=>i.name===Ne)?.objectId??null},async*changes(s,o){let i=await fetch(`${t()}/objects/${encodeURIComponent(s)}/changes`,{signal:o});if(!i.ok||!i.body)throw new Error(`explorer \u306E change stream \u3092\u958B\u3051\u307E\u305B\u3093 (${i.status})`);let a=i.body.getReader(),c=new TextDecoder,l="";try{for(yield null;;){let{done:u,value:f}=await a.read();if(u)return;let m=De(l+c.decode(f,{stream:!0}));l=m.rest;for(let y of m.events){let d=je(y);if(d===void 0)continue;let h=JSON.parse(d).tables;yield Array.isArray(h)?h.map(String):null}}}finally{a.releaseLock()}}}}function qt(e){if(e.location&&!U(e.location))return null;let t=e.location?N(e.location):"/";return t&&(se(e.listingCollection)!==t||e.refreshRequestedAt>e.refreshedAt)?t:null}function ae(e){return`${e.sessionId??""}/${e.id}`}function Bt(e){return[e.location,e.listingCollection,e.refreshRequestedAt,e.refreshedAt].join("\0")}async function Kt(e,t=new Map){let n=await e.getState();if(!n)return 0;let r=0;for(let s of n.explorers){let o=qt(s);if(!o){t.delete(ae(s));continue}let i=Bt(s);if(t.get(ae(s))===i)continue;let a=await e.listCollection(o);await e.applyListing(s.id,a,s.sessionId),t.set(ae(s),i),r+=1}return r}function We(e,t){let n=!1,r=!1,s=!1,o=[],i=new Map,a=()=>{let l=o;o=[];for(let u of l)u()},c=async()=>{if(n||s){r=r||n;return}n=!0;try{do r=!1,await Kt(e,i)>0&&(r=!0);while(r&&!s)}catch(l){t(l)}finally{n=!1,a()}};return{nudge(){c()},stop(){s=!0,a()},settled(){return n?new Promise(l=>o.push(l)):Promise.resolve()}}}import{watch as Gt}from"fs";var Jt=300,Xt=(e,t)=>{try{let n=Gt(e,{persistent:!1},()=>t());return n.on("error",()=>n.close()),n}catch{return{close:()=>{}}}};function Vt(e){if(!e||!U(e))return null;let t=N(e);if(!t)return null;try{return decodeURIComponent(t)}catch{return t}}function qe(e){let t=e.watch??Xt,n=e.debounceMs??Jt,r=new Map,s=!1,o=a=>{let c=r.get(a);c&&(c.timer&&clearTimeout(c.timer),c.timer=setTimeout(()=>{if(c.timer=null,!(s||r.get(a)!==c))for(let l of c.ids)e.onChange(l)},n))},i=(a,c)=>{c.timer&&clearTimeout(c.timer),c.handle.close(),r.delete(a)};return{sync(a){if(s)return;let c=new Map;for(let l of a){let u=Vt(l.location);if(!u)continue;let f=c.get(u)??new Set;f.add(l.id),c.set(u,f)}for(let[l,u]of r)c.has(l)||i(l,u);for(let[l,u]of c){let f=r.get(l);if(f){f.ids=u;continue}r.set(l,{handle:t(l,()=>o(l)),ids:u,timer:null})}},stop(){s=!0;for(let[a,c]of r)i(a,c)}}}async function Be(e,t=3e4){let n=e.endsWith("/")?e:`${e}/`,r=await fetch(`${n}?type=dir`,{signal:AbortSignal.timeout(t)});if(!r.ok)throw new Error(`listing \u306E\u53D6\u5F97\u306B\u5931\u6557\u3057\u307E\u3057\u305F (${r.status}): ${n}`);let s=await r.json();return{collection:s.collection,etag:s.etag,entries:s.entries}}var zt=["explorers","*"];function Ke(e){let t=new AbortController,n=e.reconnectMs??1e3,r=o=>new Promise(i=>{let a=setTimeout(i,o);t.signal.addEventListener("abort",()=>{clearTimeout(a),i()},{once:!0})}),s=async o=>{let i=new AbortController,a=()=>i.abort();t.signal.addEventListener("abort",a,{once:!0});let c=setInterval(()=>{e.client.objectId().then(l=>{l!==o&&i.abort()},()=>{})},e.objectCheckMs??1e4);try{for await(let l of e.client.changes(o,i.signal))(!l||l.some(u=>zt.includes(u)))&&e.onChange()}finally{clearInterval(c),t.signal.removeEventListener("abort",a)}};return(async()=>{let o=n;for(;!t.signal.aborted;){try{let i=await e.client.objectId();i&&(o=n,await s(i))}catch(i){!t.signal.aborted&&!(i instanceof Error&&i.name==="AbortError")&&e.onError(i)}if(t.signal.aborted)return;await r(o),o=Math.min(o*2,15e3)}})(),{stop:()=>t.abort()}}function Ge(e){let t=null,n=!1,s=setInterval(()=>{n||t||(t=e.beat().catch(e.onError).finally(()=>{t=null}))},e.intervalMs);return{async stop(){n=!0,clearInterval(s),await t}}}var Yt=15e3,Qt=5,Zt=500,Je="\0";async function Xe(e){let{client:t,fsOrigin:n}=e,r=e.onError??(()=>{}),s=e.leaseMs??Yt,o=new Date().toISOString(),i=new Set,a=!1,c=async()=>{await t.command("service-hello",{leaseMs:s,startedAt:o})};await c().catch(r);let l=qe({onChange:d=>{let[h,g]=d.split(Je);t.command("refresh",{explorerId:g},h).catch(r)}}),u=We({getState:async()=>{let d=await t.explorers();return l.sync(d.map(h=>({id:`${h.sessionId}${Je}${h.id}`,location:h.location}))),{agent:"connected",explorers:d}},listCollection:d=>Be(new URL(d,`${n}/`).href),applyListing:async(d,h,g)=>{await t.command("apply-listing",{explorerId:d,collection:ie(h.collection,n),etag:h.etag,entries:h.entries.map(E=>({...E,url:ie(E.url,n)}))},g)}},r),f=Ke({client:t,onChange:()=>u.nudge(),onError:r,reconnectMs:e.reconnectMs}),m=Ge({intervalMs:Math.max(50,Math.floor(s/3)),beat:async()=>{await c(),u.nudge()},onError:r}),y=async(d,h)=>{let g=null;for(let E=0;E<Qt&&!a&&i.has(d);E+=1)try{await t.command("attach-session",h?{home:h}:{},d);return}catch(S){g=S,await new Promise(w=>setTimeout(w,Zt*2**E))}if(i.delete(d),g)throw g};return{async attachSession(d,h){i.add(d),await y(d,h),u.nudge()},detachSession(d){i.delete(d)},sessionIds:()=>[...i],async settle(){u.nudge(),await u.settled()},async stop(){a=!0,f.stop(),u.stop(),l.stop(),await m.stop(),await t.command("service-bye",{}).catch(r)}}}var ce=(e,t,n)=>(r,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],r.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{c=await u(r,()=>i(a+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),l=!0;else throw f}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}};var Ve=Symbol();var ze=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof W?e.raw.headers:e.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?er(e,{all:n,dot:r}):{}};async function er(e,t){let n=await e.formData();return n?tr(n,t):{}}function tr(e,t){let n=Object.create(null);return e.forEach((r,s)=>{t.all||s.endsWith("[]")?rr(n,s,r):n[s]=r}),t.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(nr(n,r,s),delete n[r])}),n}var rr=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},nr=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((o,i)=>{i===s.length-1?r[o]=n:((!r[o]||typeof r[o]!="object"||Array.isArray(r[o])||r[o]instanceof File)&&(r[o]=Object.create(null)),r=r[o])})};var ue=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ye=e=>{let{groups:t,path:n}=sr(e),r=ue(n);return or(r,t)},sr=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},or=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},q={},Qe=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return q[r]||(n[2]?q[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:q[r]=[e,n[1],!0]),q[r]}return null},B=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},ir=e=>B(e,decodeURI),de=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let o=t.indexOf("?",r),i=t.slice(n,o===-1?void 0:o);return ir(i.includes("%25")?i.replace(/%25/g,"%2525"):i)}else if(s===63)break}return t.slice(n,r)};var Ze=e=>{let t=de(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},v=(e,t,...n)=>(n.length&&(t=v(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),K=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let o=s.replace("?","");r+="/"+o,n.push(r)}else r+="/"+s}),n.filter((s,o,i)=>i.indexOf(s)===o)},le=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?B(e,fe):e):e,et=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let i=e.indexOf(`?${t}`,8);for(i===-1&&(i=e.indexOf(`&${t}`,8));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return le(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);for(;o!==-1;){let i=e.indexOf("&",o+1),a=e.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=e.slice(o+1,a===-1?i===-1?void 0:i:a);if(r&&(c=le(c)),o=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),r&&(l=le(l))),n?(s[c]&&Array.isArray(s[c])||(s[c]=[]),s[c].push(l)):s[c]??=l}return t?s[t]:s},tt=et,rt=(e,t)=>et(e,t,!0),fe=decodeURIComponent;var nt=e=>B(e,fe),W=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#e=n,this.#t={}}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex][1][e],n=this.#s(t);return n&&/\%/.test(n)?nt(n):n}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of t){let r=this.#s(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=/\%/.test(r)?nt(r):r)}return e}#s(e){return this.#e[1]?this.#e[1][e]:e}query(e){return tt(this.url,e)}queries(e){return rt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return this.bodyCache.parsedBody??=await ze(this,e)}#n=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];return s?t[s].then(o=>(s==="json"&&(o=JSON.stringify(o)),new Response(o)[e]())):t[e]=n[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ve](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var st={Stringify:1,BeforeStream:2,Stream:3},ar=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var he=async(e,t,n,r,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(c=>he(c,t,!1,r,s))).then(()=>s[0]));return n?ar(await i,o):i};var cr="text/plain; charset=UTF-8",pe=(e,t)=>({"Content-Type":e,...t}),ot=class{#t;#e;env={};#r;finalized=!1;error;#o;#s;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#t=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new W(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=new Response(e.body,e);for(let[t,n]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,n)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let r=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,n){let r=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?r.append(i,a):r.set(i,a)}if(n)for(let[o,i]of Object.entries(n))if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let a of i)r.append(o,a)}let s=typeof t=="number"?t:t?.status??this.#o;return new Response(e,{status:s,headers:r})}newResponse=(...e)=>this.#i(...e);body=(e,t,n)=>this.#i(e,t,n);text=(e,t,n)=>!this.#a&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#i(e,t,pe(cr,n));json=(e,t,n)=>this.#i(JSON.stringify(e),t,pe("application/json",n));html=(e,t,n)=>{let r=s=>this.#i(s,t,pe("text/html; charset=UTF-8",n));return typeof e=="object"?he(e,st.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))};var p="ALL",it="all",at=["get","post","put","delete","options","patch"],G="Can not add a route since the matcher is already built.",J=class extends Error{};var ct="__COMPOSED_HANDLER";var lr=e=>e.text("404 Not Found",404),lt=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},me=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...at,it].forEach(s=>{this[s]=(o,...i)=>(typeof o=="string"?this.#t=o:this.#o(s,this.#t,o),i.forEach(a=>{this.#o(s,this.#t,a)}),this)}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#t=a;for(let c of[s].flat())i.map(l=>{this.#o(c.toUpperCase(),this.#t,l)})}return this},this.use=(s,...o)=>(typeof s=="string"?this.#t=s:(this.#t="*",o.unshift(s)),o.forEach(i=>{this.#o(p,this.#t,i)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??de:Ze}#e(){let e=new me({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=lr;errorHandler=lt;route(e,t){let n=this.basePath(e);return t.routes.map(r=>{let s;t.errorHandler===lt?s=r.handler:(s=async(o,i)=>(await ce([],t.errorHandler)(o,()=>r.handler(o,i))).res,s[ct]=r.handler),n.#o(r.method,r.path,s)}),this}basePath(e){let t=this.#e();return t._basePath=v(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,t,n){let r,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?r=a=>a:r=n.replaceRequest));let o=s?a=>{let c=s(a);return Array.isArray(c)?c:[c]}:a=>{let c;try{c=a.executionCtx}catch{}return[a.env,c]};r||=(()=>{let a=v(this._basePath,e),c=a==="/"?0:a.length;return l=>{let u=new URL(l.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,l)}})();let i=async(a,c)=>{let l=await t(r(a.req.raw),...o(a));if(l)return l;await c()};return this.#o(p,v(e,"*"),i),this}#o(e,t,n){e=e.toUpperCase(),t=v(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#s(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#n(e,t,n,r){if(r==="HEAD")return(async()=>new Response(null,await this.#n(e,t,n,"GET")))();let s=this.getPath(e,{env:n}),o=this.router.match(r,s),i=new ot(e,{path:s,matchResult:o,env:n,executionCtx:t,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(l){return this.#s(l,i)}return c instanceof Promise?c.then(l=>l||(i.finalized?i.res:this.#r(i))).catch(l=>this.#s(l,i)):c??this.#r(i)}let a=ce(o[0],this.errorHandler,this.#r);return(async()=>{try{let c=await a(i);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,i)}})()}fetch=(e,...t)=>this.#n(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${v("/",e)}`,t),n,r));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var X=[];function ge(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let i=n[s]||n[p],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],X];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=r,r(e,t)}var V="[^/]+",F=".*",M="(?:|/.*)",R=Symbol(),ur=new Set(".\\+*[^]$()");function dr(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===F||e===M?1:t===F||t===M?-1:e===V?1:t===V?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#t;#e;#r=Object.create(null);insert(e,t,n,r,s){if(e.length===0){if(this.#t!==void 0)throw R;if(s)return;this.#t=t;return}let[o,...i]=e,a=o==="*"?i.length===0?["","",F]:["","",V]:o==="/*"?["","",M]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(a){let l=a[1],u=a[2]||V;if(l&&a[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw R;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(f=>f!==F&&f!==M))throw R;if(s)return;c=this.#r[u]=new z,l!==""&&(c.#e=r.varIndex++)}!s&&l!==""&&n.push([l,c.#e])}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(l=>l.length>1&&l!==F&&l!==M))throw R;if(s)return;c=this.#r[o]=new z}c.insert(i,t,n,r,s)}buildRegExpStr(){let t=Object.keys(this.#r).sort(dr).map(n=>{let r=this.#r[n];return(typeof r.#e=="number"?`(${n})@${r.#e}`:ur.has(n)?`\\${n}`:n)+r.buildRegExpStr()});return typeof this.#t=="number"&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};var ut=class{#t={varIndex:0};#e=new z;insert(e,t,n){let r=[],s=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return s[i]=[l,c],i++,a=!0,l}),!a)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=s.length-1;i>=0;i--){let[a]=s[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,s[i][1]);break}}return this.#e.insert(o,t,r,this.#t,n),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(n[++t]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++t),"")),[new RegExp(`^${e}`),n,r]}};var fr=[/^$/,[],Object.create(null)],dt=Object.create(null);function ft(e){return dt[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function hr(){dt=Object.create(null)}function pr(e){let t=new ut,n=[];if(e.length===0)return fr;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[f,m])=>l?1:f?-1:u.length-m.length),s=Object.create(null);for(let l=0,u=-1,f=r.length;l<f;l++){let[m,y,d]=r[l];m?s[y]=[d.map(([g])=>[g,Object.create(null)]),X]:u++;let h;try{h=t.insert(y,u,m)}catch(g){throw g===R?new J(y):g}m||(n[u]=d.map(([g,E])=>{let S=Object.create(null);for(E-=1;E>=0;E--){let[w,te]=h[E];S[w]=te}return[g,S]}))}let[o,i,a]=t.buildRegExp();for(let l=0,u=n.length;l<u;l++)for(let f=0,m=n[l].length;f<m;f++){let y=n[l][f]?.[1];if(!y)continue;let d=Object.keys(y);for(let h=0,g=d.length;h<g;h++)y[d[h]]=a[y[d[h]]]}let c=[];for(let l in i)c[l]=n[i[l]];return[o,c,s]}function _(e,t){if(e){for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(ft(n).test(t))return[...e[n]]}}var Y=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[p]:Object.create(null)},this.#e={[p]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(G);r[e]||[r,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[p]).forEach(c=>{a[e][c]=[...a[p][c]]})}),t==="/*"&&(t="*");let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=ft(t);e===p?Object.keys(r).forEach(c=>{r[c][t]||=_(r[c],t)||_(r[p],t)||[]}):r[e][t]||=_(r[e],t)||_(r[p],t)||[],Object.keys(r).forEach(c=>{(e===p||e===c)&&Object.keys(r[c]).forEach(l=>{a.test(l)&&r[c][l].push([n,o])})}),Object.keys(s).forEach(c=>{(e===p||e===c)&&Object.keys(s[c]).forEach(l=>a.test(l)&&s[c][l].push([n,o]))});return}let i=K(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(s).forEach(u=>{(e===p||e===u)&&(s[u][l]||=[..._(r[u],l)||_(r[p],l)||[]],s[u][l].push([n,o-c+a+1]))})}}match=ge;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,hr(),e}#r(e){let t=[],n=e===p;return[this.#t,this.#e].forEach(r=>{let s=r[e]?Object.keys(r[e]).map(o=>[o,r[e][o]]):[];s.length!==0?(n||=!0,t.push(...s)):e!==p&&t.push(...Object.keys(r[p]).map(o=>[o,r[p][o]]))}),n?pr(t):null}};var ye=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw new Error(G);this.#e.push([e,t,n])}match(e,t){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,o=0,i;for(;o<s;o++){let a=n[o];try{for(let c=0,l=r.length;c<l;c++)a.add(...r[c]);i=a.match(e,t)}catch(c){if(c instanceof J)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var k=Object.create(null),Ee=class{#t;#e;#r;#o=0;#s=k;constructor(e,t,n){if(this.#e=n||Object.create(null),this.#t=[],e&&t){let r=Object.create(null);r[e]={handler:t,possibleKeys:[],score:0},this.#t=[r]}this.#r=[]}insert(e,t,n){this.#o=++this.#o;let r=this,s=Ye(t),o=[];for(let i=0,a=s.length;i<a;i++){let c=s[i],l=s[i+1],u=Qe(c,l),f=Array.isArray(u)?u[0]:c;if(f in r.#e){r=r.#e[f],u&&o.push(u[1]);continue}r.#e[f]=new Ee,u&&(r.#r.push(u),o.push(u[1])),r=r.#e[f]}return r.#t.push({[e]:{handler:n,possibleKeys:o.filter((i,a,c)=>c.indexOf(i)===a),score:this.#o}}),r}#n(e,t,n,r){let s=[];for(let o=0,i=e.#t.length;o<i;o++){let a=e.#t[o],c=a[t]||a[p],l={};if(c!==void 0&&(c.params=Object.create(null),s.push(c),n!==k||r&&r!==k))for(let u=0,f=c.possibleKeys.length;u<f;u++){let m=c.possibleKeys[u],y=l[c.score];c.params[m]=r?.[m]&&!y?r[m]:n[m]??r?.[m],l[c.score]=!0}}return s}search(e,t){let n=[];this.#s=k;let s=[this],o=ue(t),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=a===c-1,f=[];for(let m=0,y=s.length;m<y;m++){let d=s[m],h=d.#e[l];h&&(h.#s=d.#s,u?(h.#e["*"]&&n.push(...this.#n(h.#e["*"],e,d.#s)),n.push(...this.#n(h,e,d.#s))):f.push(h));for(let g=0,E=d.#r.length;g<E;g++){let S=d.#r[g],w=d.#s===k?{}:{...d.#s};if(S==="*"){let b=d.#e["*"];b&&(n.push(...this.#n(b,e,d.#s)),b.#s=w,f.push(b));continue}let[te,Ie,I]=S;if(!l&&!(I instanceof RegExp))continue;let x=d.#e[te],_t=o.slice(a).join("/");if(I instanceof RegExp){let b=I.exec(_t);if(b){if(w[Ie]=b[0],n.push(...this.#n(x,e,d.#s,w)),Object.keys(x.#e).length){x.#s=w;let Ct=b[0].match(/\//)?.length??0;(i[Ct]||=[]).push(x)}continue}}(I===!0||I.test(l))&&(w[Ie]=l,u?(n.push(...this.#n(x,e,w,d.#s)),x.#e["*"]&&n.push(...this.#n(x.#e["*"],e,w,d.#s))):(x.#s=w,f.push(x)))}}s=f.concat(i.shift()??[])}return n.length>1&&n.sort((a,c)=>a.score-c.score),[n.map(({handler:a,params:c})=>[a,c])]}};var we=class{name="TrieRouter";#t;constructor(){this.#t=new Ee}add(e,t,n){let r=K(t);if(r){for(let s=0,o=r.length;s<o;s++)this.#t.insert(e,r[s],n);return}this.#t.insert(e,t,n)}match(e,t){return this.#t.search(e,t)}};var xe=class extends me{constructor(e={}){super(e),this.router=e.router??new ye({routers:[new Y,new we]})}};import{createServer as mr}from"http";import{Http2ServerRequest as gr}from"http2";import{Http2ServerRequest as be}from"http2";import{Readable as ht}from"stream";import _r from"crypto";var P=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},yr=e=>e instanceof P?e:new P(e.message,{cause:e}),Er=global.Request,H=class extends Er{constructor(e,t){typeof e=="object"&&L in e&&(e=e[L]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},wr=e=>{let t=[],n=e.rawHeaders;for(let r=0;r<n.length;r+=2){let{[r]:s,[r+1]:o}=n;s.charCodeAt(0)!==58&&t.push([s,o])}return new Headers(t)},mt=Symbol("wrapBodyStream"),xr=(e,t,n,r,s)=>{let o={method:e,headers:n,signal:s.signal};if(e==="TRACE"){o.method="GET";let i=new H(t,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[mt]){let i;o.body=new ReadableStream({async pull(a){try{i||=ht.toWeb(r).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else o.body=ht.toWeb(r);return new H(t,o)},L=Symbol("getRequestCache"),br=Symbol("requestCache"),Q=Symbol("incomingKey"),Z=Symbol("urlKey"),Sr=Symbol("headersKey"),T=Symbol("abortControllerKey"),vr=Symbol("getAbortController"),ee={get method(){return this[Q].method||"GET"},get url(){return this[Z]},get headers(){return this[Sr]||=wr(this[Q])},[vr](){return this[L](),this[T]},[L](){return this[T]||=new AbortController,this[br]||=xr(this.method,this[Z],this.headers,this[Q],this[T])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(ee,e,{get(){return this[L]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ee,e,{value:function(){return this[L]()[e]()}})});Object.setPrototypeOf(ee,H.prototype);var Rr=(e,t)=>{let n=Object.create(ee);n[Q]=e;let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof be)throw new P("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(r);n[Z]=a.href}catch(a){throw new P("Invalid absolute URL",{cause:a})}return n}let s=(e instanceof be?e.authority:e.headers.host)||t;if(!s)throw new P("Missing host header");let o;if(e instanceof be){if(o=e.scheme,!(o==="http"||o==="https"))throw new P("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${o}://${s}${r}`);if(i.hostname.length!==s.length&&i.hostname!==s.replace(/:\d+$/,""))throw new P("Invalid host header");return n[Z]=i.href,n},pt=Symbol("responseCache"),C=Symbol("getResponseCache"),O=Symbol("cache"),Re=global.Response,$=class gt{#t;#e;[C](){return delete this[O],this[pt]||=new Re(this.#t,this.#e)}constructor(t,n){let r;if(this.#t=t,n instanceof gt){let s=n[pt];if(s){this.#e=s,this[C]();return}else this.#e=n.#e,r=new Headers(n.#e.headers)}else this.#e=n;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[O]=[n?.status||200,t,r||n?.headers])}get headers(){let t=this[O];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[C]().headers}get status(){return this[O]?.[0]??this[C]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty($.prototype,e,{get(){return this[C]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty($.prototype,e,{value:function(){return this[C]()[e]()}})});Object.setPrototypeOf($,Re);Object.setPrototypeOf($.prototype,Re.prototype);async function Pr(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function yt(e,t,n){let r=a=>{e.cancel(a).catch(()=>{})};return t.on("close",r),t.on("error",r),(n??e.read()).then(i,s),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function s(a){a&&t.destroy(a)}function o(){e.read().then(i,s)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",o);else return e.read().then(i,s)}catch(l){s(l)}}}function Or(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:yt(e.getReader(),t)}var Se=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,s]of e)r==="set-cookie"?n.push(s):t[r]=s;return n.length>0&&(t["set-cookie"]=n),t["content-type"]??="text/plain; charset=UTF-8",t},Ar="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=_r);var Pe=Symbol("outgoingEnded"),Cr=()=>new Response(null,{status:400}),Et=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),ve=(e,t)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${n.message}`),t.destroy(n))},wt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},xt=async(e,t)=>{let[n,r,s]=e[O],o=!1;if(!s)s={"content-type":"text/plain; charset=UTF-8"};else if(s instanceof Headers)o=s.has("content-length"),s=Se(s);else if(Array.isArray(s)){let i=new Headers(s);o=i.has("content-length"),s=Se(i)}else for(let i in s)if(i.length===14&&i.toLowerCase()==="content-length"){o=!0;break}o||(typeof r=="string"?s["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?s["Content-Length"]=r.byteLength:r instanceof Blob&&(s["Content-Length"]=r.size)),t.writeHead(n,s),typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(wt(t),await Or(r,t)?.catch(i=>ve(i,t))),t[Pe]?.()},Tr=e=>typeof e.then=="function",Lr=async(e,t,n={})=>{if(Tr(e))if(n.errorHandler)try{e=await e}catch(s){let o=await n.errorHandler(s);if(!o)return;e=o}else e=await e.catch(Et);if(O in e)return xt(e,t);let r=Se(e.headers);if(e.body){let s=e.body.getReader(),o=[],i=!1,a;if(r["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=s.read();let u=await Pr(a).catch(f=>{console.error(f),i=!0});if(!u){if(l===1){await new Promise(f=>setTimeout(f)),c=3;continue}break}if(a=void 0,u.value&&o.push(u.value),u.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,r),o.forEach(c=>{t.write(c)}),i?t.end():(o.length===0&&wt(t),await yt(s,t,a))}else r[Ar]||(t.writeHead(e.status,r),t.end());t[Pe]?.()},Ir=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==H&&(Object.defineProperty(global,"Request",{value:H}),Object.defineProperty(global,"Response",{value:$})),async(r,s)=>{let o,i;try{i=Rr(r,t.hostname);let a=!n||r.method==="GET"||r.method==="HEAD";if(a||(r[mt]=!0,r.on("end",()=>{a=!0}),r instanceof gr&&(s[Pe]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{r.destroy(),s.destroy()})})})),s.on("close",()=>{i[T]&&(r.errored?i[T].abort(r.errored.toString()):s.writableFinished||i[T].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{r.destroy()})})}),o=e(i,{incoming:r,outgoing:s}),O in o)return xt(o,s)}catch(a){if(o)return ve(a,s);if(t.errorHandler){if(o=await t.errorHandler(i?a:yr(a)),!o)return}else i?o=Et(a):o=Cr()}try{return await Lr(o,s,t)}catch(a){return ve(a,s)}}},Fr=e=>{let t=e.fetch,n=Ir(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||mr)(e.serverOptions||{},n)},bt=(e,t)=>{let n=Fr(e);return n.listen(e?.port??3e3,e.hostname,()=>{let r=n.address();t&&t(r)}),n};function St(e,t={}){let n=new xe;return n.get("/health",r=>r.json({status:"ok",service:"explorer",version:t.version??null})),n.get("/explorer/sessions",r=>r.json({sessions:e.sessionIds().map(s=>({sessionId:s}))})),n}function vt(e,t){return new Promise(n=>{let r=bt({fetch:e.fetch,port:t,hostname:"127.0.0.1"},s=>{n({port:s.port,close:()=>new Promise(o=>{r.close(()=>o())})})})})}import{renameSync as Mr,rmSync as kr,writeFileSync as Hr}from"fs";var $r=0;function D(e,t){let n=`${e}.${process.pid}.${++$r}.tmp`;try{Hr(n,t,"utf-8"),Mr(n,e)}catch(r){throw kr(n,{force:!0}),r}}function Oe(e,t){D(e,String(t))}function Ae(e,t){D(e,String(t))}import{existsSync as Dr,realpathSync as jr}from"fs";import{dirname as Rt,resolve as Pt}from"path";var _e="explorer.bundle.js";function Ot(e,t){let n=[];if(e){let r="";try{r=Rt(jr(e))}catch{r=Rt(e)}n.push(Pt(r,_e))}n.push(Pt(t,"dist/packages/@planx.machina.at/explorer",_e));for(let r of n)if(Dr(r))return r;throw new Error(`explorer DO \u306E bundle \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (${_e})\u3002 \u63A2\u7D22: ${n.join(", ")}`)}var At=()=>{};function Te(e){try{process.stderr.write(`${e}
12
+ `):void 0}var Ne="explorer",Ut=1e4,Wt="{ explorers { session_id id location listing_collection refresh_requested_at refreshed_at } }";function A(e){return e==null?"":String(e)}function Ue(e){let t=()=>`http://127.0.0.1:${e.domainPort()}/domain`,n=()=>AbortSignal.timeout(e.timeoutMs??Ut),r=async(s,o,i)=>{let a=await fetch(`${t()}/plugins/${Ne}/api${s}`,{method:"POST",headers:{"content-type":"application/json",...i?{[He]:i}:{}},body:JSON.stringify(o),signal:n()});if(!a.ok)throw new Error(`explorer ${s} \u306B\u5931\u6557\u3057\u307E\u3057\u305F (${a.status}): ${await a.text()}`);return await a.json()};return{command:(s,o,i)=>r(`/${s}`,o,i),async explorers(){let s=await r("/graphql",{query:Wt});if(s.errors?.length)throw new Error(`explorer \u306E explorers query \u304C error \u3092\u8FD4\u3057\u307E\u3057\u305F: ${JSON.stringify(s.errors)}`);return(s.data?.explorers??[]).map(o=>({sessionId:A(o.session_id),id:A(o.id),location:A(o.location),locationEtag:"",filter:"",listingCollection:A(o.listing_collection),refreshRequestedAt:A(o.refresh_requested_at),refreshedAt:A(o.refreshed_at),entries:[]}))},async objectId(){let s=await fetch(`${t()}/plugins`,{signal:n()});if(!s.ok)throw new Error(`domain \u306E plugin \u4E00\u89A7\u3092\u53D6\u308C\u307E\u305B\u3093 (${s.status})`);let{plugins:o}=await s.json();return o.find(i=>i.name===Ne)?.objectId??null},async*changes(s,o){let i=await fetch(`${t()}/objects/${encodeURIComponent(s)}/changes`,{signal:o});if(!i.ok||!i.body)throw new Error(`explorer \u306E change stream \u3092\u958B\u3051\u307E\u305B\u3093 (${i.status})`);let a=i.body.getReader(),c=new TextDecoder,l="";try{for(yield null;;){let{done:u,value:f}=await a.read();if(u)return;let m=De(l+c.decode(f,{stream:!0}));l=m.rest;for(let y of m.events){let d=je(y);if(d===void 0)continue;let h=JSON.parse(d).tables;yield Array.isArray(h)?h.map(String):null}}}finally{a.releaseLock()}}}}function qt(e){if(e.location&&!U(e.location))return null;let t=e.location?N(e.location):"/";return t&&(se(e.listingCollection)!==t||e.refreshRequestedAt>e.refreshedAt)?t:null}function ae(e){return`${e.sessionId??""}/${e.id}`}function Bt(e){return[e.location,e.listingCollection,e.refreshRequestedAt,e.refreshedAt].join("\0")}async function Kt(e,t=new Map){let n=await e.getState();if(!n)return 0;let r=0;for(let s of n.explorers){let o=qt(s);if(!o){t.delete(ae(s));continue}let i=Bt(s);if(t.get(ae(s))===i)continue;let a=await e.listCollection(o);await e.applyListing(s.id,a,s.sessionId),t.set(ae(s),i),r+=1}return r}function We(e,t){let n=!1,r=!1,s=!1,o=[],i=new Map,a=()=>{let l=o;o=[];for(let u of l)u()},c=async()=>{if(n||s){r=r||n;return}n=!0;try{do r=!1,await Kt(e,i)>0&&(r=!0);while(r&&!s)}catch(l){t(l)}finally{n=!1,a()}};return{nudge(){c()},stop(){s=!0,a()},settled(){return n?new Promise(l=>o.push(l)):Promise.resolve()}}}import{watch as Gt}from"fs";var Jt=300,Xt=(e,t)=>{try{let n=Gt(e,{persistent:!1},()=>t());return n.on("error",()=>n.close()),n}catch{return{close:()=>{}}}};function Vt(e){if(!e||!U(e))return null;let t=N(e);if(!t)return null;try{return decodeURIComponent(t)}catch{return t}}function qe(e){let t=e.watch??Xt,n=e.debounceMs??Jt,r=new Map,s=!1,o=a=>{let c=r.get(a);c&&(c.timer&&clearTimeout(c.timer),c.timer=setTimeout(()=>{if(c.timer=null,!(s||r.get(a)!==c))for(let l of c.ids)e.onChange(l)},n))},i=(a,c)=>{c.timer&&clearTimeout(c.timer),c.handle.close(),r.delete(a)};return{sync(a){if(s)return;let c=new Map;for(let l of a){let u=Vt(l.location);if(!u)continue;let f=c.get(u)??new Set;f.add(l.id),c.set(u,f)}for(let[l,u]of r)c.has(l)||i(l,u);for(let[l,u]of c){let f=r.get(l);if(f){f.ids=u;continue}r.set(l,{handle:t(l,()=>o(l)),ids:u,timer:null})}},stop(){s=!0;for(let[a,c]of r)i(a,c)}}}async function Be(e,t=3e4){let n=e.endsWith("/")?e:`${e}/`,r=await fetch(`${n}?type=dir`,{signal:AbortSignal.timeout(t)});if(!r.ok)throw new Error(`listing \u306E\u53D6\u5F97\u306B\u5931\u6557\u3057\u307E\u3057\u305F (${r.status}): ${n}`);let s=await r.json();return{collection:s.collection,etag:s.etag,entries:s.entries}}var zt=["explorers","*"];function Ke(e){let t=new AbortController,n=e.reconnectMs??1e3,r=o=>new Promise(i=>{let a=setTimeout(i,o);t.signal.addEventListener("abort",()=>{clearTimeout(a),i()},{once:!0})}),s=async o=>{let i=new AbortController,a=()=>i.abort();t.signal.addEventListener("abort",a,{once:!0});let c=setInterval(()=>{e.client.objectId().then(l=>{l!==o&&i.abort()},()=>{})},e.objectCheckMs??1e4);try{for await(let l of e.client.changes(o,i.signal))(!l||l.some(u=>zt.includes(u)))&&e.onChange()}finally{clearInterval(c),t.signal.removeEventListener("abort",a)}};return(async()=>{let o=n;for(;!t.signal.aborted;){try{let i=await e.client.objectId();i&&(o=n,await s(i))}catch(i){!t.signal.aborted&&!(i instanceof Error&&i.name==="AbortError")&&e.onError(i)}if(t.signal.aborted)return;await r(o),o=Math.min(o*2,15e3)}})(),{stop:()=>t.abort()}}function Ge(e){let t=null,n=!1,s=setInterval(()=>{n||t||(t=e.beat().catch(e.onError).finally(()=>{t=null}))},e.intervalMs);return{async stop(){n=!0,clearInterval(s),await t}}}var Yt=15e3,Qt=5,Zt=500,Je="\0";async function Xe(e){let{client:t,fsOrigin:n}=e,r=e.onError??(()=>{}),s=e.leaseMs??Yt,o=new Date().toISOString(),i=new Set,a=!1,c=async()=>{await t.command("service-hello",{leaseMs:s,startedAt:o})};await c().catch(r);let l=qe({onChange:d=>{let[h,g]=d.split(Je);t.command("refresh",{explorerId:g},h).catch(r)}}),u=We({getState:async()=>{let d=await t.explorers();return l.sync(d.map(h=>({id:`${h.sessionId}${Je}${h.id}`,location:h.location}))),{agent:"connected",explorers:d}},listCollection:d=>Be(new URL(d,`${n}/`).href),applyListing:async(d,h,g)=>{await t.command("apply-listing",{explorerId:d,collection:ie(h.collection,n),etag:h.etag,entries:h.entries.map(E=>({...E,url:ie(E.url,n)}))},g)}},r),f=Ke({client:t,onChange:()=>u.nudge(),onError:r,reconnectMs:e.reconnectMs}),m=Ge({intervalMs:Math.max(50,Math.floor(s/3)),beat:async()=>{await c(),u.nudge()},onError:r}),y=async(d,h)=>{let g=null;for(let E=0;E<Qt&&!a&&i.has(d);E+=1)try{await t.command("attach-session",h?{home:h}:{},d);return}catch(S){g=S,await new Promise(w=>setTimeout(w,Zt*2**E))}if(i.delete(d),g)throw g};return{async attachSession(d,h){i.add(d),await y(d,h),u.nudge()},detachSession(d){i.delete(d)},sessionIds:()=>[...i],async settle(){u.nudge(),await u.settled()},async stop(){a=!0,f.stop(),u.stop(),l.stop(),await m.stop(),await t.command("service-bye",{}).catch(r)}}}var ce=(e,t,n)=>(r,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],r.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{c=await u(r,()=>i(a+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),l=!0;else throw f}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}};var Ve=Symbol();var ze=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof W?e.raw.headers:e.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?er(e,{all:n,dot:r}):{}};async function er(e,t){let n=await e.formData();return n?tr(n,t):{}}function tr(e,t){let n=Object.create(null);return e.forEach((r,s)=>{t.all||s.endsWith("[]")?rr(n,s,r):n[s]=r}),t.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(nr(n,r,s),delete n[r])}),n}var rr=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},nr=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((o,i)=>{i===s.length-1?r[o]=n:((!r[o]||typeof r[o]!="object"||Array.isArray(r[o])||r[o]instanceof File)&&(r[o]=Object.create(null)),r=r[o])})};var ue=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ye=e=>{let{groups:t,path:n}=sr(e),r=ue(n);return or(r,t)},sr=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},or=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},q={},Qe=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return q[r]||(n[2]?q[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:q[r]=[e,n[1],!0]),q[r]}return null},B=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},ir=e=>B(e,decodeURI),de=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let o=t.indexOf("?",r),i=t.slice(n,o===-1?void 0:o);return ir(i.includes("%25")?i.replace(/%25/g,"%2525"):i)}else if(s===63)break}return t.slice(n,r)};var Ze=e=>{let t=de(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},v=(e,t,...n)=>(n.length&&(t=v(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),K=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let o=s.replace("?","");r+="/"+o,n.push(r)}else r+="/"+s}),n.filter((s,o,i)=>i.indexOf(s)===o)},le=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?B(e,fe):e):e,et=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let i=e.indexOf(`?${t}`,8);for(i===-1&&(i=e.indexOf(`&${t}`,8));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return le(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);for(;o!==-1;){let i=e.indexOf("&",o+1),a=e.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=e.slice(o+1,a===-1?i===-1?void 0:i:a);if(r&&(c=le(c)),o=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),r&&(l=le(l))),n?(s[c]&&Array.isArray(s[c])||(s[c]=[]),s[c].push(l)):s[c]??=l}return t?s[t]:s},tt=et,rt=(e,t)=>et(e,t,!0),fe=decodeURIComponent;var nt=e=>B(e,fe),W=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#e=n,this.#t={}}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex][1][e],n=this.#s(t);return n&&/\%/.test(n)?nt(n):n}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of t){let r=this.#s(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=/\%/.test(r)?nt(r):r)}return e}#s(e){return this.#e[1]?this.#e[1][e]:e}query(e){return tt(this.url,e)}queries(e){return rt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return this.bodyCache.parsedBody??=await ze(this,e)}#n=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];return s?t[s].then(o=>(s==="json"&&(o=JSON.stringify(o)),new Response(o)[e]())):t[e]=n[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ve](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var st={Stringify:1,BeforeStream:2,Stream:3},ar=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var he=async(e,t,n,r,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(c=>he(c,t,!1,r,s))).then(()=>s[0]));return n?ar(await i,o):i};var cr="text/plain; charset=UTF-8",pe=(e,t)=>({"Content-Type":e,...t}),ot=class{#t;#e;env={};#r;finalized=!1;error;#o;#s;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#t=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new W(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=new Response(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=new Response(e.body,e);for(let[t,n]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,n)=>{this.finalized&&(this.#n=new Response(this.#n.body,this.#n));let r=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,n){let r=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?r.append(i,a):r.set(i,a)}if(n)for(let[o,i]of Object.entries(n))if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let a of i)r.append(o,a)}let s=typeof t=="number"?t:t?.status??this.#o;return new Response(e,{status:s,headers:r})}newResponse=(...e)=>this.#i(...e);body=(e,t,n)=>this.#i(e,t,n);text=(e,t,n)=>!this.#a&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#i(e,t,pe(cr,n));json=(e,t,n)=>this.#i(JSON.stringify(e),t,pe("application/json",n));html=(e,t,n)=>{let r=s=>this.#i(s,t,pe("text/html; charset=UTF-8",n));return typeof e=="object"?he(e,st.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))};var p="ALL",it="all",at=["get","post","put","delete","options","patch"],G="Can not add a route since the matcher is already built.",J=class extends Error{};var ct="__COMPOSED_HANDLER";var lr=e=>e.text("404 Not Found",404),lt=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},me=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...at,it].forEach(s=>{this[s]=(o,...i)=>(typeof o=="string"?this.#t=o:this.#o(s,this.#t,o),i.forEach(a=>{this.#o(s,this.#t,a)}),this)}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#t=a;for(let c of[s].flat())i.map(l=>{this.#o(c.toUpperCase(),this.#t,l)})}return this},this.use=(s,...o)=>(typeof s=="string"?this.#t=s:(this.#t="*",o.unshift(s)),o.forEach(i=>{this.#o(p,this.#t,i)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??de:Ze}#e(){let e=new me({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=lr;errorHandler=lt;route(e,t){let n=this.basePath(e);return t.routes.map(r=>{let s;t.errorHandler===lt?s=r.handler:(s=async(o,i)=>(await ce([],t.errorHandler)(o,()=>r.handler(o,i))).res,s[ct]=r.handler),n.#o(r.method,r.path,s)}),this}basePath(e){let t=this.#e();return t._basePath=v(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,t,n){let r,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?r=a=>a:r=n.replaceRequest));let o=s?a=>{let c=s(a);return Array.isArray(c)?c:[c]}:a=>{let c;try{c=a.executionCtx}catch{}return[a.env,c]};r||=(()=>{let a=v(this._basePath,e),c=a==="/"?0:a.length;return l=>{let u=new URL(l.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,l)}})();let i=async(a,c)=>{let l=await t(r(a.req.raw),...o(a));if(l)return l;await c()};return this.#o(p,v(e,"*"),i),this}#o(e,t,n){e=e.toUpperCase(),t=v(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#s(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#n(e,t,n,r){if(r==="HEAD")return(async()=>new Response(null,await this.#n(e,t,n,"GET")))();let s=this.getPath(e,{env:n}),o=this.router.match(r,s),i=new ot(e,{path:s,matchResult:o,env:n,executionCtx:t,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(l){return this.#s(l,i)}return c instanceof Promise?c.then(l=>l||(i.finalized?i.res:this.#r(i))).catch(l=>this.#s(l,i)):c??this.#r(i)}let a=ce(o[0],this.errorHandler,this.#r);return(async()=>{try{let c=await a(i);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,i)}})()}fetch=(e,...t)=>this.#n(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${v("/",e)}`,t),n,r));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var X=[];function ge(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let i=n[s]||n[p],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],X];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=r,r(e,t)}var V="[^/]+",F=".*",M="(?:|/.*)",R=Symbol(),ur=new Set(".\\+*[^]$()");function dr(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===F||e===M?1:t===F||t===M?-1:e===V?1:t===V?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#t;#e;#r=Object.create(null);insert(e,t,n,r,s){if(e.length===0){if(this.#t!==void 0)throw R;if(s)return;this.#t=t;return}let[o,...i]=e,a=o==="*"?i.length===0?["","",F]:["","",V]:o==="/*"?["","",M]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(a){let l=a[1],u=a[2]||V;if(l&&a[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw R;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(f=>f!==F&&f!==M))throw R;if(s)return;c=this.#r[u]=new z,l!==""&&(c.#e=r.varIndex++)}!s&&l!==""&&n.push([l,c.#e])}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(l=>l.length>1&&l!==F&&l!==M))throw R;if(s)return;c=this.#r[o]=new z}c.insert(i,t,n,r,s)}buildRegExpStr(){let t=Object.keys(this.#r).sort(dr).map(n=>{let r=this.#r[n];return(typeof r.#e=="number"?`(${n})@${r.#e}`:ur.has(n)?`\\${n}`:n)+r.buildRegExpStr()});return typeof this.#t=="number"&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};var ut=class{#t={varIndex:0};#e=new z;insert(e,t,n){let r=[],s=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return s[i]=[l,c],i++,a=!0,l}),!a)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=s.length-1;i>=0;i--){let[a]=s[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,s[i][1]);break}}return this.#e.insert(o,t,r,this.#t,n),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(n[++t]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++t),"")),[new RegExp(`^${e}`),n,r]}};var fr=[/^$/,[],Object.create(null)],dt=Object.create(null);function ft(e){return dt[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function hr(){dt=Object.create(null)}function pr(e){let t=new ut,n=[];if(e.length===0)return fr;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[f,m])=>l?1:f?-1:u.length-m.length),s=Object.create(null);for(let l=0,u=-1,f=r.length;l<f;l++){let[m,y,d]=r[l];m?s[y]=[d.map(([g])=>[g,Object.create(null)]),X]:u++;let h;try{h=t.insert(y,u,m)}catch(g){throw g===R?new J(y):g}m||(n[u]=d.map(([g,E])=>{let S=Object.create(null);for(E-=1;E>=0;E--){let[w,te]=h[E];S[w]=te}return[g,S]}))}let[o,i,a]=t.buildRegExp();for(let l=0,u=n.length;l<u;l++)for(let f=0,m=n[l].length;f<m;f++){let y=n[l][f]?.[1];if(!y)continue;let d=Object.keys(y);for(let h=0,g=d.length;h<g;h++)y[d[h]]=a[y[d[h]]]}let c=[];for(let l in i)c[l]=n[i[l]];return[o,c,s]}function _(e,t){if(e){for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(ft(n).test(t))return[...e[n]]}}var Y=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[p]:Object.create(null)},this.#e={[p]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(G);r[e]||[r,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[p]).forEach(c=>{a[e][c]=[...a[p][c]]})}),t==="/*"&&(t="*");let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=ft(t);e===p?Object.keys(r).forEach(c=>{r[c][t]||=_(r[c],t)||_(r[p],t)||[]}):r[e][t]||=_(r[e],t)||_(r[p],t)||[],Object.keys(r).forEach(c=>{(e===p||e===c)&&Object.keys(r[c]).forEach(l=>{a.test(l)&&r[c][l].push([n,o])})}),Object.keys(s).forEach(c=>{(e===p||e===c)&&Object.keys(s[c]).forEach(l=>a.test(l)&&s[c][l].push([n,o]))});return}let i=K(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(s).forEach(u=>{(e===p||e===u)&&(s[u][l]||=[..._(r[u],l)||_(r[p],l)||[]],s[u][l].push([n,o-c+a+1]))})}}match=ge;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,hr(),e}#r(e){let t=[],n=e===p;return[this.#t,this.#e].forEach(r=>{let s=r[e]?Object.keys(r[e]).map(o=>[o,r[e][o]]):[];s.length!==0?(n||=!0,t.push(...s)):e!==p&&t.push(...Object.keys(r[p]).map(o=>[o,r[p][o]]))}),n?pr(t):null}};var ye=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw new Error(G);this.#e.push([e,t,n])}match(e,t){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,o=0,i;for(;o<s;o++){let a=n[o];try{for(let c=0,l=r.length;c<l;c++)a.add(...r[c]);i=a.match(e,t)}catch(c){if(c instanceof J)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var k=Object.create(null),Ee=class{#t;#e;#r;#o=0;#s=k;constructor(e,t,n){if(this.#e=n||Object.create(null),this.#t=[],e&&t){let r=Object.create(null);r[e]={handler:t,possibleKeys:[],score:0},this.#t=[r]}this.#r=[]}insert(e,t,n){this.#o=++this.#o;let r=this,s=Ye(t),o=[];for(let i=0,a=s.length;i<a;i++){let c=s[i],l=s[i+1],u=Qe(c,l),f=Array.isArray(u)?u[0]:c;if(f in r.#e){r=r.#e[f],u&&o.push(u[1]);continue}r.#e[f]=new Ee,u&&(r.#r.push(u),o.push(u[1])),r=r.#e[f]}return r.#t.push({[e]:{handler:n,possibleKeys:o.filter((i,a,c)=>c.indexOf(i)===a),score:this.#o}}),r}#n(e,t,n,r){let s=[];for(let o=0,i=e.#t.length;o<i;o++){let a=e.#t[o],c=a[t]||a[p],l={};if(c!==void 0&&(c.params=Object.create(null),s.push(c),n!==k||r&&r!==k))for(let u=0,f=c.possibleKeys.length;u<f;u++){let m=c.possibleKeys[u],y=l[c.score];c.params[m]=r?.[m]&&!y?r[m]:n[m]??r?.[m],l[c.score]=!0}}return s}search(e,t){let n=[];this.#s=k;let s=[this],o=ue(t),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],u=a===c-1,f=[];for(let m=0,y=s.length;m<y;m++){let d=s[m],h=d.#e[l];h&&(h.#s=d.#s,u?(h.#e["*"]&&n.push(...this.#n(h.#e["*"],e,d.#s)),n.push(...this.#n(h,e,d.#s))):f.push(h));for(let g=0,E=d.#r.length;g<E;g++){let S=d.#r[g],w=d.#s===k?{}:{...d.#s};if(S==="*"){let b=d.#e["*"];b&&(n.push(...this.#n(b,e,d.#s)),b.#s=w,f.push(b));continue}let[te,Ie,I]=S;if(!l&&!(I instanceof RegExp))continue;let x=d.#e[te],_t=o.slice(a).join("/");if(I instanceof RegExp){let b=I.exec(_t);if(b){if(w[Ie]=b[0],n.push(...this.#n(x,e,d.#s,w)),Object.keys(x.#e).length){x.#s=w;let Ct=b[0].match(/\//)?.length??0;(i[Ct]||=[]).push(x)}continue}}(I===!0||I.test(l))&&(w[Ie]=l,u?(n.push(...this.#n(x,e,w,d.#s)),x.#e["*"]&&n.push(...this.#n(x.#e["*"],e,w,d.#s))):(x.#s=w,f.push(x)))}}s=f.concat(i.shift()??[])}return n.length>1&&n.sort((a,c)=>a.score-c.score),[n.map(({handler:a,params:c})=>[a,c])]}};var we=class{name="TrieRouter";#t;constructor(){this.#t=new Ee}add(e,t,n){let r=K(t);if(r){for(let s=0,o=r.length;s<o;s++)this.#t.insert(e,r[s],n);return}this.#t.insert(e,t,n)}match(e,t){return this.#t.search(e,t)}};var xe=class extends me{constructor(e={}){super(e),this.router=e.router??new ye({routers:[new Y,new we]})}};import{createServer as mr}from"http";import{Http2ServerRequest as gr}from"http2";import{Http2ServerRequest as be}from"http2";import{Readable as ht}from"stream";import _r from"crypto";var P=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},yr=e=>e instanceof P?e:new P(e.message,{cause:e}),Er=global.Request,H=class extends Er{constructor(e,t){typeof e=="object"&&L in e&&(e=e[L]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},wr=e=>{let t=[],n=e.rawHeaders;for(let r=0;r<n.length;r+=2){let{[r]:s,[r+1]:o}=n;s.charCodeAt(0)!==58&&t.push([s,o])}return new Headers(t)},mt=Symbol("wrapBodyStream"),xr=(e,t,n,r,s)=>{let o={method:e,headers:n,signal:s.signal};if(e==="TRACE"){o.method="GET";let i=new H(t,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[mt]){let i;o.body=new ReadableStream({async pull(a){try{i||=ht.toWeb(r).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else o.body=ht.toWeb(r);return new H(t,o)},L=Symbol("getRequestCache"),br=Symbol("requestCache"),Q=Symbol("incomingKey"),Z=Symbol("urlKey"),Sr=Symbol("headersKey"),T=Symbol("abortControllerKey"),vr=Symbol("getAbortController"),ee={get method(){return this[Q].method||"GET"},get url(){return this[Z]},get headers(){return this[Sr]||=wr(this[Q])},[vr](){return this[L](),this[T]},[L](){return this[T]||=new AbortController,this[br]||=xr(this.method,this[Z],this.headers,this[Q],this[T])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(ee,e,{get(){return this[L]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ee,e,{value:function(){return this[L]()[e]()}})});Object.setPrototypeOf(ee,H.prototype);var Rr=(e,t)=>{let n=Object.create(ee);n[Q]=e;let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof be)throw new P("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(r);n[Z]=a.href}catch(a){throw new P("Invalid absolute URL",{cause:a})}return n}let s=(e instanceof be?e.authority:e.headers.host)||t;if(!s)throw new P("Missing host header");let o;if(e instanceof be){if(o=e.scheme,!(o==="http"||o==="https"))throw new P("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${o}://${s}${r}`);if(i.hostname.length!==s.length&&i.hostname!==s.replace(/:\d+$/,""))throw new P("Invalid host header");return n[Z]=i.href,n},pt=Symbol("responseCache"),C=Symbol("getResponseCache"),O=Symbol("cache"),Re=global.Response,$=class gt{#t;#e;[C](){return delete this[O],this[pt]||=new Re(this.#t,this.#e)}constructor(t,n){let r;if(this.#t=t,n instanceof gt){let s=n[pt];if(s){this.#e=s,this[C]();return}else this.#e=n.#e,r=new Headers(n.#e.headers)}else this.#e=n;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[O]=[n?.status||200,t,r||n?.headers])}get headers(){let t=this[O];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[C]().headers}get status(){return this[O]?.[0]??this[C]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty($.prototype,e,{get(){return this[C]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty($.prototype,e,{value:function(){return this[C]()[e]()}})});Object.setPrototypeOf($,Re);Object.setPrototypeOf($.prototype,Re.prototype);async function Pr(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function yt(e,t,n){let r=a=>{e.cancel(a).catch(()=>{})};return t.on("close",r),t.on("error",r),(n??e.read()).then(i,s),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function s(a){a&&t.destroy(a)}function o(){e.read().then(i,s)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",o);else return e.read().then(i,s)}catch(l){s(l)}}}function Or(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:yt(e.getReader(),t)}var Se=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,s]of e)r==="set-cookie"?n.push(s):t[r]=s;return n.length>0&&(t["set-cookie"]=n),t["content-type"]??="text/plain; charset=UTF-8",t},Ar="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=_r);var Pe=Symbol("outgoingEnded"),Cr=()=>new Response(null,{status:400}),Et=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),ve=(e,t)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${n.message}`),t.destroy(n))},wt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},xt=async(e,t)=>{let[n,r,s]=e[O],o=!1;if(!s)s={"content-type":"text/plain; charset=UTF-8"};else if(s instanceof Headers)o=s.has("content-length"),s=Se(s);else if(Array.isArray(s)){let i=new Headers(s);o=i.has("content-length"),s=Se(i)}else for(let i in s)if(i.length===14&&i.toLowerCase()==="content-length"){o=!0;break}o||(typeof r=="string"?s["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?s["Content-Length"]=r.byteLength:r instanceof Blob&&(s["Content-Length"]=r.size)),t.writeHead(n,s),typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(wt(t),await Or(r,t)?.catch(i=>ve(i,t))),t[Pe]?.()},Tr=e=>typeof e.then=="function",Lr=async(e,t,n={})=>{if(Tr(e))if(n.errorHandler)try{e=await e}catch(s){let o=await n.errorHandler(s);if(!o)return;e=o}else e=await e.catch(Et);if(O in e)return xt(e,t);let r=Se(e.headers);if(e.body){let s=e.body.getReader(),o=[],i=!1,a;if(r["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=s.read();let u=await Pr(a).catch(f=>{console.error(f),i=!0});if(!u){if(l===1){await new Promise(f=>setTimeout(f)),c=3;continue}break}if(a=void 0,u.value&&o.push(u.value),u.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,r),o.forEach(c=>{t.write(c)}),i?t.end():(o.length===0&&wt(t),await yt(s,t,a))}else r[Ar]||(t.writeHead(e.status,r),t.end());t[Pe]?.()},Ir=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==H&&(Object.defineProperty(global,"Request",{value:H}),Object.defineProperty(global,"Response",{value:$})),async(r,s)=>{let o,i;try{i=Rr(r,t.hostname);let a=!n||r.method==="GET"||r.method==="HEAD";if(a||(r[mt]=!0,r.on("end",()=>{a=!0}),r instanceof gr&&(s[Pe]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{r.destroy(),s.destroy()})})})),s.on("close",()=>{i[T]&&(r.errored?i[T].abort(r.errored.toString()):s.writableFinished||i[T].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{r.destroy()})})}),o=e(i,{incoming:r,outgoing:s}),O in o)return xt(o,s)}catch(a){if(o)return ve(a,s);if(t.errorHandler){if(o=await t.errorHandler(i?a:yr(a)),!o)return}else i?o=Et(a):o=Cr()}try{return await Lr(o,s,t)}catch(a){return ve(a,s)}}},Fr=e=>{let t=e.fetch,n=Ir(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||mr)(e.serverOptions||{},n)},bt=(e,t)=>{let n=Fr(e);return n.listen(e?.port??3e3,e.hostname,()=>{let r=n.address();t&&t(r)}),n};function St(e,t={}){let n=new xe;return n.get("/health",r=>r.json({status:"ok",service:"explorer",version:t.version??null})),n.get("/explorer/sessions",r=>r.json({sessions:e.sessionIds().map(s=>({sessionId:s}))})),n}function vt(e,t){return new Promise(n=>{let r=bt({fetch:e.fetch,port:t,hostname:"127.0.0.1"},s=>{n({port:s.port,close:()=>new Promise(o=>{r.close(()=>o())})})})})}import{renameSync as Mr,rmSync as kr,writeFileSync as Hr}from"fs";var $r=0;function D(e,t){let n=`${e}.${process.pid}.${++$r}.tmp`;try{Hr(n,t,"utf-8"),Mr(n,e)}catch(r){throw kr(n,{force:!0}),r}}function Oe(e,t){D(e,String(t))}function Ae(e,t){D(e,String(t))}import{existsSync as Dr,realpathSync as jr}from"fs";import{dirname as Rt,resolve as Pt}from"path";var _e="explorer.bundle.js";function Ot(e,t){let n=[];if(e){let r="";try{r=Rt(jr(e))}catch{r=Rt(e)}n.push(Pt(r,_e))}n.push(Pt(t,"dist/packages/@10p.io/explorer",_e));for(let r of n)if(Dr(r))return r;throw new Error(`explorer DO \u306E bundle \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (${_e})\u3002 \u63A2\u7D22: ${n.join(", ")}`)}var At=()=>{};function Te(e){try{process.stderr.write(`${e}
13
13
  `)}catch{}}function Le(e){return e instanceof Error?e.message:String(e)}async function Nr(){let e=Fe(),t=a=>Te(`[explorer] ${Le(a)}`),n=null,r=()=>j(e.domainPortFile,"domain child"),s=await vt(St({sessionIds:()=>n?.sessionIds()??[]},{version:globalThis.__PLANX_SERVICE_VERSION__??null}),e.port),o=Promise.resolve().then(()=>Me({deployUrl:()=>`http://127.0.0.1:${r()}/domain/objects/deploy`,bundlePath:Ot(process.argv[1],process.cwd()),headers:{"x-planx-domain-name":"explorer"}}));o.catch(t);let i=()=>{At(),Promise.resolve(n?.stop()).finally(()=>{if(s.close(),e.pidFile)try{Ce.unlinkSync(e.pidFile)}catch{}if(e.portFile)try{Ce.unlinkSync(e.portFile)}catch{}process.exit(0)})};process.on("SIGTERM",i),process.on("SIGINT",i),e.portFile&&Ae(e.portFile,s.port),e.pidFile&&Oe(e.pidFile,process.pid),process.stdout.write(JSON.stringify({service:"explorer",port:s.port,pid:process.pid})+`
14
14
  `),process.stdin.resume(),process.stdin.on("end",()=>process.exit(1)),process.on("uncaughtException",(a,c)=>{Te(`[explorer] Uncaught exception (${c}): ${Le(a)}`),process.exit(1)}),o.then(async()=>{let a=await Xe({client:Ue({domainPort:r}),fsOrigin:`http://127.0.0.1:${j(e.filesystemPortFile,"filesystem child")}`,...e.leaseMs?{leaseMs:e.leaseMs}:{},onError:t});n=a;let c=$e({sessionPort:()=>j(e.sessionPortFile,"session child"),attach:(l,u)=>a.attachSession(l,u.home),detach:async l=>a.detachSession(l),sessionIds:()=>a.sessionIds(),onError:t});At=()=>c.stop()},()=>{})}Nr().catch(e=>{Te(`Failed to start explorer server: ${Le(e)}`),process.exit(1)});