web-listener 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 David Evans
3
+ Copyright (c) 2025-2026 David Evans
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -30,17 +30,23 @@ new WebListener(router).listen(3000);
30
30
  npm install --save web-listener
31
31
  ```
32
32
 
33
- Or to just serve static content from a directory:
33
+ ### API Documentation
34
+
35
+ The full API documentation can be found in [docs/API.md](docs/API.md).
36
+
37
+ ## CLI
38
+
39
+ A full CLI tool is included for simple use-cases of serving static files or basic test fixtures.
40
+ This is primarily aimed at local development, but is robust enough for production use. To serve
41
+ static content from the current directory:
34
42
 
35
43
  ```sh
36
44
  npx web-listener . --port 8080
37
45
  ```
38
46
 
39
- The full CLI documentation can be found in [docs/CLI.md](docs/CLI.md).
40
-
41
- ## API Documentation
47
+ ### CLI Documentation
42
48
 
43
- The full API documentation can be found in [docs/API.md](docs/API.md).
49
+ The full CLI documentation can be found in [docs/CLI.md](docs/CLI.md).
44
50
 
45
51
  ## TypeScript
46
52
 
package/index.d.ts CHANGED
@@ -400,6 +400,7 @@ type TokenAuthHandler<Req, Token> = {
400
400
  } & RequestHandler<Req> & UpgradeHandler<Req>;
401
401
  declare function requireBearerAuth<Req = {}, Token = JWTToken>({ realm, extractAndValidateToken, fallbackTokenFetcher, closeOnExpiry, softCloseBufferTime, onSoftCloseError, }: BearerAuthOptions<Req, Token>): TokenAuthHandler<Req, Token>;
402
402
  declare const hasAuthScope: (req: IncomingMessage, scope: string) => boolean;
403
+ declare const getAuthScopes: (req: IncomingMessage) => Set<string>;
403
404
  declare const requireAuthScope: (scope: string) => RequestHandler & UpgradeHandler;
404
405
 
405
406
  declare function generateWeakETag(contentEncoding: string | number | string[] | undefined, fileStats: Pick<Stats, 'mtimeMs' | 'size'>): string;
@@ -1073,6 +1074,12 @@ declare function getRemainingPathComponents(req: IncomingMessage, { rejectPotent
1073
1074
  rejectPotentiallyUnsafe?: boolean | undefined;
1074
1075
  }): string[];
1075
1076
 
1077
+ declare class LoadOnDemand<T> {
1078
+ readonly load: () => MaybePromise<T>;
1079
+ constructor(load: () => MaybePromise<T>);
1080
+ }
1081
+ declare const loadOnDemand: <T>(load: () => MaybePromise<T>) => LoadOnDemand<T>;
1082
+
1076
1083
  interface CSVOptions {
1077
1084
  /**
1078
1085
  * The delimiter to use between cells
@@ -1107,6 +1114,7 @@ interface CSVOptions {
1107
1114
  end?: boolean;
1108
1115
  }
1109
1116
  type MaybeAsyncIterable<T> = Iterable<T> | AsyncIterable<T>;
1117
+ type MaybeLoadOnDemand<T> = LoadOnDemand<T> | T;
1110
1118
  /**
1111
1119
  * Output a CSV formatted table, using the format from RFC4180.
1112
1120
  * Specifically:
@@ -1117,7 +1125,7 @@ type MaybeAsyncIterable<T> = Iterable<T> | AsyncIterable<T>;
1117
1125
  *
1118
1126
  * The line and cell delimiters can be configured (e.g. `{ delimiter: '\t', newline: '\r\n' }`)
1119
1127
  */
1120
- declare function sendCSVStream(target: Writable, table: MaybeAsyncIterable<MaybeAsyncIterable<string | null | undefined>>, { delimiter, newline, quote, encoding, headerRow, end, }?: CSVOptions): Promise<void>;
1128
+ declare function sendCSVStream(target: Writable, table: MaybeLoadOnDemand<MaybeAsyncIterable<MaybeLoadOnDemand<MaybeAsyncIterable<MaybeLoadOnDemand<string | null | undefined>>>>>, { delimiter, newline, quote, encoding, headerRow, end, }?: CSVOptions): Promise<void>;
1121
1129
 
1122
1130
  declare function sendFile(req: IncomingMessage, res: ServerResponse, source: string | FileHandle | Readable | ReadableStream<Uint8Array>, fileStats?: Pick<Stats, 'mtimeMs' | 'size'> | null, options?: GetRangeOptions & SimplifyRangeOptions): Promise<void>;
1123
1131
 
@@ -1355,5 +1363,5 @@ declare class Property<T> {
1355
1363
  }
1356
1364
  declare const makeMemo: <T, Args extends any[] = []>(fn: (req: IncomingMessage, ...args: Args) => T, ...args: Args) => ((req: IncomingMessage) => T);
1357
1365
 
1358
- export { BlockingQueue, CONTINUE, FileFinder, HTTPError, NEXT_ROUTE, NEXT_ROUTER, Negotiator, Property, Queue, Router, STOP, ServerSentEvents, WebListener, WebSocketError, WebSocketMessage, WebSocketMessages, acceptBody, acceptUpgrade, addTeardown, anyHandler, checkIfModified, checkIfRange, compareETag, compressFileOffline, compressFilesInDir, conditionalErrorHandler, decompressMime, defer, delegateUpgrade, emitError, errorHandler, fileServer, findCause, generateStrongETag, generateWeakETag, getAbortSignal, getAbsolutePath, getAddressURL, getAuthorization, getBodyJSON, getBodyStream, getBodyText, getBodyTextStream, getCharset, getFormData, getFormFields, getIfRange, getMime, getPathParameter, getPathParameters, getQuery, getRange, getRemainingPathComponents, getSearch, getSearchParams, getTextDecoder, getTextDecoderStream, getWebSocketOrigin, hasAuthScope, isSoftClosed, isWebSocketRequest, jsonErrorHandler, makeAcceptWebSocket, makeAddressTester, makeGetClient, makeMemo, makeTempFileStorage, makeWebSocketFallbackTokenFetcher, negotiateEncoding, nextWebSocketMessage, parseAddress, proxy, readHTTPDateSeconds, readHTTPInteger, readHTTPKeyValues, readHTTPQualityValues, readHTTPUnquotedCommaSeparated, readMimeTypes, registerCharset, registerMime, registerUTF32, removeForwarded, replaceForwarded, requestHandler, requireAuthScope, requireBearerAuth, resetMime, restoreAbsolutePath, sanitiseAndAppendForwarded, scheduleClose, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, staticContent, staticJSON, stringPredicate, toListeners, typedErrorHandler, upgradeHandler, willSendBody };
1366
+ export { BlockingQueue, CONTINUE, FileFinder, HTTPError, LoadOnDemand, NEXT_ROUTE, NEXT_ROUTER, Negotiator, Property, Queue, Router, STOP, ServerSentEvents, WebListener, WebSocketError, WebSocketMessage, WebSocketMessages, acceptBody, acceptUpgrade, addTeardown, anyHandler, checkIfModified, checkIfRange, compareETag, compressFileOffline, compressFilesInDir, conditionalErrorHandler, decompressMime, defer, delegateUpgrade, emitError, errorHandler, fileServer, findCause, generateStrongETag, generateWeakETag, getAbortSignal, getAbsolutePath, getAddressURL, getAuthScopes, getAuthorization, getBodyJSON, getBodyStream, getBodyText, getBodyTextStream, getCharset, getFormData, getFormFields, getIfRange, getMime, getPathParameter, getPathParameters, getQuery, getRange, getRemainingPathComponents, getSearch, getSearchParams, getTextDecoder, getTextDecoderStream, getWebSocketOrigin, hasAuthScope, isSoftClosed, isWebSocketRequest, jsonErrorHandler, loadOnDemand, makeAcceptWebSocket, makeAddressTester, makeGetClient, makeMemo, makeTempFileStorage, makeWebSocketFallbackTokenFetcher, negotiateEncoding, nextWebSocketMessage, parseAddress, proxy, readHTTPDateSeconds, readHTTPInteger, readHTTPKeyValues, readHTTPQualityValues, readHTTPUnquotedCommaSeparated, readMimeTypes, registerCharset, registerMime, registerUTF32, removeForwarded, replaceForwarded, requestHandler, requireAuthScope, requireBearerAuth, resetMime, restoreAbsolutePath, sanitiseAndAppendForwarded, scheduleClose, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, staticContent, staticJSON, stringPredicate, toListeners, typedErrorHandler, upgradeHandler, willSendBody };
1359
1367
  export type { AcceptUpgradeHandler, AcceptUpgradeResult, Address, AugmentedFormData, AugmentedServer, CSVOptions, CombinedServerOptions, CommonMethod, CommonUpgrade, CompressionInfo, CompressionOptions, ErrorHandler, FileFinderCore, FileFinderOptions, FileNegotiation, FileNegotiationOption, FileServerOptions, FormField, GetClient, GetClientOptions, GetFormDataOptions, GetFormFieldsOptions, GetRangeOptions, HTTPErrorOptions, HTTPRange, HandlerResult, JSONErrorHandlerOptions, JSONOptions, ListenOptions, ListenerOptions, NativeListeners, NegotiationOutput, NegotiationOutputHeaders, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, StaticContentOptions, TokenAuthHandler, UpgradeErrorHandler, UpgradeHandler, UpgradeListener, WithPathParameters };
package/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as r,Agent as o,request as i,ServerResponse as s}from"node:http";import{createReadStream as a,constants as c,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as l,randomUUID as h}from"node:crypto";import{pipeline as d}from"node:stream/promises";import{extname as w,join as p,dirname as m,basename as y,sep as g,resolve as b}from"node:path";import{readFile as v,writeFile as E,rm as _,stat as x,readdir as S,realpath as T,open as $,mkdtemp as N}from"node:fs/promises";import k from"node:zlib";import{promisify as O}from"node:util";import{tmpdir as R,platform as A}from"node:os";import{Agent as P,request as F}from"node:https";import{TransformStream as C,TextDecoderStream as U,DecompressionStream as M,ReadableStream as B}from"node:stream/web";import{Readable as I,Duplex as D}from"node:stream";function H(n){if(!n||"unknown"===n)return;const r=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(r?.[1]&&t(r[1]))return{family:"IPv4",address:r[1],port:r[2]?Number.parseInt(r[2]):void 0};const o=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(o?.[1]&&e(o[1]))return{family:"IPv6",address:o[1].toLowerCase(),port:o[2]?Number.parseInt(o[2]):void 0};if(o?.[3]&&e(o[3]))return{family:"IPv6",address:o[3].toLowerCase(),port:void 0};const i=/^(.*?):(\d+)$/i.exec(n);return i?.[2]?{family:"alias",address:i[1],port:Number.parseInt(i[2])}:{family:"alias",address:n,port:void 0}}function j(t){const e=new Set,n=[],r=[];for(const o of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(o);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,r=e<32?4294967295>>>e:0;n.push([J(t[1])|r,r]);continue}const i=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(o);if(i?.[1]){const t=z(i[1]),e=i[2]?q>>BigInt(Number.parseInt(i[2])):0n;r.push([t|e,e]);continue}e.add(o)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const o=J(t.address);return n.some(([t,e])=>(o|e)===t);case"IPv6":const i=z(t.address);return r.some(([t,e])=>(i|e)===t);default:return!1}}}const q=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function J(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function z(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}function L(t,e,n){if(t>=2147483648||Number.isNaN(t)||!n&&t<0)throw new RangeError(`${e} must fit in a 31 bit integer - got ${t}`)}class G{constructor(t){const e={t:null,o:null};this.i=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.i.o}clear(){this.i.o=null,this.i.t=null,this.u=this.i}push(t){const e={t,o:null};this.u.o=e,this.u=e}shift(){if(!this.i.o)return null;this.i=this.i.o;const t=this.i.t;return this.i.t=null,t}remove(t){for(let e=this.i;e.o;e=e.o)if(e.o.t===t){e.o=e.o.o;break}}[Symbol.iterator](){return{next:()=>{if(!this.i.o)return{value:null,done:!0};this.i=this.i.o;const t=this.i.t;return this.i.t=null,{value:t,done:!1}}}}}class W{constructor(){this.l=new G,this.h=new G,this.m=0}push(t){if(this.m)return;const e=this.h.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.l.push(t)}shift(t){return L(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.S):new Promise((e,n)=>{const r={_:e,T:n,v:null};this.h.push(r),void 0!==t&&(r.v=setTimeout(()=>{this.h.remove(r),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}$(t){this.S=t;for(const e of this.h)e.T(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.$(t))}fail(t){this.m||(this.m=2,this.$(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 V(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return V(t.cause,e);if("error"in t)return V(t.error,e)}}function Z(t,e="http"){if(!t)throw new TypeError("no address");if("string"==typeof t)return t;const n=void 0===t.port?"":`:${t.port}`;if("IPv4"===t.family||"alias"===t.family)return`${e}://${t.address}${n}`;if("IPv6"===t.family)return`${e}://[${t.address}]${n}`;throw new TypeError(`unknown address family: ${t.family}`)}const X=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),Y=(t,e)=>{if(void 0===t)return()=>!0;if(Array.isArray(t)||(t=[t]),!t.length)return()=>!1;if(1===t.length){const n=t[0];if("string"==typeof n){if(e){const t=n.toLowerCase();return e=>e.toLowerCase()===t}return t=>t===n}const r=X(n,e);return t=>r.test(t)}const n=new Set,r=[];for(const o of t)"string"==typeof o?e?n.add(o.toLowerCase()):n.add(o):r.push(X(o,e));return t=>n.has(e?t.toLowerCase():t)||r.some(e=>e.test(t))},K=/*@__PURE__*/Buffer.alloc(0),Q=t=>new URL("http://localhost"+(t.url??"/"));class tt extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const et=globalThis.SuppressedError??tt;class nt{constructor(){this.N=!1}k(t){this.N?t!==this.O&&(this.O=new et(t,this.O)):(this.O=t,this.N=!0)}R(){this.N=!1,this.O=void 0}}const rt=new WeakMap;function ot(t,e,n){const r=rt.get(t);if(r)return r;const o=Q(t),i={A:t,P:o,F:decodeURIComponent(o.pathname),C:new AbortController,U:e,M:[],B:[],I:n?at(t):null};return rt.set(t,i),i}function it(t,e,n){e||(t.I=null),t.D=n;const r=async()=>{t.C.abort(n.H.writableEnded?"complete":"client abort");const e=new nt;await st(t.M,e,t),await st(t.B,e,t,()=>{t.j=async e=>{try{await e()}catch(e){t.U(e,"tearing down",t.A)}}}),e.N&&t.U(e.O,"tearing down",t.A)};return n.H.closed?r():n.H.once("close",r),t}async function st(t,e,n,r){for(;n.J;)await n.J;const o=(async()=>{for(;;){const n=t.pop();if(!n)return void r?.();try{await n()}catch(t){e.k(t)}}})().then(()=>{n.J===o&&(n.J=void 0)});n.J=o,await o}function at(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const ct=t=>rt.get(t),ft=t=>rt.delete(t);function ut(t){const e=ct(t);if(!e)throw new RangeError("unknown request");return e}function lt(t,e,n=lt){throw t.code=e,Error.captureStackTrace(t,n),t}class ht{constructor(t){this.L=t,this.G=Object.create(null),this.W=!1}get headersSent(){return this.W}writeHead(t,e=n[t]??"-"){return this.W&&lt(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.L.write([`HTTP/1.1 ${t} ${pt(e)}`,...dt(this.G),"",""].join("\r\n"),"ascii"),this.W=!0,this}write(t,e="utf-8",n){return this.L.write(t,e,n)}end(t,e="utf-8",n){return this.L.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.G[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 dt(t){const e=[];for(const[n,r]of Object.entries(t)){const t=wt(r);t&&e.push(`${pt(n)}: ${pt(t)}`)}return e}const wt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",pt=t=>t.replaceAll(/[^ \t!-~]/g,"");function mt(t,e){const n=ct(t);n&&yt(n,e)}function yt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>xt(e,n,t))}const gt=t=>Boolean(ct(t)?.Z);function bt(t,e,n,r=0,o){const i=ut(t),s=n-Math.max(r,0),a=i.X??Number.POSITIVE_INFINITY,c=i.K?.Y??a;s>=c&&n>=a||(n<a&&(i.X=n),s<c&&(i.K={Y:s,tt:e,U:o??i.U}),_t(i))}function vt(t,e,n){if(!t.Z){if(t.D&&!t.I){const e=t.D.H;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.D?.H.once("close",()=>t.A.socket.destroy()),t.Z={tt:e,U:n},xt(t.V,t.Z,t),_t(t)}}function Et(t){if(t.D){if(t.I){if(!t.et&&t.D.H.writable){const e=new ht(t.D.H);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.D.H;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.D.H.end(()=>t.A.socket.destroy())}else t.A.socket.destroy()}function _t(t){if(clearTimeout(t.nt),!t.X||t.j)return;const e=Date.now();if(e>=t.X)return void Et(t);let n=t.X;t.K&&!t.Z&&(e<t.K.Y?n=t.K.Y:(t.Z=t.K,xt(t.V,t.Z,t))),void 0===t.nt&&t.B.push(()=>clearTimeout(t.nt)),t.nt=setTimeout(()=>_t(t),Math.min(n-e,6048e5))}async function xt(t,e,n){try{await(t?.(e.tt))}catch(t){e.U(t,"soft closing",n.A),Et(n)}}const St=(t,e)=>{const n=ut(t);n.j?n.j(e):n.M.push(e)},Tt=(t,e)=>{const n=ut(t);n.j?n.j(e):n.B.push(e)},$t=t=>ut(t).C.signal;class Nt extends Error{}const kt=/*@__PURE__*/new Nt("STOP"),Ot=/*@__PURE__*/new Nt("CONTINUE"),Rt=/*@__PURE__*/new Nt("NEXT_ROUTE"),At=/*@__PURE__*/new Nt("NEXT_ROUTER");async function Pt(t,e){const n=ut(t);if(!n.D)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.I)throw new TypeError("not an upgrade request");if(3===n.et)throw new TypeError("upgrade already delegated");if(2===n.et)return n.rt;const r=n.D.H;if(!r.readable||!r.writable)throw kt;n.et=1;const o=await e(t,r,n.D.i);return n.D.i=K,n.ot=o.onError,o.softCloseHandler&&yt(n,o.softCloseHandler),n.et=2,n.rt=o.return,o.return}function Ft(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.I)throw new TypeError("not an upgrade request");if(e.et)throw new TypeError("upgrade already handled");e.et=3}const Ct=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ut=t=>t,Mt=t=>void 0===t?void 0:""===t?[]:t.split("/"),Bt=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t),It=/*@__PURE__*/(t=>e=>{const n=[];let r=0;for(;r<e.length;++r){const o=t.get(e[r]);if(!o)break;n.push([o,!0])}return[Object.fromEntries(n),e.substring(r)]})(
2
- /*@__PURE__*/new Map([["i","it"],["!","st"]])),Dt=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Ht=Object.freeze({});function jt(t,e,n){const r=t.A.url,o=t.F,i=t.ct??Ht;return t.A.url=encodeURIComponent(e).replaceAll("%2F","/")+t.P.search,t.F=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(i),...n]))),()=>{t.A.url=r,t.F=o,t.ct=i}}function qt(t){return ct(t)?.ct??Ht}function Jt(t,e){return n=qt(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function zt(t){const e=ct(t);return e?e.P.pathname+e.P.search:t.url??"/"}function Lt(t){const e=ct(t);e&&(t.url=e.P.pathname+e.P.search)}const Gt=t=>"function"==typeof t?{handleRequest:t}:t,Wt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Vt=(t,e=te)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Zt=t=>"function"==typeof t?{handleError:t}:t,Xt=(t,e)=>Yt(e=>e instanceof t,e),Yt=(t,e)=>({handleError:(n,r,o)=>{if(o.response&&t(n))return e(n,r,o.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),Kt=t=>"function"==typeof t?{handleRequest:t}:t,Qt=t=>"function"==typeof t?{handleUpgrade:t}:t,te=()=>!1,ee=Symbol("http");class ne{constructor(){this.ft=[],this.ut=[]}k(t,e,n,r,o){const i=n?((t,e)=>{const n=["^"],r=[],o=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{it:i,st:s},a]=It(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f={lt:null,ht:!1};const u=[f];let l=!1;for(const t of a.matchAll(o)){if(t.index>c){const e=Ct(a.substring(c,t.index));null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}const e=t[0];if("{"===e)n.push("(?:"),f={...f},u.push(f);else if("}"===e){if(u.pop(),!u.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=f;if(f=u[u.length-1],null===f.lt?(f.lt=e.lt,f.ht=e.ht):null!==e.lt&&(f.lt=`(?:${f.lt}|${e.lt})`,f.ht||=e.ht),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])f.lt=null,n.push(e),s||n.push("+");else if("\\"===e[0]){const e=Ct(t[1]);null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}else{const o=e[0],i=t[2];if(!i)throw new TypeError(`unnamed parameter or unescaped '${o}' at ${t.index}`);if(null!==f.lt&&f.ht)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===o){if(l)throw new TypeError("paths must not contain more than one multi-component path parameter");l=!0,null!==f.lt?n.push(`((?:(?!${f.lt})[^/])*?(?:/.*?)?)`):n.push("(.*?)"),r.push({dt:i,wt:s?Mt:Bt})}else null!==f.lt?n.push(`((?:(?!${f.lt})[^/])+?)`):n.push("([^/]+?)"),r.push({dt:i,wt:Ut});f.lt="",f.ht=!0}c=t.index+e.length}if(c<a.length&&n.push(Ct(a.substring(c))),u.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{yt:new RegExp(n.join(""),i?"i":""),gt:r}})(n,r):{yt:null,gt:[]};if(o.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({bt:t,vt:"string"==typeof e?e.toLowerCase():e,Et:i.yt,_t:i.gt,xt:o}),this}use(...t){return this.k(null,null,null,!0,t.map(Kt))}mount(t,...e){return this.k(null,null,t,!0,e.map(Kt))}within(t){const e=new ne;return this.mount(t,e),e}at(t,...e){return this.k(null,null,t,!1,e.map(Kt))}onRequest(t,e,...n){return this.k(oe(t),ee,e,!1,n.map(Kt))}onUpgrade(t,e,n,...r){return this.k(oe(t),e,n,!1,r.map(Qt))}onError(...t){return this.k(null,null,null,!0,t.map(Zt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.k(re,ee,t,!1,e.map(Kt));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.St(t,new nt)}async handleUpgrade(t){return this.St(t,new nt)}async handleError(t,e){const n=new nt;return n.k(t),this.St(e,n)}shouldUpgrade(t){return this.Tt(ut(t))}Tt(t){for(const e of this.ft){const n=ie(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=jt(t,n.$t,[])}catch{continue}try{for(const n of e.xt)if(ce(n,t))return!0}finally{r()}}return!1}async St(t,e){const n=ut(t),r=await this.Nt(n,e);if(e.N)throw e.O;return r}async Nt(t,e){for(const n of this.ft){const r=ie(t,n);if(!r)continue;let o=()=>{};if(!0!==r)try{const e=r.kt();o=jt(t,r.$t,e)}catch(t){e.k(t);continue}try{const r=await se(t,n.xt,this.ut,e);if(r===At)break;if(r===Rt)continue;return r}finally{o()}}return Ot}}const re=new Set(["HEAD","GET"]),oe=t=>t?"string"==typeof t?t:new Set(t):null;function ie(t,e){if("string"==typeof e.bt){if(e.bt!==t.A.method)return!1}else if(null!==e.bt&&!e.bt.has(t.A.method??""))return!1;if(e.vt===ee){if(t.I)return!1}else if(null!==e.vt&&!t.I?.has(e.vt))return!1;if(null===e.Et)return!0;const n=e.Et.exec(t.F);return!!n&&{$t:"/"+(n.groups?.rest??""),kt:()=>e._t.map((t,e)=>[t.dt,t.wt(n[e+1])])}}async function se(t,e,n,r){for(const o of e){let e=await ae(o,t,r);if(e!==Ot){if(!t.I&&!(e instanceof Nt)&&n.length)try{const r="object"==typeof e?e:void 0,o=t.A,i=t.D.H;for(const t of n)await t(r,o,i)}catch(t){r.k(t);continue}return e}}return Rt}async function ae(t,e,n){if(t instanceof ne)return t.Nt(e,n);let r=Ot;try{if(n.N){if(t.handleError){const o=n.O,i=e.I?{socket:e.D.H,head:e.D.i,hasUpgraded:Boolean(e.et)}:{response:e.D.H};t.shouldHandleError&&!t.shouldHandleError(o,e.A,i)||(n.R(),r=await t.handleError(o,e.A,i))}}else if(e.I){if(t.handleUpgrade){const n=e.D;r=await t.handleUpgrade(e.A,n.H,n.i)}}else t.handleRequest&&(r=await t.handleRequest(e.A,e.D.H))}catch(t){t instanceof Nt?r=t:n.k(t)}finally{e.M.length&&await((t,e)=>st(t.M,e,t))(e,n)}return r===kt?void 0:r}function ce(t,e){if(t instanceof ne)return t.Tt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.A)}catch(t){return e.U(t,"checking should upgrade",e.A),!1}}function fe(t){if(!t||t instanceof Headers||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,wt(e)]).filter(([t,e])=>e))}class ue extends Error{constructor(t,{message:e,statusMessage:r,headers:o,body:i,...s}={}){super(e??i,s),this.statusCode=0|t,this.statusMessage=r??n[this.statusCode]??"-",this.headers=fe(o),this.body=i??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const le=(t,e,n)=>{const r=he(n);if(!r)return;const o=V(t,ue)??new ue(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(o.headers),r.setHeader("content-length",String(Buffer.byteLength(o.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(o.statusCode,o.statusMessage),r.end(o.body,"utf-8")};function he(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new ht(e);e.destroy()}function de(t,{onError:e=we,socketCloseTimeout:n=500}={}){L(n,"socketCloseTimeout");let r=0,o="",i=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.B.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})},l=async(n,s,a)=>{let c;try{c=ot(n,e,!1)}catch(t){return e(t,"parsing request",n),void le(new ue(400),0,{response:s})}if(it(c,!1,{H:s}),a&&(c.Ot=!0),u(c),1===r)vt(c,o,i);else if(2===r)return Et(c),void ft(n);const f=new nt,l=await ae(t,c,f);f.N||l!==Ot&&l!==Rt&&l!==At||f.k(new ue(404)),f.N&&(e(f.O,"handling request",n),le(f.O,0,{response:s}),ft(n))};return{request:(t,e)=>l(t,e,!1),checkContinue:(t,e)=>l(t,e,!0),upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=ot(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void le(new ue(400),0,{socket:a,hasUpgraded:!1})}if(it(f,!0,{H:a,i:c}),c=K,u(f),1===r)vt(f,o,i);else if(2===r)return Et(f),void ft(s);const l=new nt,h=await ae(t,f,l);l.N||h!==Ot&&h!==Rt&&h!==At||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.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.`),l.k(new ue(404))),l.N&&(e(l.O,"handling upgrade",s),f.ot?f.ot(l.O):le(l.O,0,{socket:a,head:f.D?.i??K,hasUpgraded:Boolean(f.et)}),ft(s))},shouldUpgrade:n=>{try{const r=ot(n,e,!0);return ce(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.Rt,o=t.code;n.writable&&!r?.headersSent&&n.end(me.get(o)??ye),n.destroy(t),("EPIPE"!==o||n.writable)&&("ECONNRESET"!==o||n.writable)&&"HPE_INVALID_EOF_STATE"!==o&&e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,o=t,i=e;for(const n of a)vt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)Et(t)}f(t)},countConnections:()=>a.size}}const we=(t,e,n)=>{(V(t,ue)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},pe=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),me=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/pe(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/pe(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/pe(408)]]),ye=/*@__PURE__*/pe(400);class ge extends EventTarget{constructor(t){super(),this.At=t}attach(t,e={}){const n=(e,n,r)=>{const o={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:o,cancelable:!0}))&&we(e,n,r)},r=de(this.At,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.checkContinue),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const o=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let i=()=>{i=void 0,t.removeListener("checkContinue",r.checkContinue),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=o),t.removeListener("clientError",r.clientError)};return(t="",e=-1,o=!1,s)=>{if(L(e,"existingConnectionTimeout",!0),o||i?.(),e>0){const o=setTimeout(()=>{i?.(),r.hardClose()},e);r.softClose(t,n,()=>{i?.(),clearTimeout(o),s?.()})}else 0===e?(i?.(),r.hardClose(s)):(i?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=r(t),n=this.attach(e,t),o=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(o=>n(t,r,!0,()=>{e.close(()=>o()),e.closeAllConnections()}))});return o}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((o,i)=>{r.once("error",i),r.listen(t,e,n.backlog??511,()=>{r.off("error",i),o(r)})})}}const be=t=>ct(t)?.P??Q(t),ve=t=>be(t).search,Ee=t=>new URLSearchParams(be(t).searchParams),_e=(t,e)=>be(t).searchParams.get(e);function xe(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function Se(t){const e=t.headers.authorization;if(!e)return;const[n,r]=xe(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function Te(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function $e(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Pe(e)}:{}}function Ne(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:o=2}={}){const i=t.headers.range;if(!i||0===e)return;const[s,a]=xe(i,"=");if("bytes"!==s||!a)return;const c=new ue(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Oe(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,o]=xe(t.trim(),"-");if(void 0===o)throw c;let i;if(r)i={start:f(r),end:o?Math.min(f(o),e-1):e-1};else{if(!o)throw c;i={start:Math.max(e-f(o),0),end:e-1}}if(!(i.start>=e)){if(i.end<i.start||u.length>=n)throw c;u.push(i)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>o)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 c}}return{ranges:u,totalSize:e}}function ke(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 Oe(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}const Re=t=>ke(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=xe(t,"=");return[e.trim(),n?.trim()??""]})),o=e.trim(),i="*/*"===o||"*"===o?0:o.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:o,specifiers:r,specificity:i,q:s}});function Ae(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new ue(400,{body:"invalid HTTP key values"});const o=r[1].toLowerCase();void 0!==r[3]?e.set(o,r[3].replaceAll(/\\(.)/g,"$1")):e.set(o,r[2].trim())}return e}function Pe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Fe=t=>"function"==typeof t?t:()=>t;class Ce{constructor(t=Ie){this.Pt=Fe(t)}set(t,e){Me(ut(t)).set(this,e)}get(t){return Be(t,this,this.Pt)}clear(t){const e=ct(t);e?.Ft?.delete(this)}withValue(t){return Vt(e=>(this.set(e,t),Ot))}}const Ue=(t,...e)=>{const n=n=>t(n,...e);return t=>Be(t,n,n)};function Me(t){return t.Ft||(t.Ft=new Map),t.Ft}function Be(t,e,n){const r=ct(t);if(!r)return n(t);const o=Me(r);if(o.has(e))return o.get(e);const i=n(t);return o.set(e,i),i}const Ie=()=>{throw new Error("property has not been set")};function De({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:o=0,onSoftCloseError:i}){const s=Fe(t);return{...Vt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Se(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new ue(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new ue(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new ue(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new ue(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-o)throw new ue(401,{headers:f,body:"token expired"});r&&bt(t,"token expired",e,o,i)}}return qe.set(t,{Ct:c,Ut:!0,Mt:h,Bt:Je(h)}),Ot}),getTokenData:t=>{const e=qe.get(t);if(!e.Ut)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Mt}}}const He=(t,e)=>qe.get(t).Bt.has(e),je=t=>Vt(e=>{const n=qe.get(e);if(!n.Bt.has(t))throw new ue(403,{headers:{"www-authenticate":`Bearer realm="${n.Ct}", scope="${t}"`},body:`scope required: ${t}`});return Ot}),qe=/*@__PURE__*/new Ce({Ct:"",Ut:!1,Mt:null,Bt:new Set});function Je(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 ze(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${l("sha256").update(n).digest("base64").substring(0,12)}"`}async function Le(t){const e=l("sha256");return"string"==typeof t?await d(a(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const Ge=t=>{const e=l("sha256");return e.write(t),`"sha256-${e.digest("base64")}"`},We={type:{It:"accept",Dt:"content-type"},language:{It:"accept-language",Dt:"content-language"},encoding:{It:"accept-encoding",Dt:"content-encoding"}},Ve=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),Ze=t=>{return{feature:"encoding",options:(e=t,n=Ve,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class Xe{constructor(t,{maxFailedAttempts:e=10}={}){this.Ht=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(We,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{jt:t.feature,qt:Y(t.match,!0),Jt:t.options.map(t=>({zt:t.file,Lt:t.value,qt:Y(t.for??t.value,!0)}))}}).filter(t=>t.Jt.length>0),this.Gt=e}*options(t,e){const n=this.Ht,r=new Set,o=this.Gt,i={},s=new Set;let a=!1;o>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(i.vary=[...s].join(", "),a=!1),yield{filename:f,headers:i}));if(!l.qt(t))return void(yield*c(f,u+1));const h=We[l.jt];s.add(We[l.jt].It),a=!0;const d=Re(e[h.It])?.sort(Ye);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.Jt){const e=d.find(e=>t.qt(e.name));e&&p.push({...e,Wt:t})}for(const t of p.sort(Ye)){const e=Ke(f,t.Wt.zt);if(!w.has(e)&&(w.add(e),i[h.Dt]=t.Wt.Lt,yield*c(e,u+1),r.size>=o))return}delete i[h.Dt],!w.has(f)&&r.size<o&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(i.vary=[...s].join(", ")),yield{filename:t,headers:i})}}const Ye=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Ke(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):w(t))}const Qe=/*@__PURE__*/rn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;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 tn=/*@__PURE__*/new Map(Qe);function en(){tn=new Map(Qe)}function nn(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function rn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,o]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,i="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+i+s,c=o.replace("{ext}",a);e.set(a.toLowerCase(),c),i&&e.set((r+s).toLowerCase(),c)}}return e}function on(t){for(const[e,n]of t)tn.set(e.toLowerCase(),n)}function sn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=tn.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const an=/*@__PURE__*/new Map([["zstd",t=>O(k.zstdCompress)(t)],["br",t=>O(k.brotliCompress)(t,{params:{[k.constants.BROTLI_PARAM_QUALITY]:k.constants.BROTLI_MAX_QUALITY,[k.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>O(k.gzip)(t,{level:k.constants.Z_BEST_COMPRESSION})],["deflate",t=>O(k.deflate)(t)]]);async function cn(t,e,n){const r=t.byteLength-n;if(r<=0)return;const o=an.get(e);if(!o)return;const i=await o(t);return i.byteLength<=r?i:void 0}const fn=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function un(t,e,{minCompression:n=0,deleteObsolete:r=!1,filter:o=fn}={}){const i=await v(t),s={file:t,mime:sn(w(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(!o(t,s.mime))return s;for(const o of e){const e=p(m(t),Ke(y(t),o.file));if(e===o.file)continue;const a=await cn(i,o.value,n);a?(await E(e,a),s.bestSize=Math.min(s.bestSize,a.byteLength),++s.created):r&&await _(e).catch(()=>{})}return s}async function ln(t,e,n={}){const r=[];await hn(t,r);const o=new Set(r);for(const t of o)for(const n of e){const e=p(m(t),Ke(y(t),n.file));e!==t&&o.delete(e)}return Promise.all([...o].map(t=>un(t,e,n)))}async function hn(t,e){const n=await x(t);if(n.isDirectory())for(const n of await S(t))await hn(p(t,n),e);else n.isFile()&&e.push(t)}const dn=(t,e,n)=>{const r=ut(t);r.U(e,n??(r.I?"handling upgrade":"handling request"),t)},wn=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:o="application/json"}={})=>({handleError:(i,s,a)=>{if(a.hasUpgraded||e&&!pn(s,o))throw i;n&&dn(s,i);const c=he(a);if(!c)return;const f=V(i,ue)??new ue(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",o),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||pn(n,o))}),pn=(t,e)=>Re(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class mn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:o=!1,allowDirectIndexAccess:i=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.Vt=t,this.Zt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Xt=n,this.Yt=r,this.Kt=o,this.Qt=i,this.te=c,this.ee=["",...f],this.ne=new Set(s.map(t=>this.re(t))),this.oe=Y(a,!n),this.ie=new Set(c.map(t=>this.re(t))),this.se=u}static async build(t,e={}){return new mn(await T(t,{encoding:"utf-8"})+g,e)}re(t){return"exact"===this.Xt?t:t.toLowerCase()}ae(t){if(this.ne.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Kt)||"."===e[0]&&!this.Yt||this.oe(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.ie.has(this.re(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(g);if("force-lowercase"===this.Xt&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let o=b(this.Vt,r);if(!o.startsWith(this.Vt)&&o+g!==this.Vt)return n?.push(`${JSON.stringify(o)} is not inside root ${JSON.stringify(this.Vt)}`),null;let i=null,s=null;for(const t of this.ee){const e=o+t;if(i=e.substring(this.Vt.length).split(g).filter(t=>t),i.length-1>this.Zt)return n?.push(`${JSON.stringify(o)} is nested too deeply (${i.length-1} > ${this.Zt})`),null;if(i.some(t=>!this.ae(this.re(t))))return n?.push(`${JSON.stringify(o)} is not permitted`),null;const r=i[i.length-1]??"";if(!this.Qt&&this.ie.has(this.re(r))&&!this.ne.has(this.re(r)))return n?.push(`${JSON.stringify(o)} is a hidden index file`),null;if(s=await T(e,{encoding:"utf-8"}).catch(()=>null),s){o=e;break}}if(!s||!i)return n?.push(`file ${JSON.stringify(o)} does not exist`),null;if(this.re(s)!==this.re(o))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(o)}`),null;let a=s,c=await x(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(i.length>this.Zt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${i.length} > ${this.Zt})`),null;for(const t of this.te){const e=p(s,t);if(c=await x(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.se)return gn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=y(a),u=m(a);for(const t of this.se.options(f,e)){if(!t.filename||t.filename.includes(g))continue;const e=await gn({canonicalPath:a,negotiatedPath:p(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.Vt],depth:0});for(const{dir:t,depth:r}of n){const o=await S(p(...t),{withFileTypes:!0,encoding:"utf-8"}),i=new Set(o.map(t=>this.re(t.name)));for(const s of o){const o=this.re(s.name);if(!this.ae(o))continue;const a=[...t,s.name];if(s.isDirectory())r<this.Zt&&n.push({dir:a,depth:r+1}),e(this.re(a.slice(1).join("/")),yn);else if(s.isFile()){const n={file:p(...a),dir:p(...t),basename:o,siblings:i},r=this.te.indexOf(o);if(-1!==r&&(e(this.re(t.slice(1).join("/")),{...n,p:this.te.length+1-r}),!this.Qt&&!this.ne.has(o)))continue;const c=this.re(a.slice(1).join("/"));for(let t=0;t<this.ee.length;++t){const r=this.ee[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const o=t.get(this.re(e.join("/")));if(!o?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.se)return gn({canonicalPath:o.file,negotiatedPath:o.file,headers:{}},r);for(const t of this.se.options(o.basename,n)){if(!o.siblings.has(this.re(t.filename)))continue;const e=await gn({canonicalPath:o.file,negotiatedPath:p(o.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const yn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function gn(t,e){const n=await $(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),o=await n.stat().catch(r);return o?.isFile()?{handle:n,stats:o,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const bn=/*@__PURE__*/Ue(async t=>{const e=$t(t);if(e.aborted)throw kt;e.throwIfAborted();const n=await N(p(R(),"upload"));Tt(t,()=>_(n,{recursive:!0}));let r=0;const o=()=>{if(e.aborted)throw kt;return p(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:o,save:async(t,{mode:n=384}={})=>{const r=o(),i=f(r,{mode:n});try{return await d(t,i,{signal:e}),{path:r,size:i.bytesWritten}}finally{i.close()}}}}),vn=(t,e)=>e instanceof Error&&"ERR_STREAM_PREMATURE_CLOSE"===e.code&&t.closed;function En(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.C.signal.aborted)throw kt;e.Ot&&(e.Ot=!1,e.D.H.writeContinue())}function _n(t){const e=ut(t);return!e.C.signal.aborted&&!e.Ot}function xn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:r=["connection","keep-alive","transfer-encoding"],responseHeaders:s=[],agent:a,...c}={}){const f=new URL(t);let u;"https:"===f.protocol?(a??=new P({keepAlive:!0,...c}),u=i):(a??=new o({keepAlive:!0,...c}),u=F);const l=f.pathname,h=l+(l.endsWith("/")?"":"/"),w="a://a"+h;return Gt((t,o)=>new Promise((i,c)=>{if(o.closed||!o.writable)return c(kt);const p=$t(t),m=t=>c(p.aborted?kt:new ue(502,{cause:t})),y=new URL(w+t.url?.substring(1));if(!y.pathname.startsWith(h)&&y.pathname!==l)return c(new ue(400,{message:"directory traversal blocked"}));En(t);let g={...t.headers};Sn(g,e);for(const e of n)g=e(t,g);const b=u(f,{agent:a,path:y.pathname+y.search,method:t.method,headers:g,signal:p});b.once("error",m),b.once("response",e=>{if(o.closed||!o.writable)return c(kt);if(!o.headersSent){let n={...e.headers};Sn(n,r);for(const r of s)n=r(t,e,n);o.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,o).then(i,t=>c(vn(o,t)?kt:t))}),d(t,b).catch(m)}))}function Sn(t,e){for(const e of ke(t.connection)??[])Dt(t,e.toLowerCase());for(const n of e)Dt(t,n)}function Tn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?j(e):()=>!0,o=t??(e?Number.POSITIVE_INFINITY:0),i=new Set(n);return Ue(t=>{const e=e=>{if(i.has(e))return ke(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),h=[$n(t)];if(n)for(const t of n)try{const e=Ae(t);h.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(H),e=a??[],n=c??f??u??[];let r=h[0].client;for(let o=0;o<t.length;++o){const i=t[o];h.push({client:i,server:l?.[o]??(r?{...r,port:void 0}:void 0),host:e[o],proto:n[o]}),r=i}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+o,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const $n=t=>({client:{...H(t.socket.remoteAddress)??Nn,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??Nn,port:t.socket.localPort},host:t.headers.host,proto:t.socket.encrypted?"https":"http"}),Nn={family:"alias",address:"_disconnected",port:void 0};function kn(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 On(t,e){const n=kn(0,e);return n.forwarded=Pn([$n(t)]),n}const Rn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const o=kn(0,r),i=t(n);return o.forwarded=Pn([...e?i.trusted:i.outwardChain].reverse()),o};function An(t,e){let n=t.headers.forwarded;const r=Pn([$n(t)]);n?n+=", "+r:n=r;const o=kn(0,e);return o.forwarded=n,o}function Pn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,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 Fn{constructor(t,{fatal:e=!1}={}){this.ce=t,this.fe=e,this.ue=new Uint8Array(4),this.le=new DataView(this.ue.buffer),this.he=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,r=[];let o=0;if(this.he>0){if(o=4-this.he,n<o)return this.ue.set(t,this.he),this.he+=n,"";this.ue.set(t.subarray(0,o),this.he),r.push(this.le.getUint32(0,this.ce)),this.he=0}const i=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=o;for(const t=n-3;s<t;s+=4)r.push(i.getUint32(s,this.ce));if(e?(s<n&&this.ue.set(t.subarray(s)),this.he=n-s):(this.he=0,s<n&&(this.fe?lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):r.push(65533))),r.length>0){try{return String.fromCodePoint(...r)}catch{this.fe&&lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<r.length;++t)r[t]>1114111&&(r[t]=65533);return String.fromCodePoint(...r)}return""}}class Cn extends C{constructor(t){super({transform(e,n){try{const r=t.decode(e,{stream:!0});r&&n.enqueue(r)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(K);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const Un=new Map;function Mn(t,e){Un.set(t.toLowerCase(),e)}function Bn(){Mn("utf-32be",{decoder:t=>new Fn(!1,t)}),Mn("utf-32le",{decoder:t=>new Fn(!0,t)})}function In(t,e={}){const n=Un.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new ue(415,{body:`unsupported charset: ${t}`})}}function Dn(t,e={}){const n=Un.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new Cn(n.decoder(e));try{return new U(t,e)}catch{throw new ue(415,{body:`unsupported charset: ${t}`})}}const Hn=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function jn(t,e,n){const r=Pe(t.headers["if-modified-since"]),o=ke(t.headers["if-none-match"]);if(o){if(Jn(e,n,o))return!1}else if(n&&r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function qn(t,e,n){let r=!0;const o=$e(t);return o.etag&&(r&&=Jn(e,n,o.etag)),o.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===o.modifiedSeconds),r}function Jn(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!(!e||!n.some(t=>t.startsWith('W/"')))&&n.includes(ze(t.getHeader("content-encoding"),e))}class zn extends C{constructor(t,e){super({transform(r,o){n+=r.byteLength,n>t?o.error(e):o.enqueue(r)}});let n=0}}function Ln(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const o=Oe(t.headers["content-length"]);if(void 0!==o&&o>n)throw new ue(413);const i=ke(t.headers["content-encoding"])??[];if(i.length>r)throw new ue(415,{body:"too many content-encoding stages"});En(t);let s=I.toWeb(t);void 0===o&&Number.isFinite(n)&&(s=s.pipeThrough(new zn(n,new ue(413))));for(const t of i.reverse())s=s.pipeThrough(Zn(t));return Number.isFinite(e)&&(s=s.pipeThrough(new zn(e,new ue(413,{body:"decoded content too large"})))),s}function Gn(t,e={}){const n=Ln(t,e),r=Te(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Dn(r,e))}async function Wn(t,e={}){const n=[];for await(const r of Gn(t,e))n.push(r);return n.join("")}async function Vn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(3);let o=0,i=null;for(;;){const t=await n.read(),e=3-o;if(t.done){0===o?(r[0]=1,r[1]=1):1===o&&(r[1]=r[0]),r[2]=r[0],i=null;break}if(i=t.value,i.byteLength>=e){r.set(i.subarray(0,e),o);break}r.set(i,o),o+=i.byteLength}const s=Hn[(r[0]?4:0)|(r[1]?2:0)|(r[2]?1:0)];if(!s)throw n.cancel(),new ue(415,{body:"invalid JSON encoding"});const a=Dn(s,e),c=a.writable.getWriter();return o&&c.write(r.subarray(0,o)),i&&c.write(i),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Ln(t,e),e),r=[];for await(const t of n)r.push(t);try{return JSON.parse(r.join(""))}catch(t){throw new ue(400,{body:"invalid JSON",cause:t})}}function Zn(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new M("gzip");case"deflate":return new M("deflate");case"br":try{return new M("brotli")}catch{return D.toWeb(k.createBrotliDecompress())}case"zstd":try{return D.toWeb(k.createZstdDecompress())}catch{throw new ue(415,{body:"unsupported content encoding"})}default:throw new ue(415,{body:"unknown content encoding"})}}function Xn(t){if(!t)return null;const[e,n]=xe(t,";"),r=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 o=e[1].toLowerCase(),i=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";r.has(o)||r.set(o,i)}}return{mime:e.trim().toLowerCase(),params:r}}function Yn(t,e,n,r){const o=t.byteLength;for(;e<o;){for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)break;if(59!==t[e++])return!1;for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)return!1;const i=e;for(;e<o;++e){const n=t[e];if(!Kn[n]){if(61===n)break;return!1}}if(e===o)return!1;const s=t.latin1Slice(i,e).toLowerCase();if("*"===s[s.length-1]){const r=++e;for(;e<o;++e){const n=t[e];if(!tr[n]){if(39!==n)return!1;break}}if(e===o)return!1;const i=In(t.latin1Slice(r,e));for(++e;e<o&&39!==t[e];++e);if(e===o)return!1;if(++e===o)return!1;let a=e;const c=[];for(;e<o;++e){const n=t[e];if(1!==Qn[n]){if(37===n){let n,r;if(e+2<o&&16!==(n=nr[t[e+1]])&&16!==(r=nr[t[e+2]])){const o=(n<<4)+r;e>a&&c.push(i.decode(t.subarray(a,e),{stream:!0})),c.push(i.decode(Buffer.from([o]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(i.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===o)return!1;if(34===t[e]){let i=++e,a=!1;const c=[];for(;e<o;++e){const n=t[e];if(92!==n){if(34===n){if(a){i=e,a=!1;continue}c.push(r.decode(t.subarray(i,e)));break}if(a&&(i=e-1,a=!1),!er[n])return!1}else a?(i=e,a=!1):(c.push(r.decode(t.subarray(i,e),{stream:!0})),a=!0)}if(e===o)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<o;++e){const n=t[e];if(!Kn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,r.decode(t.subarray(a,e)))}return!0}const Kn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1],33),t})(),Qn=/*@__PURE__*/(()=>{const t=new Uint8Array(Kn);return t.set([0,1,0,0,0,0],37),t})(),tr=/*@__PURE__*/(()=>{const t=new Uint8Array(Kn);return t.set([0,0,0,0,1,0,1,0],39),t.set([1,0,1,1],123),t})(),er=/*@__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})(),nr=/*@__PURE__*/(()=>{const t=new Uint8Array(256).fill(16);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 rr{constructor(t,e,n){const r=t.byteLength;if(!r||r>65535)throw new RangeError("invalid needle");this.de=t,this.we=e,this.pe=n,this.me=null,this.ye=0,this.ge=null}push(t){let e=0;const n=t.byteLength,r=this.de,o=r.byteLength-1,i=n-o;let s=-this.ye;if(this.ye){const a=this.ge,c=this.me,f=r[o];if(s<i){const n=t[s+o];n!==f||t.compare(r,-s,o,0,s+o)?s+=a[n]:(this.pe(),this.ye=0,e=s+=o+1)}const u=i<0?i:0;for(;s<u;){const n=t[s+o];if(n===f&&!c.compare(r,0,-s,this.ye+s,this.ye)&&!t.compare(r,-s,o,0,s+o)){this.we(c,0,this.ye+s,!1),this.pe(),this.ye=0,e=s+=o+1;break}s+=a[n]}const l=this.ye;if(l>0){const e=r[0];for(;s<0;){const o=c.subarray(0,l).indexOf(e,l+s);if(-1===o){s=0;break}const i=l-o;if(!c.compare(r,1,i,o+1,l)&&!t.compare(r,i,i+n))return o&&(this.we(c,0,o,!1),c.copy(c,0,o,i)),c.set(t,i),void(this.ye+=n-o);s=o+1-l}this.we(c,0,l,!1),this.ye=0}}for(;s<i;){const n=t.indexOf(r,s);if(-1!==n){if(n>e&&this.we(t,e,n,!0),this.pe(),n===i+1)return;e=s=n+o+1}else s=i}const a=r[0];for(;s<n;){const i=t.indexOf(a,s);if(-1===i)return void this.we(t,e,n,!0);if(!t.compare(r,1,n-i,i+1)){if(!this.me){this.me=Buffer.allocUnsafe(o),this.ge=new Uint16Array(256).fill(o+1);for(let t=0;t<o;++t)this.ge[r[t]]=o-t}return t.copy(this.me,0,i),this.ye=n-i,void(i>e&&this.we(t,e,i,!0))}s=i+1}n>e&&this.we(t,e,n,!0)}destroy(){const t=this.ye;t&&this.me&&this.we(this.me,0,t,!1),this.ye=0}}class or{constructor(t){this.we=t,this.reset()}reset(){this.G=[],this.be=16384,this.m=0,this.ve="",this.Ee=void 0}push(t,e,n){let r=e,o=e;const i=Math.min(n,e+this.be);for(;o<i;)switch(this.m){case 0:for(;o<i&&Kn[t[o]];++o);if(o>r&&(this.ve+=t.latin1Slice(r,o)),o<i){if(58!==t[o])return-1;if(!this.ve)return-1;++o,this.Ee=cr.get(this.ve.toLowerCase()),this.ve="",this.m=1}break;case 1:for(;o<i;++o){const e=t[o];if(32!==e&&9!==e){r=o,this.m=2;break}}break;case 2:for(;o<i;++o){const e=t[o];if(e<32||127===e){if(13!==e)return-1;this.m=3;break}}this.Ee&&(this.ve+=t.latin1Slice(r,o)),++o;break;case 3:if(10!==t[o++])return-1;this.m=4;break;case 4:{const e=t[o];if(32===e||9===e)r=o,this.m=2;else{if(this.Ee){const t=this.Ee._e;void 0===this.G[t]?this.G[t]=this.ve:this.Ee.xe&&(this.G[t]+=","+this.ve)}13===e?(this.m=5,++o):(r=o,this.m=0,this.ve="",this.Ee=void 0)}break}case 5:{if(10!==t[o++])return-1;const e=this.G;return this.reset(),this.we(e),o}}return i<n?-1:(this.be-=i-e,i)}}const ir=0,sr=1,ar=2,cr=new Map([["content-type",{_e:ir,xe:!1}],["content-disposition",{_e:sr,xe:!1}],["content-transfer-encoding",{_e:ar,xe:!0}]]);function fr(t){const e=this.Se;e&&(this.Se=void 0,e())}const ur=/*@__PURE__*/Buffer.from("\r\n"),lr=()=>{},hr=37,dr=43,wr=/*@__PURE__*/new Uint8Array(256);function pr(t,e={}){const n=t["content-type"];if(!n)throw new ue(400,{body:"missing content-type"});const r=Xn(n);if(!r)throw new ue(400,{body:"malformed content-type"});const o=Oe(t["content-length"]);if(void 0!==o&&void 0!==e.maxNetworkBytes&&o>e.maxNetworkBytes)throw new ue(413,{body:"content too large"});if("application/x-www-form-urlencoded"===r.mime)return(({defCharset:t="utf-8",maxNetworkBytes:e=Number.POSITIVE_INFINITY,maxContentBytes:n=e,maxFieldSize:r=1048576,maxFieldNameSize:o=100,maxFields:i=Number.POSITIVE_INFINITY},s)=>{const a=s.get("charset")??t,c=/^utf-?8$/i.test(a)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(a)?2:0,f=In(a);return(t,s)=>new Promise((u,l)=>{let h=e,d=n,w=i,p=!0,m="",y=Math.min(o,d),g=0,b="",v=-2;const E=()=>{const t=!c||1===c&&8&g?f.decode(Buffer.from(m,"latin1")):m;if(p){if(y<0)return S(new ue(413,{body:`field name ${JSON.stringify(t)}... too long`})),!1;t&&s({name:t,type:"string",value:"",encoding:a,mimeType:"text/plain"})}else{if(y<0)return S(new ue(413,{body:`value for ${JSON.stringify(b)} too long`})),!1;s({name:b,type:"string",value:t,encoding:a,mimeType:"text/plain"})}return!0},_=t=>{if(!t.byteLength)return;if((h-=t.byteLength)<0)return S(new ue(413,{body:"content too large"}));if(!w)return S(new ue(413,{body:"too many fields"}));const e=t.byteLength;let n=0,i=v;if(-2!==i){if(-1===i){if(16===(i=nr[t[n++]]))return S(new ue(400,{body:"malformed urlencoded form"}));if(g|=i,n===e)return void(v=i)}const r=nr[t[n++]];if(16===r)return S(new ue(400,{body:"malformed urlencoded form"}));if(m+=String.fromCharCode((i<<4)+r),v=-2,n===e)return}for(wr[37]=1,wr[38]=1,wr[43]=1,wr[61]=p?1:0;;){const i=n;for(;n<e&&!wr[t[n]];++n);if(n>i&&y>=0&&((y-=n-i)<0?m+=t.latin1Slice(i,n+y):(d-=n-i,m+=t.latin1Slice(i,n))),n===e)return;switch(t[n++]){case hr:for(;;){if(--y<0){wr[37]=0,wr[43]=0;break}if(--d,n===e){v=-1;break}const r=nr[t[n++]];if(16===r)return S(new ue(400,{body:"malformed urlencoded form"}));if(g|=r,n===e)return void(v=r);const o=nr[t[n++]];if(16===o)return S(new ue(400,{body:"malformed urlencoded form"}));if(m+=String.fromCharCode((r<<4)+o),n===e)return;if(t[n]!==hr)break;n++}break;case 38:if(!E())return;if(b="",p=!0,wr[61]=1,wr[37]=1,wr[43]=1,m="",y=Math.min(o,d),g=0,! --w)return S(new ue(413,{body:"too many fields"}));break;case dr:--y<0?(wr[37]=0,wr[43]=0):(--d,m+=" ");break;case 61:if(b=!c||1===c&&8&g?f.decode(Buffer.from(m,"latin1")):m,y<0)return S(new ue(413,{body:`field name ${JSON.stringify(b)}... too long`}));p=!1,wr[61]=0,wr[37]=1,wr[43]=1,m="",g=0,y=Math.min(r,d)}if(n===e)return}},x=()=>{if(-2!==v)return S(new ue(400,{body:"malformed urlencoded form"}));E()&&(t.off("data",_),t.off("end",x),t.off("error",S),u())},S=e=>{t.off("data",_),t.off("end",x),t.off("error",S),l(e)};t.on("data",_),t.once("end",x),t.once("error",S)})})(e,r.params);if("multipart/form-data"===r.mime&&!e.blockMultipart)return function({preservePath:t,fileHwm:e,defParamCharset:n="utf-8",defCharset:r="utf-8",maxNetworkBytes:o=Number.POSITIVE_INFINITY,maxContentBytes:i=o,maxFieldSize:s=1048576,maxFileSize:a=Number.POSITIVE_INFINITY,maxTotalFileSize:c=Number.POSITIVE_INFINITY,maxFieldNameSize:f=100,maxParts:u=Number.POSITIVE_INFINITY,maxFields:l=Number.POSITIVE_INFINITY,maxFiles:h=Number.POSITIVE_INFINITY},d){const w=d.get("boundary");if(!w)throw new ue(400,{body:"multipart boundary not found"});if(w.length>70)throw new ue(400,{body:"multipart boundary too long"});const p=In(n),m={autoDestroy:!0,emitClose:!0,highWaterMark:e,read:fr};return(e,n)=>new Promise((d,y)=>{let g,b,v,E,_,x,S,T=5,$=o,N=i,k=c,O=u,R=l,A=h,P=0,F=!1,C=0,U="";const M=new or(e=>{const o=e[sr];if(!o)return void(T=5);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!Kn[t[r]]){if(!Yn(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(o,"latin1"),p);if("form-data"!==i?.type)return void(T=5);if(v=i.params.get("name"),void 0===v)return q(new ue(400,{body:"missing field name"}));const c=Buffer.byteLength(v,"utf-8"),u=Math.min(f,N);if(c>u)return q(new ue(413,{body:`field name ${JSON.stringify(v.substring(0,u))}... too long`}));N-=c,E=i.params.get("filename*")??i.params.get("filename");const l=Xn(e[ir]);if(_=l?.mime??"text/plain",x=e[ar]?.toLowerCase()??"7bit","application/octet-stream"===_||void 0!==E){if(!A--)return q(new ue(413,{body:"too many files"}));if(!E)return void(T=5);t||(E=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(E));const e=new I(m);e.once("error",lr),e.once("close",()=>{e.Se?.(),e.off("error",lr),! --C&&b&&process.nextTick(b)}),g=e,++C,P=Math.min(a,k,N,$),n({name:v,type:"file",value:e,filename:E,encoding:x,mimeType:_,sizeLimit:P}),T=4}else{if(!R--)return q(new ue(413,{body:"too many fields"}));T=4,P=Math.min(s,N,$);const t=l?.params.get("charset")?.toLowerCase()??r;S=In(t)}}),B=Buffer.from(`\r\n--${w}`,"latin1"),D=new rr(B,(t,n,r,o)=>{if(T<=2){if(0===T){if(13===t[n])T=1;else{if(45!==t[n])return void(T=5);T=2}if(++n===r)return}if(1!==T)return 45!==t[n]?void(T=5):(T=6,e.off("data",H),void e.resume());if(10!==t[n++])return void(T=5);if(!O--)return q(new ue(413,{body:"too many parts"}));if(T=3,n===r)return}if(3===T){if(-1===(n=M.push(t,n,r)))return q(new ue(400,{body:"malformed part header"}));if(n===r)return}if(4===T){const e=Math.min(r,n+P);if(P-=r-n,N-=r-n,g){if(k-=r-n,e>n){let r;r=o?t.subarray(n,e):Buffer.copyBytesFrom(t,n,e-n),g.push(r)||(F=!0)}if(P<0)return q(new ue(413,{body:`uploaded file for ${JSON.stringify(v)}: ${JSON.stringify(E)} too large`}))}else{if(P<0)return q(new ue(413,{body:`value for ${JSON.stringify(v)} too long`}));U+=t.latin1Slice(n,e)}}},()=>{if(3===T)return q(new ue(400,{body:"unexpected end of headers"}));if(4===T)if(g)g.push(null),g=void 0,F=!1;else{const t=Buffer.from(U,"latin1");U="",n({name:v,type:"string",value:S.decode(t),encoding:x,mimeType:_})}T<6&&(T=0)});D.push(ur);const H=t=>{if(($-=t.byteLength)<0)return q(new ue(413,{body:"content too large"}));F=!1,D.push(t),g&&F&&(e.pause(),g.Se=()=>e.resume())},j=()=>{if(7!==T){if(6!==T&&(D.destroy(),6!==T))return q(new ue(400,{body:"unexpected end of form"}));e.off("data",H),e.off("end",j),b=()=>{e.off("error",q),d()},C||b()}},q=t=>{7!==T&&(T=7,e.off("data",H),e.off("end",j),e.off("error",q),g?.destroy(t),g=void 0,y(t))};e.on("data",H),e.once("end",j),e.once("error",q)})}(e,r.params);throw new ue(415)}function mr(t,{closeAfterErrorDelay:e=500,...n}={}){L(e,"closeAfterErrorDelay",!0);const r=()=>{if(e>=0&&t.readable){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};try{const e=pr(t.headers,n);En(t);const o=new W;return e(t,t=>o.push(t)).then(()=>o.close("complete"),e=>{o.fail(t.readableAborted?kt:e),t.resume(),r()}),o}catch(e){throw _n(t)&&(t.resume(),r()),e}}async function yr(t,e={}){const n=new FormData,r=new Map;for await(const o of mr(t,e))if("file"===o.type){const i=o.value;let s=await(e.preCheckFile?.({fieldName:o.name,filename:o.filename,encoding:o.encoding,mimeType:o.mimeType,maxBytes:o.sizeLimit}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};Tt(t,()=>a(0));const c=await bn(t),f=await c.save(i,{mode:384});await a(f.size);const l=new File([await u(f.path)],o.filename,{type:o.mimeType});r.set(l,f.path),n.append(o.name,l)}else{let t=o.value;e.trimAllValues&&(t=t.trim()),n.append(o.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("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 gr="win32"===/*@__PURE__*/A();function br(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=ct(t);if(r){if("/"===r.F)return[];n=r.F.split("/")}else{const e=Q(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ue(400,{body:"invalid path"});if(n.shift(),e){const t=gr?Er:vr;if(n.some(e=>t.test(e)||e.includes(g)))throw new ue(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ue(400,{body:"invalid path"})}return n}const vr=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Er=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,_r=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(K,n):t.once("drain",n),t.uncork()});async function xr(t,e,{delimiter:n=",",newline:r="\n",quote:o='"',encoding:i="utf-8",headerRow:a,end:c=!0}={}){"string"==typeof n&&(n=Buffer.from(n,i)),"string"==typeof r&&(r=Buffer.from(r,i));const f="string"==typeof o?Buffer.from(o,i):o,u=o+o,l=e=>{if(!e)return!0;const n=e.includes(o);return!n&&Sr.test(e)?t.write(e,i):(t.write(f),n?t.write(e.replaceAll(o,u),i):t.write(e,i),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+i+(a?"; header=present":!1===a?"; header=absent":"")),t.cork();try{t.write(K);for await(const o of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in o)for(const r of o)e&&t.write(n),l(r)||await _r(t),++e;else for await(const r of o)e&&t.write(n),l(r)||await _r(t),++e;t.write(r)||await _r(t)}}finally{t.uncork()}c&&t.end()}const Sr=/^[^"':;,\\\r\n\t ]*$/i;function Tr(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 $r{constructor(t){(t=>"Te"in t&&"function"==typeof t.pipe)(t)&&(t=I.toWeb(t)),this.wt=t.getReader(),this.$e=null,this.Ne=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.Ne)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.Ne;this.Ne=e+1,this.m=1;const o=this,i=(t,e)=>{const o=t.byteLength;o<=r?r-=o:o>r+n?(this.$e=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=o-r,r=0):(e.enqueue(t),n-=o)};return new B({start(t){if(o.$e){const e=o.$e;o.$e=null,i(e,t)}},async pull(t){if(n<=0)return o.m=0,void t.close();const e=await o.wt.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?i(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?i(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.wt.cancel(),this.wt.releaseLock()}}function Nr(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,o=0;for(let i=0;i<r.length;++i){const s=r[i];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++o,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):o>0&&(r[i-o]=s)}t?r.length-=o:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function kr(t,e,n,r){if(e.closed||!e.writable)throw kt;if("string"==typeof n||Tr(n)||(r=Nr(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const o=r.ranges[0];if(e.setHeader("content-length",o.end-o.start+1),e.setHeader("content-range",`bytes ${o.start}-${o.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const i=await Or(n);try{if(e.closed||!e.writable)throw kt;await d(i.ke(o.start,o.end),e)}catch(t){throw vn(e,t)?kt:t}finally{i.Oe&&await i.Oe()}return}const o=e.getHeader("content-type"),i=h()+h()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${i}`);const s=r.ranges.map(t=>({i:[`--${i}`,...dt({"content-type":o,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Re:t})),a=`--${i}--`;let c=a.length;for(const{i:t,Re:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Or(n);try{for(const{i:t,Re:n}of s){if(e.closed||!e.writable)throw kt;e.write(f+t,"ascii"),await d(u.ke(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}catch(t){throw vn(e,t)?kt:t}finally{u.Oe&&await u.Oe()}}async function Or(t){if("string"==typeof t){const e=await $(t,"r");return{ke:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Oe:()=>e.close()}}if(Tr(t))return{ke:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new $r(t);return{ke:(t,n)=>e.getRange(t,n),Oe:()=>e.close()}}}async function Rr(t,e,n,r=null,o){if(e.closed||!e.writable)throw kt;if(!r&&("string"==typeof n?r=await x(n):Tr(n)&&(r=await n.stat()),e.closed||!e.writable))throw kt;if(r){if("GET"===t.method||"HEAD"===t.method){if(!jn(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const i=Ne(t,r.size,o);if(i&&qn(t,e,r))return kr(t,e,n,Nr(i,o))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method){"string"==typeof n?n=a(n):Tr(n)&&(n=n.createReadStream({start:0,autoClose:!1}));try{await d(n,e)}catch(t){throw vn(e,t)?kt:t}}else e.end()}function Ar(t,e,{replacer:n,space:r,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,r??void 0)??(o?"null":void 0);t instanceof s&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),a&&t.setHeader("content-length",Buffer.byteLength(c,i))),a?t.end(c,i):c&&t.write(c,i)}async function Pr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!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 r&&(r=" ".substring(0,r));const c={Ae:e=>t.write(e,i),Pe:()=>_r(t),Fe:n,Ce:r??""};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Cr(null,"",e,c),Ur(e))o&&c.Ae("null");else{t.cork(),t.write(K);try{await Fr(c,e,r?"\n":"")}finally{t.uncork()}}a&&t.end()}async function Fr(t,e,n){const r=(r,o,i)=>{t.Ae(r);const s=n+t.Ce,a=t.Ce?": ":":";let c=!0;return{o:async(n,r)=>{const o=Cr(e,n,r,t);i&&Ur(o)||(c?c=!1:t.Ae(","),t.Ae(s),i&&(t.Ae(JSON.stringify(n))||await t.Pe(),t.Ae(a)),await Fr(t,o,s))},Oe:()=>{c||t.Ae(n),t.Ae(o)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Mr(e))t.Ae(JSON.stringify(e)??"null")||await t.Pe();else if(e instanceof I){t.Ae('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Ae(e.substring(1,e.length-1))||await t.Pe()}t.Ae('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.o(n,r);t.Oe()}else if(Br(e)){let t=0;const n=r("[","]",!1);for(const r of e)await n.o(String(t++),r);n.Oe()}else if(Ir(e)){let t=0;const n=r("[","]",!1);for await(const r of e)await n.o(String(t++),r);n.Oe()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.o(n,r);t.Oe()}}function Cr(t,e,n,r){return r.Fe&&(n=r.Fe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Ur=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Mr=t=>JSON.isRawJSON?.(t)??!1,Br=t=>Symbol.iterator in t,Ir=t=>Symbol.asyncIterator in t;class Dr{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:o=2e3}={}){L(n,"keepaliveInterval",!0),this.Ue=e,this.Me=n,this.C=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.Be(),t.once("close",()=>this.close()),mt(t,()=>this.close(r,o))}get signal(){return this.C.signal}get open(){return!this.C.signal.aborted}Be(){this.Me>0&&(this.Ie=setTimeout(this.ping,this.Me))}ping(){!this.C.signal.aborted&&this.Ue.writable&&(clearTimeout(this.Ie),this.Ue.write(":\n\n",()=>this.Be()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.C.signal.throwIfAborted(),this.Ue.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Ue.write(e)," "===n[0]?this.Ue.write(": "):this.Ue.write(":"),this.Ue.write(n);/[\r\n]$/.test(r)?(this.Ue.write(e),this.Ue.write(":\n")):this.Ue.write("\n"),n=!0}if(!n)return;clearTimeout(this.Ie),this.Ue.write("\n",()=>e())}finally{this.Ue.uncork()}await new Promise(t=>{e=t}),this.Be()}async close(t=0,e=0){if(this.C.signal.aborted){if(this.Ue.closed)return;return new Promise(t=>this.Ue.once("close",t))}this.Me=0,clearTimeout(this.Ie),this.C.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Ue.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.Ue.end(`retry:${0|r}\n\n`,n)}else this.Ue.end(n)})}}const Hr=(t,e)=>{e&&"identity"!==e&&t.setHeader("content-encoding",e)},jr=(t,e)=>{if(e){const n=t.getHeader("vary")??"";t.setHeader("vary",(n?n+", ":"")+e)}},qr=async(t,{mode:e="dynamic",fallback:n,verbose:r,callback:o=Jr,...i}={})=>{const s=await mn.build(b(process.cwd(),t),i);let a=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),a=s.toNormalisedPath(t.split("/"))}const f="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},u="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;let n=!1;const i=br(t,f),s=[];let l=await u.find(i,t.headers,r?s:void 0);if(!l){if(!a)return r&&dn(t,new Error(s.join(", ")),"serving static content"),Ot;if(n=!0,l=await u.find(a,t.headers,s),!l)throw new ue(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c);const r=l.headers["content-type"]??sn(w(l.canonicalPath));e.setHeader("content-type",r);const i=l.headers["content-language"];i&&e.setHeader("content-language",i),Hr(e,l.headers["content-encoding"]),jr(e,l.headers.vary),await o(t,e,l,n),await Rr(t,e,l.handle,l.stats)}finally{l.handle.close().catch(()=>{})}}}};function Jr(t,e,n){e.setHeader("etag",ze(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}const zr=(t,e,{headers:n,encodings:r=[],minCompression:o=0}={})=>{const i=(async()=>{const e=new Map;e.set("",{Mt:t,De:Ge(t)});const n=[];for(const i of r){const r=await cn(t,i,o);r&&(e.set(i,{Mt:r,De:Ge(r)}),n.push({value:i,file:i}))}const i=new Xe([{feature:"encoding",options:n}]);return t=>{for(const n of i.options("",t)){const t=e.get(n.filename);if(t)return{G:n.headers,...t}}throw new Error("failed to serve static content")}})();return{handleRequest:async(t,r)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;const{G:o,De:s,Mt:a}=(await i)(t.headers);!r.closed&&r.writable&&(n&&r.setHeaders(fe(n)),Hr(r,o["content-encoding"]),jr(r,o.vary),r.setHeader("content-type",e),r.setHeader("etag",s),jn(t,r,null)?(r.setHeader("content-length",a.byteLength),r.end(a)):r.writeHead(304).end())}}},Lr=(t,e)=>zr(Buffer.from(JSON.stringify(t),"utf-8"),"application/json",e);class Gr extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}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 Wr(t,{softCloseStatusCode:e=Gr.GOING_AWAY,...n}={}){const r=(r,o,i)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,o,i,t=>{c.off("wsClientError",a),i=K,s({return:t,onError:e=>{const n=V(e,Gr);if(n)return void t.close(n.closeCode,n.closeReason);const r=V(e,ue)??new ue(500),o=r.statusCode>=500?Gr.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(o,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Pt(t,r)}class Vr{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Gr(Gr.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Gr(Gr.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class Zr{constructor(t,{limit:e=-1,signal:n}={}){this.He=new W;const r=e=>{t.off("message",i),t.off("close",o),this.He.close(new Error(e))},o=()=>r("connection closed"),i=(t,n)=>{void 0!==n?this.He.push(new Vr(t,n)):"string"==typeof t?this.He.push(new Vr(Buffer.from(t,"utf-8"),!1)):this.He.push(new Vr(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.He.close(n.reason):2===t.readyState||3===t.readyState?this.He.close(new Error("connection closed")):(t.on("message",i),t.on("close",o),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.He.shift(t)}[Symbol.asyncIterator](){return this.He[Symbol.asyncIterator]()}}function Xr(t,{timeout:e,signal:n}={}){const r=new Zr(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function Yr(t){const e=ut(t);return"GET"===t.method&&(e.I?.has("websocket")??!1)}const Kr=t=>t.headers.origin??wt(t.headers["sec-websocket-origin"]),Qr=(t,e=5e3)=>async n=>{if(!Yr(n))return;const r=await t(n);let o;try{o=await Xr(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw kt;throw new Gr(Gr.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(o.isBinary)throw new Gr(Gr.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return o.data.toString("utf-8")};export{W as BlockingQueue,Ot as CONTINUE,mn as FileFinder,ue as HTTPError,Rt as NEXT_ROUTE,At as NEXT_ROUTER,Xe as Negotiator,Ce as Property,G as Queue,ne as Router,kt as STOP,Dr as ServerSentEvents,ge as WebListener,Gr as WebSocketError,Vr as WebSocketMessage,Zr as WebSocketMessages,En as acceptBody,Pt as acceptUpgrade,Tt as addTeardown,Vt as anyHandler,jn as checkIfModified,qn as checkIfRange,Jn as compareETag,un as compressFileOffline,ln as compressFilesInDir,Yt as conditionalErrorHandler,rn as decompressMime,St as defer,Ft as delegateUpgrade,dn as emitError,Zt as errorHandler,qr as fileServer,V as findCause,Le as generateStrongETag,ze as generateWeakETag,$t as getAbortSignal,zt as getAbsolutePath,Z as getAddressURL,Se as getAuthorization,Vn as getBodyJSON,Ln as getBodyStream,Wn as getBodyText,Gn as getBodyTextStream,Te as getCharset,yr as getFormData,mr as getFormFields,$e as getIfRange,sn as getMime,Jt as getPathParameter,qt as getPathParameters,_e as getQuery,Ne as getRange,br as getRemainingPathComponents,ve as getSearch,Ee as getSearchParams,In as getTextDecoder,Dn as getTextDecoderStream,Kr as getWebSocketOrigin,He as hasAuthScope,gt as isSoftClosed,Yr as isWebSocketRequest,wn as jsonErrorHandler,Wr as makeAcceptWebSocket,j as makeAddressTester,Tn as makeGetClient,Ue as makeMemo,bn as makeTempFileStorage,Qr as makeWebSocketFallbackTokenFetcher,Ze as negotiateEncoding,Xr as nextWebSocketMessage,H as parseAddress,xn as proxy,Pe as readHTTPDateSeconds,Oe as readHTTPInteger,Ae as readHTTPKeyValues,Re as readHTTPQualityValues,ke as readHTTPUnquotedCommaSeparated,nn as readMimeTypes,Mn as registerCharset,on as registerMime,Bn as registerUTF32,kn as removeForwarded,On as replaceForwarded,Gt as requestHandler,je as requireAuthScope,De as requireBearerAuth,en as resetMime,Lt as restoreAbsolutePath,Rn as sanitiseAndAppendForwarded,bt as scheduleClose,xr as sendCSVStream,Rr as sendFile,Ar as sendJSON,Pr as sendJSONStream,kr as sendRanges,Jr as setDefaultCacheHeaders,mt as setSoftCloseHandler,An as simpleAppendForwarded,Nr as simplifyRange,zr as staticContent,Lr as staticJSON,Y as stringPredicate,de as toListeners,Xt as typedErrorHandler,Wt as upgradeHandler,_n as willSendBody};
1
+ import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as r,Agent as o,request as i,ServerResponse as s}from"node:http";import{createReadStream as a,constants as c,createWriteStream as f,openAsBlob as u}from"node:fs";import{createHash as l,randomUUID as h}from"node:crypto";import{pipeline as d}from"node:stream/promises";import{extname as w,join as p,dirname as y,basename as m,sep as g,resolve as b}from"node:path";import{readFile as v,writeFile as E,rm as _,stat as S,readdir as x,realpath as T,open as $,mkdtemp as N}from"node:fs/promises";import k from"node:zlib";import{promisify as O}from"node:util";import{tmpdir as A,platform as R}from"node:os";import{Agent as P,request as F}from"node:https";import{TransformStream as C,TextDecoderStream as U,DecompressionStream as M,ReadableStream as B}from"node:stream/web";import{Readable as I,Duplex as D}from"node:stream";function H(n){if(!n||"unknown"===n)return;const r=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(r?.[1]&&t(r[1]))return{family:"IPv4",address:r[1],port:r[2]?Number.parseInt(r[2]):void 0};const o=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(o?.[1]&&e(o[1]))return{family:"IPv6",address:o[1].toLowerCase(),port:o[2]?Number.parseInt(o[2]):void 0};if(o?.[3]&&e(o[3]))return{family:"IPv6",address:o[3].toLowerCase(),port:void 0};const i=/^(.*?):(\d+)$/i.exec(n);return i?.[2]?{family:"alias",address:i[1],port:Number.parseInt(i[2])}:{family:"alias",address:n,port:void 0}}function j(t){const e=new Set,n=[],r=[];for(const o of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(o);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,r=e<32?4294967295>>>e:0;n.push([J(t[1])|r,r]);continue}const i=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(o);if(i?.[1]){const t=z(i[1]),e=i[2]?q>>BigInt(Number.parseInt(i[2])):0n;r.push([t|e,e]);continue}e.add(o)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const o=J(t.address);return n.some(([t,e])=>(o|e)===t);case"IPv6":const i=z(t.address);return r.some(([t,e])=>(i|e)===t);default:return!1}}}const q=/*@__PURE__*/BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");function J(t){const e=t.split(".").map(Number);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}function z(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}function L(t,e,n){if(t>=2147483648||Number.isNaN(t)||!n&&t<0)throw new RangeError(`${e} must fit in a 31 bit integer - got ${t}`)}class G{constructor(t){const e={t:null,o:null};this.i=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.i.o}clear(){this.i.o=null,this.i.t=null,this.u=this.i}push(t){const e={t,o:null};this.u.o=e,this.u=e}shift(){if(!this.i.o)return null;this.i=this.i.o;const t=this.i.t;return this.i.t=null,t}remove(t){for(let e=this.i;e.o;e=e.o)if(e.o.t===t){e.o=e.o.o;break}}[Symbol.iterator](){return{next:()=>{if(!this.i.o)return{value:null,done:!0};this.i=this.i.o;const t=this.i.t;return this.i.t=null,{value:t,done:!1}}}}}class W{constructor(){this.l=new G,this.h=new G,this.m=0}push(t){if(this.m)return;const e=this.h.shift();e?(e.v&&clearTimeout(e.v),e._(t)):this.l.push(t)}shift(t){return L(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.S):new Promise((e,n)=>{const r={_:e,T:n,v:null};this.h.push(r),void 0!==t&&(r.v=setTimeout(()=>{this.h.remove(r),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}$(t){this.S=t;for(const e of this.h)e.T(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.$(t))}fail(t){this.m||(this.m=2,this.$(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 V(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return V(t.cause,e);if("error"in t)return V(t.error,e)}}function Z(t,e="http"){if(!t)throw new TypeError("no address");if("string"==typeof t)return t;const n=void 0===t.port?"":`:${t.port}`;if("IPv4"===t.family||"alias"===t.family)return`${e}://${t.address}${n}`;if("IPv6"===t.family)return`${e}://[${t.address}]${n}`;throw new TypeError(`unknown address family: ${t.family}`)}const X=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),Y=(t,e)=>{if(void 0===t)return()=>!0;if(Array.isArray(t)||(t=[t]),!t.length)return()=>!1;if(1===t.length){const n=t[0];if("string"==typeof n){if(e){const t=n.toLowerCase();return e=>e.toLowerCase()===t}return t=>t===n}const r=X(n,e);return t=>r.test(t)}const n=new Set,r=[];for(const o of t)"string"==typeof o?e?n.add(o.toLowerCase()):n.add(o):r.push(X(o,e));return t=>n.has(e?t.toLowerCase():t)||r.some(e=>e.test(t))},K=/*@__PURE__*/Buffer.alloc(0),Q=t=>new URL("http://localhost"+(t.url??"/"));class tt extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const et=globalThis.SuppressedError??tt;class nt{constructor(){this.N=!1}k(t){this.N?t!==this.O&&(this.O=new et(t,this.O)):(this.O=t,this.N=!0)}A(){this.N=!1,this.O=void 0}}const rt=new WeakMap;function ot(t,e,n){const r=rt.get(t);if(r)return r;const o=Q(t),i={R:t,P:o,F:decodeURIComponent(o.pathname),C:new AbortController,U:e,M:[],B:[],I:n?at(t):null};return rt.set(t,i),i}function it(t,e,n){e||(t.I=null),t.D=n;const r=async()=>{t.C.abort(n.H.writableEnded?"complete":"client abort");const e=new nt;await st(t.M,e,t),await st(t.B,e,t,()=>{t.j=async e=>{try{await e()}catch(e){t.U(e,"tearing down",t.R)}}}),e.N&&t.U(e.O,"tearing down",t.R)};return n.H.closed?r():n.H.once("close",r),t}async function st(t,e,n,r){for(;n.J;)await n.J;const o=(async()=>{for(;;){const n=t.pop();if(!n)return void r?.();try{await n()}catch(t){e.k(t)}}})().then(()=>{n.J===o&&(n.J=void 0)});n.J=o,await o}function at(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const ct=t=>rt.get(t),ft=t=>rt.delete(t);function ut(t){const e=ct(t);if(!e)throw new RangeError("unknown request");return e}function lt(t,e,n=lt){throw t.code=e,Error.captureStackTrace(t,n),t}class ht{constructor(t){this.L=t,this.G=Object.create(null),this.W=!1}get headersSent(){return this.W}writeHead(t,e=n[t]??"-"){return this.W&&lt(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.L.write([`HTTP/1.1 ${t} ${pt(e)}`,...dt(this.G),"",""].join("\r\n"),"ascii"),this.W=!0,this}write(t,e="utf-8",n){return this.L.write(t,e,n)}end(t,e="utf-8",n){return this.L.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.G[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 dt(t){const e=[];for(const[n,r]of Object.entries(t)){const t=wt(r);t&&e.push(`${pt(n)}: ${pt(t)}`)}return e}const wt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",pt=t=>t.replaceAll(/[^ \t!-~]/g,"");function yt(t,e){const n=ct(t);n&&mt(n,e)}function mt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>St(e,n,t))}const gt=t=>Boolean(ct(t)?.Z);function bt(t,e,n,r=0,o){const i=ut(t),s=n-Math.max(r,0),a=i.X??Number.POSITIVE_INFINITY,c=i.K?.Y??a;s>=c&&n>=a||(n<a&&(i.X=n),s<c&&(i.K={Y:s,tt:e,U:o??i.U}),_t(i))}function vt(t,e,n){if(!t.Z){if(t.D&&!t.I){const e=t.D.H;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.D?.H.once("close",()=>t.R.socket.destroy()),t.Z={tt:e,U:n},St(t.V,t.Z,t),_t(t)}}function Et(t){if(t.D){if(t.I){if(!t.et&&t.D.H.writable){const e=new ht(t.D.H);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.D.H;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.D.H.end(()=>t.R.socket.destroy())}else t.R.socket.destroy()}function _t(t){if(clearTimeout(t.nt),!t.X||t.j)return;const e=Date.now();if(e>=t.X)return void Et(t);let n=t.X;t.K&&!t.Z&&(e<t.K.Y?n=t.K.Y:(t.Z=t.K,St(t.V,t.Z,t))),void 0===t.nt&&t.B.push(()=>clearTimeout(t.nt)),t.nt=setTimeout(()=>_t(t),Math.min(n-e,6048e5))}async function St(t,e,n){try{await(t?.(e.tt))}catch(t){e.U(t,"soft closing",n.R),Et(n)}}const xt=(t,e)=>{const n=ut(t);n.j?n.j(e):n.M.push(e)},Tt=(t,e)=>{const n=ut(t);n.j?n.j(e):n.B.push(e)},$t=t=>ut(t).C.signal;class Nt extends Error{}const kt=/*@__PURE__*/new Nt("STOP"),Ot=/*@__PURE__*/new Nt("CONTINUE"),At=/*@__PURE__*/new Nt("NEXT_ROUTE"),Rt=/*@__PURE__*/new Nt("NEXT_ROUTER");async function Pt(t,e){const n=ut(t);if(!n.D)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.I)throw new TypeError("not an upgrade request");if(3===n.et)throw new TypeError("upgrade already delegated");if(2===n.et)return n.rt;const r=n.D.H;if(!r.readable||!r.writable)throw kt;n.et=1;const o=await e(t,r,n.D.i);return n.D.i=K,n.ot=o.onError,o.softCloseHandler&&mt(n,o.softCloseHandler),n.et=2,n.rt=o.return,o.return}function Ft(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.I)throw new TypeError("not an upgrade request");if(e.et)throw new TypeError("upgrade already handled");e.et=3}const Ct=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ut=t=>t,Mt=t=>void 0===t?void 0:""===t?[]:t.split("/"),Bt=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t),It=/*@__PURE__*/(t=>e=>{const n=[];let r=0;for(;r<e.length;++r){const o=t.get(e[r]);if(!o)break;n.push([o,!0])}return[Object.fromEntries(n),e.substring(r)]})(
2
+ /*@__PURE__*/new Map([["i","it"],["!","st"]])),Dt=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Ht=Object.freeze({});function jt(t,e,n){const r=t.R.url,o=t.F,i=t.ct??Ht;return t.R.url=encodeURIComponent(e).replaceAll("%2F","/")+t.P.search,t.F=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(i),...n]))),()=>{t.R.url=r,t.F=o,t.ct=i}}function qt(t){return ct(t)?.ct??Ht}function Jt(t,e){return n=qt(t),r=e,Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0;var n,r}function zt(t){const e=ct(t);return e?e.P.pathname+e.P.search:t.url??"/"}function Lt(t){const e=ct(t);e&&(t.url=e.P.pathname+e.P.search)}const Gt=t=>"function"==typeof t?{handleRequest:t}:t,Wt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Vt=(t,e=te)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Zt=t=>"function"==typeof t?{handleError:t}:t,Xt=(t,e)=>Yt(e=>e instanceof t,e),Yt=(t,e)=>({handleError:(n,r,o)=>{if(o.response&&t(n))return e(n,r,o.response);throw n},shouldHandleError:(e,n,r)=>Boolean(r.response)&&t(e)}),Kt=t=>"function"==typeof t?{handleRequest:t}:t,Qt=t=>"function"==typeof t?{handleUpgrade:t}:t,te=()=>!1,ee=Symbol("http");class ne{constructor(){this.ft=[],this.ut=[]}k(t,e,n,r,o){const i=n?((t,e)=>{const n=["^"],r=[],o=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{it:i,st:s},a]=It(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f={lt:null,ht:!1};const u=[f];let l=!1;for(const t of a.matchAll(o)){if(t.index>c){const e=Ct(a.substring(c,t.index));null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}const e=t[0];if("{"===e)n.push("(?:"),f={...f},u.push(f);else if("}"===e){if(u.pop(),!u.length)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);const e=f;if(f=u[u.length-1],null===f.lt?(f.lt=e.lt,f.ht=e.ht):null!==e.lt&&(f.lt=`(?:${f.lt}|${e.lt})`,f.ht||=e.ht),"(?:"===n[n.length-1])throw new Error(`empty optional section in path at ${t.index}`);n.push(")?")}else if("/"===e[0])f.lt=null,n.push(e),s||n.push("+");else if("\\"===e[0]){const e=Ct(t[1]);null!==f.lt&&(f.lt+=e,f.ht=!1),n.push(e)}else{const o=e[0],i=t[2];if(!i)throw new TypeError(`unnamed parameter or unescaped '${o}' at ${t.index}`);if(null!==f.lt&&f.ht)throw new TypeError(`path parameters must be separated by at least one character at ${t.index}`);if("*"===o){if(l)throw new TypeError("paths must not contain more than one multi-component path parameter");l=!0,null!==f.lt?n.push(`((?:(?!${f.lt})[^/])*?(?:/.*?)?)`):n.push("(.*?)"),r.push({dt:i,wt:s?Mt:Bt})}else null!==f.lt?n.push(`((?:(?!${f.lt})[^/])+?)`):n.push("([^/]+?)"),r.push({dt:i,wt:Ut});f.lt="",f.ht=!0}c=t.index+e.length}if(c<a.length&&n.push(Ct(a.substring(c))),u.length>1)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{yt:new RegExp(n.join(""),i?"i":""),gt:r}})(n,r):{yt:null,gt:[]};if(o.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({bt:t,vt:"string"==typeof e?e.toLowerCase():e,Et:i.yt,_t:i.gt,St:o}),this}use(...t){return this.k(null,null,null,!0,t.map(Kt))}mount(t,...e){return this.k(null,null,t,!0,e.map(Kt))}within(t){const e=new ne;return this.mount(t,e),e}at(t,...e){return this.k(null,null,t,!1,e.map(Kt))}onRequest(t,e,...n){return this.k(oe(t),ee,e,!1,n.map(Kt))}onUpgrade(t,e,n,...r){return this.k(oe(t),e,n,!1,r.map(Qt))}onError(...t){return this.k(null,null,null,!0,t.map(Zt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.k(re,ee,t,!1,e.map(Kt));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.xt(t,new nt)}async handleUpgrade(t){return this.xt(t,new nt)}async handleError(t,e){const n=new nt;return n.k(t),this.xt(e,n)}shouldUpgrade(t){return this.Tt(ut(t))}Tt(t){for(const e of this.ft){const n=ie(t,e);if(!n)continue;let r=()=>{};if(!0!==n)try{r=jt(t,n.$t,[])}catch{continue}try{for(const n of e.St)if(ce(n,t))return!0}finally{r()}}return!1}async xt(t,e){const n=ut(t),r=await this.Nt(n,e);if(e.N)throw e.O;return r}async Nt(t,e){for(const n of this.ft){const r=ie(t,n);if(!r)continue;let o=()=>{};if(!0!==r)try{const e=r.kt();o=jt(t,r.$t,e)}catch(t){e.k(t);continue}try{const r=await se(t,n.St,this.ut,e);if(r===Rt)break;if(r===At)continue;return r}finally{o()}}return Ot}}const re=new Set(["HEAD","GET"]),oe=t=>t?"string"==typeof t?t:new Set(t):null;function ie(t,e){if("string"==typeof e.bt){if(e.bt!==t.R.method)return!1}else if(null!==e.bt&&!e.bt.has(t.R.method??""))return!1;if(e.vt===ee){if(t.I)return!1}else if(null!==e.vt&&!t.I?.has(e.vt))return!1;if(null===e.Et)return!0;const n=e.Et.exec(t.F);return!!n&&{$t:"/"+(n.groups?.rest??""),kt:()=>e._t.map((t,e)=>[t.dt,t.wt(n[e+1])])}}async function se(t,e,n,r){for(const o of e){let e=await ae(o,t,r);if(e!==Ot){if(!t.I&&!(e instanceof Nt)&&n.length)try{const r="object"==typeof e?e:void 0,o=t.R,i=t.D.H;for(const t of n)await t(r,o,i)}catch(t){r.k(t);continue}return e}}return At}async function ae(t,e,n){if(t instanceof ne)return t.Nt(e,n);let r=Ot;try{if(n.N){if(t.handleError){const o=n.O,i=e.I?{socket:e.D.H,head:e.D.i,hasUpgraded:Boolean(e.et)}:{response:e.D.H};t.shouldHandleError&&!t.shouldHandleError(o,e.R,i)||(n.A(),r=await t.handleError(o,e.R,i))}}else if(e.I){if(t.handleUpgrade){const n=e.D;r=await t.handleUpgrade(e.R,n.H,n.i)}}else t.handleRequest&&(r=await t.handleRequest(e.R,e.D.H))}catch(t){t instanceof Nt?r=t:n.k(t)}finally{e.M.length&&await((t,e)=>st(t.M,e,t))(e,n)}return r===kt?void 0:r}function ce(t,e){if(t instanceof ne)return t.Tt(e);if(!t.shouldUpgrade)return Boolean(t.handleUpgrade);try{return t.shouldUpgrade(e.R)}catch(t){return e.U(t,"checking should upgrade",e.R),!1}}function fe(t){if(!t||t instanceof Headers||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,wt(e)]).filter(([t,e])=>e))}class ue extends Error{constructor(t,{message:e,statusMessage:r,headers:o,body:i,...s}={}){super(e??i,s),this.statusCode=0|t,this.statusMessage=r??n[this.statusCode]??"-",this.headers=fe(o),this.body=i??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const le=(t,e,n)=>{const r=he(n);if(!r)return;const o=V(t,ue)??new ue(500);r.setHeader("content-type","text/plain; charset=utf-8"),r.setHeader("x-content-type-options","nosniff"),r.setHeaders(o.headers),r.setHeader("content-length",String(Buffer.byteLength(o.body,"utf-8"))),n.response||r.setHeader("connection","close"),r.writeHead(o.statusCode,o.statusMessage),r.end(o.body,"utf-8")};function he(t){if(t.response){const e=t.response;return e.headersSent?void e.end():e}const e=t.socket;if(!t.hasUpgraded&&e.writable)return e.addListener("finish",()=>e.destroy()),new ht(e);e.destroy()}function de(t,{onError:e=we,socketCloseTimeout:n=500}={}){L(n,"socketCloseTimeout");let r=0,o="",i=e;const s=[],a=new Set,c=()=>{const t=[...s];s.length=0;for(const e of t)e()},f=t=>{t&&(a.size?s.push(t):setImmediate(t))},u=t=>{a.add(t),t.B.push(()=>{a.delete(t),!a.size&&s.length&&setImmediate(c)})},l=async(n,s,a)=>{let c;try{c=ot(n,e,!1)}catch(t){return e(t,"parsing request",n),void le(new ue(400),0,{response:s})}if(it(c,!1,{H:s}),a&&(c.Ot=!0),u(c),1===r)vt(c,o,i);else if(2===r)return Et(c),void ft(n);const f=new nt,l=await ae(t,c,f);f.N||l!==Ot&&l!==At&&l!==Rt||f.k(new ue(404)),f.N&&(e(f.O,"handling request",n),le(f.O,0,{response:s}),ft(n))};return{request:(t,e)=>l(t,e,!1),checkContinue:(t,e)=>l(t,e,!0),upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=ot(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void le(new ue(400),0,{socket:a,hasUpgraded:!1})}if(it(f,!0,{H:a,i:c}),c=K,u(f),1===r)vt(f,o,i);else if(2===r)return Et(f),void ft(s);const l=new nt,h=await ae(t,f,l);l.N||h!==Ot&&h!==At&&h!==Rt||(console.warn(`Upgrade ${s.headers.upgrade} request for ${s.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.`),l.k(new ue(404))),l.N&&(e(l.O,"handling upgrade",s),f.ot?f.ot(l.O):le(l.O,0,{socket:a,head:f.D?.i??K,hasUpgraded:Boolean(f.et)}),ft(s))},shouldUpgrade:n=>{try{const r=ot(n,e,!0);return ce(t,r)}catch{return!1}},clientError:(t,n)=>{const r=n.At,o=t.code;n.writable&&!r?.headersSent&&n.end(ye.get(o)??me),n.destroy(t),("EPIPE"!==o||n.writable)&&("ECONNRESET"!==o||n.writable)&&"HPE_INVALID_EOF_STATE"!==o&&e(t,"initialising request",void 0)},softClose(t,e,n){if(r<1){r=1,o=t,i=e;for(const n of a)vt(n,t,e)}f(n)},hardClose(t){if(r<2){r=2;for(const t of a)Et(t)}f(t)},countConnections:()=>a.size}}const we=(t,e,n)=>{(V(t,ue)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},pe=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),ye=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/pe(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/pe(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/pe(408)]]),me=/*@__PURE__*/pe(400);class ge extends EventTarget{constructor(t){super(),this.Rt=t}attach(t,e={}){const n=(e,n,r)=>{const o={server:t,error:e,context:n,request:r};this.dispatchEvent(new CustomEvent("error",{detail:o,cancelable:!0}))&&we(e,n,r)},r=de(this.Rt,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",r.checkContinue),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",r.request),t.addListener("request",r.request),t.addListener("upgrade",r.upgrade);const o=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=r.shouldUpgrade),t.addListener("clientError",r.clientError);let i=()=>{i=void 0,t.removeListener("checkContinue",r.checkContinue),t.removeListener("checkExpectation",r.request),t.removeListener("request",r.request),t.removeListener("upgrade",r.upgrade),t.shouldUpgradeCallback===r.shouldUpgrade&&(t.shouldUpgradeCallback=o),t.removeListener("clientError",r.clientError)};return(t="",e=-1,o=!1,s)=>{if(L(e,"existingConnectionTimeout",!0),o||i?.(),e>0){const o=setTimeout(()=>{i?.(),r.hardClose()},e);r.softClose(t,n,()=>{i?.(),clearTimeout(o),s?.()})}else 0===e?(i?.(),r.hardClose(s)):(i?.(),s&&setImmediate(s));return r}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=r(t),n=this.attach(e,t),o=Object.assign(e,{closeWithTimeout:(t,r)=>new Promise(o=>n(t,r,!0,()=>{e.close(()=>o()),e.closeAllConnections()}))});return o}listen(t,e,n={}){const r=this.createServer(n);return n.socketTimeout&&r.setTimeout(n.socketTimeout),new Promise((o,i)=>{r.once("error",i),r.listen(t,e,n.backlog??511,()=>{r.off("error",i),o(r)})})}}const be=t=>ct(t)?.P??Q(t),ve=t=>be(t).search,Ee=t=>new URLSearchParams(be(t).searchParams),_e=(t,e)=>be(t).searchParams.get(e);function Se(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function xe(t){const e=t.headers.authorization;if(!e)return;const[n,r]=Se(e," ");return void 0!==r?[n.trim().toLowerCase(),r.trim()]:void 0}function Te(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function $e(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Pe(e)}:{}}function Ne(t,e,{maxRanges:n=10,maxNonSequential:r=2,maxWithOverlap:o=2}={}){const i=t.headers.range;if(!i||0===e)return;const[s,a]=Se(i,"=");if("bytes"!==s||!a)return;const c=new ue(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Oe(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[r,o]=Se(t.trim(),"-");if(void 0===o)throw c;let i;if(r)i={start:f(r),end:o?Math.min(f(o),e-1):e-1};else{if(!o)throw c;i={start:Math.max(e-f(o),0),end:e-1}}if(!(i.start>=e)){if(i.end<i.start||u.length>=n)throw c;u.push(i)}}if(!u.length)throw c;if(u.length>r)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>o)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 c}}return{ranges:u,totalSize:e}}function ke(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 Oe(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}const Ae=t=>ke(t)?.map(t=>{const[e,...n]=t.split(";"),r=new Map(n.map(t=>{const[e,n]=Se(t,"=");return[e.trim(),n?.trim()??""]})),o=e.trim(),i="*/*"===o||"*"===o?0:o.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(r.get("q")??"1")));return{name:o,specifiers:r,specificity:i,q:s}});function Re(t){const e=new Map,n=/\s*([^=]+)=(?:([^";]*)|"((?:[^\\"]|\\.)*)"\s*)(?:;|$)/y;for(;n.lastIndex<t.length;){const r=n.exec(t);if(!r)throw new ue(400,{body:"invalid HTTP key values"});const o=r[1].toLowerCase();void 0!==r[3]?e.set(o,r[3].replaceAll(/\\(.)/g,"$1")):e.set(o,r[2].trim())}return e}function Pe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Fe=t=>"function"==typeof t?t:()=>t;class Ce{constructor(t=Ie){this.Pt=Fe(t)}set(t,e){Me(ut(t)).set(this,e)}get(t){return Be(t,this,this.Pt)}clear(t){const e=ct(t);e?.Ft?.delete(this)}withValue(t){return Vt(e=>(this.set(e,t),Ot))}}const Ue=(t,...e)=>{const n=n=>t(n,...e);return t=>Be(t,n,n)};function Me(t){return t.Ft||(t.Ft=new Map),t.Ft}function Be(t,e,n){const r=ct(t);if(!r)return n(t);const o=Me(r);if(o.has(e))return o.get(e);const i=n(t);return o.set(e,i),i}const Ie=()=>{throw new Error("property has not been set")};function De({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:r=!0,softCloseBufferTime:o=0,onSoftCloseError:i}){const s=Fe(t);return{...Vt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=xe(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new ue(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new ue(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new ue(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new ue(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-o)throw new ue(401,{headers:f,body:"token expired"});r&&bt(t,"token expired",e,o,i)}}return Je.set(t,{Ct:c,Ut:!0,Mt:h,Bt:ze(h)}),Ot}),getTokenData:t=>{const e=Je.get(t);if(!e.Ut)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Mt}}}const He=(t,e)=>Je.get(t).Bt.has(e),je=t=>new Set(Je.get(t).Bt),qe=t=>Vt(e=>{const n=Je.get(e);if(!n.Bt.has(t))throw new ue(403,{headers:{"www-authenticate":`Bearer realm="${n.Ct}", scope="${t}"`},body:`scope required: ${t}`});return Ot}),Je=/*@__PURE__*/new Ce({Ct:"",Ut:!1,Mt:null,Bt:new Set});function ze(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 Le(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${l("sha256").update(n).digest("base64").substring(0,12)}"`}async function Ge(t){const e=l("sha256");return"string"==typeof t?await d(a(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const We=t=>{const e=l("sha256");return e.write(t),`"sha256-${e.digest("base64")}"`},Ve={type:{It:"accept",Dt:"content-type"},language:{It:"accept-language",Dt:"content-language"},encoding:{It:"accept-encoding",Dt:"content-encoding"}},Ze=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),Xe=t=>{return{feature:"encoding",options:(e=t,n=Ze,Array.isArray(e)?e.map(t=>({value:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({value:t,file:e})))};var e,n};class Ye{constructor(t,{maxFailedAttempts:e=10}={}){this.Ht=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(Ve,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{jt:t.feature,qt:Y(t.match,!0),Jt:t.options.map(t=>({zt:t.file,Lt:t.value,qt:Y(t.for??t.value,!0)}))}}).filter(t=>t.Jt.length>0),this.Gt=e}*options(t,e){const n=this.Ht,r=new Set,o=this.Gt,i={},s=new Set;let a=!1;o>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(r.has(f)||(r.add(f),a&&(i.vary=[...s].join(", "),a=!1),yield{filename:f,headers:i}));if(!l.qt(t))return void(yield*c(f,u+1));const h=Ve[l.jt];s.add(Ve[l.jt].It),a=!0;const d=Ae(e[h.It])?.sort(Ke);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.Jt){const e=d.find(e=>t.qt(e.name));e&&p.push({...e,Wt:t})}for(const t of p.sort(Ke)){const e=Qe(f,t.Wt.zt);if(!w.has(e)&&(w.add(e),i[h.Dt]=t.Wt.Lt,yield*c(e,u+1),r.size>=o))return}delete i[h.Dt],!w.has(f)&&r.size<o&&(yield*c(f,u+1))}(t,0)),r.has(t)||(a&&(i.vary=[...s].join(", ")),yield{filename:t,headers:i})}}const Ke=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Qe(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):w(t))}const tn=/*@__PURE__*/on("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};webmanifest=application/manifest+json;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 en=/*@__PURE__*/new Map(tn);function nn(){en=new Map(tn)}function rn(t){const e=new Map;for(const n of t.split("\n")){const[t,...r]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of r)e.set(n.toLowerCase(),t)}return e}function on(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,r,o]=/^ *([^ =]+)=(.*)$/.exec(n)??[null,null,""];for(const t of r?.split(",")??[]){const[n,r,i="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=r+i+s,c=o.replace("{ext}",a);e.set(a.toLowerCase(),c),i&&e.set((r+s).toLowerCase(),c)}}return e}function sn(t){for(const[e,n]of t)en.set(e.toLowerCase(),n)}function an(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=en.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const cn=/*@__PURE__*/new Map([["zstd",t=>O(k.zstdCompress)(t)],["br",t=>O(k.brotliCompress)(t,{params:{[k.constants.BROTLI_PARAM_QUALITY]:k.constants.BROTLI_MAX_QUALITY,[k.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>O(k.gzip)(t,{level:k.constants.Z_BEST_COMPRESSION})],["deflate",t=>O(k.deflate)(t)]]);async function fn(t,e,n){const r=t.byteLength-n;if(r<=0)return;const o=cn.get(e);if(!o)return;const i=await o(t);return i.byteLength<=r?i:void 0}const un=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function ln(t,e,{minCompression:n=0,deleteObsolete:r=!1,filter:o=un}={}){const i=await v(t),s={file:t,mime:an(w(t)),rawSize:i.byteLength,bestSize:i.byteLength,created:0};if(!o(t,s.mime))return s;for(const o of e){const e=p(y(t),Qe(m(t),o.file));if(e===o.file)continue;const a=await fn(i,o.value,n);a?(await E(e,a),s.bestSize=Math.min(s.bestSize,a.byteLength),++s.created):r&&await _(e).catch(()=>{})}return s}async function hn(t,e,n={}){const r=[];await dn(t,r);const o=new Set(r);for(const t of o)for(const n of e){const e=p(y(t),Qe(m(t),n.file));e!==t&&o.delete(e)}return Promise.all([...o].map(t=>ln(t,e,n)))}async function dn(t,e){const n=await S(t);if(n.isDirectory())for(const n of await x(t))await dn(p(t,n),e);else n.isFile()&&e.push(t)}const wn=(t,e,n)=>{const r=ut(t);r.U(e,n??(r.I?"handling upgrade":"handling request"),t)},pn=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:r,contentType:o="application/json"}={})=>({handleError:(i,s,a)=>{if(a.hasUpgraded||e&&!yn(s,o))throw i;n&&wn(s,i);const c=he(a);if(!c)return;const f=V(i,ue)??new ue(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",o),c.setHeader("x-content-type-options","nosniff"),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),r?c.writeHead(r):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,r)=>!r.hasUpgraded&&(!e||yn(n,o))}),yn=(t,e)=>Ae(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class mn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:r=!1,allowAllTildefiles:o=!1,allowDirectIndexAccess:i=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.Vt=t,this.Zt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Xt=n,this.Yt=r,this.Kt=o,this.Qt=i,this.te=c,this.ee=["",...f],this.ne=new Set(s.map(t=>this.re(t))),this.oe=Y(a,!n),this.ie=new Set(c.map(t=>this.re(t))),this.se=u}static async build(t,e={}){return new mn(await T(t,{encoding:"utf-8"})+g,e)}re(t){return"exact"===this.Xt?t:t.toLowerCase()}ae(t){if(this.ne.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Kt)||"."===e[0]&&!this.Yt||this.oe(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.ie.has(this.re(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let r=t.join(g);if("force-lowercase"===this.Xt&&(r=r.toLowerCase()),/(^|[\\\/])\.\.($|[\\\/])|^[\\\/]/.test(r))return n?.push(`${JSON.stringify(r)} is not permitted`),null;let o=b(this.Vt,r);if(!o.startsWith(this.Vt)&&o+g!==this.Vt)return n?.push(`${JSON.stringify(o)} is not inside root ${JSON.stringify(this.Vt)}`),null;let i=null,s=null;for(const t of this.ee){const e=o+t;if(i=e.substring(this.Vt.length).split(g).filter(t=>t),i.length-1>this.Zt)return n?.push(`${JSON.stringify(o)} is nested too deeply (${i.length-1} > ${this.Zt})`),null;if(i.some(t=>!this.ae(this.re(t))))return n?.push(`${JSON.stringify(o)} is not permitted`),null;const r=i[i.length-1]??"";if(!this.Qt&&this.ie.has(this.re(r))&&!this.ne.has(this.re(r)))return n?.push(`${JSON.stringify(o)} is a hidden index file`),null;if(s=await T(e,{encoding:"utf-8"}).catch(()=>null),s){o=e;break}}if(!s||!i)return n?.push(`file ${JSON.stringify(o)} does not exist`),null;if(this.re(s)!==this.re(o))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(o)}`),null;let a=s,c=await S(s).catch(()=>null);if(!c)return n?.push(`file ${JSON.stringify(s)} does not exist`),null;if(c.isDirectory()){if(i.length>this.Zt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${i.length} > ${this.Zt})`),null;for(const t of this.te){const e=p(s,t);if(c=await S(e).catch(()=>null),c?.isFile()){a=e;break}}}if(!c?.isFile())return n?.push(`${JSON.stringify(s)} exists but is not a file`),null;if(!this.se)return bn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=m(a),u=y(a);for(const t of this.se.options(f,e)){if(!t.filename||t.filename.includes(g))continue;const e=await bn({canonicalPath:a,negotiatedPath:p(u,t.filename),headers:t.headers},n);if(e)return e}return null}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const r=t.get(e);(!r||n.p>r.p)&&t.set(e,n)},n=new G({dir:[this.Vt],depth:0});for(const{dir:t,depth:r}of n){const o=await x(p(...t),{withFileTypes:!0,encoding:"utf-8"}),i=new Set(o.map(t=>this.re(t.name)));for(const s of o){const o=this.re(s.name);if(!this.ae(o))continue;const a=[...t,s.name];if(s.isDirectory())r<this.Zt&&n.push({dir:a,depth:r+1}),e(this.re(a.slice(1).join("/")),gn);else if(s.isFile()){const n={file:p(...a),dir:p(...t),basename:o,siblings:i},r=this.te.indexOf(o);if(-1!==r&&(e(this.re(t.slice(1).join("/")),{...n,p:this.te.length+1-r}),!this.Qt&&!this.ne.has(o)))continue;const c=this.re(a.slice(1).join("/"));for(let t=0;t<this.ee.length;++t){const r=this.ee[t];s.name.endsWith(r)&&e(c.substring(0,c.length-r.length),{...n,p:-t})}}}}return{find:async(e,n={},r)=>{const o=t.get(this.re(e.join("/")));if(!o?.file)return r?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.se)return bn({canonicalPath:o.file,negotiatedPath:o.file,headers:{}},r);for(const t of this.se.options(o.basename,n)){if(!o.siblings.has(this.re(t.filename)))continue;const e=await bn({canonicalPath:o.file,negotiatedPath:p(o.dir,t.filename),headers:t.headers},r);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const gn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function bn(t,e){const n=await $(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const r=()=>(n.close().catch(()=>{}),null),o=await n.stat().catch(r);return o?.isFile()?{handle:n,stats:o,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),r())}const vn=/*@__PURE__*/Ue(async t=>{const e=$t(t);if(e.aborted)throw kt;e.throwIfAborted();const n=await N(p(A(),"upload"));Tt(t,()=>_(n,{recursive:!0}));let r=0;const o=()=>{if(e.aborted)throw kt;return p(n,(++r).toString(10).padStart(6,"0"))};return{dir:n,nextFile:o,save:async(t,{mode:n=384}={})=>{const r=o(),i=f(r,{mode:n});try{return await d(t,i,{signal:e}),{path:r,size:i.bytesWritten}}finally{i.close()}}}}),En=(t,e)=>e instanceof Error&&"ERR_STREAM_PREMATURE_CLOSE"===e.code&&t.closed;function _n(t){const e=ut(t);if(!e.D)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.C.signal.aborted)throw kt;e.Ot&&(e.Ot=!1,e.D.H.writeContinue())}function Sn(t){const e=ut(t);return!e.C.signal.aborted&&!e.Ot}function xn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:r=["connection","keep-alive","transfer-encoding"],responseHeaders:s=[],agent:a,...c}={}){const f=new URL(t);let u;"https:"===f.protocol?(a??=new P({keepAlive:!0,...c}),u=i):(a??=new o({keepAlive:!0,...c}),u=F);const l=f.pathname,h=l+(l.endsWith("/")?"":"/"),w="a://a"+h;return Gt((t,o)=>new Promise((i,c)=>{if(o.closed||!o.writable)return c(kt);const p=$t(t),y=t=>c(p.aborted?kt:new ue(502,{cause:t})),m=new URL(w+t.url?.substring(1));if(!m.pathname.startsWith(h)&&m.pathname!==l)return c(new ue(400,{message:"directory traversal blocked"}));_n(t);let g={...t.headers};Tn(g,e);for(const e of n)g=e(t,g);const b=u(f,{agent:a,path:m.pathname+m.search,method:t.method,headers:g,signal:p});b.once("error",y),b.once("response",e=>{if(o.closed||!o.writable)return c(kt);if(!o.headersSent){let n={...e.headers};Tn(n,r);for(const r of s)n=r(t,e,n);o.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,o).then(i,t=>c(En(o,t)?kt:t))}),d(t,b).catch(y)}))}function Tn(t,e){for(const e of ke(t.connection)??[])Dt(t,e.toLowerCase());for(const n of e)Dt(t,n)}function $n({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const r=e?j(e):()=>!0,o=t??(e?Number.POSITIVE_INFINITY:0),i=new Set(n);return Ue(t=>{const e=e=>{if(i.has(e))return ke(t.headers[e])?.reverse()},n=e("forwarded"),s=e("x-forwarded-for"),a=e("x-forwarded-host"),c=e("x-forwarded-proto"),f=e("x-forwarded-protocol"),u=e("x-url-scheme"),l=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^/ ]+) (.+)$/.exec(t);return e?.[3]?H(e[3]):void 0}),h=[Nn(t)];if(n)for(const t of n)try{const e=Re(t);h.push({client:H(e.get("for")),server:H(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{h.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(H),e=a??[],n=c??f??u??[];let r=h[0].client;for(let o=0;o<t.length;++o){const i=t[o];h.push({client:i,server:l?.[o]??(r?{...r,port:void 0}:void 0),host:e[o],proto:n[o]}),r=i}}else if(l)for(const t of l)h.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+o,h.length);for(let t=0;t<d-1;++t)r(h[t].client)||(d=t+1);return Object.freeze({trusted:h.slice(0,d),untrusted:h.slice(d),outwardChain:h,edge:h[d-1]})})}const Nn=t=>({client:{...H(t.socket.remoteAddress)??kn,port:t.socket.remotePort},server:{...H(t.socket.localAddress)??kn,port:t.socket.localPort},host:t.headers.host,proto:t.socket.encrypted?"https":"http"}),kn={family:"alias",address:"_disconnected",port:void 0};function On(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 An(t,e){const n=On(0,e);return n.forwarded=Fn([Nn(t)]),n}const Rn=(t,{onlyTrusted:e=!1}={})=>(n,r)=>{const o=On(0,r),i=t(n);return o.forwarded=Fn([...e?i.trusted:i.outwardChain].reverse()),o};function Pn(t,e){let n=t.headers.forwarded;const r=Fn([Nn(t)]);n?n+=", "+r:n=r;const o=On(0,e);return o.forwarded=n,o}function Fn(t){return t.filter(t=>t.server||t.client).map(t=>Object.entries({for:t.client?.address,by:t.server?.address,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 Cn{constructor(t,{fatal:e=!1}={}){this.ce=t,this.fe=e,this.ue=new Uint8Array(4),this.le=new DataView(this.ue.buffer),this.he=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,r=[];let o=0;if(this.he>0){if(o=4-this.he,n<o)return this.ue.set(t,this.he),this.he+=n,"";this.ue.set(t.subarray(0,o),this.he),r.push(this.le.getUint32(0,this.ce)),this.he=0}const i=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=o;for(const t=n-3;s<t;s+=4)r.push(i.getUint32(s,this.ce));if(e?(s<n&&this.ue.set(t.subarray(s)),this.he=n-s):(this.he=0,s<n&&(this.fe?lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):r.push(65533))),r.length>0){try{return String.fromCodePoint(...r)}catch{this.fe&&lt(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<r.length;++t)r[t]>1114111&&(r[t]=65533);return String.fromCodePoint(...r)}return""}}class Un extends C{constructor(t){super({transform(e,n){try{const r=t.decode(e,{stream:!0});r&&n.enqueue(r)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(K);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const Mn=new Map;function Bn(t,e){Mn.set(t.toLowerCase(),e)}function In(){Bn("utf-32be",{decoder:t=>new Cn(!1,t)}),Bn("utf-32le",{decoder:t=>new Cn(!0,t)})}function Dn(t,e={}){const n=Mn.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new ue(415,{body:`unsupported charset: ${t}`})}}function Hn(t,e={}){const n=Mn.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new Un(n.decoder(e));try{return new U(t,e)}catch{throw new ue(415,{body:`unsupported charset: ${t}`})}}const jn=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function qn(t,e,n){const r=Pe(t.headers["if-modified-since"]),o=ke(t.headers["if-none-match"]);if(o){if(zn(e,n,o))return!1}else if(n&&r&&(n.mtimeMs/1e3|0)<=r)return!1;return!0}function Jn(t,e,n){let r=!0;const o=$e(t);return o.etag&&(r&&=zn(e,n,o.etag)),o.modifiedSeconds&&(r&&=(n.mtimeMs/1e3|0)===o.modifiedSeconds),r}function zn(t,e,n){if(n.includes("*"))return!0;const r=t.getHeader("etag");if("string"==typeof r){if(n.includes(r))return!0;if(r.startsWith('W/"'))return!1}return!(!e||!n.some(t=>t.startsWith('W/"')))&&n.includes(Le(t.getHeader("content-encoding"),e))}class Ln extends C{constructor(t,e){super({transform(r,o){n+=r.byteLength,n>t?o.error(e):o.enqueue(r)}});let n=0}}function Gn(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:r=1}={}){const o=Oe(t.headers["content-length"]);if(void 0!==o&&o>n)throw new ue(413);const i=ke(t.headers["content-encoding"])??[];if(i.length>r)throw new ue(415,{body:"too many content-encoding stages"});_n(t);let s=I.toWeb(t);void 0===o&&Number.isFinite(n)&&(s=s.pipeThrough(new Ln(n,new ue(413))));for(const t of i.reverse())s=s.pipeThrough(Xn(t));return Number.isFinite(e)&&(s=s.pipeThrough(new Ln(e,new ue(413,{body:"decoded content too large"})))),s}function Wn(t,e={}){const n=Gn(t,e),r=Te(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Hn(r,e))}async function Vn(t,e={}){const n=[];for await(const r of Wn(t,e))n.push(r);return n.join("")}async function Zn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),r=new Uint8Array(3);let o=0,i=null;for(;;){const t=await n.read(),e=3-o;if(t.done){0===o?(r[0]=1,r[1]=1):1===o&&(r[1]=r[0]),r[2]=r[0],i=null;break}if(i=t.value,i.byteLength>=e){r.set(i.subarray(0,e),o);break}r.set(i,o),o+=i.byteLength}const s=jn[(r[0]?4:0)|(r[1]?2:0)|(r[2]?1:0)];if(!s)throw n.cancel(),new ue(415,{body:"invalid JSON encoding"});const a=Hn(s,e),c=a.writable.getWriter();return o&&c.write(r.subarray(0,o)),i&&c.write(i),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Gn(t,e),e),r=[];for await(const t of n)r.push(t);try{return JSON.parse(r.join(""))}catch(t){throw new ue(400,{body:"invalid JSON",cause:t})}}function Xn(t){switch(t.toLowerCase()){case"gzip":case"x-gzip":return new M("gzip");case"deflate":return new M("deflate");case"br":try{return new M("brotli")}catch{return D.toWeb(k.createBrotliDecompress())}case"zstd":try{return D.toWeb(k.createZstdDecompress())}catch{throw new ue(415,{body:"unsupported content encoding"})}default:throw new ue(415,{body:"unknown content encoding"})}}function Yn(t){if(!t)return null;const[e,n]=Se(t,";"),r=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 o=e[1].toLowerCase(),i=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";r.has(o)||r.set(o,i)}}return{mime:e.trim().toLowerCase(),params:r}}function Kn(t,e,n,r){const o=t.byteLength;for(;e<o;){for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)break;if(59!==t[e++])return!1;for(;e<o;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===o)return!1;const i=e;for(;e<o;++e){const n=t[e];if(!Qn[n]){if(61===n)break;return!1}}if(e===o)return!1;const s=t.latin1Slice(i,e).toLowerCase();if("*"===s[s.length-1]){const r=++e;for(;e<o;++e){const n=t[e];if(!er[n]){if(39!==n)return!1;break}}if(e===o)return!1;const i=Dn(t.latin1Slice(r,e));for(++e;e<o&&39!==t[e];++e);if(e===o)return!1;if(++e===o)return!1;let a=e;const c=[];for(;e<o;++e){const n=t[e];if(1!==tr[n]){if(37===n){let n,r;if(e+2<o&&16!==(n=rr[t[e+1]])&&16!==(r=rr[t[e+2]])){const o=(n<<4)+r;e>a&&c.push(i.decode(t.subarray(a,e),{stream:!0})),c.push(i.decode(Buffer.from([o]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(i.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===o)return!1;if(34===t[e]){let i=++e,a=!1;const c=[];for(;e<o;++e){const n=t[e];if(92!==n){if(34===n){if(a){i=e,a=!1;continue}c.push(r.decode(t.subarray(i,e)));break}if(a&&(i=e-1,a=!1),!nr[n])return!1}else a?(i=e,a=!1):(c.push(r.decode(t.subarray(i,e),{stream:!0})),a=!0)}if(e===o)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<o;++e){const n=t[e];if(!Qn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,r.decode(t.subarray(a,e)))}return!0}const Qn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,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,0,1,0,1],33),t})(),tr=/*@__PURE__*/(()=>{const t=new Uint8Array(Qn);return t.set([0,1,0,0,0,0],37),t})(),er=/*@__PURE__*/(()=>{const t=new Uint8Array(Qn);return t.set([0,0,0,0,1,0,1,0],39),t.set([1,0,1,1],123),t})(),nr=/*@__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})(),rr=/*@__PURE__*/(()=>{const t=new Uint8Array(256).fill(16);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 or{constructor(t,e,n){const r=t.byteLength;if(!r||r>65535)throw new RangeError("invalid needle");this.de=t,this.we=e,this.pe=n,this.ye=null,this.me=0,this.ge=null}push(t){let e=0;const n=t.byteLength,r=this.de,o=r.byteLength-1,i=n-o;let s=-this.me;if(this.me){const a=this.ge,c=this.ye,f=r[o];if(s<i){const n=t[s+o];n!==f||t.compare(r,-s,o,0,s+o)?s+=a[n]:(this.pe(),this.me=0,e=s+=o+1)}const u=i<0?i:0;for(;s<u;){const n=t[s+o];if(n===f&&!c.compare(r,0,-s,this.me+s,this.me)&&!t.compare(r,-s,o,0,s+o)){this.we(c,0,this.me+s,!1),this.pe(),this.me=0,e=s+=o+1;break}s+=a[n]}const l=this.me;if(l>0){const e=r[0];for(;s<0;){const o=c.subarray(0,l).indexOf(e,l+s);if(-1===o){s=0;break}const i=l-o;if(!c.compare(r,1,i,o+1,l)&&!t.compare(r,i,i+n))return o&&(this.we(c,0,o,!1),c.copy(c,0,o,i)),c.set(t,i),void(this.me+=n-o);s=o+1-l}this.we(c,0,l,!1),this.me=0}}for(;s<i;){const n=t.indexOf(r,s);if(-1!==n){if(n>e&&this.we(t,e,n,!0),this.pe(),n===i+1)return;e=s=n+o+1}else s=i}const a=r[0];for(;s<n;){const i=t.indexOf(a,s);if(-1===i)return void this.we(t,e,n,!0);if(!t.compare(r,1,n-i,i+1)){if(!this.ye){this.ye=Buffer.allocUnsafe(o),this.ge=new Uint16Array(256).fill(o+1);for(let t=0;t<o;++t)this.ge[r[t]]=o-t}return t.copy(this.ye,0,i),this.me=n-i,void(i>e&&this.we(t,e,i,!0))}s=i+1}n>e&&this.we(t,e,n,!0)}destroy(){const t=this.me;t&&this.ye&&this.we(this.ye,0,t,!1),this.me=0}}class ir{constructor(t){this.we=t,this.reset()}reset(){this.G=[],this.be=16384,this.m=0,this.ve="",this.Ee=void 0}push(t,e,n){let r=e,o=e;const i=Math.min(n,e+this.be);for(;o<i;)switch(this.m){case 0:for(;o<i&&Qn[t[o]];++o);if(o>r&&(this.ve+=t.latin1Slice(r,o)),o<i){if(58!==t[o])return-1;if(!this.ve)return-1;++o,this.Ee=fr.get(this.ve.toLowerCase()),this.ve="",this.m=1}break;case 1:for(;o<i;++o){const e=t[o];if(32!==e&&9!==e){r=o,this.m=2;break}}break;case 2:for(;o<i;++o){const e=t[o];if(e<32||127===e){if(13!==e)return-1;this.m=3;break}}this.Ee&&(this.ve+=t.latin1Slice(r,o)),++o;break;case 3:if(10!==t[o++])return-1;this.m=4;break;case 4:{const e=t[o];if(32===e||9===e)r=o,this.m=2;else{if(this.Ee){const t=this.Ee._e;void 0===this.G[t]?this.G[t]=this.ve:this.Ee.Se&&(this.G[t]+=","+this.ve)}13===e?(this.m=5,++o):(r=o,this.m=0,this.ve="",this.Ee=void 0)}break}case 5:{if(10!==t[o++])return-1;const e=this.G;return this.reset(),this.we(e),o}}return i<n?-1:(this.be-=i-e,i)}}const sr=0,ar=1,cr=2,fr=new Map([["content-type",{_e:sr,Se:!1}],["content-disposition",{_e:ar,Se:!1}],["content-transfer-encoding",{_e:cr,Se:!0}]]);function ur(t){const e=this.xe;e&&(this.xe=void 0,e())}const lr=/*@__PURE__*/Buffer.from("\r\n"),hr=()=>{},dr=37,wr=43,pr=/*@__PURE__*/new Uint8Array(256);function yr(t,e={}){const n=t["content-type"];if(!n)throw new ue(400,{body:"missing content-type"});const r=Yn(n);if(!r)throw new ue(400,{body:"malformed content-type"});const o=Oe(t["content-length"]);if(void 0!==o&&void 0!==e.maxNetworkBytes&&o>e.maxNetworkBytes)throw new ue(413,{body:"content too large"});if("application/x-www-form-urlencoded"===r.mime)return(({defCharset:t="utf-8",maxNetworkBytes:e=Number.POSITIVE_INFINITY,maxContentBytes:n=e,maxFieldSize:r=1048576,maxFieldNameSize:o=100,maxFields:i=Number.POSITIVE_INFINITY},s)=>{const a=s.get("charset")??t,c=/^utf-?8$/i.test(a)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(a)?2:0,f=Dn(a);return(t,s)=>new Promise((u,l)=>{let h=e,d=n,w=i,p=!0,y="",m=Math.min(o,d),g=0,b="",v=-2;const E=()=>{const t=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y;if(p){if(m<0)return x(new ue(413,{body:`field name ${JSON.stringify(t)}... too long`})),!1;t&&s({name:t,type:"string",value:"",encoding:a,mimeType:"text/plain"})}else{if(m<0)return x(new ue(413,{body:`value for ${JSON.stringify(b)} too long`})),!1;s({name:b,type:"string",value:t,encoding:a,mimeType:"text/plain"})}return!0},_=t=>{if(!t.byteLength)return;if((h-=t.byteLength)<0)return x(new ue(413,{body:"content too large"}));if(!w)return x(new ue(413,{body:"too many fields"}));const e=t.byteLength;let n=0,i=v;if(-2!==i){if(-1===i){if(16===(i=rr[t[n++]]))return x(new ue(400,{body:"malformed urlencoded form"}));if(g|=i,n===e)return void(v=i)}const r=rr[t[n++]];if(16===r)return x(new ue(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((i<<4)+r),v=-2,n===e)return}for(pr[37]=1,pr[38]=1,pr[43]=1,pr[61]=p?1:0;;){const i=n;for(;n<e&&!pr[t[n]];++n);if(n>i&&m>=0&&((m-=n-i)<0?y+=t.latin1Slice(i,n+m):(d-=n-i,y+=t.latin1Slice(i,n))),n===e)return;switch(t[n++]){case dr:for(;;){if(--m<0){pr[37]=0,pr[43]=0;break}if(--d,n===e){v=-1;break}const r=rr[t[n++]];if(16===r)return x(new ue(400,{body:"malformed urlencoded form"}));if(g|=r,n===e)return void(v=r);const o=rr[t[n++]];if(16===o)return x(new ue(400,{body:"malformed urlencoded form"}));if(y+=String.fromCharCode((r<<4)+o),n===e)return;if(t[n]!==dr)break;n++}break;case 38:if(!E())return;if(b="",p=!0,pr[61]=1,pr[37]=1,pr[43]=1,y="",m=Math.min(o,d),g=0,! --w)return x(new ue(413,{body:"too many fields"}));break;case wr:--m<0?(pr[37]=0,pr[43]=0):(--d,y+=" ");break;case 61:if(b=!c||1===c&&8&g?f.decode(Buffer.from(y,"latin1")):y,m<0)return x(new ue(413,{body:`field name ${JSON.stringify(b)}... too long`}));p=!1,pr[61]=0,pr[37]=1,pr[43]=1,y="",g=0,m=Math.min(r,d)}if(n===e)return}},S=()=>{if(-2!==v)return x(new ue(400,{body:"malformed urlencoded form"}));E()&&(t.off("data",_),t.off("end",S),t.off("error",x),u())},x=e=>{t.off("data",_),t.off("end",S),t.off("error",x),l(e)};t.on("data",_),t.once("end",S),t.once("error",x)})})(e,r.params);if("multipart/form-data"===r.mime&&!e.blockMultipart)return function({preservePath:t,fileHwm:e,defParamCharset:n="utf-8",defCharset:r="utf-8",maxNetworkBytes:o=Number.POSITIVE_INFINITY,maxContentBytes:i=o,maxFieldSize:s=1048576,maxFileSize:a=Number.POSITIVE_INFINITY,maxTotalFileSize:c=Number.POSITIVE_INFINITY,maxFieldNameSize:f=100,maxParts:u=Number.POSITIVE_INFINITY,maxFields:l=Number.POSITIVE_INFINITY,maxFiles:h=Number.POSITIVE_INFINITY},d){const w=d.get("boundary");if(!w)throw new ue(400,{body:"multipart boundary not found"});if(w.length>70)throw new ue(400,{body:"multipart boundary too long"});const p=Dn(n),y={autoDestroy:!0,emitClose:!0,highWaterMark:e,read:ur};return(e,n)=>new Promise((d,m)=>{let g,b,v,E,_,S,x,T=5,$=o,N=i,k=c,O=u,A=l,R=h,P=0,F=!1,C=0,U="";const M=new ir(e=>{const o=e[ar];if(!o)return void(T=5);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let r=0;for(;r<t.byteLength;++r)if(!Qn[t[r]]){if(!Kn(t,r,n,e))return null;break}return{type:t.latin1Slice(0,r).toLowerCase(),params:n}})(Buffer.from(o,"latin1"),p);if("form-data"!==i?.type)return void(T=5);if(v=i.params.get("name"),void 0===v)return q(new ue(400,{body:"missing field name"}));const c=Buffer.byteLength(v,"utf-8"),u=Math.min(f,N);if(c>u)return q(new ue(413,{body:`field name ${JSON.stringify(v.substring(0,u))}... too long`}));N-=c,E=i.params.get("filename*")??i.params.get("filename");const l=Yn(e[sr]);if(_=l?.mime??"text/plain",S=e[cr]?.toLowerCase()??"7bit","application/octet-stream"===_||void 0!==E){if(!R--)return q(new ue(413,{body:"too many files"}));if(!E)return void(T=5);t||(E=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(E));const e=new I(y);e.once("error",hr),e.once("close",()=>{e.xe?.(),e.off("error",hr),! --C&&b&&process.nextTick(b)}),g=e,++C,P=Math.min(a,k,N,$),n({name:v,type:"file",value:e,filename:E,encoding:S,mimeType:_,sizeLimit:P}),T=4}else{if(!A--)return q(new ue(413,{body:"too many fields"}));T=4,P=Math.min(s,N,$);const t=l?.params.get("charset")?.toLowerCase()??r;x=Dn(t)}}),B=Buffer.from(`\r\n--${w}`,"latin1"),D=new or(B,(t,n,r,o)=>{if(T<=2){if(0===T){if(13===t[n])T=1;else{if(45!==t[n])return void(T=5);T=2}if(++n===r)return}if(1!==T)return 45!==t[n]?void(T=5):(T=6,e.off("data",H),void e.resume());if(10!==t[n++])return void(T=5);if(!O--)return q(new ue(413,{body:"too many parts"}));if(T=3,n===r)return}if(3===T){if(-1===(n=M.push(t,n,r)))return q(new ue(400,{body:"malformed part header"}));if(n===r)return}if(4===T){const e=Math.min(r,n+P);if(P-=r-n,N-=r-n,g){if(k-=r-n,e>n){let r;r=o?t.subarray(n,e):Buffer.copyBytesFrom(t,n,e-n),g.push(r)||(F=!0)}if(P<0)return q(new ue(413,{body:`uploaded file for ${JSON.stringify(v)}: ${JSON.stringify(E)} too large`}))}else{if(P<0)return q(new ue(413,{body:`value for ${JSON.stringify(v)} too long`}));U+=t.latin1Slice(n,e)}}},()=>{if(3===T)return q(new ue(400,{body:"unexpected end of headers"}));if(4===T)if(g)g.push(null),g=void 0,F=!1;else{const t=Buffer.from(U,"latin1");U="",n({name:v,type:"string",value:x.decode(t),encoding:S,mimeType:_})}T<6&&(T=0)});D.push(lr);const H=t=>{if(($-=t.byteLength)<0)return q(new ue(413,{body:"content too large"}));F=!1,D.push(t),g&&F&&(e.pause(),g.xe=()=>e.resume())},j=()=>{if(7!==T){if(6!==T&&(D.destroy(),6!==T))return q(new ue(400,{body:"unexpected end of form"}));e.off("data",H),e.off("end",j),b=()=>{e.off("error",q),d()},C||b()}},q=t=>{7!==T&&(T=7,e.off("data",H),e.off("end",j),e.off("error",q),g?.destroy(t),g=void 0,m(t))};e.on("data",H),e.once("end",j),e.once("error",q)})}(e,r.params);throw new ue(415)}function mr(t,{closeAfterErrorDelay:e=500,...n}={}){L(e,"closeAfterErrorDelay",!0);const r=()=>{if(e>=0&&t.readable){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};try{const e=yr(t.headers,n);_n(t);const o=new W;return e(t,t=>o.push(t)).then(()=>o.close("complete"),e=>{o.fail(t.readableAborted?kt:e),t.resume(),r()}),o}catch(e){throw Sn(t)&&(t.resume(),r()),e}}async function gr(t,e={}){const n=new FormData,r=new Map;for await(const o of mr(t,e))if("file"===o.type){const i=o.value;let s=await(e.preCheckFile?.({fieldName:o.name,filename:o.filename,encoding:o.encoding,mimeType:o.mimeType,maxBytes:o.sizeLimit}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};Tt(t,()=>a(0));const c=await vn(t),f=await c.save(i,{mode:384});await a(f.size);const l=new File([await u(f.path)],o.filename,{type:o.mimeType});r.set(l,f.path),n.append(o.name,l)}else{let t=o.value;e.trimAllValues&&(t=t.trim()),n.append(o.name,t)}return Object.assign(n,{getTempFilePath(t){const e=r.get(t);if(!e)throw new RangeError("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 br="win32"===/*@__PURE__*/R();function vr(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const r=ct(t);if(r){if("/"===r.F)return[];n=r.F.split("/")}else{const e=Q(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ue(400,{body:"invalid path"});if(n.shift(),e){const t=br?_r:Er;if(n.some(e=>t.test(e)||e.includes(g)))throw new ue(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ue(400,{body:"invalid path"})}return n}const Er=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,_r=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i;class Sr{constructor(t){this.load=t}}const xr=t=>new Sr(t);function Tr(t){if(t&&("object"==typeof t||"function"==typeof t)){if(t instanceof I)return void t.destroy();if(Symbol.dispose&&Symbol.dispose in t)return void t[Symbol.dispose]();if(Symbol.asyncDispose&&Symbol.asyncDispose in t)return t[Symbol.asyncDispose]();if("return"in t&&"function"==typeof t.return){const e=t.return();return e instanceof Promise?e:void 0}}}const $r=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(K,n):t.once("drain",n),t.uncork()});async function Nr(t,e,{delimiter:n=",",newline:r="\n",quote:o='"',encoding:i="utf-8",headerRow:a,end:c=!0}={}){if(t.writableAborted)return;"string"==typeof n&&(n=Buffer.from(n,i)),"string"==typeof r&&(r=Buffer.from(r,i));const f="string"==typeof o?Buffer.from(o,i):o,u=o+o,l=e=>{if(!e)return!0;const n=e.includes(o);return!n&&kr.test(e)?t.write(e,i):(t.write(f),n?t.write(e.replaceAll(o,u),i):t.write(e,i),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+i+(a?"; header=present":!1===a?"; header=absent":"")),t.cork(),e instanceof Sr&&(e=await e.load());try{t.write(K);for await(let o of e){if(t.writableAborted)break;o instanceof Sr&&(o=await o.load());try{let e=0;if(Symbol.iterator in o)for(let r of o){if(e&&t.write(n),r instanceof Sr){if(t.writableAborted)break;r=await r.load()}try{l(r)||await $r(t)}finally{const t=Tr(r);t&&await t}++e}else for await(let r of o){if(t.writableAborted)break;e&&t.write(n),r instanceof Sr&&(r=await r.load());try{l(r)||await $r(t)}finally{const t=Tr(r);t&&await t}++e}}finally{const t=Tr(o);t&&await t}t.write(r)||await $r(t)}}finally{t.uncork();const n=Tr(e);n&&await n}c&&t.end()}const kr=/^[^"':;,\\\r\n\t ]*$/i;function Or(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 Ar{constructor(t){(t=>"Te"in t&&"function"==typeof t.pipe)(t)&&(t=I.toWeb(t)),this.wt=t.getReader(),this.$e=null,this.Ne=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.Ne)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,r=t-this.Ne;this.Ne=e+1,this.m=1;const o=this,i=(t,e)=>{const o=t.byteLength;o<=r?r-=o:o>r+n?(this.$e=t.subarray(r+n),e.enqueue(t.subarray(r,r+n)),n=0):r>0?(e.enqueue(t.subarray(r)),n-=o-r,r=0):(e.enqueue(t),n-=o)};return new B({start(t){if(o.$e){const e=o.$e;o.$e=null,i(e,t)}},async pull(t){if(n<=0)return o.m=0,void t.close();const e=await o.wt.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?i(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?i(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.wt.cancel(),this.wt.releaseLock()}}function Rr(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const r=[];if(n>=0)for(const e of t.ranges){let t=null,o=0;for(let i=0;i<r.length;++i){const s=r[i];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++o,t.start=Math.min(t.start,s.start),t.end=Math.max(t.end,s.end)):(t=s,t.start=Math.min(t.start,e.start),t.end=Math.max(t.end,e.end)):o>0&&(r[i-o]=s)}t?r.length-=o:r.push({...e})}else r.push(...t.ranges);if(e)for(let t=0;t<r.length-1;++t)if(r[t].start>r[t+1].start){r.sort((t,e)=>t.start-e.start);break}return{ranges:r,totalSize:t.totalSize}}async function Pr(t,e,n,r){if(e.closed||!e.writable)throw kt;if("string"==typeof n||Or(n)||(r=Rr(r,{mergeOverlapDistance:0,forceSequential:!0})),1===r.ranges.length){const o=r.ranges[0];if(e.setHeader("content-length",o.end-o.start+1),e.setHeader("content-range",`bytes ${o.start}-${o.end}/${r.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const i=await Fr(n);try{if(e.closed||!e.writable)throw kt;await d(i.ke(o.start,o.end),e)}catch(t){throw En(e,t)?kt:t}finally{i.Oe&&await i.Oe()}return}const o=e.getHeader("content-type"),i=h()+h()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${i}`);const s=r.ranges.map(t=>({i:[`--${i}`,...dt({"content-type":o,"content-range":`bytes ${t.start}-${t.end}/${r.totalSize??"*"}`}),"",""].join("\r\n"),Ae:t})),a=`--${i}--`;let c=a.length;for(const{i:t,Ae:e}of s)c+=t.length+e.end-e.start+1+2;if(e.setHeader("content-length",c),"HEAD"===t.method)return void e.end();let f="";const u=await Fr(n);try{for(const{i:t,Ae:n}of s){if(e.closed||!e.writable)throw kt;e.write(f+t,"ascii"),await d(u.ke(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}catch(t){throw En(e,t)?kt:t}finally{u.Oe&&await u.Oe()}}async function Fr(t){if("string"==typeof t){const e=await $(t,"r");return{ke:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Oe:()=>e.close()}}if(Or(t))return{ke:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Ar(t);return{ke:(t,n)=>e.getRange(t,n),Oe:()=>e.close()}}}async function Cr(t,e,n,r=null,o){if(e.closed||!e.writable)throw kt;if(!r&&("string"==typeof n?r=await S(n):Or(n)&&(r=await n.stat()),e.closed||!e.writable))throw kt;if(r){if("GET"===t.method||"HEAD"===t.method){if(!qn(t,e,r))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const i=Ne(t,r.size,o);if(i&&Jn(t,e,r))return Pr(t,e,n,Rr(i,o))}e.setHeader("content-length",r.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method){"string"==typeof n?n=a(n):Or(n)&&(n=n.createReadStream({start:0,autoClose:!1}));try{await d(n,e)}catch(t){throw En(e,t)?kt:t}}else e.end()}function Ur(t,e,{replacer:n,space:r,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,r??void 0)??(o?"null":void 0);t instanceof s&&!t.headersSent&&(t.hasHeader("content-type")||t.setHeader("content-type","application/json"),a&&t.setHeader("content-length",Buffer.byteLength(c,i))),a?t.end(c,i):c&&t.write(c,i)}async function Mr(t,e,{replacer:n=null,space:r=null,undefinedAsNull:o=!1,encoding:i="utf-8",end:a=!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 r&&(r=" ".substring(0,r));try{if(t.writableAborted)return;const a=new AbortController;t.once("close",()=>a.abort());const c={Re:e=>t.write(e,i),Pe:()=>$r(t),Fe:n,Ce:r??"",Ue:a.signal};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e instanceof Sr&&(e=await e.load()),e=Ir(null,"",e,c),Dr(e))o&&c.Re("null");else{t.cork(),t.write(K);try{await Br(c,e,r?"\n":"")}finally{t.uncork()}}}finally{const t=Tr(e);t&&await t}a&&t.end()}async function Br(t,e,n){const r=(r,o,i)=>{t.Re(r);const s=n+t.Ce,a=t.Ce?": ":":";let c=!0;return{o:async(n,r)=>{if(!t.Ue.aborted){r instanceof Sr&&(r=await r.load());try{const o=Ir(e,n,r,t);i&&Dr(o)||(c?c=!1:t.Re(","),t.Re(s),i&&(t.Re(JSON.stringify(n))||await t.Pe(),t.Re(a)),await Br(t,o,s))}finally{const t=Tr(r);t&&await t}}},Oe:()=>{c||t.Re(n),t.Re(o)}}};if(!t.Ue.aborted)if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Hr(e))t.Re(JSON.stringify(e)??"null")||await t.Pe();else if(e instanceof I){t.Re('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");if(t.Ue.aborted)break;const e=JSON.stringify(n);t.Re(e.substring(1,e.length-1))||await t.Pe()}t.Re('"')}else if(e instanceof Map){const t=r("{","}",!0);for(const[n,r]of e)await t.o(n,r);t.Oe()}else if(jr(e)){let t=0;const n=r("[","]",!1);for(const r of e)await n.o(String(t++),r);n.Oe()}else if(qr(e)){let n=0;const o=r("[","]",!1);for await(const r of e){if(t.Ue.aborted)break;await o.o(String(n++),r)}o.Oe()}else{const t=r("{","}",!0);for(const[n,r]of Object.entries(e))await t.o(n,r);t.Oe()}}function Ir(t,e,n,r){return r.Fe&&(n=r.Fe.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Dr=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Hr=t=>JSON.isRawJSON?.(t)??!1,jr=t=>Symbol.iterator in t,qr=t=>Symbol.asyncIterator in t;class Jr{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:r=500,softCloseReconnectStagger:o=2e3}={}){L(n,"keepaliveInterval",!0),this.Me=e,this.Be=n,this.C=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.Ie(),t.once("close",()=>this.close()),yt(t,()=>this.close(r,o))}get signal(){return this.C.signal}get open(){return!this.C.signal.aborted}Ie(){this.Be>0&&(this.De=setTimeout(this.ping,this.Be))}ping(){!this.C.signal.aborted&&this.Me.writable&&(clearTimeout(this.De),this.Me.write(":\n\n",()=>this.Ie()))}send({event:t,id:e,data:n,reconnectDelay:r=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",r>=0?String(0|r):void 0]])}async sendFields(t){let e;this.C.signal.throwIfAborted(),this.Me.cork();try{let n=!1;for(const[e,r]of t){if(void 0===r)continue;const t=r.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Me.write(e)," "===n[0]?this.Me.write(": "):this.Me.write(":"),this.Me.write(n);/[\r\n]$/.test(r)?(this.Me.write(e),this.Me.write(":\n")):this.Me.write("\n"),n=!0}if(!n)return;clearTimeout(this.De),this.Me.write("\n",()=>e())}finally{this.Me.uncork()}await new Promise(t=>{e=t}),this.Ie()}async close(t=0,e=0){if(this.C.signal.aborted){if(this.Me.closed)return;return new Promise(t=>this.Me.once("close",t))}this.Be=0,clearTimeout(this.De),this.C.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Me.writable&&(t>0||e>0)){const r=t+Math.random()*e;this.Me.end(`retry:${0|r}\n\n`,n)}else this.Me.end(n)})}}const zr=(t,e)=>{e&&"identity"!==e&&t.setHeader("content-encoding",e)},Lr=(t,e)=>{if(e){const n=t.getHeader("vary")??"";t.setHeader("vary",(n?n+", ":"")+e)}},Gr=async(t,{mode:e="dynamic",fallback:n,verbose:r,callback:o=Wr,...i}={})=>{const s=await mn.build(b(process.cwd(),t),i);let a=null;const c=n?.statusCode??200;if(n){let t=n.filePath;t.startsWith("/")&&(t=t.substring(1)),a=s.toNormalisedPath(t.split("/"))}const f="dynamic"===e?{}:{rejectPotentiallyUnsafe:!1},u="dynamic"===e?s:await s.precompute();return{handleRequest:async(t,e)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;let n=!1;const i=vr(t,f),s=[];let l=await u.find(i,t.headers,r?s:void 0);if(!l){if(!a)return r&&wn(t,new Error(s.join(", ")),"serving static content"),Ot;if(n=!0,l=await u.find(a,t.headers,s),!l)throw new ue(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c);const r=l.headers["content-type"]??an(w(l.canonicalPath));e.setHeader("content-type",r);const i=l.headers["content-language"];i&&e.setHeader("content-language",i),zr(e,l.headers["content-encoding"]),Lr(e,l.headers.vary),await o(t,e,l,n),await Cr(t,e,l.handle,l.stats)}finally{l.handle.close().catch(()=>{})}}}};function Wr(t,e,n){e.setHeader("etag",Le(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}const Vr=(t,e,{headers:n,encodings:r=[],minCompression:o=0}={})=>{const i=(async()=>{const e=new Map;e.set("",{Mt:t,He:We(t)});const n=[];for(const i of r){const r=await fn(t,i,o);r&&(e.set(i,{Mt:r,He:We(r)}),n.push({value:i,file:i}))}const i=new Ye([{feature:"encoding",options:n}]);return t=>{for(const n of i.options("",t)){const t=e.get(n.filename);if(t)return{G:n.headers,...t}}throw new Error("failed to serve static content")}})();return{handleRequest:async(t,r)=>{if("GET"!==t.method&&"HEAD"!==t.method)return Ot;const{G:o,He:s,Mt:a}=(await i)(t.headers);!r.closed&&r.writable&&(n&&r.setHeaders(fe(n)),zr(r,o["content-encoding"]),Lr(r,o.vary),r.setHeader("content-type",e),r.setHeader("etag",s),qn(t,r,null)?(r.setHeader("content-length",a.byteLength),r.end(a)):r.writeHead(304).end())}}},Zr=(t,e)=>Vr(Buffer.from(JSON.stringify(t),"utf-8"),"application/json",e);class Xr extends Error{constructor(t,{message:e,closeReason:n,...r}={}){super(e,r),this.closeCode=0|t,this.closeReason=n??"",this.name=`WebSocketError(${this.closeCode} ${this.closeReason})`}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 Yr(t,{softCloseStatusCode:e=Xr.GOING_AWAY,...n}={}){const r=(r,o,i)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(r,o,i,t=>{c.off("wsClientError",a),i=K,s({return:t,onError:e=>{const n=V(e,Xr);if(n)return void t.close(n.closeCode,n.closeReason);const r=V(e,ue)??new ue(500),o=r.statusCode>=500?Xr.INTERNAL_SERVER_ERROR:4e3+r.statusCode;t.close(o,r.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Pt(t,r)}class Kr{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Xr(Xr.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Xr(Xr.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class Qr{constructor(t,{limit:e=-1,signal:n}={}){this.je=new W;const r=e=>{t.off("message",i),t.off("close",o),this.je.close(new Error(e))},o=()=>r("connection closed"),i=(t,n)=>{void 0!==n?this.je.push(new Kr(t,n)):"string"==typeof t?this.je.push(new Kr(Buffer.from(t,"utf-8"),!1)):this.je.push(new Kr(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.je.close(n.reason):2===t.readyState||3===t.readyState?this.je.close(new Error("connection closed")):(t.on("message",i),t.on("close",o),n?.addEventListener("abort",()=>r("signal aborted")),this.detach=()=>r("WebSocket listener detached"))}next(t){return this.je.shift(t)}[Symbol.asyncIterator](){return this.je[Symbol.asyncIterator]()}}function to(t,{timeout:e,signal:n}={}){const r=new Qr(t,{limit:1,signal:n});return r.next(e).finally(()=>r.detach())}function eo(t){const e=ut(t);return"GET"===t.method&&(e.I?.has("websocket")??!1)}const no=t=>t.headers.origin??wt(t.headers["sec-websocket-origin"]),ro=(t,e=5e3)=>async n=>{if(!eo(n))return;const r=await t(n);let o;try{o=await to(r,{timeout:e})}catch(t){if((r.readyState??0)>=2)throw kt;throw new Xr(Xr.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(o.isBinary)throw new Xr(Xr.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return o.data.toString("utf-8")};export{W as BlockingQueue,Ot as CONTINUE,mn as FileFinder,ue as HTTPError,At as NEXT_ROUTE,Rt as NEXT_ROUTER,Ye as Negotiator,Ce as Property,G as Queue,ne as Router,kt as STOP,Jr as ServerSentEvents,ge as WebListener,Xr as WebSocketError,Kr as WebSocketMessage,Qr as WebSocketMessages,_n as acceptBody,Pt as acceptUpgrade,Tt as addTeardown,Vt as anyHandler,qn as checkIfModified,Jn as checkIfRange,zn as compareETag,ln as compressFileOffline,hn as compressFilesInDir,Yt as conditionalErrorHandler,on as decompressMime,xt as defer,Ft as delegateUpgrade,wn as emitError,Zt as errorHandler,Gr as fileServer,V as findCause,Ge as generateStrongETag,Le as generateWeakETag,$t as getAbortSignal,zt as getAbsolutePath,Z as getAddressURL,je as getAuthScopes,xe as getAuthorization,Zn as getBodyJSON,Gn as getBodyStream,Vn as getBodyText,Wn as getBodyTextStream,Te as getCharset,gr as getFormData,mr as getFormFields,$e as getIfRange,an as getMime,Jt as getPathParameter,qt as getPathParameters,_e as getQuery,Ne as getRange,vr as getRemainingPathComponents,ve as getSearch,Ee as getSearchParams,Dn as getTextDecoder,Hn as getTextDecoderStream,no as getWebSocketOrigin,He as hasAuthScope,gt as isSoftClosed,eo as isWebSocketRequest,pn as jsonErrorHandler,xr as loadOnDemand,Yr as makeAcceptWebSocket,j as makeAddressTester,$n as makeGetClient,Ue as makeMemo,vn as makeTempFileStorage,ro as makeWebSocketFallbackTokenFetcher,Xe as negotiateEncoding,to as nextWebSocketMessage,H as parseAddress,xn as proxy,Pe as readHTTPDateSeconds,Oe as readHTTPInteger,Re as readHTTPKeyValues,Ae as readHTTPQualityValues,ke as readHTTPUnquotedCommaSeparated,rn as readMimeTypes,Bn as registerCharset,sn as registerMime,In as registerUTF32,On as removeForwarded,An as replaceForwarded,Gt as requestHandler,qe as requireAuthScope,De as requireBearerAuth,nn as resetMime,Lt as restoreAbsolutePath,Rn as sanitiseAndAppendForwarded,bt as scheduleClose,Nr as sendCSVStream,Cr as sendFile,Ur as sendJSON,Mr as sendJSONStream,Pr as sendRanges,Wr as setDefaultCacheHeaders,yt as setSoftCloseHandler,Pn as simpleAppendForwarded,Rr as simplifyRange,Vr as staticContent,Zr as staticJSON,Y as stringPredicate,de as toListeners,Xt as typedErrorHandler,Wt as upgradeHandler,Sn as willSendBody};
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "a small server abstraction for creating API and resource endpoints with middleware",
5
5
  "author": "David Evans",
6
6
  "license": "MIT",
@@ -16,6 +16,7 @@
16
16
  "type": "module",
17
17
  "main": "./index.js",
18
18
  "types": "./index.d.ts",
19
+ "man": "./man1/web-listener.1.gz",
19
20
  "sideEffects": false,
20
21
  "bin": "./run.js",
21
22
  "repository": {
package/run.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env -S node --disable-proto=delete --disallow-code-generation-from-strings --force-node-api-uncaught-exceptions-policy --no-addons
2
- import{readFile as e}from"node:fs/promises";import{join as t,dirname as o,resolve as r,basename as s}from"node:path";import{createServer as n}from"node:http";import{Router as i,requestHandler as a,addTeardown as c,CONTINUE as f,proxy as p,Negotiator as l,fileServer as u,getSearch as h,getQuery as d,getPathParameter as m,WebListener as g,findCause as w,HTTPError as y,stringPredicate as b,compressFilesInDir as x,readMimeTypes as $,decompressMime as v,resetMime as S,registerMime as z}from"./index.js";const j=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),k=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]),N=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const O=e=>(t,o)=>{if(t!==e)throw new R(`expected ${JSON.stringify(e)}`,o,8);return e},E=e=>(t,o)=>{if(!e.has(t))throw new R(`expected one of ${JSON.stringify(e)}`,o,7);return t},P=e=>(t,o)=>{const r=[];let s=9;for(const n of e)try{return n(t,o)}catch(e){if(e instanceof R){if(e.p>s)continue;e.p!==s&&(s=e.p,r.length=0)}else s=-1;r.push(e)}throw 1===r.length?r[0]:new AggregateError(r)},A=e=>(t,o)=>{if(!Array.isArray(t))throw new R("expected list, got "+typeof t,o);return t.map((t,r)=>e(t,{...o,path:`${o.path}[${r}]`}))},J=(e,t)=>{if("boolean"!=typeof e)throw new R("expected boolean, got "+typeof e,t);return e},T=(e,t,o)=>(r,s)=>{if("number"!=typeof r)throw new R("expected number, got "+typeof r,s);if(e&&(0|r)!==r)throw new R(`expected integer, got ${r}`,s);if("number"==typeof t&&r<t)throw new R(`value cannot be less than ${t}`,s);if("number"==typeof o&&r>o)throw new R(`value cannot be greater than ${o}`,s);return r},I=()=>(e,t)=>{if("string"!=typeof e)throw new R("expected string, got "+typeof e,t);try{return new RegExp(e)}catch{throw new R("expected regular expression",t)}},q=(e,t)=>(s,n)=>{if("string"!=typeof s)throw new R("expected string, got "+typeof s,n);if(e&&!e.test(s))throw new R(`expected string matching ${e}`,n);if("uri-reference"===t&&n.file){if(s.startsWith("file://"))return"file://"+r(o(n.file),s.substring(7));if(!s.includes("://"))return r(o(n.file),s)}return s},C=(e,t,o)=>(r,s)=>{if("object"!=typeof r)throw new R("expected object, got "+typeof r,s);if(!r)throw new R("expected object, got null",s);if(Array.isArray(r))throw new R("expected object, got list",s);const n=[],i=new Set;for(const[o,a]of Object.entries(r)){i.add(o);const r=(e.get(o)??t)(a,{...s,path:`${s.path}.${o}`});void 0!==r&&n.push([o,r])}for(const e of o)if(!i.has(e))throw new R(`missing required property ${JSON.stringify(e)}`,s);for(const[t,o]of e)if(!i.has(t)){const e=o(void 0,{...s,path:`${s.path}.${t}`});void 0!==e&&n.push([t,e])}return Object.fromEntries(n)},D=e=>e,M=(e,t)=>{throw new R("unknown property",t)};class R extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const G=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,H=(e,t,o="raw")=>e.replaceAll(/\$\{(?:(raw|html|json|int|uri)\()?([^${}():]+)(?:(\))?:-((?:[^})\\]|\\.)*))?(\))?\}/g,(e,r,s,n,i,a)=>{if((n?1:0)+(a?1:0)!=(r?1:0))return e;const c=t(s),f=_[r??o];let p=c.t;return n&&p&&f&&(p=f(p)),p??=i?.replaceAll(/\\(.)/g,"$1")??"",a&&f&&(p=f(p)),!r&&f&&c.o!==o&&(p=f(p)),U(p)}),_={html:e=>U(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),json:e=>JSON.stringify(U(e)),int:e=>{if(Array.isArray(e))return"0";const t=/^(?:\+|(-))?0*(\d+)$/.exec(e);return t?(t[1]??"")+t[2]:"0"},uri:e=>Array.isArray(e)?e.map(encodeURIComponent):encodeURIComponent(e)},U=e=>Array.isArray(e)?e.join("/"):e,B=e=>t=>"?"===t?{t:h(e)||void 0,o:"uri"}:"?"===t[0]?{t:d(e,t.substring(1)),o:"raw"}:{t:m(e,t),o:"raw"};class L{constructor(e,t){this.i=!1,this.l=!1,this.u=!1,this.h=e,this.m=t,this.$=new Map}async set(e){if(!this.l&&!this.u)try{this.l=!0;const t=new Set,o=[];for(let r=0;r<e.length;++r){const s=e[r],n=s.port;n<=0||n>65535?this.h(0,`servers[${r}] must have a specific port from 1 to 65535`):t.has(n)?this.h(0,`skipping servers[${r}] because port ${n} has already been defined`):(t.add(n),o.push(async()=>{const e=await this.v(s,this.$.get(n));e?this.$.set(n,e):this.$.delete(n)}))}this.i||=o.length>0;for(const[e,r]of this.$)t.has(e)||(o.push(r.close),this.$.delete(e));await Promise.all(o.map(e=>e())),this.u?this.S():this.$.size?this.h(1,"all servers ready"):this.h(1,"no servers configured")}finally{this.l=!1}}async v({port:e,host:t,options:o,mount:r},s){const h=this.m("34",`http://${t}:${e}`),d=await(async(e,t=()=>{})=>{const o=new i;o.use(a((e,o)=>{const r=Date.now();return c(e,()=>{const s=Date.now()-r;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:s})}),f}));for(const t of e)switch(t.type){case"files":if("/dev/null"!==t.dir){const e=t.options.negotiation&&t.options.negotiation.length>0?new l(t.options.negotiation):void 0;o.mount(t.path,await u(t.dir,{...t.options,negotiator:e}))}break;case"proxy":o.mount(t.path,p(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[r,s]of Object.entries(t.headers))"string"==typeof s?o.setHeader(r,H(s,B(e))):"number"==typeof s?o.setHeader(r,s):o.setHeader(r,s.map(t=>H(t,B(e))));o.statusCode=t.status,o.end(H(t.body,B(e)))};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e);break;case"redirect":o.at(t.path,a((e,o)=>{let r=H(t.target,B(e),"uri");"/"===t.target[0]&&(r=r.replace(/^\/{2,}/,"/")),o.setHeader("location",r),o.statusCode=t.status,o.end()}))}return o})(r,o.logRequests?e=>{const t=this.m("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),r=this.m(W[e.status/100|0]??"",String(e.status)),s=this.m("2",`(${e.duration}ms)`);this.h(0,`${h} ${t} ${o} ${r} ${s}`)}:()=>{}),m=new g(d);let b,x;if(m.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:r}=e.detail;(w(t,y)?.statusCode??500)>=500&&this.h(0,`${h} ${this.m("91","error")}: ${o} ${r?.url} ${t}`)}),s&&t===s.host&&((e,t)=>{for(const o of Y)if(e[o]!==t[o])return!1;return!0})(o,s.options))b=s.server,this.h(2,`${h} updated`),s.detach();else{if(s?(this.h(2,`${h} ${this.m("2","restarting (step 1: shutdown)")}`),await s.close(),this.h(2,`${h} ${this.m("2","restarting (step 2: start)")}`)):this.h(2,`${h} ${this.m("2","starting")}`),this.u)return;b=n(o),b.setTimeout(o.socketTimeout),x=F(b,e,t,o.backlog)}const $=m.attach(b,o);return x&&(await x,await new Promise(e=>setTimeout(e,1)),this.h(2,`${h} ready`)),{host:t,options:o,server:b,detach:()=>$("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=$("shutdown",o.shutdownTimeout,!0,()=>{b.close(()=>{this.h(2,`${h} closed`),e()}),b.closeAllConnections()}).countConnections();t>0&&this.h(2,`${h} ${this.m("2",`closing (remaining connections: ${t})`)}`)})}}async S(){this.$.size&&(this.h(2,this.m("2","shutting down")),await Promise.all([...this.$.values()].map(e=>e.close()))),this.i&&this.h(2,"shutdown complete")}shutdown(){this.u||(this.u=!0,this.l||this.S())}}const W=["","37","32","36","31","41;97"],F=async(e,t,o,r=511)=>new Promise((s,n)=>{e.once("error",n),e.listen(t,o,r,()=>{e.off("error",n),s()})}),Y=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function Z(e){return e.reduce((e,t)=>({rawSize:e.rawSize+t.rawSize,bestSize:e.bestSize+t.bestSize,created:e.created+t.created}),{rawSize:0,bestSize:0,created:0})}const K=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),Q=["none","ready","progress"];process.on("SIGUSR1",()=>{});let V=2;const X=(e,t)=>e<=V&&process.stderr.write(t+"\n");function ee(e){process.stdin.destroy(),X(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",ee),process.on("uncaughtException",ee);const te=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,oe=(e=>{const t=[];for(let o=0;o<e.length;++o){const r=e[o];if("--"===r)continue;const s=/^--([^ =\-][^ =]*)=(.*)$/.exec(r);if(s){t.push([s[1],s[2]]);continue}const n=/^-([^ =]*)([^ =])=(.*)$/.exec(r);if(n&&"-"!==r[1]){for(const e of n[1])t.push(["-"+e,""]);t.push(["-"+n[2],n[3]]);continue}if("-"!==r[0]||"-"===r){if(0!==o)throw new Error(`value without key: ${r}`);t.push(["",r]);continue}let i=e[o+1];if(i&&"-"===i[0]&&i.length>1&&(i=void 0),void 0!==i&&++o,"-"===r[1])t.push([r.slice(2),i??""]);else{for(const e of r.slice(1,r.length-1))t.push(["-"+e,""]);t.push(["-"+r[r.length-1],i??""])}}const o=new Map;for(const[e,r]of t){const t=(j.get(e)??e).toLowerCase(),s=k.get(t);if(!s)throw new Error(`unknown flag: ${e}`);let n;switch(s.type){case"string":n=r;break;case"number":n=Number.parseFloat(r);break;case"boolean":n=["","on","true","yes","y","1"].includes(r.toLowerCase())}if(s.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(n)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,n)}}return o})(process.argv.slice(2));if(oe.get("version")||oe.get("help")){const r=JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${r.name} ${r.version}\n`),oe.get("help")&&process.stdout.write((re=r.name,["","HTTP/1.1 server for Node.js","","Serves the current directory on port 8080 by default.","When running, send SIGINT (Ctrl+C) to stop.","Send SIGHUP or press enter to reload config.","",` npx ${re} -- [dir] [flags]`,"","Options:"," --config-file=..., -c Path to a JSON configuration file to use (see below)"," --config-json=..., -C Inline JSON configuration to use (see below)",' --port=..., -p The port to bind to. Default "8080"',' --host=..., -a The host address to bind to. Default "localhost"',' --dir=... The directory to serve. Default "."'," --ext=... Implicit file extension to attempt if the requested file"," does not exist (can be specified multiple times)"," --404=... File to use for file-not-found, with status 404"," --spa=... File to use for file-not-found, with status 200"," (e.g. to serve an index file for Single-Page-Apps)"," --zstd, --zst Serve .zst files if zstd compression is requested"," --brotli, --br, -b Serve .br files if brotli compression is requested"," --gzip, --gz, -g Serve .gz files if gzip compression is requested"," --deflate Serve .deflate files if deflate compression is requested"," --proxy=..., -P Proxy requests which match no files to this server"," --mime=... Extra file-extension-to-mime-types to use, in the format",' "ext1=mime1;ext2=mime2" (e.g. "txt=text/plain")'," --mime-types=... Path to an Apache .types file of mime types to register"," --write-compressed Generate and save zstd, brotli, gzip, or deflate files"," for each served file before starting"," --min-compress=... The minimum number of bytes that compression must save,",' otherwise the file is not written. Default "300"'," --no-serve Stop after validating the configuration and optionally"," writing any compressed files",' --log=... "none" / "ready" / "progress" / "full". Set the logging',' level. "ready" prints only the "all servers ready" line,',' "progress" prints server startup and shutdown progress,',' and "full" logs all requests. Default "full"'," --help, -h Print this message and exit"," --version, -v Print the current version and exit","","JSON Configuration:","","JSON offers a more powerful way to configure the server. You can define one or","more servers (one per port), each with its own set of mounted handlers.","Example definition:",""," {",' "servers": ['," {",' "port": 9000,',' "mount": [',' { "type": "files", "dir": "." }',' { "type": "fixture", "method": "GET", "path": "/hello.txt", "body": "Hi!" }',' { "type": "proxy", "target": "https://example.com" }'," ]"," }"," ],",' "mime": ["foo=application/x-foo"],'," }","","All CLI flags are compatible with JSON configuration except --dir and --proxy.","--port is not compatible with JSON configurations with more than one server.","","MIME definitions:","","When defining mime types, some shorthands are available:","- multiple mappings separated by semicolons: foo=text/x-foo;bar=text/x-bar","- multiple file extensions separated by commas: foo,bar=text/plain","- use the file extension in the mime type with {ext}: css,csv=text/{ext}","- optional parts in brackets: jp(e)g,tif(f)=image/{ext}"," ({ext} always maps to the full name, so the example maps .jpg to image/jpeg)","","When using an apache .types file, each line contains a mime type, any amount of","whitespace, then a list of space-separated extensions (without a dot). Lines","starting with # are ignored as comments.","","Example usage:","",` npx ${re} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${re} /dev/null --proxy https://example.com`,"",` npx ${re} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`,"",` npx ${re} . --write-compressed --min-compress 500 --brotli --gzip`,"",` npx ${re} . --write-compressed --brotli --no-serve`]).join("\n")+"\n"),process.exit(0)}var re;(async()=>{const r=new L(X,te);process.on("unhandledRejection",()=>r.shutdown()),process.on("uncaughtException",()=>r.shutdown());const n=function(e){const t=o=>{const r=o.$ref;if(r&&r.startsWith("#/$defs/")){const t=G(e.$defs,r.substring(8));if(!t)throw new Error(`unable to find ${r} in schema`);o={...t,...o}}const s=((e,t)=>{if(void 0!==e.const)return O(e.const);if(e.enum)return E(new Set(e.enum));if(e.anyOf)return P(e.anyOf.map(t));switch(e.type){case"array":return A(t(e.items));case"boolean":return J;case"integer":return T(!0,e.minimum,e.maximum);case"number":return T(!1,e.minimum,e.maximum);case"object":const o=e.additionalProperties??!0,r=C(new Map(Object.entries(e.properties??{}).map(([e,o])=>[e,t(o)])),"object"==typeof o?t(o):o?D:M,e.required??[]);if(e.$comment?.startsWith("flatten:")){const t=e.$comment.substring(8);return(e,o)=>r(e,o)[t]}return r;case"string":if("regex"===e.format)return I();let s=null;return e.pattern&&(s=new RegExp(e.pattern)),q(s,e.format??"");default:throw new Error(`unknown part type ${JSON.stringify(e)}`)}})(o,t);if(void 0!==o.default){const e=JSON.stringify(o.default);return(t,o)=>s(void 0===t?JSON.parse(e):t,o)}return(e,t)=>void 0===e?void 0:s(e,t)};return t(e)}(await(async()=>JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function i(){process.stdin.destroy(),r.shutdown()}async function a(){const t=await(async(t,o)=>{const r=e=>o.get(e)??[],s=e=>o.get(e),n=e=>o.get(e),i=s("config-file"),a=s("config-json"),c=n("port"),f=s("host"),p=s("dir")||".",l=r("ext").map(e=>e.startsWith(".")?e:`.${e}`),u=s("404"),h=s("spa"),d=s("proxy"),m=n("min-compress"),g=r("mime"),w=r("mime-types"),y=s("log");if(Number(Boolean(i))+Number(Boolean(a))+Number(Boolean(d))>1)throw new Error("multiple config files are not supported");let b;if(i)b=t(JSON.parse(await e(i,"utf-8")),{file:i,path:""});else if(a)b=t(JSON.parse(a),{file:"",path:""});else{let e;h?e={statusCode:200,filePath:h}:u&&(e={statusCode:404,filePath:u});const o=[{type:"files",dir:p,options:{fallback:e}}];d&&o.push({type:"proxy",target:d}),b=t({servers:[{port:8080,mount:o}]},{file:"",path:""})}const x=1===b.servers.length?b.servers[0]:void 0;if(void 0!==c){if((0|c)!==c)throw new Error("port must be an integer");if(!x)throw new Error("cannot specify port on commandline when defining multiple servers");x.port=c}if(void 0!==f)for(const e of b.servers)e.host=f;const $=(e,t)=>{for(const o of b.servers)for(const r of o.mount)if("files"===r.type){r.options.negotiation??=[];let o=r.options.negotiation.find(t=>t.feature===e);o||(o={feature:e,options:[]},r.options.negotiation=[...r.options.negotiation,o]),o.options.find(e=>e.value===t.value)||o.options.push(t)}};for(const[e,t]of N)o.get(e)&&$("encoding",t);if(l.length)for(const e of b.servers)for(const t of e.mount)"files"===t.type&&(t.options.implicitSuffixes=l);switch((g.length||w.length)&&(Array.isArray(b.mime)||(b.mime?b.mime=[b.mime]:b.mime=[]),b.mime.push(...g),b.mime.push(...w.map(e=>`file://${e}`))),o.get("write-compressed")&&(b.writeCompressed=!0),void 0!==m&&(b.minCompress=m),o.get("no-serve")&&(b.noServe=!0),y){case"none":case"ready":case"progress":b.log=y;for(const e of b.servers)e.options.logRequests=!1;break;case"full":b.log="progress"}return b})(n,oe);V=Q.indexOf(t.log),await(async t=>{const o=[];for(const r of Array.isArray(t)?t:[t])"string"!=typeof r?o.push(new Map(Object.entries(r))):r.startsWith("file://")?o.push($(await e(r.substring(7),"utf-8"))):o.push(v(r));S();for(const e of o)z(e)})(t.mime),t.writeCompressed&&await(async(e,t,o)=>{let r=0;for(const n of e)for(const e of n.mount)if("files"===e.type){const n=e.options.negotiation?.find(e=>"encoding"===e.feature);if(!n?.options?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}const i=n.match?` matching ${n.match}`:"";o(2,`compressing files in ${e.dir}${i} using ${n.options.map(e=>e.value).join(", ")}`);const a=b(n.match,!0),c=await x(e.dir,n.options,{minCompression:t,filter:(e,t)=>!["image","video","audio","font"].includes(t.split("/")[0])&&a(s(e))}),f=Z(c.filter(({mime:e})=>e.startsWith("text/"))),p=Z(c.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${K(f.rawSize)} / ${K(f.bestSize)} compressed`),o(2,`other: ${K(p.rawSize)} / ${K(p.bestSize)} compressed`),r+=f.created+p.created}o(2,`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(r,"compressed file")} written`)})(t.servers,t.minCompress,X),t.noServe?i():r.set(t.servers)}function c(){return X(2,"refreshing config"),a()}a(),process.on("SIGHUP",()=>c()),process.stdin.on("data",e=>{e.includes("\n")&&c()}),process.on("SIGINT",()=>{X(2,""),i()})})();
2
+ import{readFile as e}from"node:fs/promises";import{join as t,dirname as o,resolve as n,basename as r}from"node:path";import{spawn as s,spawnSync as i}from"node:child_process";import{createServer as c}from"node:http";import{Router as a,requestHandler as f,addTeardown as p,CONTINUE as l,proxy as u,Negotiator as h,fileServer as d,getSearch as w,getQuery as g,getPathParameter as m,WebListener as y,findCause as $,HTTPError as b,stringPredicate as v,compressFilesInDir as x,readMimeTypes as S,decompressMime as k,resetMime as E,registerMime as O}from"./index.js";const j=new Map([["","dir"],["-a","host"],["-b","brotli"],["-c","config-file"],["-C","config-json"],["-d","dir"],["-e","ext"],["-g","gzip"],["-h","help"],["-p","port"],["-P","proxy"],["-v","version"],["br","brotli"],["gz","gzip"],["zst","zstd"]]),z=new Map([["config-file",{type:"string"}],["config-json",{type:"string"}],["dir",{type:"string"}],["exec",{type:"string",multi:!0}],["ext",{type:"string",multi:!0}],["port",{type:"number"}],["host",{type:"string"}],["zstd",{type:"boolean"}],["brotli",{type:"boolean"}],["gzip",{type:"boolean"}],["deflate",{type:"boolean"}],["proxy",{type:"string"}],["404",{type:"string"}],["spa",{type:"string"}],["mime",{type:"string",multi:!0}],["mime-types",{type:"string",multi:!0}],["write-compressed",{type:"boolean"}],["min-compress",{type:"number"}],["no-serve",{type:"boolean"}],["log",{type:"string"}],["help",{type:"boolean"}],["version",{type:"boolean"}]]),N=new Map([["zstd",{value:"zstd",file:"{file}.zst"}],["brotli",{value:"br",file:"{file}.br"}],["gzip",{value:"gzip",file:"{file}.gz"}],["deflate",{value:"deflate",file:"{file}.deflate"}]]);const A=e=>(t,o)=>{if(t!==e)throw new q(`expected ${JSON.stringify(e)}`,o,8);return e},R=e=>(t,o)=>{if(!e.has(t))throw new q(`expected one of ${JSON.stringify(e)}`,o,7);return t},J=e=>(t,o)=>{const n=[];let r=9;for(const s of e)try{return s(t,o)}catch(e){if(e instanceof q){if(e.p>r)continue;e.p!==r&&(r=e.p,n.length=0)}else r=-1;n.push(e)}throw 1===n.length?n[0]:new AggregateError(n)},T=e=>(t,o)=>{if(!Array.isArray(t))throw new q("expected list, got "+typeof t,o);return t.map((t,n)=>e(t,{...o,path:`${o.path}[${n}]`}))},M=(e,t)=>{if("boolean"!=typeof e)throw new q("expected boolean, got "+typeof e,t);return e},_=(e,t,o)=>(n,r)=>{if("number"!=typeof n)throw new q("expected number, got "+typeof n,r);if(e&&(0|n)!==n)throw new q(`expected integer, got ${n}`,r);if("number"==typeof t&&n<t)throw new q(`value cannot be less than ${t}`,r);if("number"==typeof o&&n>o)throw new q(`value cannot be greater than ${o}`,r);return n},P=()=>(e,t)=>{if("string"!=typeof e)throw new q("expected string, got "+typeof e,t);try{return new RegExp(e)}catch{throw new q("expected regular expression",t)}},C=(e,t)=>(r,s)=>{if("string"!=typeof r)throw new q("expected string, got "+typeof r,s);if(e&&!e.test(r))throw new q(`expected string matching ${e}`,s);if("uri-reference"===t&&s.file){if(r.startsWith("file://"))return"file://"+n(o(s.file),r.substring(7));if(!r.includes("://"))return n(o(s.file),r)}return r},I=(e,t,o)=>(n,r)=>{if("object"!=typeof n)throw new q("expected object, got "+typeof n,r);if(!n)throw new q("expected object, got null",r);if(Array.isArray(n))throw new q("expected object, got list",r);const s=[],i=new Set;for(const[o,c]of Object.entries(n)){i.add(o);const n=(e.get(o)??t)(c,{...r,path:`${r.path}.${o}`});void 0!==n&&s.push([o,n])}for(const e of o)if(!i.has(e))throw new q(`missing required property ${JSON.stringify(e)}`,r);for(const[t,o]of e)if(!i.has(t)){const e=o(void 0,{...r,path:`${r.path}.${t}`});void 0!==e&&s.push([t,e])}return Object.fromEntries(s)},B=e=>e,U=(e,t)=>{throw new q("unknown property",t)};class q extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const G=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,H=(e,t,o="raw")=>e.replaceAll(/\$\{(?:(raw|html|json|int|uri)\()?([^${}():]+)(?:(\))?:-((?:[^})\\]|\\.)*))?(\))?\}/g,(e,n,r,s,i,c)=>{if((s?1:0)+(c?1:0)!=(n?1:0))return e;const a=t(r),f=D[n??o];let p=a.t;return s&&p&&f&&(p=f(p)),p??=i?.replaceAll(/\\(.)/g,"$1")??"",c&&f&&(p=f(p)),!n&&f&&a.o!==o&&(p=f(p)),L(p)}),D={html:e=>L(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),json:e=>JSON.stringify(L(e)),int:e=>{if(Array.isArray(e))return"0";const t=/^(?:\+|(-))?0*(\d+)$/.exec(e);return t?(t[1]??"")+t[2]:"0"},uri:e=>Array.isArray(e)?e.map(encodeURIComponent):encodeURIComponent(e)},L=e=>Array.isArray(e)?e.join("/"):e,K=e=>t=>"?"===t?{t:w(e)||void 0,o:"uri"}:"?"===t[0]?{t:g(e,t.substring(1)),o:"raw"}:{t:m(e,t),o:"raw"};class W{constructor(e,t){this.i=!1,this.l=!1,this.u=!1,this.h=e,this.m=t,this.$=new Map,this.v=new Set}async set(e,t){if(!this.l&&!this.u)try{this.l=!0;const o=[],n=[],r=this.v;this.v=new Set;e:for(let e=0;e<t.length;++e){const o=t[e];for(const e of r)if(V(e.config,o)){this.v.add(e),r.delete(e);continue e}n.push(async()=>{this.v.add(await this.S(o))})}for(const e of r)o.push(e.close);const s=new Set;for(let t=0;t<e.length;++t){const o=e[t],r=o.port;r<=0||r>65535?this.h(0,`servers[${t}] must have a specific port from 1 to 65535`):s.has(r)?this.h(0,`skipping servers[${t}] because port ${r} has already been defined`):(s.add(r),n.push(async()=>{const e=await this.k(o,this.$.get(r));e?this.$.set(r,e):this.$.delete(r)}))}this.i||=n.length>0;for(const[e,t]of this.$)s.has(e)||(n.push(t.close),this.$.delete(e));const i=async e=>{let t=[];if(await Promise.all(e.map(async e=>{try{await e()}catch(e){t.push(e)}})),t.length)throw await this.O(),t.length>1?new AggregateError(t):t[0]};await i(o),await i(n),this.u?this.O():this.$.size?this.h(1,"all servers ready"):this.h(1,"no servers configured")}finally{this.l=!1}}async S(e){const t=this.m("35",e.command),o=new AbortController;return new Promise((n,r)=>{this.h(2,`${t} ${this.m("2","starting")}`);const i=s(e.command,e.arguments,{cwd:e.cwd,env:{...process.env,TERM:"",COLORTERM:"",NO_COLOR:"1",...e.environment},killSignal:e.options.killSignal,uid:e.options.uid,gid:e.options.gid,stdio:["ignore","pipe","pipe"],signal:o.signal});e.options.displayStdout?F(i.stdout,`${t} ${this.m("2","[stdout]")} `,process.stderr):i.stdout.resume(),e.options.displayStderr?F(i.stderr,`${t} ${this.m("2","[stderr]")} `,process.stderr):i.stderr.resume(),i.addListener("error",e=>{this.h(0,`${t} startup failed: ${e.message}`),r(e)}),i.addListener("exit",(e,o)=>{null!==e?this.h(2,`${t} closed ${this.m("2",`(exit code ${e})`)}`):this.h(2,`${t} closed ${this.m("2",`(exit signal ${o})`)}`)}),i.addListener("spawn",()=>n({config:e,close:()=>new Promise(o=>{null!==i.signalCode||null!==i.exitCode?o():(this.h(2,`${t} ${this.m("2",`closing (signal ${e.options.killSignal})`)}`),i.addListener("exit",o),i.kill(e.options.killSignal))})}))})}async k({port:e,host:t,options:o,mount:n},r){const s=this.m("34",`http://${t}:${e}`),i=await(async(e,t=()=>{})=>{const o=new a;o.use(f((e,o)=>{const n=Date.now();return p(e,()=>{const r=Date.now()-n;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:r})}),l}));for(const t of e)switch(t.type){case"files":if("/dev/null"!==t.dir){const e=t.options.negotiation&&t.options.negotiation.length>0?new h(t.options.negotiation):void 0;o.mount(t.path,await d(t.dir,{...t.options,negotiator:e}))}break;case"proxy":o.mount(t.path,u(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[n,r]of Object.entries(t.headers))"string"==typeof r?o.setHeader(n,H(r,K(e))):"number"==typeof r?o.setHeader(n,r):o.setHeader(n,r.map(t=>H(t,K(e))));o.statusCode=t.status,o.end(H(t.body,K(e)))};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e);break;case"redirect":o.at(t.path,f((e,o)=>{let n=H(t.target,K(e),"uri");"/"===t.target[0]&&(n=n.replace(/^\/{2,}/,"/")),o.setHeader("location",n),o.statusCode=t.status,o.end()}))}return o})(n,o.logRequests?e=>{const t=this.m("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),n=this.m(Z[e.status/100|0]??"",String(e.status)),r=this.m("2",`(${e.duration}ms)`);this.h(0,`${s} ${t} ${o} ${n} ${r}`)}:()=>{}),w=new y(i);let g,m;if(w.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:n}=e.detail;($(t,b)?.statusCode??500)>=500&&this.h(0,`${s} ${this.m("91","error")}: ${o} ${n?.url} ${t}`)}),r&&t===r.host&&((e,t)=>{for(const o of X)if(e[o]!==t[o])return!1;return!0})(o,r.options))g=r.server,this.h(2,`${s} updated`),r.detach();else{if(r?(this.h(2,`${s} ${this.m("2","restarting (step 1: shutdown)")}`),await r.close(),this.h(2,`${s} ${this.m("2","restarting (step 2: start)")}`)):this.h(2,`${s} ${this.m("2","starting")}`),this.u)return;g=c(o),g.setTimeout(o.socketTimeout),m=Q(g,e,t,o.backlog)}const v=w.attach(g,o);return m&&(await m,await new Promise(e=>setTimeout(e,1)),this.h(2,`${s} ready`)),{host:t,options:o,server:g,detach:()=>v("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=v("shutdown",o.shutdownTimeout,!0,()=>{g.close(()=>{this.h(2,`${s} closed`),e()}),g.closeAllConnections()}).countConnections();t>0&&this.h(2,`${s} ${this.m("2",`closing (remaining connections: ${t})`)}`)})}}async O(){this.$.size&&(this.h(2,this.m("2","shutting down")),await Promise.all([...this.$.values(),...this.v].map(e=>e.close()))),this.i&&this.h(2,"shutdown complete")}shutdown(){this.u||(this.u=!0,this.l||this.O())}}const Z=["","37","32","36","31","41;97"];function F(e,t,o){let n="";const r=e=>o.write(t+e.replaceAll(/\x1b\[[\d;]*[A-K]/g,"").replaceAll(/[\x00-\x1f]/g,e=>`\\x${e.charCodeAt(0).toString(16).padStart(2,"0")}`)+"\n");e.addListener("data",e=>{n+=e;const t=n.split("\n");n=t.pop();for(const e of t)r(e)}),e.addListener("end",()=>{n&&r(n)})}const Q=async(e,t,o,n=511)=>new Promise((r,s)=>{e.once("error",s),e.listen(t,o,n,()=>{e.off("error",s),r()})});function V(e,t){return e.command===t.command&&e.arguments.length===t.arguments.length&&e.arguments.every((e,o)=>e===t.arguments[o])&&e.cwd===t.cwd&&JSON.stringify(e.environment)===JSON.stringify(t.environment)&&e.options.uid===t.options.uid&&e.options.gid===t.options.gid&&e.options.killSignal===t.options.killSignal&&e.options.displayStdout===t.options.displayStdout&&e.options.displayStderr===t.options.displayStderr}const X=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function Y(e){return e.reduce((e,t)=>({rawSize:e.rawSize+t.rawSize,bestSize:e.bestSize+t.bestSize,created:e.created+t.created}),{rawSize:0,bestSize:0,created:0})}const ee=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),te=["none","ready","progress"];process.on("SIGUSR1",()=>{});let oe=2;const ne=(e,t)=>e<=oe&&process.stderr.write(t+"\n");function re(e){process.stdin.destroy(),ne(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",re),process.on("uncaughtException",re);const se=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,ie=(e=>{const t=[];for(let o=0;o<e.length;++o){const n=e[o];if("--"===n)continue;const r=/^--([^ =\-][^ =]*)=(.*)$/.exec(n);if(r){t.push([r[1],r[2]]);continue}const s=/^-([^ =]*)([^ =])=(.*)$/.exec(n);if(s&&"-"!==n[1]){for(const e of s[1])t.push(["-"+e,""]);t.push(["-"+s[2],s[3]]);continue}if("-"!==n[0]||"-"===n){if(0!==o)throw new Error(`value without key: ${n}`);t.push(["",n]);continue}let i=e[o+1];if(i&&"-"===i[0]&&i.length>1&&(i=void 0),void 0!==i&&++o,"-"===n[1])t.push([n.slice(2),i??""]);else{for(const e of n.slice(1,n.length-1))t.push(["-"+e,""]);t.push(["-"+n[n.length-1],i??""])}}const o=new Map;for(const[e,n]of t){const t=(j.get(e)??e).toLowerCase(),r=z.get(t);if(!r)throw new Error(`unknown flag: ${e}`);let s;switch(r.type){case"string":s=n;break;case"number":s=Number.parseFloat(n);break;case"boolean":s=["","on","true","yes","y","1"].includes(n.toLowerCase())}if(r.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(s)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,s)}}return o})(process.argv.slice(2)),ce=o(new URL(import.meta.url).pathname);if(ie.get("version")||ie.get("help")){let o={name:"web-listener",version:"unknown"};try{o=JSON.parse(await e(t(ce,"package.json"),"utf-8"))}catch{}ie.get("help")?i("man",["-M",ce,o.name],{stdio:["inherit","inherit","inherit"]}):process.stdout.write(`${o.name} ${o.version}\n`),process.exit(0)}(async()=>{const n=new W(ne,se);process.on("unhandledRejection",()=>n.shutdown()),process.on("uncaughtException",()=>n.shutdown());const s=function(e){const t=o=>{const n=o.$ref;if(n&&n.startsWith("#/$defs/")){const t=G(e.$defs,n.substring(8));if(!t)throw new Error(`unable to find ${n} in schema`);o={...t,...o}}const r=((e,t)=>{if(void 0!==e.const)return A(e.const);if(e.enum)return R(new Set(e.enum));if(e.anyOf)return J(e.anyOf.map(t));switch(e.type){case"array":return T(t(e.items));case"boolean":return M;case"integer":return _(!0,e.minimum,e.maximum);case"number":return _(!1,e.minimum,e.maximum);case"object":const o=e.additionalProperties??!0,n=I(new Map(Object.entries(e.properties??{}).map(([e,o])=>[e,t(o)])),"object"==typeof o?t(o):o?B:U,e.required??[]);if(e.$comment?.startsWith("flatten:")){const t=e.$comment.substring(8);return(e,o)=>n(e,o)[t]}return n;case"string":if("regex"===e.format)return P();let r=null;return e.pattern&&(r=new RegExp(e.pattern)),C(r,e.format??"");default:throw new Error(`unknown part type ${JSON.stringify(e)}`)}})(o,t);if(void 0!==o.default){const e=JSON.stringify(o.default);return(t,o)=>r(void 0===t?JSON.parse(e):t,o)}return(e,t)=>void 0===e?void 0:r(e,t)};return t(e)}(await(async()=>JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"schema.json"),"utf-8")))());function i(){process.stdin.destroy(),n.shutdown()}async function c(){const t=await(async(t,o)=>{const n=e=>o.get(e)??[],r=e=>o.get(e),s=e=>o.get(e),i=r("config-file"),c=r("config-json"),a=s("port"),f=r("host"),p=r("dir")||".",l=n("exec").map(e=>e.split(" ")),u=n("ext").map(e=>e.startsWith(".")?e:`.${e}`),h=r("404"),d=r("spa"),w=r("proxy"),g=s("min-compress"),m=n("mime"),y=n("mime-types"),$=r("log");if(Number(Boolean(i))+Number(Boolean(c))+Number(Boolean(w))>1)throw new Error("multiple config files are not supported");let b;if(i)b=t(JSON.parse(await e(i,"utf-8")),{file:i,path:""});else if(c)b=t(JSON.parse(c),{file:"",path:""});else{let e;d?e={statusCode:200,filePath:d}:h&&(e={statusCode:404,filePath:h});const o=[{type:"files",dir:p,options:{fallback:e}}];w&&o.push({type:"proxy",target:w}),b=t({servers:[{port:8080,mount:o}]},{file:"",path:""})}for(const e of l)b.backgroundTasks.push({command:e[0],arguments:e.slice(1),cwd:process.cwd(),environment:{},options:{killSignal:"SIGTERM",displayStdout:!0,displayStderr:!0}});const v=1===b.servers.length?b.servers[0]:void 0;if(void 0!==a){if((0|a)!==a)throw new Error("port must be an integer");if(!v)throw new Error("cannot specify port on commandline when defining multiple servers");v.port=a}if(void 0!==f)for(const e of b.servers)e.host=f;const x=(e,t)=>{for(const o of b.servers)for(const n of o.mount)if("files"===n.type){n.options.negotiation??=[];let o=n.options.negotiation.find(t=>t.feature===e);o||(o={feature:e,options:[]},n.options.negotiation=[...n.options.negotiation,o]),o.options.find(e=>e.value===t.value)||o.options.push(t)}};for(const[e,t]of N)o.get(e)&&x("encoding",t);if(u.length)for(const e of b.servers)for(const t of e.mount)"files"===t.type&&(t.options.implicitSuffixes=u);switch((m.length||y.length)&&(Array.isArray(b.mime)||(b.mime?b.mime=[b.mime]:b.mime=[]),b.mime.push(...m),b.mime.push(...y.map(e=>`file://${e}`))),o.get("write-compressed")&&(b.writeCompressed=!0),void 0!==g&&(b.minCompress=g),o.get("no-serve")&&(b.noServe=!0),$){case"none":case"ready":case"progress":b.log=$;for(const e of b.servers)e.options.logRequests=!1;for(const e of b.backgroundTasks)e.options.displayStderr=!1,e.options.displayStdout=!1;break;case"full":b.log="progress"}return b})(s,ie);oe=te.indexOf(t.log),await(async t=>{const o=[];for(const n of Array.isArray(t)?t:[t])"string"!=typeof n?o.push(new Map(Object.entries(n))):n.startsWith("file://")?o.push(S(await e(n.substring(7),"utf-8"))):o.push(k(n));E();for(const e of o)O(e)})(t.mime),t.writeCompressed&&await(async(e,t,o)=>{let n=0;for(const s of e)for(const e of s.mount)if("files"===e.type){const s=e.options.negotiation?.find(e=>"encoding"===e.feature);if(!s?.options?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}const i=s.match?` matching ${s.match}`:"";o(2,`compressing files in ${e.dir}${i} using ${s.options.map(e=>e.value).join(", ")}`);const c=v(s.match,!0),a=await x(e.dir,s.options,{minCompression:t,filter:(e,t)=>!["image","video","audio","font"].includes(t.split("/")[0])&&c(r(e))}),f=Y(a.filter(({mime:e})=>e.startsWith("text/"))),p=Y(a.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${ee(f.rawSize)} / ${ee(f.bestSize)} compressed`),o(2,`other: ${ee(p.rawSize)} / ${ee(p.bestSize)} compressed`),n+=f.created+p.created}o(2,`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(n,"compressed file")} written`)})(t.servers,t.minCompress,ne),t.noServe?i():n.set(t.servers,t.backgroundTasks).catch(e=>{if(e instanceof AggregateError)for(const t of e.errors)ne(0,t instanceof Error?t.message:String(t));else ne(0,e instanceof Error?e.message:String(e));process.stdin.destroy(),process.exit(1)})}function a(){return ne(2,"refreshing config"),c()}c(),process.on("SIGHUP",()=>a()),process.stdin.on("data",e=>{e.includes("\n")&&a()});let f=!1;process.on("SIGINT",()=>{f||(f=!0,ne(2,""),i())})})();
package/schema.json CHANGED
@@ -1 +1 @@
1
- {"$schema":"https://json-schema.org/draft-07/schema#","title":"Configuration for running one or more servers via the web-listener CLI","type":"object","additionalProperties":false,"required":["servers"],"properties":{"$schema":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/$defs/server"}},"mime":{"anyOf":[{"type":"array","items":{"$ref":"#/$defs/mime"}},{"$ref":"#/$defs/mime"}],"default":[]},"writeCompressed":{"title":"Generate and save zstd, brotli, gzip, or deflate files for each served file before starting","type":"boolean","default":false},"minCompress":{"title":"The minimum number of bytes that compression must save, otherwise the file is not written","type":"integer","default":300},"noServe":{"title":"Stop after validating the configuration and optionally writing any compressed files","type":"boolean","default":false},"log":{"title":"Set the logging level. \"ready\" prints only the \"all servers ready\" line, \"progress\" prints server startup and shutdown progress.","enum":["none","ready","progress"],"default":"progress"}},"$defs":{"server":{"title":"Configuration for one server","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"server","description":"Defines a server on a given port","body":{"port":"^${1:80}","mount":[]}}],"required":["port","mount"],"properties":{"port":{"type":"integer","minimum":1,"maximum":65535},"host":{"type":"string","default":"localhost"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"requestTimeout":{"type":"integer"},"keepAliveTimeout":{"type":"integer"},"keepAliveTimeoutBuffer":{"type":"integer"},"connectionsCheckingInterval":{"type":"integer"},"headersTimeout":{"type":"integer"},"highWaterMark":{"type":"integer"},"maxHeaderSize":{"type":"integer"},"noDelay":{"type":"boolean"},"requireHostHeader":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"uniqueHeaders":{"type":"array","items":{"type":"string"}},"backlog":{"type":"integer","default":511},"socketTimeout":{"type":"integer"},"rejectNonStandardExpect":{"type":"boolean","default":false},"autoContinue":{"type":"boolean","default":false},"logRequests":{"type":"boolean","default":true},"restartTimeout":{"type":"integer","default":2000},"shutdownTimeout":{"type":"integer","default":500}}},"mount":{"type":"array","items":{"title":"Service to mount on the server","defaultSnippets":[{"label":"files","body":{"type":"files","path":"${1:/}","dir":"${2:.}"}},{"label":"proxy","body":{"type":"proxy","path":"${1:/}","target":"${2:http://localhost:8080}"}},{"label":"fixture","body":{"type":"fixture","method":"${1:GET}","path":"${2:/}","status":"^${3:200}","body":"$4"}}],"anyOf":[{"$ref":"#/$defs/mount-files"},{"$ref":"#/$defs/mount-proxy"},{"$ref":"#/$defs/mount-fixture"},{"$ref":"#/$defs/mount-redirect"}]}}}},"mount-files":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"files"},"path":{"type":"string","default":"/"},"dir":{"type":"string","default":".","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"fallback":{"type":"object","additionalProperties":false,"required":["filePath"],"properties":{"statusCode":{"$ref":"#/$defs/status","default":200},"filePath":{"type":"string"}}},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"allowDirectIndexAccess":{"type":"boolean","default":false},"hide":{"type":"array","default":[],"items":{"$ref":"#/$defs/stringOrRegex"}},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]},"indexFiles":{"type":"array","items":{"type":"string"},"default":["index.htm","index.html"]},"implicitSuffixes":{"type":"array","items":{"type":"string"},"default":[]},"negotiation":{"type":"array","default":[],"items":{"type":"object","additionalProperties":false,"required":["feature","options"],"properties":{"feature":{"enum":["type","language","encoding"]},"match":{"$ref":"#/$defs/stringOrRegex"},"options":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["value","file"],"properties":{"value":{"type":"string"},"for":{"type":"string","format":"regex"},"file":{"type":"string"}}}}}}}}}}},"mount-proxy":{"type":"object","additionalProperties":false,"required":["type","target"],"properties":{"type":{"const":"proxy"},"path":{"type":"string","default":"/"},"target":{"type":"string"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"noDelay":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"keepAliveMsecs":{"type":"integer"},"agentKeepAliveTimeoutBuffer":{"type":"integer"},"maxSockets":{"type":"integer"},"maxFreeSockets":{"type":"integer"},"timeout":{"type":"integer"},"blockRequestHeaders":{"type":"array","items":{"type":"string"}},"blockResponseHeaders":{"type":"array","items":{"type":"string"}},"servername":{"type":"string"},"ca":{"type":"string"},"cert":{"type":"string"},"sigalgs":{"type":"string"},"ciphers":{"type":"string"},"crl":{"type":"string"},"ecdhCurve":{"type":"string"},"key":{"type":"string"},"passphrase":{"type":"string"},"pfx":{"type":"string"},"sessionTimeout":{"type":"integer"},"maxCachedSessions":{"type":"integer"}}}}},"mount-fixture":{"type":"object","additionalProperties":false,"required":["type","path","body"],"properties":{"type":{"const":"fixture"},"path":{"type":"string"},"method":{"type":"string","default":"GET"},"status":{"$ref":"#/$defs/status","default":200},"headers":{"type":"object","default":{},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"array","items":{"type":"string"}}]}},"body":{"type":"string"}}},"mount-redirect":{"type":"object","additionalProperties":false,"required":["type","path","target"],"properties":{"type":{"const":"redirect"},"path":{"type":"string"},"status":{"$ref":"#/$defs/status","default":307},"target":{"type":"string"}}},"mime":{"anyOf":[{"type":"string","pattern":"^file://","format":"uri-reference"},{"type":"string","pattern":"^([^=;]+=[^/;]+/[^;]+(;|$))+$"},{"type":"object","additionalProperties":{"type":"string","pattern":"/"}}]},"stringOrRegex":{"anyOf":[{"type":"string"},{"type":"object","additionalProperties":false,"required":["pattern"],"properties":{"pattern":{"type":"string","format":"regex"}},"$comment":"flatten:pattern"}]},"status":{"type":"integer","minimum":200,"maximum":599}}}
1
+ {"$schema":"https://json-schema.org/draft-07/schema#","title":"Configuration for running one or more servers via the web-listener CLI","type":"object","additionalProperties":false,"required":["servers"],"properties":{"$schema":{"type":"string"},"servers":{"type":"array","items":{"$ref":"#/$defs/server"}},"backgroundTasks":{"type":"array","items":{"$ref":"#/$defs/task"},"default":[]},"mime":{"anyOf":[{"type":"array","items":{"$ref":"#/$defs/mime"}},{"$ref":"#/$defs/mime"}],"default":[]},"writeCompressed":{"title":"Generate and save zstd, brotli, gzip, or deflate files for each served file before starting","type":"boolean","default":false},"minCompress":{"title":"The minimum number of bytes that compression must save, otherwise the file is not written","type":"integer","default":300},"noServe":{"title":"Stop after validating the configuration and optionally writing any compressed files","type":"boolean","default":false},"log":{"title":"Set the logging level. \"ready\" prints only the \"all servers ready\" line, \"progress\" prints server startup and shutdown progress.","enum":["none","ready","progress"],"default":"progress"}},"$defs":{"server":{"title":"Configuration for one server","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"server","description":"Defines a server on a given port","body":{"port":"^${1:80}","mount":[]}}],"required":["port","mount"],"properties":{"port":{"type":"integer","minimum":1,"maximum":65535},"host":{"type":"string","default":"localhost"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"requestTimeout":{"type":"integer"},"keepAliveTimeout":{"type":"integer"},"keepAliveTimeoutBuffer":{"type":"integer"},"connectionsCheckingInterval":{"type":"integer"},"headersTimeout":{"type":"integer"},"highWaterMark":{"type":"integer"},"maxHeaderSize":{"type":"integer"},"noDelay":{"type":"boolean"},"requireHostHeader":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"uniqueHeaders":{"type":"array","items":{"type":"string"}},"backlog":{"type":"integer","default":511},"socketTimeout":{"type":"integer"},"rejectNonStandardExpect":{"type":"boolean","default":false},"autoContinue":{"type":"boolean","default":false},"logRequests":{"type":"boolean","default":true},"restartTimeout":{"type":"integer","default":2000},"shutdownTimeout":{"type":"integer","default":500}}},"mount":{"type":"array","items":{"title":"Service to mount on the server","defaultSnippets":[{"label":"files","body":{"type":"files","path":"${1:/}","dir":"${2:.}"}},{"label":"proxy","body":{"type":"proxy","path":"${1:/}","target":"${2:http://localhost:8080}"}},{"label":"fixture","body":{"type":"fixture","method":"${1:GET}","path":"${2:/}","status":"^${3:200}","body":"$4"}}],"anyOf":[{"$ref":"#/$defs/mount-files"},{"$ref":"#/$defs/mount-proxy"},{"$ref":"#/$defs/mount-fixture"},{"$ref":"#/$defs/mount-redirect"}]}}}},"mount-files":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"type":{"const":"files"},"path":{"type":"string","default":"/"},"dir":{"type":"string","default":".","format":"uri-reference"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"mode":{"enum":["dynamic","static-paths"],"default":"dynamic"},"fallback":{"type":"object","additionalProperties":false,"required":["filePath"],"properties":{"statusCode":{"$ref":"#/$defs/status","default":200},"filePath":{"type":"string"}}},"verbose":{"type":"boolean","default":false},"subDirectories":{"anyOf":[{"type":"boolean"},{"type":"integer"}],"default":true},"caseSensitive":{"enum":["exact","filesystem","force-lowercase"],"default":"exact"},"allowAllDotfiles":{"type":"boolean","default":false},"allowAllTildefiles":{"type":"boolean","default":false},"allowDirectIndexAccess":{"type":"boolean","default":false},"hide":{"type":"array","default":[],"items":{"$ref":"#/$defs/stringOrRegex"}},"allow":{"type":"array","items":{"type":"string"},"default":[".well-known"]},"indexFiles":{"type":"array","items":{"type":"string"},"default":["index.htm","index.html"]},"implicitSuffixes":{"type":"array","items":{"type":"string"},"default":[]},"negotiation":{"type":"array","default":[],"items":{"type":"object","additionalProperties":false,"required":["feature","options"],"properties":{"feature":{"enum":["type","language","encoding"]},"match":{"$ref":"#/$defs/stringOrRegex"},"options":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["value","file"],"properties":{"value":{"type":"string"},"for":{"type":"string","format":"regex"},"file":{"type":"string"}}}}}}}}}}},"mount-proxy":{"type":"object","additionalProperties":false,"required":["type","target"],"properties":{"type":{"const":"proxy"},"path":{"type":"string","default":"/"},"target":{"type":"string"},"options":{"type":"object","default":{},"additionalProperties":false,"properties":{"noDelay":{"type":"boolean"},"keepAlive":{"type":"boolean"},"keepAliveInitialDelay":{"type":"integer"},"keepAliveMsecs":{"type":"integer"},"agentKeepAliveTimeoutBuffer":{"type":"integer"},"maxSockets":{"type":"integer"},"maxFreeSockets":{"type":"integer"},"timeout":{"type":"integer"},"blockRequestHeaders":{"type":"array","items":{"type":"string"}},"blockResponseHeaders":{"type":"array","items":{"type":"string"}},"servername":{"type":"string"},"ca":{"type":"string"},"cert":{"type":"string"},"sigalgs":{"type":"string"},"ciphers":{"type":"string"},"crl":{"type":"string"},"ecdhCurve":{"type":"string"},"key":{"type":"string"},"passphrase":{"type":"string"},"pfx":{"type":"string"},"sessionTimeout":{"type":"integer"},"maxCachedSessions":{"type":"integer"}}}}},"mount-fixture":{"type":"object","additionalProperties":false,"required":["type","path","body"],"properties":{"type":{"const":"fixture"},"path":{"type":"string"},"method":{"type":"string","default":"GET"},"status":{"$ref":"#/$defs/status","default":200},"headers":{"type":"object","default":{},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"array","items":{"type":"string"}}]}},"body":{"type":"string"}}},"mount-redirect":{"type":"object","additionalProperties":false,"required":["type","path","target"],"properties":{"type":{"const":"redirect"},"path":{"type":"string"},"status":{"$ref":"#/$defs/status","default":307},"target":{"type":"string"}}},"task":{"title":"Configuration for a background task","type":"object","additionalProperties":false,"defaultSnippets":[{"label":"task","description":"Run an executable","body":{"command":"$1"}}],"required":["command"],"properties":{"command":{"anyOf":[{"type":"string","pattern":"[\\\\/]","format":"uri-reference"},{"type":"string","pattern":"^[^\\\\/]*$"}]},"arguments":{"type":"array","items":{"type":"string"},"default":[]},"cwd":{"type":"string","default":".","format":"uri-reference"},"environment":{"type":"object","additionalProperties":{"type":"string"},"default":{}},"options":{"type":"object","additionalProperties":false,"properties":{"uid":{"type":"number"},"gid":{"type":"number"},"killSignal":{"anyOf":[{"enum":["SIGABRT","SIGALRM","SIGBUS","SIGCHLD","SIGCONT","SIGFPE","SIGHUP","SIGILL","SIGINT","SIGIO","SIGIOT","SIGKILL","SIGPIPE","SIGPOLL","SIGPROF","SIGPWR","SIGQUIT","SIGSEGV","SIGSTKFLT","SIGSTOP","SIGSYS","SIGTERM","SIGTRAP","SIGTSTP","SIGTTIN","SIGTTOU","SIGUNUSED","SIGURG","SIGUSR1","SIGUSR2","SIGVTALRM","SIGWINCH","SIGXCPU","SIGXFSZ","SIGBREAK","SIGLOST","SIGINFO"]},{"type":"number"}],"default":"SIGTERM"},"displayStdout":{"type":"boolean","default":true},"displayStderr":{"type":"boolean","default":true}},"default":{}}}},"mime":{"anyOf":[{"type":"string","pattern":"^file://","format":"uri-reference"},{"type":"string","pattern":"^([^=;]+=[^/;]+/[^;]+(;|$))+$"},{"type":"object","additionalProperties":{"type":"string","pattern":"/"}}]},"stringOrRegex":{"anyOf":[{"type":"string"},{"type":"object","additionalProperties":false,"required":["pattern"],"properties":{"pattern":{"type":"string","format":"regex"}},"$comment":"flatten:pattern"}]},"status":{"type":"integer","minimum":200,"maximum":599}}}