web-listener 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +1 -1
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1 +1 @@
1
- import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as i,Agent as r,request as s,ServerResponse as o}from"node:http";import{createReadStream as c,constants as a,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as h,randomUUID as l}from"node:crypto";import{pipeline as d}from"node:stream/promises";import w from"node:zlib";import{promisify as p}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as _,resolve as v}from"node:path";import{readFile as E,writeFile as x,stat as T,readdir as S,realpath as k,open as $,mkdtemp as A,rm as P}from"node:fs/promises";import{tmpdir as N,platform as O}from"node:os";import{Agent as M,request as R}from"node:https";import{TransformStream as F,TextDecoderStream as C,DecompressionStream as U,ReadableStream as B}from"node:stream/web";import{Readable as I,Duplex as j,Writable as D}from"node:stream";function H(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{type:"IPv4",ip:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{type:"IPv6",ip:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{type:"IPv6",ip:r[3].toLowerCase(),port:void 0};const s=/^(.*?):(\d+)$/i.exec(n);return s?.[2]?{type:"alias",ip:s[1],port:Number.parseInt(s[2])}:{type:"alias",ip:n,port:void 0}}function q(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([z(t[1])|i,i]);continue}const s=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(s?.[1]){const t=W(s[1]),e=s[2]?L>>BigInt(Number.parseInt(s[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.type){case"alias":return e.has(t.ip);case"IPv4":const r=z(t.ip);return n.some(([t,e])=>(r|e)===t);case"IPv6":const s=W(t.ip);return i.some(([t,e])=>(s|e)===t);default:return!1}}}const L=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function z(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function W(t){const e=t.split(":").map(t=>t?Number.parseInt(t,16):-1);let n=0n;for(const t of e)t<0?n<<=16n*BigInt(9-e.length):n=n<<16n|BigInt(t);return n}class V{t;i;constructor(t){const e={o:null,u:null};this.t=e,this.i=e,void 0!==t&&this.push(t)}isEmpty(){return!this.t.u}clear(){this.t.u=null,this.t.o=null,this.i=this.t}push(t){const e={o:t,u:null};this.i.u=e,this.i=e}shift(){if(!this.t.u)return null;this.t=this.t.u;const t=this.t.o;return this.t.o=null,t}remove(t){for(let e=this.t;e.u;e=e.u)if(e.u.o===t){e.u=e.u.u;break}}[Symbol.iterator](){return{next:()=>{if(!this.t.u)return{value:null,done:!0};this.t=this.t.u;const t=this.t.o;return this.t.o=null,{value:t,done:!1}}}}}class J{h;l;m;_;constructor(){this.h=new V,this.l=new V,this.m=0}push(t){if(this.m)return;const e=this.l.shift();e?(e.v&&clearTimeout(e.v),e.T(t)):this.h.push(t)}shift(t){return this.h.isEmpty()?this.m?Promise.reject(this._):new Promise((e,n)=>{const i={T:e,S:n,v:null};this.l.push(i),void 0!==t&&(i.v=setTimeout(()=>{this.l.remove(i),n(new Error(`Timeout after ${t}ms`))},t))}):Promise.resolve(this.h.shift())}k(t){this._=t;for(const e of this.l)e.S(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.k(t))}fail(t){this.m||(this.m=2,this.k(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.m)throw t;return{value:null,done:!0}})}}}function G(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return G(t.cause,e);if("error"in t)return G(t.error,e)}}function Z(t,e="http"){if(!t)throw new Error("no address");if("string"==typeof t)return t;if("IPv4"===t.family)return`${e}://${t.address}:${t.port}`;if("IPv6"===t.family)return`${e}://[${t.address}]:${t.port}`;throw new Error(`unknown address family: ${t.family}`)}const K=/*@__PURE__*/Buffer.alloc(0),X=t=>new URL("http://localhost"+(t.url??"/"));class Y extends Error{error;suppressed;constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const Q=globalThis.SuppressedError??Y;class tt{$;A;constructor(){this.$=!1}P(t){this.$?t!==this.A&&(this.A=new Q(t,this.A)):(this.A=t,this.$=!0)}N(){this.$=!1,this.A=void 0}}class et{O;M;R;constructor(t){this.O=t,this.M=Object.create(null),this.R=!1}get headersSent(){return this.R}writeHead(t,e,i){if(this.R)throw new Error("headers already sent");const r={...this.M};for(const[t,e]of(t=>{if(!t)return[];const e=[];if(Array.isArray(t)){const n=t.length;if(1&n)throw new Error("headers must be a list of alternating keys and values");for(let i=0;i<n;i+=2){const n=t[i],r=t[i+1];if("string"!=typeof n)throw new Error("invalid header name");void 0!==r&&e.push([n.toLowerCase(),r])}}else for(const[n,i]of Object.entries(t))void 0!==i&&e.push([n.toLowerCase(),i]);return e})(i))r[t]=e;return this.O.write([`HTTP/1.1 ${t} ${rt(e??n[t]??"-")}`,...nt(r),"",""].join("\r\n"),"ascii"),this.R=!0,this}write(t,e="utf-8",n){return this.O.write(t,e,n)}end(t,e="utf-8",n){return this.O.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.M[n]="string"==typeof e||"number"==typeof e?e:[...e],this}setHeaders(t){for(const[e,n]of t)this.setHeader(e,n);return this}}function nt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=it(i);t&&e.push(`${rt(n)}: ${rt(t)}`)}return e}const it=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",rt=t=>t.replaceAll(/[^ \t!-~]/g,"");class st extends Error{statusCode;statusMessage;headers;body;constructor(t,{message:e,statusMessage:i,headers:r,body:s,...o}={}){super(e??("string"==typeof s?s:void 0),o),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=r,this.body=s??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}static INTERNAL_SERVER_ERROR=new st(500);send(t,e){t.setHeaders((t=>{if(t){if(t instanceof Headers)return t;if(Array.isArray(t))return new Headers(t);{const e=t instanceof Map?[...t.entries()]:Object.entries(t);return new Headers(e.map(([t,e])=>[t,it(e)]).filter(([t,e])=>e))}}return new Headers})(this.headers));const n=Buffer.byteLength(this.body,"utf-8");t.setHeader("content-length",String(n)),t.writeHead(this.statusCode,this.statusMessage,e),t.end(this.body,"utf-8")}}const ot=(t,e,n)=>{n.headersSent?n.end():(G(t,st)??st.INTERNAL_SERVER_ERROR).send(n)},ct=(t,e,n)=>{if(n.writable){n.addListener("finish",()=>n.destroy());const e=new et(n);(G(t,st)??st.INTERNAL_SERVER_ERROR).send(e,{connection:"close"})}else n.destroy()},at=(t,e,n)=>{(G(t,st)?.statusCode??1)&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},ft=new WeakMap;function ut(t,e){const n=ft.get(t);if(n)return n;const i=X(t),r={F:t,C:i,U:decodeURIComponent(i.pathname),B:ct,I:new AbortController,j:[],D:[],H:e?dt(t):null};return ft.set(t,r),r}function ht(t,e,n,i){e||(t.H=null),t.L=n;const r=async()=>{t.I.abort(n.W.writableEnded?"complete":"client abort");const e=new tt;await lt(t.j,e,t),await lt(t.D,e,t,()=>{t.V=async e=>{try{await e()}catch(e){i(e,t.F)}}}),e.$&&i(e.A,t.F)};return n.W.closed?r():n.W.once("close",r),t}async function lt(t,e,n,i){for(;n.J;)await n.J;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.P(t)}}})().then(()=>{n.J===r&&(n.J=void 0)});n.J=r,await r}function dt(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const wt=t=>ft.get(t);function pt(t){const e=wt(t);if(!e)throw new Error("unknown request");return e}function mt(t,e){const n=wt(t);n&&yt(n,e)}function yt(t,e){t.G=e;const n=t.Z;n&&queueMicrotask(()=>Et(e,t.F,n))}const gt=t=>Boolean(wt(t)?.Z);function bt(t,e,n){if(!t.Z){if(t.L&&!t.H){const e=t.L.W;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.L?.W.once("close",()=>t.F.socket.destroy()),t.Z={K:e,X:n},Et(t.G,t.F,t.Z),vt(t)}}function _t(t){if(t.L){if(!t.H){const e=t.L.W;e.headersSent||(e.statusCode=503,e.hasHeader("connection")||e.setHeader("connection","close"))}t.L.W.end(()=>t.F.socket.destroy())}else t.F.socket.destroy()}function vt(t){if(clearTimeout(t.Y),!t.tt||t.V)return;const e=Date.now();if(e>=t.tt)return void _t(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,Et(t.G,t.F,t.Z))),void 0===t.Y&&t.D.push(()=>clearTimeout(t.Y)),t.Y=setTimeout(()=>vt(t),n-e)}async function Et(t,e,n){try{await(t?.(n.K))}catch(t){n.X(t,"soft closing",e)}}const xt=(t,e)=>{const n=pt(t);n.V?n.V(e):n.j.push(e)},Tt=(t,e)=>{const n=pt(t);n.V?n.V(e):n.D.push(e)},St=t=>pt(t).I.signal;class kt extends Error{}const $t=new kt("STOP"),At=new kt("CONTINUE"),Pt=new kt("NEXT_ROUTE"),Nt=new kt("NEXT_ROUTER");async function Ot(t,e){const n=pt(t);if(!n.L)throw new Error("cannot call acceptUpgrade from shouldUpgrade");if(!n.H)throw new Error("not an upgrade request");if(n.it)return n.rt;const i=n.L.W;if(!i.readable||!i.writable)throw $t;const r=await e(t,i,n.L.t);return n.L.t=K,n.B=r.onError,yt(n,r.softCloseHandler),n.rt=r.return,n.it=!0,r.return}const Mt=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Rt=t=>t,Ft=t=>void 0===t?void 0:""===t?[]:t.split("/"),Ct=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t);function Ut(t){const e={},n=new Map;for(const[i,r]of Object.entries(t))e[i]=!1,n.set(r,i);return t=>{const i={...e};for(let e=0;e<t.length;++e){const r=n.get(t[e]);if(!r)return[i,t.substring(e)];i[r]=!0}return[i,""]}}const Bt=/*@__PURE__*/Ut({st:"i",ot:"!"}),It=Object.freeze({});function jt(t,e,n){const i=t.F.url,r=t.U,s=t.ct??It;return t.F.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.C.search,t.U=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.F.url=i,t.U=r,t.ct=s}}function Dt(t){return wt(t)?.ct??It}function Ht(t,e){return Dt(t)[e]}function qt(t){const e=wt(t);return e?e.C.pathname+e.C.search:t.url??"/"}function Lt(t){const e=wt(t);e&&(t.url=e.C.pathname+e.C.search)}const zt=t=>"function"==typeof t?{handleRequest:t}:t,Wt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Vt=(t,e=Kt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Jt=t=>"function"==typeof t?{handleError:t}:t,Gt=t=>"function"==typeof t?{handleRequest:t}:t,Zt=t=>"function"==typeof t?{handleUpgrade:t}:t,Kt=()=>!1,Xt=Symbol("http");class Yt{ft;ut;constructor(){this.ft=[],this.ut=[]}P(t,e,n,i,r){const s=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{st:s,ot:o},c]=Bt(t);if("/"!==c[0])throw new Error("path must begin with '/' or flags");let a=0,f=0;for(const t of c.matchAll(r)){t.index>a&&n.push(Mt(c.substring(a,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new Error(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),o||n.push("+");else if("\\"===e[0])n.push(Mt(t[1]));else{const r=e[0],s=t[2];if(!s)throw new Error(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({ht:s,lt:o?Ft:Ct})):(n.push("([^/]+?)"),i.push({ht:s,lt:Rt}))}a=t.index+e.length}if(a<c.length&&n.push(Mt(c.substring(a))),f>0)throw new Error("unbalanced optional braces in path");return e&&(n.push("(?:"),o?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{dt:new RegExp(n.join(""),s?"i":""),wt:i}})(n,i):{dt:null,wt:[]};return this.ft.push({yt:t,gt:"string"==typeof e?e.toLowerCase():e,bt:s.dt,_t:s.wt,vt:r}),this}use(...t){return this.P(null,null,null,!0,t.map(Gt))}mount(t,...e){return this.P(null,null,t,!0,e.map(Gt))}within(t,e){const n=new Yt;return e(n),this.mount(t,n)}at(t,...e){return this.P(null,null,t,!1,e.map(Gt))}onRequest(t,e,...n){return this.P(te(t),Xt,e,!1,n.map(Gt))}onUpgrade(t,e,n,...i){return this.P(te(t),e,n,!1,i.map(Zt))}onError(...t){return this.P(null,null,null,!0,t.map(Jt))}onReturn(...t){return this.ut.push(...t),this}on(t,...e){const n=/^([A-Z]+) (\/.*)$/.exec(t);if(!n)throw new Error("invalid method + path spec: "+JSON.stringify(t));return this.P(n[1],Xt,n[2],!1,e.map(Gt))}get=(t,...e)=>this.P(Qt,Xt,t,!1,e.map(Gt));delete=(...t)=>this.onRequest("DELETE",...t);getOnly=(...t)=>this.onRequest("GET",...t);head=(...t)=>this.onRequest("HEAD",...t);options=(...t)=>this.onRequest("OPTIONS",...t);patch=(...t)=>this.onRequest("PATCH",...t);post=(...t)=>this.onRequest("POST",...t);put=(...t)=>this.onRequest("PUT",...t);ws=(...t)=>this.onUpgrade("GET","websocket",...t);async handleRequest(t){return this.Et(t,new tt)}async handleUpgrade(t){return this.Et(t,new tt)}async handleError(t,e){const n=new tt;return n.P(t),this.Et(e,n)}shouldUpgrade(t){return this.xt(pt(t))}xt(t){for(const e of this.ft){const n=ee(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=jt(t,n.Tt,[])}catch{continue}try{for(const n of e.vt)if(re(n,t))return!0}finally{i()}}return!1}async Et(t,e){const n=pt(t),i=await this.St(n,e);if(e.$)throw e.A;return i}async St(t,e){for(const n of this.ft){const i=ee(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.kt();r=jt(t,i.Tt,e)}catch(t){e.P(t);continue}try{const i=await ne(t,n.vt,this.ut,e);if(i===Nt)break;if(i===Pt)continue;return i}finally{r()}}return At}}const Qt=new Set(["HEAD","GET"]),te=t=>t?"string"==typeof t?t:new Set(t):null;function ee(t,e){if("string"==typeof e.yt){if(e.yt!==t.F.method)return!1}else if(null!==e.yt&&!e.yt.has(t.F.method??""))return!1;if(e.gt===Xt){if(t.H)return!1}else if(null!==e.gt&&!t.H?.has(e.gt))return!1;if(null===e.bt)return!0;const n=e.bt.exec(t.U);return!!n&&{Tt:"/"+(n.groups?.rest??""),kt:()=>e._t.map((t,e)=>[t.ht,t.lt(n[e+1])])}}async function ne(t,e,n,i){for(const r of e){let e=await ie(r,t,i);if(e!==At){if(!t.H&&!(e instanceof kt)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.F,s=t.L.W;for(const t of n)await t(i,r,s)}catch(t){i.P(t);continue}return e}}return Pt}async function ie(t,e,n){if(t instanceof Yt)return t.St(e,n);let i=At;try{if(n.$){if(t.handleError){const r=n.A;n.N(),i=await t.handleError(r,e.F,e.H?{socket:e.L.W,head:e.L.t}:{response:e.L.W})}}else if(e.H){if(t.handleUpgrade){const n=e.L;i=await t.handleUpgrade(e.F,n.W,n.t)}}else t.handleRequest&&(i=await t.handleRequest(e.F,e.L.W))}catch(t){t instanceof kt?i=t:n.P(t)}finally{await((t,e)=>lt(t.j,e,t))(e,n)}return i===$t?void 0:i}function re(t,e){if(t instanceof Yt)return t.xt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.F)}catch(t){return e.$t(t),!1}}function se(t,{onError:e=at,socketCloseTimeout:n=500}={}){const i=[],r=new Set,s=()=>{const t=[...i];i.length=0;for(const e of t)e()},o=t=>{t&&(r.size?i.push(t):setImmediate(t))},c=t=>{r.add(t),t.D.push(()=>{r.delete(t),!r.size&&i.length&&setImmediate(s)})},a=(t,n)=>e(t,"tearing down",n);return{request:async(n,i)=>{let r;try{r=ut(n,!1)}catch(t){return e(t,"parsing request",n),void ot(new st(400),0,i)}ht(r,!1,{W:i},a),c(r);const s=new tt,o=await ie(t,r,s);s.$?(e(s.A,"handling request",n),ot(s.A,0,i)):o!==At&&o!==Pt&&o!==Nt||ot(new st(404),0,i)},upgrade:async(i,r,s)=>{let o;r.once("finish",()=>{const t=setTimeout(()=>r.destroy(),n);r.once("close",()=>clearTimeout(t))});try{o=ut(i,!0)}catch(t){return e(t,"parsing upgrade",i),void ct(new st(400),0,r)}ht(o,!0,{W:r,t:s},a),s=K,c(o);const f=new tt,u=await ie(t,o,f);f.$?(e(f.A,"handling upgrade",i),o.B(f.A,i,r)):u!==At&&u!==Pt&&u!==Nt||(console.warn(`Upgrade ${i.headers.upgrade} request for ${i.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),o.B(new st(404),i,r))},shouldUpgrade:n=>{try{const i=ut(n,!0);return i.$t=t=>e(t,"checking should upgrade",n),re(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.At,r=t.code;n.writable&&!i?.headersSent&&n.end(ce.get(r)??ae),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request")},softClose(t,e,n){for(const n of r)bt(n,t,e);o(n)},hardClose(t){for(const t of r)_t(t);o(t)},countConnections:()=>r.size}}const oe=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),ce=new Map([["HPE_HEADER_OVERFLOW",oe(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",oe(413)],["ERR_HTTP_REQUEST_TIMEOUT",oe(408)]]),ae=oe(400);class fe extends EventTarget{Pt;constructor(t){super(),this.Pt=t}attach(t,e={}){const n=se(this.Pt,{...e,onError:this.Nt.bind(this,t)});!1===e.autoContinue&&t.addListener("checkContinue",n.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",n.request),t.addListener("request",n.request),t.addListener("upgrade",n.upgrade);const i=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=n.shouldUpgrade),t.addListener("clientError",n.clientError);let r=!1;return(e="",s=-1,o=!1)=>{r||(r=!0,t.removeListener("checkContinue",n.request),t.removeListener("checkExpectation",n.request),t.removeListener("request",n.request),t.removeListener("upgrade",n.upgrade),t.shouldUpgradeCallback===n.shouldUpgrade&&(t.shouldUpgradeCallback=i),t.removeListener("clientError",n.clientError));const c=()=>{o&&t.closeAllConnections()};if(s>0){const i=setTimeout(n.hardClose,s);n.softClose(e,this.Nt.bind(this,t),()=>{clearTimeout(i),c()})}else 0===s&&n.hardClose(c);return n}}listen(t,e,n={}){n.shouldUpgradeCallback&&(n={overrideShouldUpgradeCallback:!1,...n});const r=i(n);n.socketTimeout&&r.setTimeout(n.socketTimeout);const s=this.attach(r,n),o=Object.assign(r,{closeWithTimeout:(t,e)=>new Promise(n=>{r.close(()=>n()),s(t,e,!0)})});return new Promise((i,s)=>{r.once("error",s),r.listen(t,e,n.backlog??511,()=>{r.off("error",s),i(o)})})}Nt(t,e,n,i){const r={error:e,server:t,action:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r}))&&at(e,n,i)}}const ue=t=>wt(t)?.C??X(t),he=t=>ue(t).search,le=t=>new URLSearchParams(ue(t).searchParams),de=(t,e)=>ue(t).searchParams.get(e);function we(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function pe(t){const e=t.headers.authorization;if(!e)return;const[n,i]=we(e," ");return void 0!==i?[n.trim().toLowerCase(),i.trim()]:void 0}function me(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function ye(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:xe(e)}:{}}function ge(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const s=t.headers.range;if(!s||0===e)return;const[o,c]=we(s,"=");if("bytes"!==o||!c)return;const a=new st(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=_e(t);if(void 0===e)throw a;return e},u=[];for(const t of c.split(",")){const[i,r]=we(t.trim(),"-");if(void 0===r)throw a;let s;if(i)s={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw a;s={start:Math.max(e-f(r),0),end:e-1}}if(!(s.start>=e)){if(s.end<s.start||u.length>=n)throw a;u.push(s)}}if(!u.length)throw a;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw a;if(u.length>r)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw a}}return{ranges:u,totalSize:e}}function be(t){if(void 0!==t)return"number"==typeof t?[String(t)]:t.length?"string"==typeof t?t.split(",").map(t=>t.trim()):t.flatMap(t=>t.split(",").map(t=>t.trim())):[]}function _e(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}function ve(t){if(t)return t.split(",").map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=we(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),s="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,o=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:s,q:o}})}function Ee(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new st(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let s=i[2];'"'===s[0]&&(s=s.substring(1,s.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,s)}return e}function xe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Te=t=>"function"==typeof t?t:()=>t;class Se{Ot;constructor(t=Oe){this.Ot=Te(t)}set(t,e){Ae(t,this,e)}get(t){return Pe(t,this)}clear(t){Ne(t,this)}withValue(t){return Vt(e=>(Ae(e,this,t),At))}}const ke=(t,...e)=>{const n={Ot:n=>t(n,...e)};return t=>Pe(t,n)};function $e(t){return t.Mt||(t.Mt=new Map),t.Mt}function Ae(t,e,n){$e(pt(t)).set(e,n)}function Pe(t,e){const n=wt(t);if(!n)return e.Ot(t);const i=$e(n);if(i.has(e))return i.get(e);const r=e.Ot(t);return i.set(e,r),r}function Ne(t,e){const n=wt(t);n?.Mt?.delete(e)}const Oe=()=>{throw new Error("property has not been set")};function Me({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:s}){const o=Te(t);return Vt(async t=>{const c=Date.now(),a=await o(t),f={"www-authenticate":`Bearer realm="${a}"`},u=pe(t),h="bearer"===u?.[0]?u[1]:await(n?.(t));if(!h)throw new st(401,{headers:f,body:"no token provided"});const l=await e(h,a,t);if(!l)throw new st(401,{headers:f,body:"invalid token"});if("object"==typeof l){if("nbf"in l&&"number"==typeof l.nbf&&c<1e3*l.nbf)throw new st(401,{headers:f,body:"token not valid yet"});if("exp"in l&&"number"==typeof l.exp){const e=1e3*l.exp;if(c>=e-r)throw new st(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r=at)=>{const s=pt(t),o=n-Math.max(i,0),c=s.tt??Number.POSITIVE_INFINITY,a=s.et?.nt??c;o>=a&&n>=c||(n<c&&(s.tt=n),o<a&&(s.et={nt:o,K:e,X:r}),vt(s))})(t,"token expired",e,r,s)}}return Ue.set(t,{realm:a,data:l,scopes:Be(l)}),At})}const Re=t=>Ue.get(t).data,Fe=(t,e)=>Ue.get(t).scopes.has(e),Ce=t=>Vt(e=>{const n=Ue.get(e);if(!n.scopes.has(t))throw new st(403,{headers:{"www-authenticate":`Bearer realm="${n.realm}", scope="${t}"`},body:`scope required: ${t}`});return At}),Ue=/*@__PURE__*/new Se({realm:"",data:null,scopes:new Set});function Be(t){if(!t||"object"!=typeof t||!("scopes"in t))return new Set;const{scopes:e}=t;return Array.isArray(e)?new Set(e):"string"==typeof e?new Set([e]):e&&"object"==typeof e?new Set(Object.entries(e).filter(([t,e])=>e).map(([t])=>t)):new Set}function Ie(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${h("sha256").update(n).digest("base64").substring(0,12)}"`}async function je(t){const e=h("sha256");return"string"==typeof t?await d(c(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const De=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),He={mime:"accept",language:"accept-language",encoding:"accept-encoding"},qe={zstd:"{file}.zst",br:"{file}.br",gzip:"{file}.gz",deflate:"{file}.deflate",identity:"{file}"},Le=t=>{return{type:"encoding",options:(e=t,n=qe,Array.isArray(e)?e.map(t=>[t,n[t]]):Object.entries(e)).map(([t,e])=>({match:t,file:e}))};var e,n};function ze(t,e=10){const n=t.map(t=>({Rt:t.type,Ft:t.options.map(t=>({Ct:t.file,Ut:"string"==typeof t.match?t.match.toLowerCase():De(t.match,!0),Bt:t.as??("string"==typeof t.match?t.match:void 0)}))})).filter(t=>t.Ft.length>0);return{options(t,i){let r=e;const s={},o={mime:We(i.mime),language:We(i.language),encoding:We(i.encoding)};return function*t(e,i){const c=n[i];if(!c)return--r,void(yield{filename:e,info:s});const a=new Set,f=o[c.Rt]??[];for(const n of f){const o=n.name.toLowerCase();for(const n of c.Ft)if("string"==typeof n.Ut?n.Ut===o:n.Ut.test(o)){const o=Ve(e,n.Ct);if(a.has(o))continue;if(a.add(o),s[c.Rt]=n.Bt,yield*t(o,i+1),r<=0)return}}s[c.Rt]=void 0,!a.has(e)&&r>0&&(yield*t(e,i+1))}(t,0)},vary:[...new Set(n.map(t=>He[t.Rt]))].join(" ")}}function We(t){if(t?.length)return 1===t.length?t:[...t].sort((t,e)=>e.q-t.q||e.specificity-t.specificity)}function Ve(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Je=/*@__PURE__*/Xe("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let Ge=/*@__PURE__*/new Map(Je);function Ze(){Ge=new Map(Je)}function Ke(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function Xe(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,s="",o=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),c=i+s+o,a=r.replace("{ext}",c);e.set(c.toLowerCase(),a),s&&e.set((i+o).toLowerCase(),a)}}return e}function Ye(t){for(const[e,n]of t)Ge.set(e.toLowerCase(),n)}function Qe(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ge.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}async function tn(t,e,n){const i=await E(t),r={file:t,mime:Qe(m(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(r.rawSize<=n)return r;if(["image","video","audio","font"].includes(r.mime.split("/")[0]))return r;for(const s of e){const e=rn.get(s.match),o=y(g(t),Ve(b(t),s.file));if(!e||o===s.file)continue;const c=await e(i);c.byteLength<=r.rawSize-n&&(await x(o,c),r.bestSize=Math.min(r.bestSize,c.byteLength),++r.created)}return r}async function en(t,e,n){const i=[];await nn(t,i);const r=new Set(i);for(const t of r)for(const n of e){const e=y(g(t),Ve(b(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>tn(t,e,n)))}async function nn(t,e){const n=await T(t);if(n.isDirectory())for(const n of await S(t))await nn(y(t,n),e);else n.isFile()&&e.push(t)}const rn=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["brotli",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]);class sn{It;jt;Dt;Ht;qt;Lt;zt;Wt;Vt;Jt;Gt;Zt;Kt;vary;constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:s=!1,allow:o=[".well-known"],hide:c=[],indexFiles:a=["index.htm","index.html"],implicitSuffixes:f=[],negotiation:u}){this.It=t,this.jt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Dt=n,this.Ht=i,this.qt=r,this.Lt=s,this.Jt=a,this.Zt=["",...f],this.zt=new Set(o.map(t=>this.Xt(t))),this.Wt=new Set,this.Vt=[];for(const t of c)"string"==typeof t?this.Wt.add(this.Xt(t)):this.Vt.push(De(t,!n));this.Gt=new Set(a.map(t=>this.Xt(t))),u?.length?(this.Kt=ze(u),this.vary=this.Kt.vary):this.vary=""}static async build(t,e){return new sn(await k(t,{encoding:"utf-8"})+_,e)}Xt(t){return"exact"===this.Dt?t:t.toLowerCase()}Yt(t){if(this.zt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.qt)||"."===e[0]&&!this.Ht||this.Wt.has(e)||this.Vt.some(t=>t.test(e)))}async find(t,e={}){let n=t.join(_);"force-lowercase"===this.Dt&&(n=n.toLowerCase());let i=v(this.It,n);if(!i.startsWith(this.It)&&i+_!==this.It)return null;let r=null,s=null;for(const t of this.Zt){const e=i+t;if(r=e.substring(this.It.length).split(_).filter(t=>t),r.length>this.jt+1)return null;if(r.some(t=>!this.Yt(this.Xt(t))))return null;const n=r[r.length-1]??"";if(!this.Lt&&this.Gt.has(this.Xt(n))&&!this.zt.has(this.Xt(n)))return null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){i=e;break}}if(!s||!r)return null;if(this.Xt(s)!==this.Xt(i))return null;let o=s,c=await T(s).catch(()=>null);if(!c)return null;if(c.isDirectory()){if(r.length>this.jt)return null;for(const t of this.Jt){const e=y(s,t);if(c=await T(e).catch(()=>null),c?.isFile()){o=e;break}}}if(!c?.isFile())return null;if(this.Kt){const t=b(o),n=g(o);for(const i of this.Kt.options(t,e)){if(!i.filename||i.filename.includes(_))continue;const t=await cn({canonicalPath:o,negotiatedPath:y(n,i.filename),...i.info});if(t)return t}}return cn({canonicalPath:o,negotiatedPath:o})}async precompute(){const t=new Map,e=(e,n)=>{const i=t.get(e);(!i||n.p>i.p)&&t.set(e,n)},n=new V({dir:[this.It],depth:0});for(const{dir:t,depth:i}of n){const r=await S(y(...t),{withFileTypes:!0,encoding:"utf-8"}),s=new Set(r.map(t=>this.Xt(t.name)));for(const o of r){const r=this.Xt(o.name);if(!this.Yt(r))continue;const c=[...t,o.name];if(o.isDirectory())i<this.jt&&n.push({dir:c,depth:i+1}),e(this.Xt(c.slice(1).join("/")),on);else if(o.isFile()){const n={file:y(...c),dir:y(...t),basename:r,siblings:s},i=this.Jt.indexOf(r);if(-1!==i&&(e(this.Xt(t.slice(1).join("/")),{...n,p:this.Jt.length+1-i}),!this.Lt&&!this.zt.has(r)))continue;const a=this.Xt(c.slice(1).join("/"));for(let t=0;t<this.Zt.length;++t){const i=this.Zt[t];o.name.endsWith(i)&&e(a.substring(0,a.length-i.length),{...n,p:-t})}}}}return{find:async(e,n={})=>{const i=t.get(this.Xt(e.join("/")));if(!i?.file)return null;if(this.Kt)for(const t of this.Kt.options(i.basename,n)){if(!i.siblings.has(this.Xt(t.filename)))continue;const e=await cn({canonicalPath:i.file,negotiatedPath:y(i.dir,t.filename),...t.info});if(e)return e}return cn({canonicalPath:i.file,negotiatedPath:i.file})},vary:this.vary}}}const on={file:"",dir:"",basename:"",siblings:new Set,p:1};async function cn(t){const e=await $(t.negotiatedPath,a.O_RDONLY).catch(()=>null);if(!e)return null;const n=()=>(e.close().catch(()=>{}),null),i=await e.stat().catch(n);return i?.isFile()?{handle:e,stats:i,...t}:n()}const an=/*@__PURE__*/ke(async t=>{const e=St(t);if(e.aborted)throw $t;e.throwIfAborted();const n=await A(y(N(),"upload"));Tt(t,()=>P(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw $t;return y(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),s=f(i,{mode:n});try{return await d(t,s,{signal:e}),{path:i,size:s.bytesWritten}}finally{s.close()}}}});function fn(t){const e=pt(t);if(!e.L)throw new Error("cannot call acceptBody from shouldUpgrade");if(e.I.signal.aborted)throw $t;e.Qt||e.H||(e.Qt=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.L.W.writeContinue())}function un(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["connection","keep-alive","transfer-encoding"],responseHeaders:o=[],agent:c,keepAlive:a=!0,maxSockets:f=10,...u}={}){let h;t.startsWith("https://")?(c??=new M({keepAlive:a,maxSockets:f,...u}),h=s):(c??=new r({keepAlive:a,maxSockets:f,...u}),h=R);const l=t.endsWith("/")?t:t+"/";return zt((r,s)=>new Promise((a,f)=>{const u=St(r),w=t=>f(u.aborted?$t:new st(502,{cause:t})),p=new URL(l+r.url?.substring(1)),m=p.toString();if(!m.startsWith(l)&&m!==t)return f(new st(400,{message:"directory traversal blocked"}));fn(r);let y={...r.headers};hn(y,e);for(const t of n)y=t(r,y);const g=h(p,{agent:c,method:r.method,headers:y,signal:u});g.once("error",w),g.once("response",t=>{if(!s.headersSent){let e={...t.headers};hn(e,i);for(const n of o)e=n(r,t,e);s.writeHead(t.statusCode??200,t.statusMessage,e)}d(t,s).then(a,f)}),d(r,g).catch(w)}))}function hn(t,e){for(const e of be(t.connection)??[])delete t[e.toLowerCase()];for(const n of e)delete t[n]}function ln({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?q(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),s=new Set(n);return ke(t=>{const e=e=>{if(s.has(e))return be(t.headers[e])?.reverse()},n=e("forwarded"),o=e("x-forwarded-for"),c=e("x-forwarded-host"),a=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),h=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),l=[dn(t)];if(n)for(const t of n)try{const e=Ee(t);l.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{l.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(o){const t=o.map(H),e=c??[],n=a??f??u??[];let i=l[0].client;for(let r=0;r<t.length;++r){const s=t[r];l.push({client:s,server:h?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=s}}else if(h)for(const t of h)l.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+r,l.length);for(let t=0;t<d-1;++t)i(l[t].client)||(d=t+1);return Object.freeze({trusted:l.slice(0,d),untrusted:l.slice(d),outwardChain:l,edge:l[d-1]})})}const dn=t=>({client:{...H(t.socket.remoteAddress)??wn,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??wn,port:t.socket.localPort},host:t.headers.host,proto:void 0}),wn={type:"alias",ip:"_disconnected",port:void 0};function pn(t,e){return delete e.forwarded,delete e["x-forwarded-for"],delete e["x-forwarded-host"],delete e["x-forwarded-proto"],delete e["x-forwarded-protocol"],delete e["x-url-scheme"],e}function mn(t,e){const n=pn(0,e);return n.forwarded=bn([dn(t)]),n}const yn=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=pn(0,i),s=t(n);return r.forwarded=bn([...e?s.trusted:s.outwardChain].reverse()),r};function gn(t,e){let n=t.headers.forwarded;const i=bn([dn(t)]);n?n+=", "+i:n=i;const r=pn(0,e);return r.forwarded=n,r}function bn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.ip,by:t.server?.ip,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}class _n{te;ee;ne;ie;re;constructor(t,{fatal:e=!1}={}){this.te=t,this.ee=e,this.ne=new Uint8Array(4),this.ie=new DataView(this.ne.buffer),this.re=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,i=[];let r=0;if(this.re>0){if(r=4-this.re,n<r)return this.ne.set(t,this.re),this.re+=n,"";this.ne.set(t.subarray(0,r),this.re),i.push(this.ie.getUint32(0,this.te)),this.re=0}const s=new DataView(t.buffer,t.byteOffset,t.byteLength);let o=r;for(const t=n-3;o<t;o+=4)i.push(s.getUint32(o,this.te));if(e)o<n&&this.ne.set(t.subarray(o)),this.re=n-o;else if(this.re=0,o<n){if(this.ee)throw new Error("invalid byte length for utf-32 content");i.push(65533)}return i.length>0?String.fromCodePoint(...i):""}}class vn extends F{constructor(t){super({transform(e,n){try{const i=t.decode(e,{stream:!0});i&&n.enqueue(i)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(K);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const En=new Map;function xn(t,e){En.set(t.toLowerCase(),e)}function Tn(){xn("utf-32be",{decoder:t=>new _n(!1,t)}),xn("utf-32le",{decoder:t=>new _n(!0,t)})}function Sn(t,e={}){const n=En.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new st(415,{body:`unsupported charset: ${t}`})}}function kn(t,e={}){const n=En.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new vn(n.decoder(e));try{return new C(t,e)}catch{throw new st(415,{body:`unsupported charset: ${t}`})}}const $n=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function An(t,e,n){const i=xe(t.headers["if-modified-since"]),r=be(t.headers["if-none-match"]);if(r){if(Nn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function Pn(t,e,n){let i=!0;const r=ye(t);return r.etag&&(i&&=Nn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function Nn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Ie(t.getHeader("content-encoding"),e))}class On extends F{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function Mn(t,{maxExpandedLength:e=Number.POSITIVE_INFINITY,maxContentLength:n=e,maxEncodingSteps:i=1}={}){const r=_e(t.headers["content-length"]);if(void 0!==r&&r>n)throw new st(413);const s=be(t.headers["content-encoding"])??[];if(s.length>i)throw new st(415,{body:"too many content-encoding stages"});fn(t);let o=I.toWeb(t);void 0===r&&Number.isFinite(n)&&(o=o.pipeThrough(new On(n,new st(413))));for(const t of s.reverse())o=o.pipeThrough(Un(t));return Number.isFinite(e)&&(o=o.pipeThrough(new On(e,new st(413,{body:"decoded content too large"})))),o}function Rn(t,e={}){const n=Mn(t,e),i=me(t)??e.defaultCharset??"utf-8";return n.pipeThrough(kn(i,e))}async function Fn(t,e={}){const n=[];for await(const i of Rn(t,e))n.push(i);return n.join("")}async function Cn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,s=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],s=null;break}if(s=t.value,s.byteLength>=e){i.set(s.subarray(0,e),r);break}i.set(s,r),r+=s.byteLength}const o=$n[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!o)throw n.cancel(),new st(415,{body:"invalid JSON encoding"});const c=kn(o,e),a=c.writable.getWriter();return r&&a.write(i.subarray(0,r)),s&&a.write(s),n.releaseLock(),a.releaseLock(),t.pipeThrough(c)})(Mn(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Un(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new U("gzip");case"deflate":return new U("deflate");case"br":try{return new U("brotli")}catch{return j.toWeb(w.createBrotliDecompress())}case"zstd":try{return j.toWeb(w.createZstdDecompress())}catch{throw new st(415,{body:"unsupported content encoding"})}default:throw new st(415,{body:"unknown content encoding"})}}function Bn(t){if(!t)return null;const[e,n]=we(t,";"),i=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const r=e[1].toLowerCase(),s=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";i.has(r)||i.set(r,s)}}return{mime:e.trim().toLowerCase(),params:i}}function In(t,e,n,i){const r=t.byteLength;for(;e<r;){for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)break;if(59!==t[e++])return!1;for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)return!1;const s=e;for(;e<r;++e){const n=t[e];if(!Hn[n]){if(61===n)break;return!1}}if(e===r)return!1;const o=t.subarray(s,e),c=jn.decode(o).toLowerCase();if(42===o[o.byteLength-1]){const i=++e;for(;e<r;++e){const n=t[e];if(!Ln[n]){if(39!==n)return!1;break}}if(e===r)return!1;const s=Sn(jn.decode(t.subarray(i,e)));for(++e;e<r&&39!==t[e];++e);if(e===r)return!1;if(++e===r)return!1;let o=e;const a=[];for(;e<r;++e){const n=t[e];if(1!==qn[n]){if(37===n){let n,i;if(e+2<r&&-1!==(n=Wn[t[e+1]])&&-1!==(i=Wn[t[e+2]])){const r=(n<<4)+i;e>o&&a.push(s.decode(t.subarray(o,e),{stream:!0})),a.push(s.decode(Buffer.from([r]),{stream:!0})),o=(e+=2)+1;continue}return!1}break}}a.push(s.decode(t.subarray(o,e)));const f=a.join("");n.has(c)||n.set(c,f);continue}if(++e===r)return!1;if(34===t[e]){let s=++e,o=!1;const a=[];for(;e<r;++e){const n=t[e];if(92!==n){if(34===n){if(o){s=e,o=!1;continue}a.push(i.decode(t.subarray(s,e)));break}if(o&&(s=e-1,o=!1),!zn[n])return!1}else o?(s=e,o=!1):(a.push(i.decode(t.subarray(s,e),{stream:!0})),o=!0)}if(e===r)return!1;++e,n.has(c)||n.set(c,a.join(""));continue}let a=e;for(;e<r;++e){const n=t[e];if(!Hn[n]){if(e===a)return!1;break}}n.has(c)||n.set(c,i.decode(t.subarray(a,e)))}return!0}const jn=/*@__PURE__*/new TextDecoder("iso-8859-1"),Dn=[1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Hn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...Dn,0,1,0,1],33),t})(),qn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...Dn,0,1,0,1],33),t})(),Ln=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...Dn,1,0,1,1],33),t})(),zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),Wn=/*@__PURE__*/(()=>{const t=new Int8Array(256).fill(-1);for(let e=0;e<10;++e)t[48+e]=e;for(let e=0;e<6;++e)t[65+e]=e+10,t[97+e]=e+10;return t})();class Vn{se;oe;ce;ae;fe;constructor(t,e){const n=t.byteLength;if(!n||n>65535)throw new Error("invalid needle");this.se=t,this.oe=e,this.ce=null,this.ae=0,this.fe=null}push(t){let e=0;const n=t.byteLength,i=this.se,r=i.byteLength-1,s=n-r;let o=-this.ae;if(this.ae){const c=this.fe,a=this.ce,f=i[r];if(s>0){const n=t[o+r];n!==f||t.compare(i,-o,r,0,o+r)?o+=c[n]:(this.oe(!0,K,0,0,!0),this.ae=0,e=o+=r+1)}const u=s<0?s:0;for(;o<u;){const n=t[o+r];if(n===f&&!a.compare(i,0,-o,this.ae+o,this.ae)&&!t.compare(i,-o,r,0,o+r)){this.oe(!0,a,0,this.ae+o,!1),this.ae=0,e=o+=r+1;break}o+=c[n]}const h=this.ae;if(h>0){const e=i[0];for(;o<0;){const r=a.indexOf(e,h+o);if(-1===r){o=0;break}const s=h-r;if(!a.compare(i,1,s,r+1,h)&&!t.compare(i,s,s+n))return r&&(this.oe(!1,a,0,r,!1),a.copy(a,0,r,s)),a.set(t,s),void(this.ae+=n-r);o=r+1-h}this.oe(!1,a,0,h,!1),this.ae=0}}for(;o<s;){const n=t.indexOf(i,o);if(-1!==n){if(this.oe(!0,t,e,n,!0),n===s+1)return;e=o=n+r+1}else o=s}const c=i[0];for(;o<n;){const s=t.indexOf(c,o);if(-1===s)return void this.oe(!1,t,e,n,!0);if(!t.compare(i,1,n-s,s+1)){if(!this.ce){this.ce=Buffer.allocUnsafe(r),this.fe=new Uint16Array(256).fill(r+1);for(let t=0;t<r;++t)this.fe[i[t]]=r-t}return t.copy(this.ce,0,s),this.ae=n-s,void(s>e&&this.oe(!1,t,e,s,!0))}o=s+1}n>e&&this.oe(!1,t,e,n,!0)}destroy(){const t=this.ae;t&&this.ce&&this.oe(!1,this.ce,0,t,!1),this.ae=0}}class Jn extends D{ue;he;le;de;we;pe;me;constructor({limits:t={},preservePath:e,highWaterMark:n,fileHwm:i,defParamCharset:r="utf-8",defCharset:s="utf-8"},o){super({autoDestroy:!0,emitClose:!0,highWaterMark:n});const c=o.get("boundary");if(!c)throw new st(400,{body:"Multipart: Boundary not found"});const a=Sn(r),f={autoDestroy:!0,emitClose:!0,highWaterMark:i},u=t.fieldSize??1048576,h=t.fileSize??Number.POSITIVE_INFINITY,l=t.fieldNameSize??100,d=t.files??Number.POSITIVE_INFINITY,w=t.fields??Number.POSITIVE_INFINITY,p=t.parts??Number.POSITIVE_INFINITY;let m=-1,y=0,g=0,b=!1;this.pe=0,this.de=!1;let _,v,E,x,T,S=0,k=0,$=!1,A=!1,P=!1,N=!1;const O=new Zn(t=>{this.we=void 0,b=!1,x="text/plain";let n,i=s;E="7bit",T=void 0,$=!1,A=!1;const r=t["content-disposition"]?.[0];if(!r)return void(b=!0);const o=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let i=0;for(;i<t.byteLength;++i)if(!Hn[t[i]]){if(!In(t,i,n,e))return null;break}return{type:jn.decode(t.subarray(0,i)).toLowerCase(),params:n}})(r,a);if("form-data"!==o?.type)return void(b=!0);o.params&&(T=o.params.get("name")??"",T.length>l&&(T=T.substring(0,l),$=!0),n=o.params.get("filename*")??o.params.get("filename"),void 0===n||e||(n=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(n)));const c=t["content-type"]?.[0];if(c){const t=Bn(jn.decode(c));t&&(x=t.mime,i=t.params.get("charset")?.toLowerCase()??s)}v=Sn(i);const u=t["content-transfer-encoding"]?.[0];if(u&&(E=jn.decode(u).toLowerCase()),"application/octet-stream"===x||void 0!==n){if(g===d)return P||(P=!0,this.emit("filesLimit")),void(b=!0);if(++g,0===this.listenerCount("file"))return void(b=!0);S=0,this.le=new Kn(f,this),++this.pe,this.emit("file",T,this.le,{nameTruncated:$,filename:n,encoding:E,mimeType:x})}else{if(y===w)return N||(N=!0,this.emit("fieldsLimit")),void(b=!0);if(++y,0===this.listenerCount("field"))return void(b=!0);_=[],k=0}});let M=0;const R=Buffer.from(`\r\n--${c}`,"latin1");this.ue=new Vn(R,(t,e,n,i,r)=>{const s=(t,n)=>{if(r)return e.subarray(t,n);const i=Buffer.allocUnsafe(n-t);return e.copy(i,0,t,n),i};for(;n!==i;){if(this.we){const t=this.we.push(e,n,i,r);if(-1===t){this.we=void 0,O.reset(),this.emit("error",new Error("Malformed part header"));break}if(t===i)break;n=t}if(M){if(1===M){switch(e[n]){case 45:M=2,++n;break;case 13:M=3,++n;break;default:M=0}if(n===i)return}if(2===M){if(M=0,45===e[n])return this.de=!0,void(this.ue=Xn)}else if(3===M&&(M=0,10===e[n])){if(++n,m>=p)break;this.we=O;continue}}if(!b)if(this.le){const t=s(n,Math.min(i,n+h-S));S+=t.byteLength,S===h?(t.length>0&&this.le.push(t),this.le.emit("limit"),this.le.truncated=!0,b=!0):this.le.push(t)||(this.he&&(this.le.ye=this.he),this.he=void 0)}else if(_){const t=s(n,Math.min(i,n+u-k));k+=t.byteLength,_.push(v.decode(t)),k===u&&(b=!0,A=!0)}break}if(t){if(M=1,this.le)this.le.push(null),this.le=void 0;else if(_){const t=_.join("");_=void 0,k=0,this.emit("field",T,t,{nameTruncated:$,valueTruncated:A,encoding:E,mimeType:x})}++m===p&&this.emit("partsLimit")}}),this.write(Yn)}ge(t,e,n){this.he=n,this.ue.push(t);const i=this.he;i&&(this.he=void 0,i())}be(t,e){this.we=void 0,this.ue=Xn,t??=this._e();const n=this.le;n&&(this.le=void 0,n.destroy(t??void 0)),e(t)}ve(t){if(this.ue.destroy(),!this.de)return t(new Error("Unexpected end of form"));this.pe?this.me=()=>t(this._e()):t(this._e())}_e(){if(this.we)return new Error("Malformed part header");const t=this.le;return t&&(this.le=void 0,t.destroy(new Error("Unexpected end of file"))),this.de?null:new Error("Unexpected end of form")}}const Gn=16384;class Zn{Ee;xe;Te;m;ht;Se;ke;oe;constructor(t){this.Ee=Object.create(null),this.xe=0,this.Te=0,this.m=0,this.ht=[],this.Se=[],this.ke=0,this.oe=t}reset(){this.Ee=Object.create(null),this.xe=0,this.Te=0,this.m=0,this.ht.length=0,this.Se.length=0,this.ke=0}push(t,e,n,i){let r=e;t:for(;e<n;)switch(this.m){case 0:for(;e<n;++e){if(this.Te===Gn)return-1;++this.Te;const n=t[e];if(!Hn[n]){if(58!==n)return-1;if(e>r&&this.ht.push(jn.decode(t.subarray(r,e))),!this.ht.length)return-1;++e,this.m=1;continue t}}e>r&&this.ht.push(jn.decode(t.subarray(r,e)));break;case 1:for(;e<n;++e){if(this.Te===Gn)return-1;++this.Te;const n=t[e];if(32!==n&&9!==n){r=e,this.m=2;continue t}}break;case 2:switch(this.ke){case 0:for(;e<n;++e){if(this.Te===Gn)return-1;++this.Te;const n=t[e];if(n<32||127===n){if(13!==n)return-1;++this.ke;break}}if(i)this.Se.push(t.subarray(r,e));else{const n=Buffer.allocUnsafe(e-r);t.copy(n,0,r,e),this.Se.push(n)}++e;break;case 1:if(this.Te===Gn)return-1;if(++this.Te,10!==t[e++])return-1;++this.ke;break;case 2:{if(this.Te===Gn)return-1;++this.Te;const n=t[e];if(32===n||9===n)r=e,this.ke=0;else{if(++this.xe<2e3){const t=this.ht.join("").toLowerCase(),e=Buffer.concat(this.Se),n=this.Ee[t];n?n.push(e):this.Ee[t]=[e]}13===n?(++this.ke,++e):(r=e,this.ke=0,this.m=0,this.ht.length=0,this.Se.length=0)}break}case 3:{if(this.Te===Gn)return-1;if(++this.Te,10!==t[e++])return-1;const n=this.Ee;return this.reset(),this.oe(n),e}}}return e}}class Kn extends I{ye;truncated;constructor(t,e){super(t),this.truncated=!1,this.once("end",()=>{if(this.$e(),0===--e.pe&&e.me){const t=e.me;e.me=void 0,process.nextTick(t)}})}$e(){const t=this.ye;t&&(this.ye=void 0,t())}}const Xn={push:()=>{},destroy:()=>{}},Yn=/*@__PURE__*/Buffer.from("\r\n");class Qn extends D{Ae;Pe;Ne;Oe;Me;Re;Fe;Ce;Ue;Be;Ie;je;De;He;qe;constructor({limits:t={},highWaterMark:e,defCharset:n="utf-8"},i){super({autoDestroy:!0,emitClose:!0,highWaterMark:e}),this.Ae=i.get("charset")??n,this.Pe=t.fieldSize??1048576,this.Ne=t.fields??Number.POSITIVE_INFINITY,this.Oe=t.fieldNameSize??100,this.Me=!0,this.Re=!1,this.Fe=!1,this.Ce=0,this.Ue=0,this.Be=0,this.Ie=[],this.je=[],this.De=-2,this.He=0,this.qe=Sn(this.Ae)}Le(t,e){const n=this.Me?this.Ie:this.je,i=this.qe.decode(t,{stream:!e});i&&n.push(i)}ge(t,e,n){if(this.Be>=this.Ne)return n();let i=0;const r=t.length;if(this.He=0,-2!==this.De){if(i=this.ze(t,i,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();this.Me?++this.Ce:++this.Ue}t:for(;i<r;)if(this.Me){for(i=this.We(t,i,r);i<r;){switch(t[i]){case 61:this.Le(t.subarray(this.He,i),!0),this.He=++i,this.Me=!1;continue t;case 38:if(this.Le(t.subarray(this.He,i),!0),this.He=++i,this.Ie.length>0&&(this.emit("field",this.Ie.join(""),"",{nameTruncated:this.Re,valueTruncated:!1,encoding:this.Ae,mimeType:"text/plain"}),this.Ie.length=0),this.Re=!1,this.Ce=0,++this.Be>=this.Ne)return this.emit("fieldsLimit"),n();continue;case 43:this.He<i&&this.Le(t.subarray(this.He,i),!1),this.Le(ti,!1),this.He=i+1;break;case 37:if(this.He<i&&this.Le(t.subarray(this.He,i),!1),this.He=i+1,this.De=-1,i=this.ze(t,i+1,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();++this.Ce,i=this.We(t,i,r);continue}++i,++this.Ce,i=this.We(t,i,r)}this.He<i&&this.Le(t.subarray(this.He,i),!1)}else{for(i=this.Ve(t,i,r);i<r;){switch(t[i]){case 38:if(this.Le(t.subarray(this.He,i),!0),this.He=++i,this.Me=!0,this.emit("field",this.Ie.join(""),this.je.join(""),{nameTruncated:this.Re,valueTruncated:this.Fe,encoding:this.Ae,mimeType:"text/plain"}),this.Ie.length=0,this.je.length=0,this.Re=!1,this.Fe=!1,this.Ce=0,this.Ue=0,++this.Be>=this.Ne)return this.emit("fieldsLimit"),n();continue t;case 43:this.He<i&&this.Le(t.subarray(this.He,i),!1),this.Le(ti,!1),this.He=i+1;break;case 37:if(this.He<i&&this.Le(t.subarray(this.He,i),!1),this.He=i+1,this.De=-1,i=this.ze(t,i+1,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();++this.Ue,i=this.Ve(t,i,r);continue}++i,++this.Ue,i=this.Ve(t,i,r)}this.He<i&&this.Le(t.subarray(this.He,i),!1)}n()}ve(t){if(-2!==this.De)return t(new Error("Malformed urlencoded form"));this.Le(K,!0),(!this.Me||this.Ie.length>0)&&this.emit("field",this.Ie.join(""),this.Me?"":this.je.join(""),{nameTruncated:this.Re,valueTruncated:this.Fe,encoding:this.Ae,mimeType:"text/plain"}),t()}ze(t,e,n){if(e>=n)return n;if(-1===this.De){const i=Wn[t[e++]];if(-1===i)return-1;if(e<n){const n=Wn[t[e++]];if(-1===n)return-1;this.Le(Buffer.from([(i<<4)+n]),!1),this.De=-2,this.He=e}else this.De=i}else{const n=Wn[t[e++]];if(-1===n)return-1;this.Le(Buffer.from([(this.De<<4)+n]),!1),this.De=-2,this.He=e}return e}We(t,e,n){if(this.Ce>this.Oe){for(this.Re||this.He<e&&this.Le(t.subarray(this.He,e-1),!1),this.Re=!0;e<n;++e){const n=t[e];if(61===n||38===n)break}this.He=e}return e}Ve(t,e,n){if(this.Ue>this.Pe){for(this.Fe||this.He<e&&this.Le(t.subarray(this.He,e-1),!1),this.Fe=!0;e<n&&38!==t[e];++e);this.He=e}return e}}const ti=/*@__PURE__*/Buffer.from(" ","utf-8");function ei(t,{closeAfterErrorDelay:e=500,...n}={}){const i=((t,e={})=>{const n=t["content-type"];if(!n)throw new st(400,{body:"Missing Content-Type"});const i=Bn(n);if(!i)throw new st(400,{body:"Malformed content type"});const r="application/x-www-form-urlencoded"===i.mime?Qn:"multipart/form-data"!==i.mime||e.blockMultipart?null:Jn;if(!r)throw new st(415);return new r(e,i.params)})(t.headers,n);fn(t);const r=new J,s=(n,s)=>{if(r.fail(new st(n,s)),i.removeAllListeners(),t.unpipe(i),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};i.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:o,mimeType:c})=>t?n?s(400,{body:`field name ${JSON.stringify(t)}... too long`}):i?s(400,{body:`value for ${JSON.stringify(t)} too long`}):void r.push({name:t,encoding:o,mimeType:c,type:"string",value:e}):s(400,{body:"missing field name"})),i.on("file",(t,e,{nameTruncated:n,filename:i,encoding:o,mimeType:c})=>t?n?s(400,{body:`field name ${JSON.stringify(t)}... too long`}):void(i?(e.once("limit",()=>s(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(i)} too large`})),r.push({name:t,encoding:o,mimeType:c,type:"file",value:e,filename:i})):e.resume()):s(400,{body:"missing field name"})),t.once("error",e=>{t.readableAborted?r.fail($t):s(500,{body:"request error",headers:{connection:"close"},cause:e})}),i.once("error",t=>s(400,{body:"error parsing form data",cause:t})),i.once("partsLimit",()=>s(400,{body:"too many parts"})),i.once("filesLimit",()=>s(400,{body:"too many files"})),i.once("fieldsLimit",()=>s(400,{body:"too many fields"}));const o=()=>r.close("complete");return i.once("close",o),Tt(t,o),t.pipe(i),r}async function ni(t,e={}){const n=new FormData,i=new Map;for await(const r of ei(t,e))if("file"===r.type){const s=r.value;let o=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const c=t=>{if("function"==typeof o){const e=o;return o=void 0,e({actualBytes:t})}};Tt(t,()=>c(0));const a=await an(t),f=await a.save(s,{mode:384});await c(f.size);const h=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(h,f.path),n.append(r.name,h)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new Error("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const ii="win32"===/*@__PURE__*/O();function ri(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=wt(t);if(i){if("/"===i.U)return[];n=i.U.split("/")}else{const e=X(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new Error("invalid path");if(n.shift(),e){const t=ii?oi:si;if(n.some(e=>t.test(e)||e.includes(_)))throw new Error("invalid path");if(n.slice(0,n.length-1).includes(""))throw new Error("invalid path")}return n}const si=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,oi=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,ci=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof o?t.write(K,n):t.once("drain",n),t.uncork()});async function ai(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:s="utf-8",headerRow:c,end:a=!0}={}){"string"==typeof n&&(n=Buffer.from(n,s)),"string"==typeof i&&(i=Buffer.from(i,s));const f="string"==typeof r?Buffer.from(r,s):r,u=r+r,h=e=>{if(!e)return!0;const n=e.includes(r);return!n&&fi.test(e)?t.write(e,s):(t.write(f),n?t.write(e.replaceAll(r,u),s):t.write(e,s),t.write(f))};t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+s+(c?"; header=present":!1===c?"; header=absent":"")),t.cork();try{t.write(K);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),h(i)||await ci(t),++e;else for await(const i of r)e&&t.write(n),h(i)||await ci(t),++e;t.write(i)||await ci(t)}}finally{t.uncork()}a&&t.end()}const fi=/^[^"':;,\\\r\n\t ]*$/i;function ui(t){if(!t||"object"!=typeof t)return!1;const e=t;return"number"==typeof e.fd&&"function"==typeof e.stat&&"function"==typeof e.createReadStream}class hi{lt;Je;Ge;m;constructor(t){(t=>{const e=t;return"function"==typeof e.$e&&"function"==typeof e.pipe})(t)&&(t=I.toWeb(t)),this.lt=t.getReader(),this.Je=null,this.Ge=0,this.m=0}getRange(t,e){if(e<t)throw new Error("invalid range");if(t<this.Ge)throw new Error("non-sequential range");if(this.m)throw new Error("previous range still active");let n=e-t+1,i=t-this.Ge;this.Ge=e+1,this.m=1;const r=this,s=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.Je=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new B({start(t){if(r.Je){const e=r.Je;r.Je=null,s(e,t)}},async pull(t){if(n<=0)return r.m=0,void t.close();const e=await r.lt.read();e.done?t.error(new Error("range exceeds content")):"string"==typeof e.value?s(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?s(e.value,t):t.error(new Error("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.lt.cancel(),this.lt.releaseLock()}}function li(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let s=0;s<i.length;++s){const o=i[s];e.end>=o.start-n-1&&o.end>=e.start-n-1?t?(++r,t.start=Math.min(t.start,o.start),t.end=Math.max(t.end,o.end)):(t=o,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):r>0&&(i[s-r]=o)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function di(t,e,n,i){if("string"==typeof n||ui(n)||(i=li(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const s=await wi(n);return await d(s.Ze(r.start,r.end),e),void(s.Ke&&await s.Ke())}const r=e.getHeader("content-type"),s=l()+l()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${s}`);const o=i.ranges.map(t=>({t:[`--${s}`,...nt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Xe:t})),c=`--${s}--`;let a=c.length;for(const{t,Xe:e}of o)a+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",a),"HEAD"===t.method)return void e.end();let f="";const u=await wi(n);try{for(const{t,Xe:n}of o)e.write(f+t,"ascii"),await d(u.Ze(n.start,n.end),e,{end:!1}),f="\r\n";e.end(f+c)}finally{u.Ke&&await u.Ke()}}async function wi(t){if("string"==typeof t){const e=await $(t,"r");return{Ze:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ke:()=>e.close()}}if(ui(t))return{Ze:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new hi(t);return{Ze:(t,n)=>e.getRange(t,n),Ke:()=>e.close()}}}async function pi(t,e,n,i,r){if(i||("string"==typeof n?i=await T(n):ui(n)&&(i=await n.stat())),i){if("GET"===t.method||"HEAD"===t.method){if(!An(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const s=ge(t,i.size,r);if(s&&Pn(t,e,i))return di(t,e,n,li(s,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=c(n):ui(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}function mi(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){const a=JSON.stringify(e,n,i)??(r?"null":void 0);t instanceof o&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),c&&t.setHeader("content-length",Buffer.byteLength(a,s))),c?t.end(a,s):a&&t.write(a,s)}async function yi(t,e,{replacer:n=null,space:i="",undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof i&&(i=" ".substring(0,i));const a={ge:e=>t.write(e,s),Ye:()=>ci(t),Qe:n,tn:i};if(t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=bi(null,"",e,a),_i(e))r&&a.ge("null");else{t.cork(),t.write(K);try{await gi(a,e,i?"\n":"")}finally{t.uncork()}}c&&t.end()}async function gi(t,e,n){const i=(i,r,s)=>{t.ge(i);const o=n+t.tn,c=t.tn?": ":":";let a=!0;return{u:async(n,i)=>{const r=bi(e,n,i,t);s&&_i(r)||(a?a=!1:t.ge(","),t.ge(o),s&&(t.ge(JSON.stringify(n))||await t.Ye(),t.ge(c)),await gi(t,r,o))},Ke:()=>{a||t.ge(n),t.ge(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||vi(e))t.ge(JSON.stringify(e)??"null")||await t.Ye();else if(e instanceof I){t.ge('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.ge(e.substring(1,e.length-1))||await t.Ye()}t.ge('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.u(n,i);t.Ke()}else if(Ei(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.u(String(t++),i);n.Ke()}else if(xi(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.u(String(t++),i);n.Ke()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.u(n,i);t.Ke()}}function bi(t,e,n,i){return i.Qe&&(n=i.Qe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const _i=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,vi=t=>JSON.isRawJSON?.(t)??!1,Ei=t=>Symbol.iterator in t,xi=t=>Symbol.asyncIterator in t;class Ti{en;I;nn;rn;constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){this.en=e,this.nn=n??0,this.I=new AbortController,e.setHeader("content-type","text/event-stream"),e.setHeader("x-accel-buffering","no"),e.setHeader("cache-control","no-store"),e.writeHead(200),e.flushHeaders(),this.ping=this.ping.bind(this),this.sn(),t.once("close",()=>this.close()),mt(t,()=>this.close(i,r))}get signal(){return this.I.signal}get open(){return!this.I.signal.aborted}sn(){this.nn&&(this.rn=setTimeout(this.ping,this.nn))}ping(){!this.I.signal.aborted&&this.en.writable&&(clearTimeout(this.rn),this.en.write(":\n\n",()=>this.sn()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){if(this.I.signal.aborted)throw new Error("ServerSentEvents closed");let e;this.en.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.en.write(e)," "===n[0]?this.en.write(": "):this.en.write(":"),this.en.write(n);/[\r\n]$/.test(i)?(this.en.write(e),this.en.write(":\n")):this.en.write("\n"),n=!0}if(!n)return;clearTimeout(this.rn),this.en.write("\n",()=>e())}finally{this.en.uncork()}await new Promise(t=>{e=t}),this.sn()}async close(t=0,e=0){if(this.I.signal.aborted){if(this.en.closed)return;return new Promise(t=>this.en.once("close",t))}this.nn=0,clearTimeout(this.rn),this.I.abort(),await new Promise(n=>{if(this.en.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.en.end(`retry:${0|i}\n\n`,n)}else this.en.end(n)})}}const Si=async(t,{mode:e="dynamic",fallback:n,callback:i=ki,...r}={})=>{const s=await sn.build(v(process.cwd(),t),r);let o=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),o=t.split("/")}const a="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},f="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return At;let n=!1;const r=ri(t,a),s={mime:ve(t.headers.accept),language:ve(t.headers["accept-language"]),encoding:ve(t.headers["accept-encoding"])};let u=await f.find(r,s);if(!u&&o&&(n=!0,u=await f.find(o,s)),!u)return At;try{n&&(e.statusCode=c),e.setHeader("content-type",u.mime??Qe(m(u.canonicalPath))),u.encoding&&"identity"!==u.encoding&&e.setHeader("content-encoding",u.encoding);const r=f.vary;if(r){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+r)}await i(t,e,u,n),await pi(t,e,u.handle,u.stats)}finally{u.handle.close().catch(()=>{})}}}};function ki(t,e,n){e.setHeader("etag",Ie(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class $i extends Error{statusCode;statusMessage;constructor(t,{message:e,statusMessage:n,...i}={}){super(e,i),this.statusCode=0|t,this.statusMessage=n??"",this.name=`WebSocketError(${this.statusCode} ${this.statusMessage})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function Ai(t,{softCloseStatusCode:e=$i.GOING_AWAY,...n}={}){const i=(i,r,s)=>new Promise((o,c)=>{const a=new t({...n,noServer:!0,clientTracking:!1});a.once("wsClientError",c),a.handleUpgrade(i,r,s,t=>{a.off("wsClientError",c),o({return:t,onError:e=>{const n=G(e,$i);if(n)return void t.close(n.statusCode,n.statusMessage);const i=G(e,st)??st.INTERNAL_SERVER_ERROR,r=i.statusCode>=500?$i.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Ot(t,i)}class Pi{data;isBinary;constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new $i($i.UNSUPPORTED_DATA,{statusMessage:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new $i($i.UNSUPPORTED_DATA,{statusMessage:"expected binary"});return this.data}}class Ni{cn;detach;constructor(t,{limit:e=-1,signal:n}={}){this.cn=new J;const i=e=>{t.off("message",s),t.off("close",r),this.cn.close(new Error(e))},r=()=>i("connection closed"),s=(t,n)=>{void 0!==n?this.cn.push(new Pi(t,n)):"string"==typeof t?this.cn.push(new Pi(Buffer.from(t,"utf8"),!1)):this.cn.push(new Pi(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.cn.close(new Error("signal aborted")):2===t.readyState||3===t.readyState?this.cn.close(new Error("connection closed")):(t.on("message",s),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.cn.shift(t)}[Symbol.asyncIterator](){return this.cn[Symbol.asyncIterator]()}}function Oi(t,{timeout:e,signal:n}={}){const i=new Ni(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function Mi(t){const e=pt(t);return"GET"===t.method&&(e.H?.has("websocket")??!1)}const Ri=t=>t.headers.origin??it(t.headers["sec-websocket-origin"]),Fi=(t,e=5e3)=>async n=>{if(!Mi(n))return;const i=await t(n);let r;try{r=await Oi(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw $t;throw new $i($i.POLICY_VIOLATION,{statusMessage:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new $i($i.UNSUPPORTED_DATA,{statusMessage:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{J as BlockingQueue,At as CONTINUE,sn as FileFinder,st as HTTPError,Pt as NEXT_ROUTE,Nt as NEXT_ROUTER,Se as Property,V as Queue,Yt as Router,$t as STOP,Ti as ServerSentEvents,fe as WebListener,$i as WebSocketError,Pi as WebSocketMessage,Ni as WebSocketMessages,fn as acceptBody,Ot as acceptUpgrade,Tt as addTeardown,Vt as anyHandler,An as checkIfModified,Pn as checkIfRange,Ne as clearProperty,Nn as compareETag,tn as compressFileOffline,en as compressFilesInDir,Xe as decompressMime,xt as defer,Jt as errorHandler,Si as fileServer,G as findCause,je as generateStrongETag,Ie as generateWeakETag,St as getAbortSignal,qt as getAbsolutePath,Z as getAddressURL,Re as getAuthData,pe as getAuthorization,Cn as getBodyJson,Mn as getBodyStream,Fn as getBodyText,Rn as getBodyTextStream,me as getCharset,ni as getFormData,ei as getFormFields,ye as getIfRange,Qe as getMime,Ht as getPathParameter,Dt as getPathParameters,Pe as getProperty,de as getQuery,ge as getRange,ri as getRemainingPathComponents,he as getSearch,le as getSearchParams,Sn as getTextDecoder,kn as getTextDecoderStream,Ri as getWebSocketOrigin,Fe as hasAuthScope,gt as isSoftClosed,Mi as isWebSocketRequest,Ai as makeAcceptWebSocket,q as makeAddressTester,ln as makeGetClient,ke as makeMemo,ze as makeNegotiator,an as makeTempFileStorage,Fi as makeWebSocketFallbackTokenFetcher,Le as negotiateEncoding,Oi as nextWebSocketMessage,H as parseAddress,un as proxy,xe as readHTTPDateSeconds,_e as readHTTPInteger,Ee as readHTTPKeyValues,ve as readHTTPQualityValues,be as readHTTPUnquotedCommaSeparated,Ke as readMimeTypes,xn as registerCharset,Ye as registerMime,Tn as registerUTF32,pn as removeForwarded,mn as replaceForwarded,zt as requestHandler,Ce as requireAuthScope,Me as requireBearerAuth,Ze as resetMime,Lt as restoreAbsolutePath,yn as sanitiseAndAppendForwarded,ai as sendCSVStream,pi as sendFile,mi as sendJSON,yi as sendJSONStream,di as sendRanges,ki as setDefaultCacheHeaders,Ae as setProperty,mt as setSoftCloseHandler,gn as simpleAppendForwarded,li as simplifyRange,se as toListeners,Wt as upgradeHandler};
1
+ import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as i,Agent as r,request as s,ServerResponse as o}from"node:http";import{createReadStream as c,constants as a,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as h,randomUUID as l}from"node:crypto";import{pipeline as d}from"node:stream/promises";import w from"node:zlib";import{promisify as p}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as v,resolve as _}from"node:path";import{readFile as E,writeFile as x,stat as T,readdir as S,realpath as k,open as $,mkdtemp as A,rm as P}from"node:fs/promises";import{tmpdir as N,platform as O}from"node:os";import{Agent as M,request as R}from"node:https";import{TransformStream as F,TextDecoderStream as C,DecompressionStream as U,ReadableStream as B}from"node:stream/web";import{Readable as I,Duplex as j,Writable as D}from"node:stream";function H(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{type:"IPv4",ip:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{type:"IPv6",ip:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{type:"IPv6",ip:r[3].toLowerCase(),port:void 0};const s=/^(.*?):(\d+)$/i.exec(n);return s?.[2]?{type:"alias",ip:s[1],port:Number.parseInt(s[2])}:{type:"alias",ip:n,port:void 0}}function q(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([z(t[1])|i,i]);continue}const s=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(s?.[1]){const t=W(s[1]),e=s[2]?L>>BigInt(Number.parseInt(s[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.type){case"alias":return e.has(t.ip);case"IPv4":const r=z(t.ip);return n.some(([t,e])=>(r|e)===t);case"IPv6":const s=W(t.ip);return i.some(([t,e])=>(s|e)===t);default:return!1}}}const L=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function z(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function W(t){const e=t.split(":").map(t=>t?Number.parseInt(t,16):-1);let n=0n;for(const t of e)t<0?n<<=16n*BigInt(9-e.length):n=n<<16n|BigInt(t);return n}class V{t;i;constructor(t){const e={o:null,u:null};this.t=e,this.i=e,void 0!==t&&this.push(t)}isEmpty(){return!this.t.u}clear(){this.t.u=null,this.t.o=null,this.i=this.t}push(t){const e={o:t,u:null};this.i.u=e,this.i=e}shift(){if(!this.t.u)return null;this.t=this.t.u;const t=this.t.o;return this.t.o=null,t}remove(t){for(let e=this.t;e.u;e=e.u)if(e.u.o===t){e.u=e.u.u;break}}[Symbol.iterator](){return{next:()=>{if(!this.t.u)return{value:null,done:!0};this.t=this.t.u;const t=this.t.o;return this.t.o=null,{value:t,done:!1}}}}}class J{h;l;m;v;constructor(){this.h=new V,this.l=new V,this.m=0}push(t){if(this.m)return;const e=this.l.shift();e?(e._&&clearTimeout(e._),e.T(t)):this.h.push(t)}shift(t){return this.h.isEmpty()?this.m?Promise.reject(this.v):new Promise((e,n)=>{const i={T:e,S:n,_:null};this.l.push(i),void 0!==t&&(i._=setTimeout(()=>{this.l.remove(i),n(new Error(`Timeout after ${t}ms`))},t))}):Promise.resolve(this.h.shift())}k(t){this.v=t;for(const e of this.l)e.S(t),e._&&clearTimeout(e._)}close(t){this.m||(this.m=1,this.k(t))}fail(t){this.m||(this.m=2,this.k(t))}[Symbol.asyncIterator](){return{next:()=>this.shift().then(t=>({value:t,done:!1}),t=>{if(2===this.m)throw t;return{value:null,done:!0}})}}}function G(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return G(t.cause,e);if("error"in t)return G(t.error,e)}}function Z(t,e="http"){if(!t)throw new Error("no address");if("string"==typeof t)return t;if("IPv4"===t.family)return`${e}://${t.address}:${t.port}`;if("IPv6"===t.family)return`${e}://[${t.address}]:${t.port}`;throw new Error(`unknown address family: ${t.family}`)}const K=/*@__PURE__*/Buffer.alloc(0),X=t=>new URL("http://localhost"+(t.url??"/"));class Y extends Error{error;suppressed;constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const Q=globalThis.SuppressedError??Y;class tt{$;A;constructor(){this.$=!1}P(t){this.$?t!==this.A&&(this.A=new Q(t,this.A)):(this.A=t,this.$=!0)}N(){this.$=!1,this.A=void 0}}class et{O;M;R;constructor(t){this.O=t,this.M=Object.create(null),this.R=!1}get headersSent(){return this.R}writeHead(t,e,i){if(this.R)throw new Error("headers already sent");const r={...this.M};for(const[t,e]of(t=>{if(!t)return[];const e=[];if(Array.isArray(t)){const n=t.length;if(1&n)throw new Error("headers must be a list of alternating keys and values");for(let i=0;i<n;i+=2){const n=t[i],r=t[i+1];if("string"!=typeof n)throw new Error("invalid header name");void 0!==r&&e.push([n.toLowerCase(),r])}}else for(const[n,i]of Object.entries(t))void 0!==i&&e.push([n.toLowerCase(),i]);return e})(i))r[t]=e;return this.O.write([`HTTP/1.1 ${t} ${rt(e??n[t]??"-")}`,...nt(r),"",""].join("\r\n"),"ascii"),this.R=!0,this}write(t,e="utf-8",n){return this.O.write(t,e,n)}end(t,e="utf-8",n){return this.O.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.M[n]="string"==typeof e||"number"==typeof e?e:[...e],this}setHeaders(t){for(const[e,n]of t)this.setHeader(e,n);return this}}function nt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=it(i);t&&e.push(`${rt(n)}: ${rt(t)}`)}return e}const it=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",rt=t=>t.replaceAll(/[^ \t!-~]/g,"");class st extends Error{statusCode;statusMessage;headers;body;constructor(t,{message:e,statusMessage:i,headers:r,body:s,...o}={}){super(e??("string"==typeof s?s:void 0),o),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=r,this.body=s??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}static INTERNAL_SERVER_ERROR=new st(500);send(t,e){t.setHeaders((t=>{if(t){if(t instanceof Headers)return t;if(Array.isArray(t))return new Headers(t);{const e=t instanceof Map?[...t.entries()]:Object.entries(t);return new Headers(e.map(([t,e])=>[t,it(e)]).filter(([t,e])=>e))}}return new Headers})(this.headers));const n=Buffer.byteLength(this.body,"utf-8");t.setHeader("content-length",String(n)),t.writeHead(this.statusCode,this.statusMessage,e),t.end(this.body,"utf-8")}}const ot=(t,e,n)=>{n.headersSent?n.end():(G(t,st)??st.INTERNAL_SERVER_ERROR).send(n)},ct=(t,e,n)=>{if(n.writable){n.addListener("finish",()=>n.destroy());const e=new et(n);(G(t,st)??st.INTERNAL_SERVER_ERROR).send(e,{connection:"close"})}else n.destroy()},at=(t,e,n)=>{(G(t,st)?.statusCode??1)&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},ft=new WeakMap;function ut(t,e){const n=ft.get(t);if(n)return n;const i=X(t),r={F:t,C:i,U:decodeURIComponent(i.pathname),B:ct,I:new AbortController,j:[],D:[],H:e?dt(t):null};return ft.set(t,r),r}function ht(t,e,n,i){e||(t.H=null),t.L=n;const r=async()=>{t.I.abort(n.W.writableEnded?"complete":"client abort");const e=new tt;await lt(t.j,e,t),await lt(t.D,e,t,()=>{t.V=async e=>{try{await e()}catch(e){i(e,t.F)}}}),e.$&&i(e.A,t.F)};return n.W.closed?r():n.W.once("close",r),t}async function lt(t,e,n,i){for(;n.J;)await n.J;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.P(t)}}})().then(()=>{n.J===r&&(n.J=void 0)});n.J=r,await r}function dt(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const wt=t=>ft.get(t);function pt(t){const e=wt(t);if(!e)throw new Error("unknown request");return e}function mt(t,e){const n=wt(t);n&&yt(n,e)}function yt(t,e){t.G=e;const n=t.Z;n&&queueMicrotask(()=>Et(e,t.F,n))}const gt=t=>Boolean(wt(t)?.Z);function bt(t,e,n){if(!t.Z){if(t.L&&!t.H){const e=t.L.W;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.L?.W.once("close",()=>t.F.socket.destroy()),t.Z={K:e,X:n},Et(t.G,t.F,t.Z),_t(t)}}function vt(t){if(t.L){if(!t.H){const e=t.L.W;e.headersSent||(e.statusCode=503,e.hasHeader("connection")||e.setHeader("connection","close"))}t.L.W.end(()=>t.F.socket.destroy())}else t.F.socket.destroy()}function _t(t){if(clearTimeout(t.Y),!t.tt||t.V)return;const e=Date.now();if(e>=t.tt)return void vt(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,Et(t.G,t.F,t.Z))),void 0===t.Y&&t.D.push(()=>clearTimeout(t.Y)),t.Y=setTimeout(()=>_t(t),n-e)}async function Et(t,e,n){try{await(t?.(n.K))}catch(t){n.X(t,"soft closing",e)}}const xt=(t,e)=>{const n=pt(t);n.V?n.V(e):n.j.push(e)},Tt=(t,e)=>{const n=pt(t);n.V?n.V(e):n.D.push(e)},St=t=>pt(t).I.signal;class kt extends Error{}const $t=new kt("STOP"),At=new kt("CONTINUE"),Pt=new kt("NEXT_ROUTE"),Nt=new kt("NEXT_ROUTER");async function Ot(t,e){const n=pt(t);if(!n.L)throw new Error("cannot call acceptUpgrade from shouldUpgrade");if(!n.H)throw new Error("not an upgrade request");if(n.it)return n.rt;const i=n.L.W;if(!i.readable||!i.writable)throw $t;const r=await e(t,i,n.L.t);return n.L.t=K,n.B=r.onError,yt(n,r.softCloseHandler),n.rt=r.return,n.it=!0,r.return}const Mt=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Rt=t=>t,Ft=t=>void 0===t?void 0:""===t?[]:t.split("/"),Ct=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t);function Ut(t){const e={},n=new Map;for(const[i,r]of Object.entries(t))e[i]=!1,n.set(r,i);return t=>{const i={...e};for(let e=0;e<t.length;++e){const r=n.get(t[e]);if(!r)return[i,t.substring(e)];i[r]=!0}return[i,""]}}const Bt=/*@__PURE__*/Ut({st:"i",ot:"!"}),It=Object.freeze({});function jt(t,e,n){const i=t.F.url,r=t.U,s=t.ct??It;return t.F.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.C.search,t.U=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(s),...n]))),()=>{t.F.url=i,t.U=r,t.ct=s}}function Dt(t){return wt(t)?.ct??It}function Ht(t,e){return Dt(t)[e]}function qt(t){const e=wt(t);return e?e.C.pathname+e.C.search:t.url??"/"}function Lt(t){const e=wt(t);e&&(t.url=e.C.pathname+e.C.search)}const zt=t=>"function"==typeof t?{handleRequest:t}:t,Wt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Vt=(t,e=Kt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Jt=t=>"function"==typeof t?{handleError:t}:t,Gt=t=>"function"==typeof t?{handleRequest:t}:t,Zt=t=>"function"==typeof t?{handleUpgrade:t}:t,Kt=()=>!1,Xt=Symbol("http");class Yt{ft;ut;constructor(){this.ft=[],this.ut=[]}P(t,e,n,i,r){const s=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{st:s,ot:o},c]=Bt(t);if("/"!==c[0])throw new Error("path must begin with '/' or flags");let a=0,f=0;for(const t of c.matchAll(r)){t.index>a&&n.push(Mt(c.substring(a,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new Error(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),o||n.push("+");else if("\\"===e[0])n.push(Mt(t[1]));else{const r=e[0],s=t[2];if(!s)throw new Error(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({ht:s,lt:o?Ft:Ct})):(n.push("([^/]+?)"),i.push({ht:s,lt:Rt}))}a=t.index+e.length}if(a<c.length&&n.push(Mt(c.substring(a))),f>0)throw new Error("unbalanced optional braces in path");return e&&(n.push("(?:"),o?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{dt:new RegExp(n.join(""),s?"i":""),wt:i}})(n,i):{dt:null,wt:[]};return this.ft.push({yt:t,gt:"string"==typeof e?e.toLowerCase():e,bt:s.dt,vt:s.wt,_t:r}),this}use(...t){return this.P(null,null,null,!0,t.map(Gt))}mount(t,...e){return this.P(null,null,t,!0,e.map(Gt))}within(t,e){const n=new Yt;return e(n),this.mount(t,n)}at(t,...e){return this.P(null,null,t,!1,e.map(Gt))}onRequest(t,e,...n){return this.P(te(t),Xt,e,!1,n.map(Gt))}onUpgrade(t,e,n,...i){return this.P(te(t),e,n,!1,i.map(Zt))}onError(...t){return this.P(null,null,null,!0,t.map(Jt))}onReturn(...t){return this.ut.push(...t),this}on(t,...e){const n=/^([A-Z]+) (\/.*)$/.exec(t);if(!n)throw new Error("invalid method + path spec: "+JSON.stringify(t));return this.P(n[1],Xt,n[2],!1,e.map(Gt))}get=(t,...e)=>this.P(Qt,Xt,t,!1,e.map(Gt));delete=(...t)=>this.onRequest("DELETE",...t);getOnly=(...t)=>this.onRequest("GET",...t);head=(...t)=>this.onRequest("HEAD",...t);options=(...t)=>this.onRequest("OPTIONS",...t);patch=(...t)=>this.onRequest("PATCH",...t);post=(...t)=>this.onRequest("POST",...t);put=(...t)=>this.onRequest("PUT",...t);ws=(...t)=>this.onUpgrade("GET","websocket",...t);async handleRequest(t){return this.Et(t,new tt)}async handleUpgrade(t){return this.Et(t,new tt)}async handleError(t,e){const n=new tt;return n.P(t),this.Et(e,n)}shouldUpgrade(t){return this.xt(pt(t))}xt(t){for(const e of this.ft){const n=ee(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=jt(t,n.Tt,[])}catch{continue}try{for(const n of e._t)if(re(n,t))return!0}finally{i()}}return!1}async Et(t,e){const n=pt(t),i=await this.St(n,e);if(e.$)throw e.A;return i}async St(t,e){for(const n of this.ft){const i=ee(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.kt();r=jt(t,i.Tt,e)}catch(t){e.P(t);continue}try{const i=await ne(t,n._t,this.ut,e);if(i===Nt)break;if(i===Pt)continue;return i}finally{r()}}return At}}const Qt=new Set(["HEAD","GET"]),te=t=>t?"string"==typeof t?t:new Set(t):null;function ee(t,e){if("string"==typeof e.yt){if(e.yt!==t.F.method)return!1}else if(null!==e.yt&&!e.yt.has(t.F.method??""))return!1;if(e.gt===Xt){if(t.H)return!1}else if(null!==e.gt&&!t.H?.has(e.gt))return!1;if(null===e.bt)return!0;const n=e.bt.exec(t.U);return!!n&&{Tt:"/"+(n.groups?.rest??""),kt:()=>e.vt.map((t,e)=>[t.ht,t.lt(n[e+1])])}}async function ne(t,e,n,i){for(const r of e){let e=await ie(r,t,i);if(e!==At){if(!t.H&&!(e instanceof kt)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.F,s=t.L.W;for(const t of n)await t(i,r,s)}catch(t){i.P(t);continue}return e}}return Pt}async function ie(t,e,n){if(t instanceof Yt)return t.St(e,n);let i=At;try{if(n.$){if(t.handleError){const r=n.A;n.N(),i=await t.handleError(r,e.F,e.H?{socket:e.L.W,head:e.L.t}:{response:e.L.W})}}else if(e.H){if(t.handleUpgrade){const n=e.L;i=await t.handleUpgrade(e.F,n.W,n.t)}}else t.handleRequest&&(i=await t.handleRequest(e.F,e.L.W))}catch(t){t instanceof kt?i=t:n.P(t)}finally{await((t,e)=>lt(t.j,e,t))(e,n)}return i===$t?void 0:i}function re(t,e){if(t instanceof Yt)return t.xt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.F)}catch(t){return e.$t(t),!1}}function se(t,{onError:e=at,socketCloseTimeout:n=500}={}){const i=[],r=new Set,s=()=>{const t=[...i];i.length=0;for(const e of t)e()},o=t=>{t&&(r.size?i.push(t):setImmediate(t))},c=t=>{r.add(t),t.D.push(()=>{r.delete(t),!r.size&&i.length&&setImmediate(s)})},a=(t,n)=>e(t,"tearing down",n);return{request:async(n,i)=>{let r;try{r=ut(n,!1)}catch(t){return e(t,"parsing request",n),void ot(new st(400),0,i)}ht(r,!1,{W:i},a),c(r);const s=new tt,o=await ie(t,r,s);s.$?(e(s.A,"handling request",n),ot(s.A,0,i)):o!==At&&o!==Pt&&o!==Nt||ot(new st(404),0,i)},upgrade:async(i,r,s)=>{let o;r.once("finish",()=>{const t=setTimeout(()=>r.destroy(),n);r.once("close",()=>clearTimeout(t))});try{o=ut(i,!0)}catch(t){return e(t,"parsing upgrade",i),void ct(new st(400),0,r)}ht(o,!0,{W:r,t:s},a),s=K,c(o);const f=new tt,u=await ie(t,o,f);f.$?(e(f.A,"handling upgrade",i),o.B(f.A,i,r)):u!==At&&u!==Pt&&u!==Nt||(console.warn(`Upgrade ${i.headers.upgrade} request for ${i.url} fell-through. This probably means you need to add shouldUpgrade to one of your upgrade handlers, or if this is intentional, explicitly reject the request (throw new HTTPError(404)) instead of using CONTINUE.`),o.B(new st(404),i,r))},shouldUpgrade:n=>{try{const i=ut(n,!0);return i.$t=t=>e(t,"checking should upgrade",n),re(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.At,r=t.code;n.writable&&!i?.headersSent&&n.end(ce.get(r)??ae),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request")},softClose(t,e,n){for(const n of r)bt(n,t,e);o(n)},hardClose(t){for(const t of r)vt(t);o(t)},countConnections:()=>r.size}}const oe=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),ce=new Map([["HPE_HEADER_OVERFLOW",oe(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",oe(413)],["ERR_HTTP_REQUEST_TIMEOUT",oe(408)]]),ae=oe(400);class fe extends EventTarget{Pt;constructor(t){super(),this.Pt=t}attach(t,e={}){const n=se(this.Pt,{...e,onError:this.Nt.bind(this,t)});!1===e.autoContinue&&t.addListener("checkContinue",n.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",n.request),t.addListener("request",n.request),t.addListener("upgrade",n.upgrade);const i=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=n.shouldUpgrade),t.addListener("clientError",n.clientError);let r=!1;return(e="",s=-1,o=!1)=>{r||(r=!0,t.removeListener("checkContinue",n.request),t.removeListener("checkExpectation",n.request),t.removeListener("request",n.request),t.removeListener("upgrade",n.upgrade),t.shouldUpgradeCallback===n.shouldUpgrade&&(t.shouldUpgradeCallback=i),t.removeListener("clientError",n.clientError));const c=()=>{o&&t.closeAllConnections()};if(s>0){const i=setTimeout(n.hardClose,s);n.softClose(e,this.Nt.bind(this,t),()=>{clearTimeout(i),c()})}else 0===s&&n.hardClose(c);return n}}listen(t,e,n={}){n.shouldUpgradeCallback&&(n={overrideShouldUpgradeCallback:!1,...n});const r=i(n);n.socketTimeout&&r.setTimeout(n.socketTimeout);const s=this.attach(r,n),o=Object.assign(r,{closeWithTimeout:(t,e)=>new Promise(n=>{r.close(()=>n()),s(t,e,!0)})});return new Promise((i,s)=>{r.once("error",s),r.listen(t,e,n.backlog??511,()=>{r.off("error",s),i(o)})})}Nt(t,e,n,i){const r={error:e,server:t,action:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r}))&&at(e,n,i)}}const ue=t=>wt(t)?.C??X(t),he=t=>ue(t).search,le=t=>new URLSearchParams(ue(t).searchParams),de=(t,e)=>ue(t).searchParams.get(e);function we(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function pe(t){const e=t.headers.authorization;if(!e)return;const[n,i]=we(e," ");return void 0!==i?[n.trim().toLowerCase(),i.trim()]:void 0}function me(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function ye(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:xe(e)}:{}}function ge(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const s=t.headers.range;if(!s||0===e)return;const[o,c]=we(s,"=");if("bytes"!==o||!c)return;const a=new st(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=ve(t);if(void 0===e)throw a;return e},u=[];for(const t of c.split(",")){const[i,r]=we(t.trim(),"-");if(void 0===r)throw a;let s;if(i)s={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw a;s={start:Math.max(e-f(r),0),end:e-1}}if(!(s.start>=e)){if(s.end<s.start||u.length>=n)throw a;u.push(s)}}if(!u.length)throw a;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw a;if(u.length>r)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw a}}return{ranges:u,totalSize:e}}function be(t){if(void 0!==t)return"number"==typeof t?[String(t)]:t.length?"string"==typeof t?t.split(",").map(t=>t.trim()):t.flatMap(t=>t.split(",").map(t=>t.trim())):[]}function ve(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}function _e(t){if(t)return t.split(",").map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=we(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),s="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,o=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:s,q:o}})}function Ee(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new st(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let s=i[2];'"'===s[0]&&(s=s.substring(1,s.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,s)}return e}function xe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Te=t=>"function"==typeof t?t:()=>t;class Se{Ot;constructor(t=Oe){this.Ot=Te(t)}set(t,e){Ae(t,this,e)}get(t){return Pe(t,this)}clear(t){Ne(t,this)}withValue(t){return Vt(e=>(Ae(e,this,t),At))}}const ke=(t,...e)=>{const n={Ot:n=>t(n,...e)};return t=>Pe(t,n)};function $e(t){return t.Mt||(t.Mt=new Map),t.Mt}function Ae(t,e,n){$e(pt(t)).set(e,n)}function Pe(t,e){const n=wt(t);if(!n)return e.Ot(t);const i=$e(n);if(i.has(e))return i.get(e);const r=e.Ot(t);return i.set(e,r),r}function Ne(t,e){const n=wt(t);n?.Mt?.delete(e)}const Oe=()=>{throw new Error("property has not been set")};function Me({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:s}){const o=Te(t);return Vt(async t=>{const c=Date.now(),a=await o(t),f={"www-authenticate":`Bearer realm="${a}"`},u=pe(t),h="bearer"===u?.[0]?u[1]:await(n?.(t));if(!h)throw new st(401,{headers:f,body:"no token provided"});const l=await e(h,a,t);if(!l)throw new st(401,{headers:f,body:"invalid token"});if("object"==typeof l){if("nbf"in l&&"number"==typeof l.nbf&&c<1e3*l.nbf)throw new st(401,{headers:f,body:"token not valid yet"});if("exp"in l&&"number"==typeof l.exp){const e=1e3*l.exp;if(c>=e-r)throw new st(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r=at)=>{const s=pt(t),o=n-Math.max(i,0),c=s.tt??Number.POSITIVE_INFINITY,a=s.et?.nt??c;o>=a&&n>=c||(n<c&&(s.tt=n),o<a&&(s.et={nt:o,K:e,X:r}),_t(s))})(t,"token expired",e,r,s)}}return Ue.set(t,{realm:a,data:l,scopes:Be(l)}),At})}const Re=t=>Ue.get(t).data,Fe=(t,e)=>Ue.get(t).scopes.has(e),Ce=t=>Vt(e=>{const n=Ue.get(e);if(!n.scopes.has(t))throw new st(403,{headers:{"www-authenticate":`Bearer realm="${n.realm}", scope="${t}"`},body:`scope required: ${t}`});return At}),Ue=/*@__PURE__*/new Se({realm:"",data:null,scopes:new Set});function Be(t){if(!t||"object"!=typeof t||!("scopes"in t))return new Set;const{scopes:e}=t;return Array.isArray(e)?new Set(e):"string"==typeof e?new Set([e]):e&&"object"==typeof e?new Set(Object.entries(e).filter(([t,e])=>e).map(([t])=>t)):new Set}function Ie(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${h("sha256").update(n).digest("base64").substring(0,12)}"`}async function je(t){const e=h("sha256");return"string"==typeof t?await d(c(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const De=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),He={mime:"accept",language:"accept-language",encoding:"accept-encoding"},qe={zstd:"{file}.zst",br:"{file}.br",gzip:"{file}.gz",deflate:"{file}.deflate",identity:"{file}"},Le=t=>{return{type:"encoding",options:(e=t,n=qe,Array.isArray(e)?e.map(t=>[t,n[t]]):Object.entries(e)).map(([t,e])=>({match:t,file:e}))};var e,n};function ze(t,e=10){const n=t.map(t=>({Rt:t.type,Ft:t.options.map(t=>({Ct:t.file,Ut:"string"==typeof t.match?t.match.toLowerCase():De(t.match,!0),Bt:t.as??("string"==typeof t.match?t.match:void 0)}))})).filter(t=>t.Ft.length>0);return{options(t,i){let r=e;const s={},o={mime:We(i.mime),language:We(i.language),encoding:We(i.encoding)};return function*t(e,i){const c=n[i];if(!c)return--r,void(yield{filename:e,info:s});const a=new Set,f=o[c.Rt]??[];for(const n of f){const o=n.name.toLowerCase();for(const n of c.Ft)if("string"==typeof n.Ut?n.Ut===o:n.Ut.test(o)){const o=Ve(e,n.Ct);if(a.has(o))continue;if(a.add(o),s[c.Rt]=n.Bt,yield*t(o,i+1),r<=0)return}}s[c.Rt]=void 0,!a.has(e)&&r>0&&(yield*t(e,i+1))}(t,0)},vary:[...new Set(n.map(t=>He[t.Rt]))].join(" ")}}function We(t){if(t?.length)return 1===t.length?t:[...t].sort((t,e)=>e.q-t.q||e.specificity-t.specificity)}function Ve(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Je=/*@__PURE__*/Xe("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let Ge=/*@__PURE__*/new Map(Je);function Ze(){Ge=new Map(Je)}function Ke(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function Xe(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,s="",o=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),c=i+s+o,a=r.replace("{ext}",c);e.set(c.toLowerCase(),a),s&&e.set((i+o).toLowerCase(),a)}}return e}function Ye(t){for(const[e,n]of t)Ge.set(e.toLowerCase(),n)}function Qe(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ge.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}async function tn(t,e,n){const i=await E(t),r={file:t,mime:Qe(m(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(r.rawSize<=n)return r;if(["image","video","audio","font"].includes(r.mime.split("/")[0]))return r;for(const s of e){const e=rn.get(s.match),o=y(g(t),Ve(b(t),s.file));if(!e||o===s.file)continue;const c=await e(i);c.byteLength<=r.rawSize-n&&(await x(o,c),r.bestSize=Math.min(r.bestSize,c.byteLength),++r.created)}return r}async function en(t,e,n){const i=[];await nn(t,i);const r=new Set(i);for(const t of r)for(const n of e){const e=y(g(t),Ve(b(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>tn(t,e,n)))}async function nn(t,e){const n=await T(t);if(n.isDirectory())for(const n of await S(t))await nn(y(t,n),e);else n.isFile()&&e.push(t)}const rn=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["brotli",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]);class sn{It;jt;Dt;Ht;qt;Lt;zt;Wt;Vt;Jt;Gt;Zt;Kt;vary;constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:s=!1,allow:o=[".well-known"],hide:c=[],indexFiles:a=["index.htm","index.html"],implicitSuffixes:f=[],negotiation:u}){this.It=t,this.jt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Dt=n,this.Ht=i,this.qt=r,this.Lt=s,this.Jt=a,this.Zt=["",...f],this.zt=new Set(o.map(t=>this.Xt(t))),this.Wt=new Set,this.Vt=[];for(const t of c)"string"==typeof t?this.Wt.add(this.Xt(t)):this.Vt.push(De(t,!n));this.Gt=new Set(a.map(t=>this.Xt(t))),u?.length?(this.Kt=ze(u),this.vary=this.Kt.vary):this.vary=""}static async build(t,e){return new sn(await k(t,{encoding:"utf-8"})+v,e)}Xt(t){return"exact"===this.Dt?t:t.toLowerCase()}Yt(t){if(this.zt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.qt)||"."===e[0]&&!this.Ht||this.Wt.has(e)||this.Vt.some(t=>t.test(e)))}async find(t,e={}){let n=t.join(v);"force-lowercase"===this.Dt&&(n=n.toLowerCase());let i=_(this.It,n);if(!i.startsWith(this.It)&&i+v!==this.It)return null;let r=null,s=null;for(const t of this.Zt){const e=i+t;if(r=e.substring(this.It.length).split(v).filter(t=>t),r.length>this.jt+1)return null;if(r.some(t=>!this.Yt(this.Xt(t))))return null;const n=r[r.length-1]??"";if(!this.Lt&&this.Gt.has(this.Xt(n))&&!this.zt.has(this.Xt(n)))return null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){i=e;break}}if(!s||!r)return null;if(this.Xt(s)!==this.Xt(i))return null;let o=s,c=await T(s).catch(()=>null);if(!c)return null;if(c.isDirectory()){if(r.length>this.jt)return null;for(const t of this.Jt){const e=y(s,t);if(c=await T(e).catch(()=>null),c?.isFile()){o=e;break}}}if(!c?.isFile())return null;if(this.Kt){const t=b(o),n=g(o);for(const i of this.Kt.options(t,e)){if(!i.filename||i.filename.includes(v))continue;const t=await cn({canonicalPath:o,negotiatedPath:y(n,i.filename),...i.info});if(t)return t}}return cn({canonicalPath:o,negotiatedPath:o})}async precompute(){const t=new Map,e=(e,n)=>{const i=t.get(e);(!i||n.p>i.p)&&t.set(e,n)},n=new V({dir:[this.It],depth:0});for(const{dir:t,depth:i}of n){const r=await S(y(...t),{withFileTypes:!0,encoding:"utf-8"}),s=new Set(r.map(t=>this.Xt(t.name)));for(const o of r){const r=this.Xt(o.name);if(!this.Yt(r))continue;const c=[...t,o.name];if(o.isDirectory())i<this.jt&&n.push({dir:c,depth:i+1}),e(this.Xt(c.slice(1).join("/")),on);else if(o.isFile()){const n={file:y(...c),dir:y(...t),basename:r,siblings:s},i=this.Jt.indexOf(r);if(-1!==i&&(e(this.Xt(t.slice(1).join("/")),{...n,p:this.Jt.length+1-i}),!this.Lt&&!this.zt.has(r)))continue;const a=this.Xt(c.slice(1).join("/"));for(let t=0;t<this.Zt.length;++t){const i=this.Zt[t];o.name.endsWith(i)&&e(a.substring(0,a.length-i.length),{...n,p:-t})}}}}return{find:async(e,n={})=>{const i=t.get(this.Xt(e.join("/")));if(!i?.file)return null;if(this.Kt)for(const t of this.Kt.options(i.basename,n)){if(!i.siblings.has(this.Xt(t.filename)))continue;const e=await cn({canonicalPath:i.file,negotiatedPath:y(i.dir,t.filename),...t.info});if(e)return e}return cn({canonicalPath:i.file,negotiatedPath:i.file})},vary:this.vary}}}const on={file:"",dir:"",basename:"",siblings:new Set,p:1};async function cn(t){const e=await $(t.negotiatedPath,a.O_RDONLY).catch(()=>null);if(!e)return null;const n=()=>(e.close().catch(()=>{}),null),i=await e.stat().catch(n);return i?.isFile()?{handle:e,stats:i,...t}:n()}const an=/*@__PURE__*/ke(async t=>{const e=St(t);if(e.aborted)throw $t;e.throwIfAborted();const n=await A(y(N(),"upload"));Tt(t,()=>P(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw $t;return y(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),s=f(i,{mode:n});try{return await d(t,s,{signal:e}),{path:i,size:s.bytesWritten}}finally{s.close()}}}});function fn(t){const e=pt(t);if(!e.L)throw new Error("cannot call acceptBody from shouldUpgrade");if(e.I.signal.aborted)throw $t;e.Qt||e.H||(e.Qt=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.L.W.writeContinue())}function un(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["connection","keep-alive","transfer-encoding"],responseHeaders:o=[],agent:c,keepAlive:a=!0,maxSockets:f=10,...u}={}){let h;t.startsWith("https://")?(c??=new M({keepAlive:a,maxSockets:f,...u}),h=s):(c??=new r({keepAlive:a,maxSockets:f,...u}),h=R);const l=t.endsWith("/")?t:t+"/";return zt((r,s)=>new Promise((a,f)=>{const u=St(r),w=t=>f(u.aborted?$t:new st(502,{cause:t})),p=new URL(l+r.url?.substring(1)),m=p.toString();if(!m.startsWith(l)&&m!==t)return f(new st(400,{message:"directory traversal blocked"}));fn(r);let y={...r.headers};hn(y,e);for(const t of n)y=t(r,y);const g=h(p,{agent:c,method:r.method,headers:y,signal:u});g.once("error",w),g.once("response",t=>{if(!s.headersSent){let e={...t.headers};hn(e,i);for(const n of o)e=n(r,t,e);s.writeHead(t.statusCode??200,t.statusMessage,e)}d(t,s).then(a,f)}),d(r,g).catch(w)}))}function hn(t,e){for(const e of be(t.connection)??[])delete t[e.toLowerCase()];for(const n of e)delete t[n]}function ln({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?q(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),s=new Set(n);return ke(t=>{const e=e=>{if(s.has(e))return be(t.headers[e])?.reverse()},n=e("forwarded"),o=e("x-forwarded-for"),c=e("x-forwarded-host"),a=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),h=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),l=[dn(t)];if(n)for(const t of n)try{const e=Ee(t);l.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{l.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(o){const t=o.map(H),e=c??[],n=a??f??u??[];let i=l[0].client;for(let r=0;r<t.length;++r){const s=t[r];l.push({client:s,server:h?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=s}}else if(h)for(const t of h)l.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+r,l.length);for(let t=0;t<d-1;++t)i(l[t].client)||(d=t+1);return Object.freeze({trusted:l.slice(0,d),untrusted:l.slice(d),outwardChain:l,edge:l[d-1]})})}const dn=t=>({client:{...H(t.socket.remoteAddress)??wn,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??wn,port:t.socket.localPort},host:t.headers.host,proto:void 0}),wn={type:"alias",ip:"_disconnected",port:void 0};function pn(t,e){return delete e.forwarded,delete e["x-forwarded-for"],delete e["x-forwarded-host"],delete e["x-forwarded-proto"],delete e["x-forwarded-protocol"],delete e["x-url-scheme"],e}function mn(t,e){const n=pn(0,e);return n.forwarded=bn([dn(t)]),n}const yn=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=pn(0,i),s=t(n);return r.forwarded=bn([...e?s.trusted:s.outwardChain].reverse()),r};function gn(t,e){let n=t.headers.forwarded;const i=bn([dn(t)]);n?n+=", "+i:n=i;const r=pn(0,e);return r.forwarded=n,r}function bn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.ip,by:t.server?.ip,host:t.host,proto:t.proto}).filter(([t,e])=>e).map(([t,e])=>e&&/[^a-zA-Z0-9._]/.test(e)?`${t}="${e.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(",","-")}"`:`${t}=${e}`).join("; ")).join(", ")}class vn{te;ee;ne;ie;re;constructor(t,{fatal:e=!1}={}){this.te=t,this.ee=e,this.ne=new Uint8Array(4),this.ie=new DataView(this.ne.buffer),this.re=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,i=[];let r=0;if(this.re>0){if(r=4-this.re,n<r)return this.ne.set(t,this.re),this.re+=n,"";this.ne.set(t.subarray(0,r),this.re),i.push(this.ie.getUint32(0,this.te)),this.re=0}const s=new DataView(t.buffer,t.byteOffset,t.byteLength);let o=r;for(const t=n-3;o<t;o+=4)i.push(s.getUint32(o,this.te));if(e)o<n&&this.ne.set(t.subarray(o)),this.re=n-o;else if(this.re=0,o<n){if(this.ee)throw new Error("invalid byte length for utf-32 content");i.push(65533)}return i.length>0?String.fromCodePoint(...i):""}}class _n extends F{constructor(t){super({transform(e,n){try{const i=t.decode(e,{stream:!0});i&&n.enqueue(i)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(K);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const En=new Map;function xn(t,e){En.set(t.toLowerCase(),e)}function Tn(){xn("utf-32be",{decoder:t=>new vn(!1,t)}),xn("utf-32le",{decoder:t=>new vn(!0,t)})}function Sn(t,e={}){const n=En.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new st(415,{body:`unsupported charset: ${t}`})}}function kn(t,e={}){const n=En.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new _n(n.decoder(e));try{return new C(t,e)}catch{throw new st(415,{body:`unsupported charset: ${t}`})}}const $n=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function An(t,e,n){const i=xe(t.headers["if-modified-since"]),r=be(t.headers["if-none-match"]);if(r){if(Nn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function Pn(t,e,n){let i=!0;const r=ye(t);return r.etag&&(i&&=Nn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function Nn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Ie(t.getHeader("content-encoding"),e))}class On extends F{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function Mn(t,{maxExpandedLength:e=Number.POSITIVE_INFINITY,maxContentLength:n=e,maxEncodingSteps:i=1}={}){const r=ve(t.headers["content-length"]);if(void 0!==r&&r>n)throw new st(413);const s=be(t.headers["content-encoding"])??[];if(s.length>i)throw new st(415,{body:"too many content-encoding stages"});fn(t);let o=I.toWeb(t);void 0===r&&Number.isFinite(n)&&(o=o.pipeThrough(new On(n,new st(413))));for(const t of s.reverse())o=o.pipeThrough(Un(t));return Number.isFinite(e)&&(o=o.pipeThrough(new On(e,new st(413,{body:"decoded content too large"})))),o}function Rn(t,e={}){const n=Mn(t,e),i=me(t)??e.defaultCharset??"utf-8";return n.pipeThrough(kn(i,e))}async function Fn(t,e={}){const n=[];for await(const i of Rn(t,e))n.push(i);return n.join("")}async function Cn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,s=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],s=null;break}if(s=t.value,s.byteLength>=e){i.set(s.subarray(0,e),r);break}i.set(s,r),r+=s.byteLength}const o=$n[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!o)throw n.cancel(),new st(415,{body:"invalid JSON encoding"});const c=kn(o,e),a=c.writable.getWriter();return r&&a.write(i.subarray(0,r)),s&&a.write(s),n.releaseLock(),a.releaseLock(),t.pipeThrough(c)})(Mn(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Un(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new U("gzip");case"deflate":return new U("deflate");case"br":try{return new U("brotli")}catch{return j.toWeb(w.createBrotliDecompress())}case"zstd":try{return j.toWeb(w.createZstdDecompress())}catch{throw new st(415,{body:"unsupported content encoding"})}default:throw new st(415,{body:"unknown content encoding"})}}function Bn(t){if(!t)return null;const[e,n]=we(t,";"),i=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const r=e[1].toLowerCase(),s=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";i.has(r)||i.set(r,s)}}return{mime:e.trim().toLowerCase(),params:i}}function In(t,e,n,i){const r=t.byteLength;for(;e<r;){for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)break;if(59!==t[e++])return!1;for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)return!1;const s=e;for(;e<r;++e){const n=t[e];if(!Hn[n]){if(61===n)break;return!1}}if(e===r)return!1;const o=t.subarray(s,e),c=jn.decode(o).toLowerCase();if(42===o[o.byteLength-1]){const i=++e;for(;e<r;++e){const n=t[e];if(!Ln[n]){if(39!==n)return!1;break}}if(e===r)return!1;const s=Sn(jn.decode(t.subarray(i,e)));for(++e;e<r&&39!==t[e];++e);if(e===r)return!1;if(++e===r)return!1;let o=e;const a=[];for(;e<r;++e){const n=t[e];if(1!==qn[n]){if(37===n){let n,i;if(e+2<r&&-1!==(n=Wn[t[e+1]])&&-1!==(i=Wn[t[e+2]])){const r=(n<<4)+i;e>o&&a.push(s.decode(t.subarray(o,e),{stream:!0})),a.push(s.decode(Buffer.from([r]),{stream:!0})),o=(e+=2)+1;continue}return!1}break}}a.push(s.decode(t.subarray(o,e)));const f=a.join("");n.has(c)||n.set(c,f);continue}if(++e===r)return!1;if(34===t[e]){let s=++e,o=!1;const a=[];for(;e<r;++e){const n=t[e];if(92!==n){if(34===n){if(o){s=e,o=!1;continue}a.push(i.decode(t.subarray(s,e)));break}if(o&&(s=e-1,o=!1),!zn[n])return!1}else o?(s=e,o=!1):(a.push(i.decode(t.subarray(s,e),{stream:!0})),o=!0)}if(e===r)return!1;++e,n.has(c)||n.set(c,a.join(""));continue}let a=e;for(;e<r;++e){const n=t[e];if(!Hn[n]){if(e===a)return!1;break}}n.has(c)||n.set(c,i.decode(t.subarray(a,e)))}return!0}const jn=/*@__PURE__*/new TextDecoder("iso-8859-1"),Dn=[1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],Hn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...Dn,0,1,0,1],33),t})(),qn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...Dn,0,1,0,1],33),t})(),Ln=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...Dn,1,0,1,1],33),t})(),zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),Wn=/*@__PURE__*/(()=>{const t=new Int8Array(256).fill(-1);for(let e=0;e<10;++e)t[48+e]=e;for(let e=0;e<6;++e)t[65+e]=e+10,t[97+e]=e+10;return t})();class Vn{se;oe;ce;ae;fe;constructor(t,e){const n=t.byteLength;if(!n||n>65535)throw new Error("invalid needle");this.se=t,this.oe=e,this.ce=null,this.ae=0,this.fe=null}push(t){let e=0;const n=t.byteLength,i=this.se,r=i.byteLength-1,s=n-r;let o=-this.ae;if(this.ae){const c=this.fe,a=this.ce,f=i[r];if(s>0){const n=t[o+r];n!==f||t.compare(i,-o,r,0,o+r)?o+=c[n]:(this.oe(!0,K,0,0,!0),this.ae=0,e=o+=r+1)}const u=s<0?s:0;for(;o<u;){const n=t[o+r];if(n===f&&!a.compare(i,0,-o,this.ae+o,this.ae)&&!t.compare(i,-o,r,0,o+r)){this.oe(!0,a,0,this.ae+o,!1),this.ae=0,e=o+=r+1;break}o+=c[n]}const h=this.ae;if(h>0){const e=i[0];for(;o<0;){const r=a.indexOf(e,h+o);if(-1===r){o=0;break}const s=h-r;if(!a.compare(i,1,s,r+1,h)&&!t.compare(i,s,s+n))return r&&(this.oe(!1,a,0,r,!1),a.copy(a,0,r,s)),a.set(t,s),void(this.ae+=n-r);o=r+1-h}this.oe(!1,a,0,h,!1),this.ae=0}}for(;o<s;){const n=t.indexOf(i,o);if(-1!==n){if(this.oe(!0,t,e,n,!0),n===s+1)return;e=o=n+r+1}else o=s}const c=i[0];for(;o<n;){const s=t.indexOf(c,o);if(-1===s)return void this.oe(!1,t,e,n,!0);if(!t.compare(i,1,n-s,s+1)){if(!this.ce){this.ce=Buffer.allocUnsafe(r),this.fe=new Uint16Array(256).fill(r+1);for(let t=0;t<r;++t)this.fe[i[t]]=r-t}return t.copy(this.ce,0,s),this.ae=n-s,void(s>e&&this.oe(!1,t,e,s,!0))}o=s+1}n>e&&this.oe(!1,t,e,n,!0)}destroy(){const t=this.ae;t&&this.ce&&this.oe(!1,this.ce,0,t,!1),this.ae=0}}class Jn extends D{ue;he;le;de;we;pe;me;constructor({limits:t={},preservePath:e,highWaterMark:n,fileHwm:i,defParamCharset:r="utf-8",defCharset:s="utf-8"},o){super({autoDestroy:!0,emitClose:!0,highWaterMark:n,write:Gn,destroy:Zn,final:Kn});const c=o.get("boundary");if(!c)throw new st(400,{body:"Multipart: Boundary not found"});const a=Sn(r),f={autoDestroy:!0,emitClose:!0,highWaterMark:i},u=t.fieldSize??1048576,h=t.fileSize??Number.POSITIVE_INFINITY,l=t.fieldNameSize??100,d=t.files??Number.POSITIVE_INFINITY,w=t.fields??Number.POSITIVE_INFINITY,p=t.parts??Number.POSITIVE_INFINITY;let m=-1,y=0,g=0,b=!1;this.pe=0,this.de=!1;let v,_,E,x,T,S=0,k=0,$=!1,A=!1,P=!1,N=!1;const O=new Yn(t=>{this.we=void 0,b=!1,x="text/plain";let n,i=s;E="7bit",T=void 0,$=!1,A=!1;const r=t["content-disposition"]?.[0];if(!r)return void(b=!0);const o=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let i=0;for(;i<t.byteLength;++i)if(!Hn[t[i]]){if(!In(t,i,n,e))return null;break}return{type:jn.decode(t.subarray(0,i)).toLowerCase(),params:n}})(r,a);if("form-data"!==o?.type)return void(b=!0);o.params&&(T=o.params.get("name")??"",T.length>l&&(T=T.substring(0,l),$=!0),n=o.params.get("filename*")??o.params.get("filename"),void 0===n||e||(n=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(n)));const c=t["content-type"]?.[0];if(c){const t=Bn(jn.decode(c));t&&(x=t.mime,i=t.params.get("charset")?.toLowerCase()??s)}_=Sn(i);const u=t["content-transfer-encoding"]?.[0];if(u&&(E=jn.decode(u).toLowerCase()),"application/octet-stream"===x||void 0!==n){if(g===d)return P||(P=!0,this.emit("filesLimit")),void(b=!0);if(++g,0===this.listenerCount("file"))return void(b=!0);S=0,this.le=new Qn(f,this),++this.pe,this.emit("file",T,this.le,{nameTruncated:$,filename:n,encoding:E,mimeType:x})}else{if(y===w)return N||(N=!0,this.emit("fieldsLimit")),void(b=!0);if(++y,0===this.listenerCount("field"))return void(b=!0);v=[],k=0}});let M=0;const R=Buffer.from(`\r\n--${c}`,"latin1");this.ue=new Vn(R,(t,e,n,i,r)=>{const s=(t,n)=>{if(r)return e.subarray(t,n);const i=Buffer.allocUnsafe(n-t);return e.copy(i,0,t,n),i};for(;n!==i;){if(this.we){const t=this.we.push(e,n,i,r);if(-1===t){this.we=void 0,O.reset(),this.emit("error",new Error("Malformed part header"));break}if(t===i)break;n=t}if(M){if(1===M){switch(e[n]){case 45:M=2,++n;break;case 13:M=3,++n;break;default:M=0}if(n===i)return}if(2===M){if(M=0,45===e[n])return this.de=!0,void(this.ue=ei)}else if(3===M&&(M=0,10===e[n])){if(++n,m>=p)break;this.we=O;continue}}if(!b)if(this.le){const t=s(n,Math.min(i,n+h-S));S+=t.byteLength,S===h?(t.length>0&&this.le.push(t),this.le.emit("limit"),this.le.truncated=!0,b=!0):this.le.push(t)||(this.he&&(this.le.ye=this.he),this.he=void 0)}else if(v){const t=s(n,Math.min(i,n+u-k));k+=t.byteLength,v.push(_.decode(t)),k===u&&(b=!0,A=!0)}break}if(t){if(M=1,this.le)this.le.push(null),this.le=void 0;else if(v){const t=v.join("");v=void 0,k=0,this.emit("field",T,t,{nameTruncated:$,valueTruncated:A,encoding:E,mimeType:x})}++m===p&&this.emit("partsLimit")}}),this.write(ni)}ge(){if(this.we)return new Error("Malformed part header");const t=this.le;return t&&(this.le=void 0,t.destroy(new Error("Unexpected end of file"))),this.de?null:new Error("Unexpected end of form")}}function Gn(t,e,n){this.he=n,this.ue.push(t);const i=this.he;i&&(this.he=void 0,i())}function Zn(t,e){this.we=void 0,this.ue=ei,t??=this.ge();const n=this.le;n&&(this.le=void 0,n.destroy(t??void 0)),e(t)}function Kn(t){if(this.ue.destroy(),!this.de)return t(new Error("Unexpected end of form"));this.pe?this.me=()=>t(this.ge()):t(this.ge())}const Xn=16384;class Yn{be;ve;_e;m;ht;Ee;xe;oe;constructor(t){this.be=Object.create(null),this.ve=0,this._e=0,this.m=0,this.ht=[],this.Ee=[],this.xe=0,this.oe=t}reset(){this.be=Object.create(null),this.ve=0,this._e=0,this.m=0,this.ht.length=0,this.Ee.length=0,this.xe=0}push(t,e,n,i){let r=e;t:for(;e<n;)switch(this.m){case 0:for(;e<n;++e){if(this._e===Xn)return-1;++this._e;const n=t[e];if(!Hn[n]){if(58!==n)return-1;if(e>r&&this.ht.push(jn.decode(t.subarray(r,e))),!this.ht.length)return-1;++e,this.m=1;continue t}}e>r&&this.ht.push(jn.decode(t.subarray(r,e)));break;case 1:for(;e<n;++e){if(this._e===Xn)return-1;++this._e;const n=t[e];if(32!==n&&9!==n){r=e,this.m=2;continue t}}break;case 2:switch(this.xe){case 0:for(;e<n;++e){if(this._e===Xn)return-1;++this._e;const n=t[e];if(n<32||127===n){if(13!==n)return-1;++this.xe;break}}if(i)this.Ee.push(t.subarray(r,e));else{const n=Buffer.allocUnsafe(e-r);t.copy(n,0,r,e),this.Ee.push(n)}++e;break;case 1:if(this._e===Xn)return-1;if(++this._e,10!==t[e++])return-1;++this.xe;break;case 2:{if(this._e===Xn)return-1;++this._e;const n=t[e];if(32===n||9===n)r=e,this.xe=0;else{if(++this.ve<2e3){const t=this.ht.join("").toLowerCase(),e=Buffer.concat(this.Ee),n=this.be[t];n?n.push(e):this.be[t]=[e]}13===n?(++this.xe,++e):(r=e,this.xe=0,this.m=0,this.ht.length=0,this.Ee.length=0)}break}case 3:{if(this._e===Xn)return-1;if(++this._e,10!==t[e++])return-1;const n=this.be;return this.reset(),this.oe(n),e}}}return e}}class Qn extends I{ye;truncated;constructor(t,e){super({...t,read:ti}),this.truncated=!1,this.once("end",()=>{if(this.Te(0),0===--e.pe&&e.me){const t=e.me;e.me=void 0,process.nextTick(t)}})}}function ti(t){const e=this.ye;e&&(this.ye=void 0,e())}const ei={push:()=>{},destroy:()=>{}},ni=/*@__PURE__*/Buffer.from("\r\n");class ii extends D{Se;ke;$e;Ae;Pe;Ne;Oe;Me;Re;Fe;Ce;Ue;Be;Ie;je;constructor({limits:t={},highWaterMark:e,defCharset:n="utf-8"},i){super({autoDestroy:!0,emitClose:!0,highWaterMark:e,write:ri,final:si}),this.Se=i.get("charset")??n,this.ke=t.fieldSize??1048576,this.$e=t.fields??Number.POSITIVE_INFINITY,this.Ae=t.fieldNameSize??100,this.Pe=!0,this.Ne=!1,this.Oe=!1,this.Me=0,this.Re=0,this.Fe=0,this.Ce=[],this.Ue=[],this.Be=-2,this.Ie=0,this.je=Sn(this.Se)}De(t,e){const n=this.Pe?this.Ce:this.Ue,i=this.je.decode(t,{stream:!e});i&&n.push(i)}He(t,e,n){if(e>=n)return n;if(-1===this.Be){const i=Wn[t[e++]];if(-1===i)return-1;if(e<n){const n=Wn[t[e++]];if(-1===n)return-1;this.De(Buffer.from([(i<<4)+n]),!1),this.Be=-2,this.Ie=e}else this.Be=i}else{const n=Wn[t[e++]];if(-1===n)return-1;this.De(Buffer.from([(this.Be<<4)+n]),!1),this.Be=-2,this.Ie=e}return e}qe(t,e,n){if(this.Me>this.Ae){for(this.Ne||this.Ie<e&&this.De(t.subarray(this.Ie,e-1),!1),this.Ne=!0;e<n;++e){const n=t[e];if(61===n||38===n)break}this.Ie=e}return e}Le(t,e,n){if(this.Re>this.ke){for(this.Oe||this.Ie<e&&this.De(t.subarray(this.Ie,e-1),!1),this.Oe=!0;e<n&&38!==t[e];++e);this.Ie=e}return e}}function ri(t,e,n){if(this.Fe>=this.$e)return n();let i=0;const r=t.length;if(this.Ie=0,-2!==this.Be){if(i=this.He(t,i,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();this.Pe?++this.Me:++this.Re}t:for(;i<r;)if(this.Pe){for(i=this.qe(t,i,r);i<r;){switch(t[i]){case 61:this.De(t.subarray(this.Ie,i),!0),this.Ie=++i,this.Pe=!1;continue t;case 38:if(this.De(t.subarray(this.Ie,i),!0),this.Ie=++i,this.Ce.length>0&&(this.emit("field",this.Ce.join(""),"",{nameTruncated:this.Ne,valueTruncated:!1,encoding:this.Se,mimeType:"text/plain"}),this.Ce.length=0),this.Ne=!1,this.Me=0,++this.Fe>=this.$e)return this.emit("fieldsLimit"),n();continue;case 43:this.Ie<i&&this.De(t.subarray(this.Ie,i),!1),this.De(oi,!1),this.Ie=i+1;break;case 37:if(this.Ie<i&&this.De(t.subarray(this.Ie,i),!1),this.Ie=i+1,this.Be=-1,i=this.He(t,i+1,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();++this.Me,i=this.qe(t,i,r);continue}++i,++this.Me,i=this.qe(t,i,r)}this.Ie<i&&this.De(t.subarray(this.Ie,i),!1)}else{for(i=this.Le(t,i,r);i<r;){switch(t[i]){case 38:if(this.De(t.subarray(this.Ie,i),!0),this.Ie=++i,this.Pe=!0,this.emit("field",this.Ce.join(""),this.Ue.join(""),{nameTruncated:this.Ne,valueTruncated:this.Oe,encoding:this.Se,mimeType:"text/plain"}),this.Ce.length=0,this.Ue.length=0,this.Ne=!1,this.Oe=!1,this.Me=0,this.Re=0,++this.Fe>=this.$e)return this.emit("fieldsLimit"),n();continue t;case 43:this.Ie<i&&this.De(t.subarray(this.Ie,i),!1),this.De(oi,!1),this.Ie=i+1;break;case 37:if(this.Ie<i&&this.De(t.subarray(this.Ie,i),!1),this.Ie=i+1,this.Be=-1,i=this.He(t,i+1,r),-1===i)return n(new Error("Malformed urlencoded form"));if(i>=r)return n();++this.Re,i=this.Le(t,i,r);continue}++i,++this.Re,i=this.Le(t,i,r)}this.Ie<i&&this.De(t.subarray(this.Ie,i),!1)}n()}function si(t){if(-2!==this.Be)return t(new Error("Malformed urlencoded form"));this.De(K,!0),(!this.Pe||this.Ce.length>0)&&this.emit("field",this.Ce.join(""),this.Pe?"":this.Ue.join(""),{nameTruncated:this.Ne,valueTruncated:this.Oe,encoding:this.Se,mimeType:"text/plain"}),t()}const oi=/*@__PURE__*/Buffer.from(" ","utf-8");function ci(t,{closeAfterErrorDelay:e=500,...n}={}){const i=((t,e={})=>{const n=t["content-type"];if(!n)throw new st(400,{body:"Missing Content-Type"});const i=Bn(n);if(!i)throw new st(400,{body:"Malformed content type"});const r="application/x-www-form-urlencoded"===i.mime?ii:"multipart/form-data"!==i.mime||e.blockMultipart?null:Jn;if(!r)throw new st(415);return new r(e,i.params)})(t.headers,n);fn(t);const r=new J,s=(n,s)=>{if(r.fail(new st(n,s)),i.removeAllListeners(),t.unpipe(i),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};i.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:o,mimeType:c})=>t?n?s(400,{body:`field name ${JSON.stringify(t)}... too long`}):i?s(400,{body:`value for ${JSON.stringify(t)} too long`}):void r.push({name:t,encoding:o,mimeType:c,type:"string",value:e}):s(400,{body:"missing field name"})),i.on("file",(t,e,{nameTruncated:n,filename:i,encoding:o,mimeType:c})=>t?n?s(400,{body:`field name ${JSON.stringify(t)}... too long`}):void(i?(e.once("limit",()=>s(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(i)} too large`})),r.push({name:t,encoding:o,mimeType:c,type:"file",value:e,filename:i})):e.resume()):s(400,{body:"missing field name"})),t.once("error",e=>{t.readableAborted?r.fail($t):s(500,{body:"request error",headers:{connection:"close"},cause:e})}),i.once("error",t=>s(400,{body:"error parsing form data",cause:t})),i.once("partsLimit",()=>s(400,{body:"too many parts"})),i.once("filesLimit",()=>s(400,{body:"too many files"})),i.once("fieldsLimit",()=>s(400,{body:"too many fields"}));const o=()=>r.close("complete");return i.once("close",o),Tt(t,o),t.pipe(i),r}async function ai(t,e={}){const n=new FormData,i=new Map;for await(const r of ci(t,e))if("file"===r.type){const s=r.value;let o=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const c=t=>{if("function"==typeof o){const e=o;return o=void 0,e({actualBytes:t})}};Tt(t,()=>c(0));const a=await an(t),f=await a.save(s,{mode:384});await c(f.size);const h=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(h,f.path),n.append(r.name,h)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new Error("unknown file");return e},getBoolean(t){const e=n.get(t);return null===e?null:"true"===e||"on"===e},getString(t){const e=n.get(t);return"string"==typeof e?e:null},getAllStrings:t=>n.getAll(t).filter(t=>"string"==typeof t),getFile(t){const e=n.get(t);return"string"==typeof e?null:e},getAllFiles:t=>n.getAll(t).filter(t=>"string"!=typeof t)})}const fi="win32"===/*@__PURE__*/O();function ui(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=wt(t);if(i){if("/"===i.U)return[];n=i.U.split("/")}else{const e=X(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new Error("invalid path");if(n.shift(),e){const t=fi?li:hi;if(n.some(e=>t.test(e)||e.includes(v)))throw new Error("invalid path");if(n.slice(0,n.length-1).includes(""))throw new Error("invalid path")}return n}const hi=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,li=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,di=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof o?t.write(K,n):t.once("drain",n),t.uncork()});async function wi(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:s="utf-8",headerRow:c,end:a=!0}={}){"string"==typeof n&&(n=Buffer.from(n,s)),"string"==typeof i&&(i=Buffer.from(i,s));const f="string"==typeof r?Buffer.from(r,s):r,u=r+r,h=e=>{if(!e)return!0;const n=e.includes(r);return!n&&pi.test(e)?t.write(e,s):(t.write(f),n?t.write(e.replaceAll(r,u),s):t.write(e,s),t.write(f))};t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+s+(c?"; header=present":!1===c?"; header=absent":"")),t.cork();try{t.write(K);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),h(i)||await di(t),++e;else for await(const i of r)e&&t.write(n),h(i)||await di(t),++e;t.write(i)||await di(t)}}finally{t.uncork()}a&&t.end()}const pi=/^[^"':;,\\\r\n\t ]*$/i;function mi(t){if(!t||"object"!=typeof t)return!1;const e=t;return"number"==typeof e.fd&&"function"==typeof e.stat&&"function"==typeof e.createReadStream}class yi{lt;ze;We;m;constructor(t){(t=>{const e=t;return"function"==typeof e.Te&&"function"==typeof e.pipe})(t)&&(t=I.toWeb(t)),this.lt=t.getReader(),this.ze=null,this.We=0,this.m=0}getRange(t,e){if(e<t)throw new Error("invalid range");if(t<this.We)throw new Error("non-sequential range");if(this.m)throw new Error("previous range still active");let n=e-t+1,i=t-this.We;this.We=e+1,this.m=1;const r=this,s=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.ze=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new B({start(t){if(r.ze){const e=r.ze;r.ze=null,s(e,t)}},async pull(t){if(n<=0)return r.m=0,void t.close();const e=await r.lt.read();e.done?t.error(new Error("range exceeds content")):"string"==typeof e.value?s(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?s(e.value,t):t.error(new Error("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.lt.cancel(),this.lt.releaseLock()}}function gi(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let s=0;s<i.length;++s){const o=i[s];e.end>=o.start-n-1&&o.end>=e.start-n-1?t?(++r,t.start=Math.min(t.start,o.start),t.end=Math.max(t.end,o.end)):(t=o,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):r>0&&(i[s-r]=o)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function bi(t,e,n,i){if("string"==typeof n||mi(n)||(i=gi(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const s=await vi(n);return await d(s.Ve(r.start,r.end),e),void(s.Je&&await s.Je())}const r=e.getHeader("content-type"),s=l()+l()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${s}`);const o=i.ranges.map(t=>({t:[`--${s}`,...nt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Ge:t})),c=`--${s}--`;let a=c.length;for(const{t,Ge:e}of o)a+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",a),"HEAD"===t.method)return void e.end();let f="";const u=await vi(n);try{for(const{t,Ge:n}of o)e.write(f+t,"ascii"),await d(u.Ve(n.start,n.end),e,{end:!1}),f="\r\n";e.end(f+c)}finally{u.Je&&await u.Je()}}async function vi(t){if("string"==typeof t){const e=await $(t,"r");return{Ve:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Je:()=>e.close()}}if(mi(t))return{Ve:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new yi(t);return{Ve:(t,n)=>e.getRange(t,n),Je:()=>e.close()}}}async function _i(t,e,n,i,r){if(i||("string"==typeof n?i=await T(n):mi(n)&&(i=await n.stat())),i){if("GET"===t.method||"HEAD"===t.method){if(!An(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const s=ge(t,i.size,r);if(s&&Pn(t,e,i))return bi(t,e,n,gi(s,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=c(n):mi(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}function Ei(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){const a=JSON.stringify(e,n,i)??(r?"null":void 0);t instanceof o&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),c&&t.setHeader("content-length",Buffer.byteLength(a,s))),c?t.end(a,s):a&&t.write(a,s)}async function xi(t,e,{replacer:n=null,space:i="",undefinedAsNull:r=!1,encoding:s="utf-8",end:c=!0}={}){if(Array.isArray(n)){const t=new Set(n.map(t=>String(t)));n=function(e,n){return null===this||Array.isArray(this)||t.has(e)?n:void 0}}"number"==typeof i&&(i=" ".substring(0,i));const a={Ze:e=>t.write(e,s),Ke:()=>di(t),Xe:n,Ye:i};if(t instanceof o&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Si(null,"",e,a),ki(e))r&&a.Ze("null");else{t.cork(),t.write(K);try{await Ti(a,e,i?"\n":"")}finally{t.uncork()}}c&&t.end()}async function Ti(t,e,n){const i=(i,r,s)=>{t.Ze(i);const o=n+t.Ye,c=t.Ye?": ":":";let a=!0;return{u:async(n,i)=>{const r=Si(e,n,i,t);s&&ki(r)||(a?a=!1:t.Ze(","),t.Ze(o),s&&(t.Ze(JSON.stringify(n))||await t.Ke(),t.Ze(c)),await Ti(t,r,o))},Je:()=>{a||t.Ze(n),t.Ze(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||$i(e))t.Ze(JSON.stringify(e)??"null")||await t.Ke();else if(e instanceof I){t.Ze('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Ze(e.substring(1,e.length-1))||await t.Ke()}t.Ze('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.u(n,i);t.Je()}else if(Ai(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.u(String(t++),i);n.Je()}else if(Pi(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.u(String(t++),i);n.Je()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.u(n,i);t.Je()}}function Si(t,e,n,i){return i.Xe&&(n=i.Xe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const ki=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,$i=t=>JSON.isRawJSON?.(t)??!1,Ai=t=>Symbol.iterator in t,Pi=t=>Symbol.asyncIterator in t;class Ni{Qe;I;tn;en;constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){this.Qe=e,this.tn=n??0,this.I=new AbortController,e.setHeader("content-type","text/event-stream"),e.setHeader("x-accel-buffering","no"),e.setHeader("cache-control","no-store"),e.writeHead(200),e.flushHeaders(),this.ping=this.ping.bind(this),this.nn(),t.once("close",()=>this.close()),mt(t,()=>this.close(i,r))}get signal(){return this.I.signal}get open(){return!this.I.signal.aborted}nn(){this.tn&&(this.en=setTimeout(this.ping,this.tn))}ping(){!this.I.signal.aborted&&this.Qe.writable&&(clearTimeout(this.en),this.Qe.write(":\n\n",()=>this.nn()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){if(this.I.signal.aborted)throw new Error("ServerSentEvents closed");let e;this.Qe.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Qe.write(e)," "===n[0]?this.Qe.write(": "):this.Qe.write(":"),this.Qe.write(n);/[\r\n]$/.test(i)?(this.Qe.write(e),this.Qe.write(":\n")):this.Qe.write("\n"),n=!0}if(!n)return;clearTimeout(this.en),this.Qe.write("\n",()=>e())}finally{this.Qe.uncork()}await new Promise(t=>{e=t}),this.nn()}async close(t=0,e=0){if(this.I.signal.aborted){if(this.Qe.closed)return;return new Promise(t=>this.Qe.once("close",t))}this.tn=0,clearTimeout(this.en),this.I.abort(),await new Promise(n=>{if(this.Qe.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.Qe.end(`retry:${0|i}\n\n`,n)}else this.Qe.end(n)})}}const Oi=async(t,{mode:e="dynamic",fallback:n,callback:i=Mi,...r}={})=>{const s=await sn.build(_(process.cwd(),t),r);let o=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),o=t.split("/")}const a="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},f="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return At;let n=!1;const r=ui(t,a),s={mime:_e(t.headers.accept),language:_e(t.headers["accept-language"]),encoding:_e(t.headers["accept-encoding"])};let u=await f.find(r,s);if(!u&&o&&(n=!0,u=await f.find(o,s)),!u)return At;try{n&&(e.statusCode=c),e.setHeader("content-type",u.mime??Qe(m(u.canonicalPath))),u.encoding&&"identity"!==u.encoding&&e.setHeader("content-encoding",u.encoding);const r=f.vary;if(r){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+r)}await i(t,e,u,n),await _i(t,e,u.handle,u.stats)}finally{u.handle.close().catch(()=>{})}}}};function Mi(t,e,n){e.setHeader("etag",Ie(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class Ri extends Error{statusCode;statusMessage;constructor(t,{message:e,statusMessage:n,...i}={}){super(e,i),this.statusCode=0|t,this.statusMessage=n??"",this.name=`WebSocketError(${this.statusCode} ${this.statusMessage})`}static NORMAL_CLOSURE=1e3;static GOING_AWAY=1001;static UNSUPPORTED_DATA=1003;static POLICY_VIOLATION=1008;static MESSAGE_TOO_BIG=1009;static INTERNAL_SERVER_ERROR=1011;static SERVICE_RESTART=1012;static TRY_AGAIN_LATER=1013;static BAD_GATEWAY=1014}function Fi(t,{softCloseStatusCode:e=Ri.GOING_AWAY,...n}={}){const i=(i,r,s)=>new Promise((o,c)=>{const a=new t({...n,noServer:!0,clientTracking:!1});a.once("wsClientError",c),a.handleUpgrade(i,r,s,t=>{a.off("wsClientError",c),o({return:t,onError:e=>{const n=G(e,Ri);if(n)return void t.close(n.statusCode,n.statusMessage);const i=G(e,st)??st.INTERNAL_SERVER_ERROR,r=i.statusCode>=500?Ri.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Ot(t,i)}class Ci{data;isBinary;constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Ri(Ri.UNSUPPORTED_DATA,{statusMessage:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Ri(Ri.UNSUPPORTED_DATA,{statusMessage:"expected binary"});return this.data}}class Ui{rn;detach;constructor(t,{limit:e=-1,signal:n}={}){this.rn=new J;const i=e=>{t.off("message",s),t.off("close",r),this.rn.close(new Error(e))},r=()=>i("connection closed"),s=(t,n)=>{void 0!==n?this.rn.push(new Ci(t,n)):"string"==typeof t?this.rn.push(new Ci(Buffer.from(t,"utf8"),!1)):this.rn.push(new Ci(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.rn.close(new Error("signal aborted")):2===t.readyState||3===t.readyState?this.rn.close(new Error("connection closed")):(t.on("message",s),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.rn.shift(t)}[Symbol.asyncIterator](){return this.rn[Symbol.asyncIterator]()}}function Bi(t,{timeout:e,signal:n}={}){const i=new Ui(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function Ii(t){const e=pt(t);return"GET"===t.method&&(e.H?.has("websocket")??!1)}const ji=t=>t.headers.origin??it(t.headers["sec-websocket-origin"]),Di=(t,e=5e3)=>async n=>{if(!Ii(n))return;const i=await t(n);let r;try{r=await Bi(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw $t;throw new Ri(Ri.POLICY_VIOLATION,{statusMessage:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new Ri(Ri.UNSUPPORTED_DATA,{statusMessage:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{J as BlockingQueue,At as CONTINUE,sn as FileFinder,st as HTTPError,Pt as NEXT_ROUTE,Nt as NEXT_ROUTER,Se as Property,V as Queue,Yt as Router,$t as STOP,Ni as ServerSentEvents,fe as WebListener,Ri as WebSocketError,Ci as WebSocketMessage,Ui as WebSocketMessages,fn as acceptBody,Ot as acceptUpgrade,Tt as addTeardown,Vt as anyHandler,An as checkIfModified,Pn as checkIfRange,Ne as clearProperty,Nn as compareETag,tn as compressFileOffline,en as compressFilesInDir,Xe as decompressMime,xt as defer,Jt as errorHandler,Oi as fileServer,G as findCause,je as generateStrongETag,Ie as generateWeakETag,St as getAbortSignal,qt as getAbsolutePath,Z as getAddressURL,Re as getAuthData,pe as getAuthorization,Cn as getBodyJson,Mn as getBodyStream,Fn as getBodyText,Rn as getBodyTextStream,me as getCharset,ai as getFormData,ci as getFormFields,ye as getIfRange,Qe as getMime,Ht as getPathParameter,Dt as getPathParameters,Pe as getProperty,de as getQuery,ge as getRange,ui as getRemainingPathComponents,he as getSearch,le as getSearchParams,Sn as getTextDecoder,kn as getTextDecoderStream,ji as getWebSocketOrigin,Fe as hasAuthScope,gt as isSoftClosed,Ii as isWebSocketRequest,Fi as makeAcceptWebSocket,q as makeAddressTester,ln as makeGetClient,ke as makeMemo,ze as makeNegotiator,an as makeTempFileStorage,Di as makeWebSocketFallbackTokenFetcher,Le as negotiateEncoding,Bi as nextWebSocketMessage,H as parseAddress,un as proxy,xe as readHTTPDateSeconds,ve as readHTTPInteger,Ee as readHTTPKeyValues,_e as readHTTPQualityValues,be as readHTTPUnquotedCommaSeparated,Ke as readMimeTypes,xn as registerCharset,Ye as registerMime,Tn as registerUTF32,pn as removeForwarded,mn as replaceForwarded,zt as requestHandler,Ce as requireAuthScope,Me as requireBearerAuth,Ze as resetMime,Lt as restoreAbsolutePath,yn as sanitiseAndAppendForwarded,wi as sendCSVStream,_i as sendFile,Ei as sendJSON,xi as sendJSONStream,bi as sendRanges,Mi as setDefaultCacheHeaders,Ae as setProperty,mt as setSoftCloseHandler,gn as simpleAppendForwarded,gi as simplifyRange,se as toListeners,Wt as upgradeHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "a small server abstraction for creating API and resource endpoints with middleware",
5
5
  "author": "David Evans",
6
6
  "license": "MIT",