web-listener 0.13.2 → 0.14.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/index.d.ts CHANGED
@@ -43,6 +43,8 @@ declare class Queue<T> {
43
43
  [Symbol.iterator](): Iterator<T, unknown, undefined>;
44
44
  }
45
45
 
46
+ declare const stringPredicate: (conditions: (string | RegExp)[] | string | RegExp | undefined, caseInsensitive: boolean) => ((value: string) => boolean);
47
+
46
48
  type MaybePromise<T> = Promise<T> | T;
47
49
 
48
50
  type ServerErrorCallback = (error: unknown, context: string, req: IncomingMessage) => void;
@@ -400,14 +402,27 @@ declare const requireAuthScope: (scope: string) => RequestHandler & UpgradeHandl
400
402
  declare function generateWeakETag(contentEncoding: string | number | string[] | undefined, fileStats: Pick<Stats, 'mtimeMs' | 'size'>): string;
401
403
  declare function generateStrongETag(file: string | FileHandle): Promise<string>;
402
404
 
403
- declare const HEADERS: {
404
- mime: string;
405
- language: string;
406
- encoding: string;
405
+ declare const FEATURES: {
406
+ type: {
407
+ _requestHeader: string;
408
+ _responseHeader: string;
409
+ };
410
+ language: {
411
+ _requestHeader: string;
412
+ _responseHeader: string;
413
+ };
414
+ encoding: {
415
+ _requestHeader: string;
416
+ _responseHeader: string;
417
+ };
407
418
  };
408
- type NegotiationType = keyof typeof HEADERS;
419
+ type NegotiationFeature = keyof typeof FEATURES;
409
420
  interface FileNegotiation {
410
- type: NegotiationType;
421
+ /** Feature to negotiate ('type', 'language', or 'encoding') */
422
+ feature: NegotiationFeature;
423
+ /** Filename filter (only apply this negotiation for requests with filenames matching the pattern) */
424
+ match?: string | RegExp;
425
+ /** List of negotiation options available, ordered by server preference */
411
426
  options: FileNegotiationOption[];
412
427
  }
413
428
  interface FileNegotiationOption {
@@ -446,20 +461,22 @@ interface FileNegotiationOption {
446
461
  }
447
462
  type FileEncodingFormat = 'zstd' | 'br' | 'gzip' | 'deflate' | 'identity';
448
463
  declare const negotiateEncoding: (options: FileEncodingFormat[] | Record<FileEncodingFormat, string>) => FileNegotiation;
449
- interface NegotiationOutputInfo {
464
+ type NegotiationOutputHeaders = {
450
465
  /** The negotiated mime type for the resolved file */
451
- mime?: string | undefined;
466
+ 'content-type'?: string;
452
467
  /** The negotiated language for the resolved file */
453
- language?: string | undefined;
468
+ 'content-language'?: string;
454
469
  /** The negotiated encoding for the resolved file */
455
- encoding?: string | undefined;
456
- }
470
+ 'content-encoding'?: string;
471
+ /** A list of request headers which were considered when negotiating this file */
472
+ vary?: string;
473
+ } & Record<string, string>;
457
474
  interface NegotiationOutput {
458
475
  filename: string;
459
- info: NegotiationOutputInfo;
476
+ /** Response headers relevant to the negotiation */
477
+ headers: NegotiationOutputHeaders;
460
478
  }
461
479
  declare class Negotiator {
462
- readonly vary: string;
463
480
  /**
464
481
  * Content negotiation rules.
465
482
  *
@@ -509,8 +526,16 @@ interface CompressionOptions {
509
526
  * @default false
510
527
  */
511
528
  deleteObsolete?: boolean;
529
+ /**
530
+ * Filter to apply to files (does not attempt to compress files if the function returns `false`)
531
+ * @param path the full path to the file
532
+ * @param mime the mime type of the file (if known, else 'application/binary')
533
+ * @returns `true` if the file should be compressed
534
+ * @default (_, mime) => !['image', 'video', 'audio', 'font'].includes(mime.split('/')[0])
535
+ */
536
+ filter?: (path: string, mime: string) => boolean;
512
537
  }
513
- declare function compressFileOffline(file: string, encodings: FileNegotiationOption[], { minCompression, deleteObsolete }?: CompressionOptions): Promise<CompressionInfo>;
538
+ declare function compressFileOffline(file: string, encodings: FileNegotiationOption[], { minCompression, deleteObsolete, filter }?: CompressionOptions): Promise<CompressionInfo>;
514
539
  declare function compressFilesInDir(dir: string, encodings: FileNegotiationOption[], options?: CompressionOptions): Promise<CompressionInfo[]>;
515
540
 
516
541
  declare const emitError: (req: IncomingMessage, error: unknown, context?: string) => void;
@@ -644,10 +669,8 @@ interface FileFinderOptions {
644
669
  interface FileFinderCore {
645
670
  find(pathParts: string[], reqHeaders?: IncomingHttpHeaders, warnings?: string[] | undefined): Promise<ResolvedFileInfo | null>;
646
671
  debugAllPaths(): Promise<Set<string>>;
647
- readonly vary: string;
648
672
  }
649
673
  declare class FileFinder implements FileFinderCore {
650
- readonly vary: string;
651
674
  static build(absBaseDir: string, options?: FileFinderOptions): Promise<FileFinder>;
652
675
  toNormalisedPath(pathParts: string[]): string[];
653
676
  /**
@@ -663,7 +686,7 @@ declare class FileFinder implements FileFinderCore {
663
686
  debugAllPaths(): Promise<Set<string>>;
664
687
  precompute(): Promise<FileFinderCore>;
665
688
  }
666
- interface ResolvedFileInfo extends NegotiationOutputInfo {
689
+ interface ResolvedFileInfo {
667
690
  /** An active filehandle for the resolved file. Note that this MUST be closed by the caller. */
668
691
  handle: FileHandle;
669
692
  /** The full path of the requested file (after adding implicit extensions and index files) */
@@ -672,6 +695,8 @@ interface ResolvedFileInfo extends NegotiationOutputInfo {
672
695
  negotiatedPath: string;
673
696
  /** Filesystem stats about the resolved file */
674
697
  stats: Stats;
698
+ /** Response headers relevant to the negotiation of this file */
699
+ headers: NegotiationOutputHeaders;
675
700
  }
676
701
 
677
702
  interface SavedFile {
@@ -1027,7 +1052,7 @@ interface QualityValue {
1027
1052
  }
1028
1053
  declare function readHTTPUnquotedCommaSeparated(raw: LooseHeaderValue | undefined): string[] | undefined;
1029
1054
  declare function readHTTPInteger(raw: string | undefined): number | undefined;
1030
- declare function readHTTPQualityValues(raw: string | undefined): QualityValue[] | undefined;
1055
+ declare const readHTTPQualityValues: (raw: LooseHeaderValue | undefined) => QualityValue[] | undefined;
1031
1056
  declare function readHTTPKeyValues(raw: string): Map<string, string>;
1032
1057
  declare function readHTTPDateSeconds(raw: LooseHeaderValue | undefined): number | undefined;
1033
1058
  type LooseHeaderValue = string | number | string[];
@@ -1308,5 +1333,5 @@ declare class Property<T> {
1308
1333
  }
1309
1334
  declare const makeMemo: <T, Args extends any[] = []>(fn: (req: IncomingMessage, ...args: Args) => T, ...args: Args) => ((req: IncomingMessage) => T);
1310
1335
 
1311
- 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, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, toListeners, typedErrorHandler, upgradeHandler };
1312
- 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, NegotiationOutputInfo, ParametersFromPath, PostCheckFile, PostCheckFileInfo, PreCheckFile, PreCheckFileInfo, ProxyChain, ProxyNode, ProxyOptions, ProxyRequestHeaderAdapter, ProxyResponseHeaderAdapter, QualityValue, RangePart, RequestHandler, ResolvedFileInfo, ServerErrorCallback, ServerGeneralErrorCallback, ServerSentEvent, SimplifyRangeOptions, TokenAuthHandler, UpgradeErrorHandler, UpgradeHandler, UpgradeListener, WithPathParameters };
1336
+ 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, sendCSVStream, sendFile, sendJSON, sendJSONStream, sendRanges, setDefaultCacheHeaders, setSoftCloseHandler, simpleAppendForwarded, simplifyRange, stringPredicate, toListeners, typedErrorHandler, upgradeHandler };
1337
+ 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, 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 i,Agent as r,request as o,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 h,randomUUID as l}from"node:crypto";import{pipeline as d}from"node:stream/promises";import w from"node:zlib";import{promisify as p}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as v,resolve as E}from"node:path";import{readFile as T,writeFile as _,rm as x,stat as S,readdir as $,realpath as k,open as N,mkdtemp as O}from"node:fs/promises";import{tmpdir as A,platform as R}from"node:os";import{Agent as P,request as C}from"node:https";import{TransformStream as F,TextDecoderStream as U,DecompressionStream as M,ReadableStream as B}from"node:stream/web";import{Readable as D,Duplex as I,Writable as j}from"node:stream";function q(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{family:"IPv4",address:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{family:"IPv6",address:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{family:"IPv6",address:r[3].toLowerCase(),port:void 0};const o=/^(.*?):(\d+)$/i.exec(n);return o?.[2]?{family:"alias",address:o[1],port:Number.parseInt(o[2])}:{family:"alias",address:n,port:void 0}}function H(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([J(t[1])|i,i]);continue}const o=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(o?.[1]){const t=z(o[1]),e=o[2]?L>>BigInt(Number.parseInt(o[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const r=J(t.address);return n.some(([t,e])=>(r|e)===t);case"IPv6":const o=z(t.address);return i.some(([t,e])=>(o|e)===t);default:return!1}}}const L=/*@__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 W(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,i:null};this.o=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.o.i}clear(){this.o.i=null,this.o.t=null,this.u=this.o}push(t){const e={t,i:null};this.u.i=e,this.u=e}shift(){if(!this.o.i)return null;this.o=this.o.i;const t=this.o.t;return this.o.t=null,t}remove(t){for(let e=this.o;e.i;e=e.i)if(e.i.t===t){e.i=e.i.i;break}}[Symbol.iterator](){return{next:()=>{if(!this.o.i)return{value:null,done:!0};this.o=this.o.i;const t=this.o.t;return this.o.t=null,{value:t,done:!1}}}}}class V{constructor(){this.h=new G,this.l=new G,this.m=0}push(t){if(this.m)return;const e=this.l.shift();e?(e.v&&clearTimeout(e.v),e.T(t)):this.h.push(t)}shift(t){return W(t??0,"timeout"),this.h.isEmpty()?this.m?Promise.reject(this._):new Promise((e,n)=>{const i={T:e,S:n,v:null};this.l.push(i),void 0!==t&&(i.v=setTimeout(()=>{this.l.remove(i),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.h.shift())}$(t){this._=t;for(const e of this.l)e.S(t),e.v&&clearTimeout(e.v)}close(t){this.m||(this.m=1,this.$(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 Z(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return Z(t.cause,e);if("error"in t)return Z(t.error,e)}}function X(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 Y=/*@__PURE__*/Buffer.alloc(0),K=t=>new URL("http://localhost"+(t.url??"/"));class Q extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const tt=globalThis.SuppressedError??Q;class et{constructor(){this.k=!1}N(t){this.k?t!==this.O&&(this.O=new tt(t,this.O)):(this.O=t,this.k=!0)}A(){this.k=!1,this.O=void 0}}const nt=new WeakMap;function it(t,e,n){const i=nt.get(t);if(i)return i;const r=K(t),o={R:t,P:r,C:decodeURIComponent(r.pathname),F:new AbortController,U:e,M:[],B:[],D:n?st(t):null};return nt.set(t,o),o}function rt(t,e,n){e||(t.D=null),t.I=n;const i=async()=>{t.F.abort(n.j.writableEnded?"complete":"client abort");const e=new et;await ot(t.M,e,t),await ot(t.B,e,t,()=>{t.H=async e=>{try{await e()}catch(e){t.U(e,"tearing down",t.R)}}}),e.k&&t.U(e.O,"tearing down",t.R)};return n.j.closed?i():n.j.once("close",i),t}async function ot(t,e,n,i){for(;n.L;)await n.L;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.N(t)}}})().then(()=>{n.L===r&&(n.L=void 0)});n.L=r,await r}function st(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const at=t=>nt.get(t),ct=t=>nt.delete(t);function ft(t){const e=at(t);if(!e)throw new RangeError("unknown request");return e}function ut(t,e,n=ut){throw t.code=e,Error.captureStackTrace(t,n),t}class ht{constructor(t){this.J=t,this.W=Object.create(null),this.G=!1}get headersSent(){return this.G}writeHead(t,e=n[t]??"-"){return this.G&&ut(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.J.write([`HTTP/1.1 ${t} ${wt(e)}`,...lt(this.W),"",""].join("\r\n"),"ascii"),this.G=!0,this}write(t,e="utf-8",n){return this.J.write(t,e,n)}end(t,e="utf-8",n){return this.J.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.W[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 lt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=dt(i);t&&e.push(`${wt(n)}: ${wt(t)}`)}return e}const dt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",wt=t=>t.replaceAll(/[^ \t!-~]/g,"");function pt(t,e){const n=at(t);n&&mt(n,e)}function mt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>Et(e,n,t))}const yt=t=>Boolean(at(t)?.Z);function gt(t,e,n){if(!t.Z){if(t.I&&!t.D){const e=t.I.j;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.I?.j.once("close",()=>t.R.socket.destroy()),t.Z={X:e,U:n},Et(t.V,t.Z,t),vt(t)}}function bt(t){if(t.I){if(t.D){if(!t.Y&&t.I.j.writable){const e=new ht(t.I.j);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.I.j;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.I.j.end(()=>t.R.socket.destroy())}else t.R.socket.destroy()}function vt(t){if(clearTimeout(t.K),!t.tt||t.H)return;const e=Date.now();if(e>=t.tt)return void bt(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,Et(t.V,t.Z,t))),void 0===t.K&&t.B.push(()=>clearTimeout(t.K)),t.K=setTimeout(()=>vt(t),Math.min(n-e,6048e5))}async function Et(t,e,n){try{await(t?.(e.X))}catch(t){e.U(t,"soft closing",n.R),bt(n)}}const Tt=(t,e)=>{const n=ft(t);n.H?n.H(e):n.M.push(e)},_t=(t,e)=>{const n=ft(t);n.H?n.H(e):n.B.push(e)},xt=t=>ft(t).F.signal;class St extends Error{}const $t=new St("STOP"),kt=new St("CONTINUE"),Nt=new St("NEXT_ROUTE"),Ot=new St("NEXT_ROUTER");async function At(t,e){const n=ft(t);if(!n.I)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.D)throw new TypeError("not an upgrade request");if(3===n.Y)throw new TypeError("upgrade already delegated");if(2===n.Y)return n.it;const i=n.I.j;if(!i.readable||!i.writable)throw $t;n.Y=1;const r=await e(t,i,n.I.o);return n.I.o=Y,n.rt=r.onError,r.softCloseHandler&&mt(n,r.softCloseHandler),n.Y=2,n.it=r.return,r.return}function Rt(t){const e=ft(t);if(!e.I)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.D)throw new TypeError("not an upgrade request");if(e.Y)throw new TypeError("upgrade already handled");e.Y=3}const Pt=RegExp.escape??(t=>t.replaceAll(/[^a-zA-Z0-9_ ]/g,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))),Ct=t=>t,Ft=t=>void 0===t?void 0:""===t?[]:t.split("/"),Ut=t=>void 0===t?void 0:""===t?[]:t.split("/").filter(t=>t),Mt=/*@__PURE__*/(t=>e=>{const n=[];let i=0;for(;i<e.length;++i){const r=t.get(e[i]);if(!r)break;n.push([r,!0])}return[Object.fromEntries(n),e.substring(i)]})(
2
- /*@__PURE__*/new Map([["i","ot"],["!","st"]])),Bt=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Dt=Object.freeze({});function It(t,e,n){const i=t.R.url,r=t.C,o=t.ct??Dt;return t.R.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.P.search,t.C=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(o),...n]))),()=>{t.R.url=i,t.C=r,t.ct=o}}function jt(t){return at(t)?.ct??Dt}function qt(t,e){return n=jt(t),i=e,Object.prototype.hasOwnProperty.call(n,i)?n[i]:void 0;var n,i}function Ht(t){const e=at(t);return e?e.P.pathname+e.P.search:t.url??"/"}function Lt(t){const e=at(t);e&&(t.url=e.P.pathname+e.P.search)}const Jt=t=>"function"==typeof t?{handleRequest:t}:t,zt=(t,e)=>"function"==typeof t?{handleUpgrade:t,shouldUpgrade:e}:{shouldUpgrade:e,...t},Wt=(t,e=Kt)=>({handleRequest:t,handleUpgrade:t,shouldUpgrade:e}),Gt=t=>"function"==typeof t?{handleError:t}:t,Vt=(t,e)=>Zt(e=>e instanceof t,e),Zt=(t,e)=>({handleError:(n,i,r)=>{if(r.response&&t(n))return e(n,i,r.response);throw n},shouldHandleError:(e,n,i)=>Boolean(i.response)&&t(e)}),Xt=t=>"function"==typeof t?{handleRequest:t}:t,Yt=t=>"function"==typeof t?{handleUpgrade:t}:t,Kt=()=>!1,Qt=Symbol("http");class te{constructor(){this.ft=[],this.ut=[]}N(t,e,n,i,r){const o=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{ot:o,st:s},a]=Mt(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f=0;for(const t of a.matchAll(r)){t.index>c&&n.push(Pt(a.substring(c,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),s||n.push("+");else if("\\"===e[0])n.push(Pt(t[1]));else{const r=e[0],o=t[2];if(!o)throw new TypeError(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({ht:o,lt:s?Ft:Ut})):(n.push("([^/]+?)"),i.push({ht:o,lt:Ct}))}c=t.index+e.length}if(c<a.length&&n.push(Pt(a.substring(c))),f>0)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{dt:new RegExp(n.join(""),o?"i":""),wt:i}})(n,i):{dt:null,wt:[]};if(r.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({yt:t,gt:"string"==typeof e?e.toLowerCase():e,bt:o.dt,vt:o.wt,Et:r}),this}use(...t){return this.N(null,null,null,!0,t.map(Xt))}mount(t,...e){return this.N(null,null,t,!0,e.map(Xt))}within(t){const e=new te;return this.mount(t,e),e}at(t,...e){return this.N(null,null,t,!1,e.map(Xt))}onRequest(t,e,...n){return this.N(ne(t),Qt,e,!1,n.map(Xt))}onUpgrade(t,e,n,...i){return this.N(ne(t),e,n,!1,i.map(Yt))}onError(...t){return this.N(null,null,null,!0,t.map(Gt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.N(ee,Qt,t,!1,e.map(Xt));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.Tt(t,new et)}async handleUpgrade(t){return this.Tt(t,new et)}async handleError(t,e){const n=new et;return n.N(t),this.Tt(e,n)}shouldUpgrade(t){return this._t(ft(t))}_t(t){for(const e of this.ft){const n=ie(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=It(t,n.xt,[])}catch{continue}try{for(const n of e.Et)if(se(n,t))return!0}finally{i()}}return!1}async Tt(t,e){const n=ft(t),i=await this.St(n,e);if(e.k)throw e.O;return i}async St(t,e){for(const n of this.ft){const i=ie(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.$t();r=It(t,i.xt,e)}catch(t){e.N(t);continue}try{const i=await re(t,n.Et,this.ut,e);if(i===Ot)break;if(i===Nt)continue;return i}finally{r()}}return kt}}const ee=new Set(["HEAD","GET"]),ne=t=>t?"string"==typeof t?t:new Set(t):null;function ie(t,e){if("string"==typeof e.yt){if(e.yt!==t.R.method)return!1}else if(null!==e.yt&&!e.yt.has(t.R.method??""))return!1;if(e.gt===Qt){if(t.D)return!1}else if(null!==e.gt&&!t.D?.has(e.gt))return!1;if(null===e.bt)return!0;const n=e.bt.exec(t.C);return!!n&&{xt:"/"+(n.groups?.rest??""),$t:()=>e.vt.map((t,e)=>[t.ht,t.lt(n[e+1])])}}async function re(t,e,n,i){for(const r of e){let e=await oe(r,t,i);if(e!==kt){if(!t.D&&!(e instanceof St)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.R,o=t.I.j;for(const t of n)await t(i,r,o)}catch(t){i.N(t);continue}return e}}return Nt}async function oe(t,e,n){if(t instanceof te)return t.St(e,n);let i=kt;try{if(n.k){if(t.handleError){const r=n.O,o=e.D?{socket:e.I.j,head:e.I.o,hasUpgraded:Boolean(e.Y)}:{response:e.I.j};t.shouldHandleError&&!t.shouldHandleError(r,e.R,o)||(n.A(),i=await t.handleError(r,e.R,o))}}else if(e.D){if(t.handleUpgrade){const n=e.I;i=await t.handleUpgrade(e.R,n.j,n.o)}}else t.handleRequest&&(i=await t.handleRequest(e.R,e.I.j))}catch(t){t instanceof St?i=t:n.N(t)}finally{e.M.length&&await((t,e)=>ot(t.M,e,t))(e,n)}return i===$t?void 0:i}function se(t,e){if(t instanceof te)return t._t(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}}class ae extends Error{constructor(t,{message:e,statusMessage:i,headers:r,body:o,...s}={}){super(e??o,s),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=(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,dt(e)]).filter(([t,e])=>e))})(r),this.body=o??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const ce=(t,e,n)=>{const i=fe(n);if(!i)return;const r=Z(t,ae)??new ae(500);i.setHeader("content-type","text/plain; charset=utf-8"),i.setHeaders(r.headers),i.setHeader("content-length",String(Buffer.byteLength(r.body,"utf-8"))),n.response||i.setHeader("connection","close"),i.writeHead(r.statusCode,r.statusMessage),i.end(r.body,"utf-8")};function fe(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 ue(t,{onError:e=he,socketCloseTimeout:n=500}={}){W(n,"socketCloseTimeout");let i=0,r="",o=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)})};return{request:async(n,s)=>{let a;try{a=it(n,e,!1)}catch(t){return e(t,"parsing request",n),void ce(new ae(400),0,{response:s})}if(rt(a,!1,{j:s}),u(a),1===i)gt(a,r,o);else if(2===i)return bt(a),void ct(n);const c=new et,f=await oe(t,a,c);c.k||f!==kt&&f!==Nt&&f!==Ot||c.N(new ae(404)),c.k&&(e(c.O,"handling request",n),ce(c.O,0,{response:s}),ct(n))},upgrade:async(s,a,c)=>{let f;a.once("finish",()=>{const t=setTimeout(()=>a.destroy(),n);a.once("close",()=>clearTimeout(t))});try{f=it(s,e,!0)}catch(t){return e(t,"parsing upgrade",s),void ce(new ae(400),0,{socket:a,hasUpgraded:!1})}if(rt(f,!0,{j:a,o:c}),c=Y,u(f),1===i)gt(f,r,o);else if(2===i)return bt(f),void ct(s);const h=new et,l=await oe(t,f,h);h.k||l!==kt&&l!==Nt&&l!==Ot||(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.`),h.N(new ae(404))),h.k&&(e(h.O,"handling upgrade",s),f.rt?f.rt(h.O):ce(h.O,0,{socket:a,head:f.I?.o??Y,hasUpgraded:Boolean(f.Y)}),ct(s))},shouldUpgrade:n=>{try{const i=it(n,e,!0);return se(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.kt,r=t.code;n.writable&&!i?.headersSent&&n.end(de.get(r)??we),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request",void 0)},softClose(t,e,n){if(i<1){i=1,r=t,o=e;for(const n of a)gt(n,t,e)}f(n)},hardClose(t){if(i<2){i=2;for(const t of a)bt(t)}f(t)},countConnections:()=>a.size}}const he=(t,e,n)=>{(Z(t,ae)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},le=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),de=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/le(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/le(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/le(408)]]),we=/*@__PURE__*/le(400);class pe extends EventTarget{constructor(t){super(),this.Nt=t}attach(t,e={}){const n=(e,n,i)=>{const r={server:t,error:e,context:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r,cancelable:!0}))&&he(e,n,i)},i=ue(this.Nt,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",i.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",i.request),t.addListener("request",i.request),t.addListener("upgrade",i.upgrade);const r=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=i.shouldUpgrade),t.addListener("clientError",i.clientError);let o=()=>{o=void 0,t.removeListener("checkContinue",i.request),t.removeListener("checkExpectation",i.request),t.removeListener("request",i.request),t.removeListener("upgrade",i.upgrade),t.shouldUpgradeCallback===i.shouldUpgrade&&(t.shouldUpgradeCallback=r),t.removeListener("clientError",i.clientError)};return(t="",e=-1,r=!1,s)=>{if(W(e,"existingConnectionTimeout",!0),r||o?.(),e>0){const r=setTimeout(()=>{o?.(),i.hardClose()},e);i.softClose(t,n,()=>{o?.(),clearTimeout(r),s?.()})}else 0===e?(o?.(),i.hardClose(s)):(o?.(),s&&setImmediate(s));return i}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=i(t),n=this.attach(e,t),r=Object.assign(e,{closeWithTimeout:(t,i)=>new Promise(r=>n(t,i,!0,()=>{e.close(()=>r()),e.closeAllConnections()}))});return r}listen(t,e,n={}){const i=this.createServer(n);return n.socketTimeout&&i.setTimeout(n.socketTimeout),new Promise((r,o)=>{i.once("error",o),i.listen(t,e,n.backlog??511,()=>{i.off("error",o),r(i)})})}}const me=t=>at(t)?.P??K(t),ye=t=>me(t).search,ge=t=>new URLSearchParams(me(t).searchParams),be=(t,e)=>me(t).searchParams.get(e);function ve(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function Ee(t){const e=t.headers.authorization;if(!e)return;const[n,i]=ve(e," ");return void 0!==i?[n.trim().toLowerCase(),i.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:Oe(e)}:{}}function xe(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const o=t.headers.range;if(!o||0===e)return;const[s,a]=ve(o,"=");if("bytes"!==s||!a)return;const c=new ae(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=$e(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[i,r]=ve(t.trim(),"-");if(void 0===r)throw c;let o;if(i)o={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw c;o={start:Math.max(e-f(r),0),end:e-1}}if(!(o.start>=e)){if(o.end<o.start||u.length>=n)throw c;u.push(o)}}if(!u.length)throw c;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>r)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw c}}return{ranges:u,totalSize:e}}function Se(t){if(void 0!==t)return"number"==typeof t?[String(t)]:t.length?"string"==typeof t?t.split(",").map(t=>t.trim()):t.flatMap(t=>t.split(",").map(t=>t.trim())):[]}function $e(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}function ke(t){if(t)return t.split(",").map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=ve(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),o="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:o,q:s}})}function Ne(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new ae(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let o=i[2];'"'===o[0]&&(o=o.substring(1,o.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,o)}return e}function Oe(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Ae=t=>"function"==typeof t?t:()=>t;class Re{constructor(t=Ue){this.Ot=Ae(t)}set(t,e){Ce(ft(t)).set(this,e)}get(t){return Fe(t,this,this.Ot)}clear(t){const e=at(t);e?.At?.delete(this)}withValue(t){return Wt(e=>(this.set(e,t),kt))}}const Pe=(t,...e)=>{const n=n=>t(n,...e);return t=>Fe(t,n,n)};function Ce(t){return t.At||(t.At=new Map),t.At}function Fe(t,e,n){const i=at(t);if(!i)return n(t);const r=Ce(i);if(r.has(e))return r.get(e);const o=n(t);return r.set(e,o),o}const Ue=()=>{throw new Error("property has not been set")};function Me({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:o}){const s=Ae(t);return{...Wt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Ee(t),h="bearer"===u?.[0]?u[1]:await(n?.(t));if(!h)throw new ae(401,{headers:f,body:"no token provided"});let l;try{l=await e(h,c,t)}catch(t){throw new ae(401,{headers:f,body:"invalid token",cause:t})}if(!l)throw new ae(401,{headers:f,body:"invalid token"});if("object"==typeof l){if("nbf"in l&&"number"==typeof l.nbf&&a<1e3*l.nbf)throw new ae(401,{headers:f,body:"token not valid yet"});if("exp"in l&&"number"==typeof l.exp){const e=1e3*l.exp;if(a>=e-r)throw new ae(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r)=>{const o=ft(t),s=n-Math.max(i,0),a=o.tt??Number.POSITIVE_INFINITY,c=o.et?.nt??a;s>=c&&n>=a||(n<a&&(o.tt=n),s<c&&(o.et={nt:s,X:e,U:r??o.U}),vt(o))})(t,"token expired",e,r,o)}}return Ie.set(t,{Rt:c,Pt:!0,Ct:l,Ft:je(l)}),kt}),getTokenData:t=>{const e=Ie.get(t);if(!e.Pt)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Ct}}}const Be=(t,e)=>Ie.get(t).Ft.has(e),De=t=>Wt(e=>{const n=Ie.get(e);if(!n.Ft.has(t))throw new ae(403,{headers:{"www-authenticate":`Bearer realm="${n.Rt}", scope="${t}"`},body:`scope required: ${t}`});return kt}),Ie=/*@__PURE__*/new Re({Rt:"",Pt:!1,Ct:null,Ft: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 qe(t,e){const n=`${0|e.mtimeMs} ${e.size} ${t??""}`;return`W/"${h("sha256").update(n).digest("base64").substring(0,12)}"`}async function He(t){const e=h("sha256");return"string"==typeof t?await d(a(t),e):await d(t.createReadStream({start:0,autoClose:!1}),e),`"sha256-${e.digest("base64")}"`}const Le=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),Je={mime:"accept",language:"accept-language",encoding:"accept-encoding"},ze=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),We=t=>{return{type:"encoding",options:(e=t,n=ze,Array.isArray(e)?e.map(t=>({match:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({match:t,file:e})))};var e,n};class Ge{constructor(t,{maxFailedAttempts:e=10}={}){this.Ut=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(Je,t.type))throw new RangeError(`unknown rule type: ${t.type}`);return{Mt:t.type,Bt:t.options.map(t=>({Dt:t.file,It:"string"==typeof t.match?t.match.toLowerCase():Le(t.match,!0),jt:t.as??("string"==typeof t.match?t.match:void 0)}))}}).filter(t=>t.Bt.length>0),this.qt=e,this.vary=[...new Set(this.Ut.map(t=>Je[t.Mt]))].join(" ")}options(t,e){const n={mime:ke(e.accept),language:ke(e["accept-language"]),encoding:ke(e["accept-encoding"])};let i=this.qt;const r=this.Ut,o={};return function*t(e,s){const a=r[s];if(!a)return--i,void(yield{filename:e,info:o});const c=new Set,f=(h=n[a.Mt],h?.length?1===h.length?h:[...h].sort(Ve):[]),u=[];var h;for(const t of a.Bt){const e=f.find(e=>"string"==typeof t.It?e.name.toLowerCase()===t.It:t.It.test(e.name));e&&u.push({...e,Ht:t})}for(const n of u.sort(Ve)){const r=Ze(e,n.Ht.Dt);if(!c.has(r)&&(c.add(r),o[a.Mt]=n.Ht.jt,yield*t(r,s+1),i<=0))return}o[a.Mt]=void 0,!c.has(e)&&i>0&&(yield*t(e,s+1))}(t,0)}}const Ve=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Ze(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Xe=/*@__PURE__*/tn("bin=application/octet-stream;gz(ip),json,ogg,pdf,wasm,xml,y(a)ml,zip,zst(d)=application/{ext};aac,flac,mid(i),wav(e)=audio/{ext};mp3=audio/mpeg;oga,opus=audio/ogg;otf,ttf,woff,woff2=font/{ext};apng,avif,bmp,gif,heic,heif,jp(e)g,png,tif(f),webp=image/{ext};ico,cur=image/x-icon;svg=image/svg+xml;3mf,obj,stl,u3d=model/{ext};wrl=model/vrml;x3d=model/x3d+xml;x3db=model/x3d+binary;x3dv=model/x3d+vrml;css,csv,htm(l),rtf,vcard=text/{ext};(m)js=text/javascript;md=text/markdown;txt=text/plain;3gp(p),3g(pp)2,mp4,mp(e)g,h264=video/{ext};mov=video/quicktime;ogv=video/ogg");let Ye=/*@__PURE__*/new Map(Xe);function Ke(){Ye=new Map(Xe)}function Qe(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function tn(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,o="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=i+o+s,c=r.replace("{ext}",a);e.set(a.toLowerCase(),c),o&&e.set((i+s).toLowerCase(),c)}}return e}function en(t){for(const[e,n]of t)Ye.set(e.toLowerCase(),n)}function nn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ye.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}async function rn(t,e,{minCompression:n=0,deleteObsolete:i=!1}={}){const r=await T(t),o={file:t,mime:nn(m(t)),rawSize:r.byteLength,bestSize:r.byteLength,created:0};if(["image","video","audio","font"].includes(o.mime.split("/")[0]))return o;const s=o.rawSize-n;for(const n of e){const e=an.get(n.match),a=y(g(t),Ze(b(t),n.file));if(!e||a===n.file)continue;const c=s>0?await e(r):void 0;c&&c.byteLength<=s?(await _(a,c),o.bestSize=Math.min(o.bestSize,c.byteLength),++o.created):i&&await x(a).catch(()=>{})}return o}async function on(t,e,n={}){const i=[];await sn(t,i);const r=new Set(i);for(const t of r)for(const n of e){const e=y(g(t),Ze(b(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>rn(t,e,n)))}async function sn(t,e){const n=await S(t);if(n.isDirectory())for(const n of await $(t))await sn(y(t,n),e);else n.isFile()&&e.push(t)}const an=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["br",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]),cn=(t,e,n)=>{const i=ft(t);i.U(e,n??(i.D?"handling upgrade":"handling request"),t)},fn=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:i,contentType:r="application/json"}={})=>({handleError:(o,s,a)=>{if(a.hasUpgraded||e&&!un(s,r))throw o;n&&cn(s,o);const c=fe(a);if(!c)return;const f=Z(o,ae)??new ae(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",r),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),i?c.writeHead(i):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,i)=>!i.hasUpgraded&&(!e||un(n,r))}),un=(t,e)=>ke(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class hn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:o=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.Lt=t,this.Jt=!0===e?Number.POSITIVE_INFINITY:e||0,this.zt=n,this.Wt=i,this.Gt=r,this.Vt=o,this.Zt=c,this.Xt=["",...f],this.Yt=new Set(s.map(t=>this.Kt(t))),this.Qt=new Set,this.te=[];for(const t of a)"string"==typeof t?this.Qt.add(this.Kt(t)):this.te.push(Le(t,!n));this.ee=new Set(c.map(t=>this.Kt(t))),this.ne=u,this.vary=u?.vary??""}static async build(t,e={}){return new hn(await k(t,{encoding:"utf-8"})+v,e)}Kt(t){return"exact"===this.zt?t:t.toLowerCase()}ie(t){if(this.Yt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Gt)||"."===e[0]&&!this.Wt||this.Qt.has(e)||this.te.some(t=>t.test(e)))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.ee.has(this.Kt(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let i=t.join(v);"force-lowercase"===this.zt&&(i=i.toLowerCase());let r=E(this.Lt,i);if(!r.startsWith(this.Lt)&&r+v!==this.Lt)return n?.push(`${JSON.stringify(r)} is not inside root ${JSON.stringify(this.Lt)}`),null;let o=null,s=null;for(const t of this.Xt){const e=r+t;if(o=e.substring(this.Lt.length).split(v).filter(t=>t),o.length-1>this.Jt)return n?.push(`${JSON.stringify(r)} is nested too deeply (${o.length-1} > ${this.Jt})`),null;if(o.some(t=>!this.ie(this.Kt(t))))return n?.push(`${JSON.stringify(r)} is not permitted`),null;const i=o[o.length-1]??"";if(!this.Vt&&this.ee.has(this.Kt(i))&&!this.Yt.has(this.Kt(i)))return n?.push(`${JSON.stringify(r)} is a hidden index file`),null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){r=e;break}}if(!s||!o)return n?.push(`file ${JSON.stringify(r)} does not exist`),null;if(this.Kt(s)!==this.Kt(r))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(r)}`),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(o.length>this.Jt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${o.length} > ${this.Jt})`),null;for(const t of this.Zt){const e=y(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.ne){const t=b(a),i=g(a);for(const r of this.ne.options(t,e)){if(!r.filename||r.filename.includes(v))continue;const t=await dn({canonicalPath:a,negotiatedPath:y(i,r.filename),...r.info},n);if(t)return t}}return dn({canonicalPath:a,negotiatedPath:a},n)}async debugAllPaths(){return(await this.precompute()).debugAllPaths()}async precompute(){const t=new Map,e=(e,n)=>{const i=t.get(e);(!i||n.p>i.p)&&t.set(e,n)},n=new G({dir:[this.Lt],depth:0});for(const{dir:t,depth:i}of n){const r=await $(y(...t),{withFileTypes:!0,encoding:"utf-8"}),o=new Set(r.map(t=>this.Kt(t.name)));for(const s of r){const r=this.Kt(s.name);if(!this.ie(r))continue;const a=[...t,s.name];if(s.isDirectory())i<this.Jt&&n.push({dir:a,depth:i+1}),e(this.Kt(a.slice(1).join("/")),ln);else if(s.isFile()){const n={file:y(...a),dir:y(...t),basename:r,siblings:o},i=this.Zt.indexOf(r);if(-1!==i&&(e(this.Kt(t.slice(1).join("/")),{...n,p:this.Zt.length+1-i}),!this.Vt&&!this.Yt.has(r)))continue;const c=this.Kt(a.slice(1).join("/"));for(let t=0;t<this.Xt.length;++t){const i=this.Xt[t];s.name.endsWith(i)&&e(c.substring(0,c.length-i.length),{...n,p:-t})}}}}return{find:async(e,n={},i)=>{const r=t.get(this.Kt(e.join("/")));if(!r?.file)return i?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(this.ne)for(const t of this.ne.options(r.basename,n)){if(!r.siblings.has(this.Kt(t.filename)))continue;const e=await dn({canonicalPath:r.file,negotiatedPath:y(r.dir,t.filename),...t.info},i);if(e)return e}return dn({canonicalPath:r.file,negotiatedPath:r.file},i)},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t))),vary:this.vary}}}const ln={file:"",dir:"",basename:"",siblings:new Set,p:1};async function dn(t,e){const n=await N(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const i=()=>(n.close().catch(()=>{}),null),r=await n.stat().catch(i);return r?.isFile()?{handle:n,stats:r,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),i())}const wn=/*@__PURE__*/Pe(async t=>{const e=xt(t);if(e.aborted)throw $t;e.throwIfAborted();const n=await O(y(A(),"upload"));_t(t,()=>x(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw $t;return y(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),o=f(i,{mode:n});try{return await d(t,o,{signal:e}),{path:i,size:o.bytesWritten}}finally{o.close()}}}});function pn(t){const e=ft(t);if(!e.I)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.F.signal.aborted)throw $t;e.re||e.D||(e.re=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.I.j.writeContinue())}function mn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["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=o):(a??=new r({keepAlive:!0,...c}),u=C);const h=f.pathname,l=h+(h.endsWith("/")?"":"/"),w="a://a"+l;return Jt((t,r)=>new Promise((o,c)=>{const p=xt(t),m=t=>c(p.aborted?$t:new ae(502,{cause:t})),y=new URL(w+t.url?.substring(1));if(!y.pathname.startsWith(l)&&y.pathname!==h)return c(new ae(400,{message:"directory traversal blocked"}));pn(t);let g={...t.headers};yn(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(!r.headersSent){let n={...e.headers};yn(n,i);for(const i of s)n=i(t,e,n);r.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,r).then(o,c)}),d(t,b).catch(m)}))}function yn(t,e){for(const e of Se(t.connection)??[])Bt(t,e.toLowerCase());for(const n of e)Bt(t,n)}function gn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?H(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),o=new Set(n);return Pe(t=>{const e=e=>{if(o.has(e))return Se(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"),h=e("via")?.map(t=>{const e=/^([^/ ]+\/)?([^ ]+) (.+)$/.exec(t);return e?.[3]?q(e[3]):void 0}),l=[bn(t)];if(n)for(const t of n)try{const e=Ne(t);l.push({client:q(e.get("for")),server:q(e.get("by")),host:e.get("host"),proto:e.get("proto")})}catch{l.push({client:void 0,server:void 0,host:void 0,proto:void 0})}else if(s){const t=s.map(q),e=a??[],n=c??f??u??[];let i=l[0].client;for(let r=0;r<t.length;++r){const o=t[r];l.push({client:o,server:h?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=o}}else if(h)for(const t of h)l.push({client:void 0,server:t,host:void 0,proto:void 0});let d=Math.min(1+r,l.length);for(let t=0;t<d-1;++t)i(l[t].client)||(d=t+1);return Object.freeze({trusted:l.slice(0,d),untrusted:l.slice(d),outwardChain:l,edge:l[d-1]})})}const bn=t=>({client:{...q(t.socket.remoteAddress)??vn,port:t.socket.remotePort},server:{...q(t.socket.localAddress)??vn,port:t.socket.localPort},host:t.headers.host,proto:void 0}),vn={family:"alias",address:"_disconnected",port:void 0};function En(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 Tn(t,e){const n=En(0,e);return n.forwarded=Sn([bn(t)]),n}const _n=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=En(0,i),o=t(n);return r.forwarded=Sn([...e?o.trusted:o.outwardChain].reverse()),r};function xn(t,e){let n=t.headers.forwarded;const i=Sn([bn(t)]);n?n+=", "+i:n=i;const r=En(0,e);return r.forwarded=n,r}function Sn(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 $n{constructor(t,{fatal:e=!1}={}){this.oe=t,this.se=e,this.ae=new Uint8Array(4),this.ce=new DataView(this.ae.buffer),this.fe=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,i=[];let r=0;if(this.fe>0){if(r=4-this.fe,n<r)return this.ae.set(t,this.fe),this.fe+=n,"";this.ae.set(t.subarray(0,r),this.fe),i.push(this.ce.getUint32(0,this.oe)),this.fe=0}const o=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=r;for(const t=n-3;s<t;s+=4)i.push(o.getUint32(s,this.oe));if(e?(s<n&&this.ae.set(t.subarray(s)),this.fe=n-s):(this.fe=0,s<n&&(this.se?ut(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):i.push(65533))),i.length>0){try{return String.fromCodePoint(...i)}catch{this.se&&ut(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<i.length;++t)i[t]>1114111&&(i[t]=65533);return String.fromCodePoint(...i)}return""}}class kn extends F{constructor(t){super({transform(e,n){try{const i=t.decode(e,{stream:!0});i&&n.enqueue(i)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(Y);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const Nn=new Map;function On(t,e){Nn.set(t.toLowerCase(),e)}function An(){On("utf-32be",{decoder:t=>new $n(!1,t)}),On("utf-32le",{decoder:t=>new $n(!0,t)})}function Rn(t,e={}){const n=Nn.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new ae(415,{body:`unsupported charset: ${t}`})}}function Pn(t,e={}){const n=Nn.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new kn(n.decoder(e));try{return new U(t,e)}catch{throw new ae(415,{body:`unsupported charset: ${t}`})}}const Cn=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function Fn(t,e,n){const i=Oe(t.headers["if-modified-since"]),r=Se(t.headers["if-none-match"]);if(r){if(Mn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function Un(t,e,n){let i=!0;const r=_e(t);return r.etag&&(i&&=Mn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function Mn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(qe(t.getHeader("content-encoding"),e))}class Bn extends F{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function Dn(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:i=1}={}){const r=$e(t.headers["content-length"]);if(void 0!==r&&r>n)throw new ae(413);const o=Se(t.headers["content-encoding"])??[];if(o.length>i)throw new ae(415,{body:"too many content-encoding stages"});pn(t);let s=D.toWeb(t);void 0===r&&Number.isFinite(n)&&(s=s.pipeThrough(new Bn(n,new ae(413))));for(const t of o.reverse())s=s.pipeThrough(Hn(t));return Number.isFinite(e)&&(s=s.pipeThrough(new Bn(e,new ae(413,{body:"decoded content too large"})))),s}function In(t,e={}){const n=Dn(t,e),i=Te(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Pn(i,e))}async function jn(t,e={}){const n=[];for await(const i of In(t,e))n.push(i);return n.join("")}async function qn(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,o=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],o=null;break}if(o=t.value,o.byteLength>=e){i.set(o.subarray(0,e),r);break}i.set(o,r),r+=o.byteLength}const s=Cn[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!s)throw n.cancel(),new ae(415,{body:"invalid JSON encoding"});const a=Pn(s,e),c=a.writable.getWriter();return r&&c.write(i.subarray(0,r)),o&&c.write(o),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Dn(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Hn(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 I.toWeb(w.createBrotliDecompress())}case"zstd":try{return I.toWeb(w.createZstdDecompress())}catch{throw new ae(415,{body:"unsupported content encoding"})}default:throw new ae(415,{body:"unknown content encoding"})}}function Ln(t){if(!t)return null;const[e,n]=ve(t,";"),i=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const r=e[1].toLowerCase(),o=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";i.has(r)||i.set(r,o)}}return{mime:e.trim().toLowerCase(),params:i}}function Jn(t,e,n,i){const r=t.byteLength;for(;e<r;){for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)break;if(59!==t[e++])return!1;for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)return!1;const o=e;for(;e<r;++e){const n=t[e];if(!Wn[n]){if(61===n)break;return!1}}if(e===r)return!1;const s=t.latin1Slice(o,e).toLowerCase();if("*"===s[s.length-1]){const i=++e;for(;e<r;++e){const n=t[e];if(!Vn[n]){if(39!==n)return!1;break}}if(e===r)return!1;const o=Rn(t.latin1Slice(i,e));for(++e;e<r&&39!==t[e];++e);if(e===r)return!1;if(++e===r)return!1;let a=e;const c=[];for(;e<r;++e){const n=t[e];if(1!==Gn[n]){if(37===n){let n,i;if(e+2<r&&16!==(n=Xn[t[e+1]])&&16!==(i=Xn[t[e+2]])){const r=(n<<4)+i;e>a&&c.push(o.decode(t.subarray(a,e),{stream:!0})),c.push(o.decode(Buffer.from([r]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(o.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===r)return!1;if(34===t[e]){let o=++e,a=!1;const c=[];for(;e<r;++e){const n=t[e];if(92!==n){if(34===n){if(a){o=e,a=!1;continue}c.push(i.decode(t.subarray(o,e)));break}if(a&&(o=e-1,a=!1),!Zn[n])return!1}else a?(o=e,a=!1):(c.push(i.decode(t.subarray(o,e),{stream:!0})),a=!0)}if(e===r)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<r;++e){const n=t[e];if(!Wn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,i.decode(t.subarray(a,e)))}return!0}const zn=[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],Wn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...zn,0,1,0,1],33),t})(),Gn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...zn,0,1,0,1],33),t})(),Vn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...zn,1,0,1,1],33),t})(),Zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.fill(1,32,256),t[9]=1,t[34]=0,t[92]=0,t[127]=0,t})(),Xn=/*@__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 Yn{constructor(t,e){const n=t.byteLength;if(!n||n>65535)throw new RangeError("invalid needle");this.ue=t,this.he=e,this.le=null,this.de=0,this.we=null}push(t){let e=0;const n=t.byteLength,i=this.ue,r=i.byteLength-1,o=n-r;let s=-this.de;if(this.de){const a=this.we,c=this.le,f=i[r];if(o>0){const n=t[s+r];n!==f||t.compare(i,-s,r,0,s+r)?s+=a[n]:(this.he(!0,Y,0,0,!0),this.de=0,e=s+=r+1)}const u=o<0?o:0;for(;s<u;){const n=t[s+r];if(n===f&&!c.compare(i,0,-s,this.de+s,this.de)&&!t.compare(i,-s,r,0,s+r)){this.he(!0,c,0,this.de+s,!1),this.de=0,e=s+=r+1;break}s+=a[n]}const h=this.de;if(h>0){const e=i[0];for(;s<0;){const r=c.subarray(0,h).indexOf(e,h+s);if(-1===r){s=0;break}const o=h-r;if(!c.compare(i,1,o,r+1,h)&&!t.compare(i,o,o+n))return r&&(this.he(!1,c,0,r,!1),c.copy(c,0,r,o)),c.set(t,o),void(this.de+=n-r);s=r+1-h}this.he(!1,c,0,h,!1),this.de=0}}for(;s<o;){const n=t.indexOf(i,s);if(-1!==n){if(this.he(!0,t,e,n,!0),n===o+1)return;e=s=n+r+1}else s=o}const a=i[0];for(;s<n;){const o=t.indexOf(a,s);if(-1===o)return void this.he(!1,t,e,n,!0);if(!t.compare(i,1,n-o,o+1)){if(!this.le){this.le=Buffer.allocUnsafe(r),this.we=new Uint16Array(256).fill(r+1);for(let t=0;t<r;++t)this.we[i[t]]=r-t}return t.copy(this.le,0,o),this.de=n-o,void(o>e&&this.he(!1,t,e,o,!0))}s=o+1}n>e&&this.he(!1,t,e,n,!0)}destroy(){const t=this.de;t&&this.le&&this.he(!1,this.le,0,t,!1),this.de=0}}class Kn extends j{constructor({limits:t={},preservePath:e,highWaterMark:n,fileHwm:i,defParamCharset:r="utf-8",defCharset:o="utf-8"},s){super({autoDestroy:!0,emitClose:!0,highWaterMark:n,write:Qn,destroy:ti,final:ei});const a=s.get("boundary");if(!a)throw new ae(400,{body:"multipart boundary not found"});if(a.length>70)throw new ae(400,{body:"multipart boundary too long"});const c=Rn(r),f={autoDestroy:!0,emitClose:!0,highWaterMark:i},u=t.fieldSize??1048576,h=t.fileSize??Number.POSITIVE_INFINITY,l=t.fieldNameSize??100,d=t.files??Number.POSITIVE_INFINITY,w=t.fields??Number.POSITIVE_INFINITY,p=t.parts??Number.POSITIVE_INFINITY;let m,y,g,b,v,E=0,T=0,_=0,x=-1;this.pe=0,this.me=!1;let S=!1;const $=new ni(t=>{this.ye=void 0;const n=t["content-disposition"];if(!n)return void(x=-1);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let i=0;for(;i<t.byteLength;++i)if(!Wn[t[i]]){if(!Jn(t,i,n,e))return null;break}return{type:t.latin1Slice(0,i).toLowerCase(),params:n}})(Buffer.from(n,"latin1"),c);if("form-data"!==i?.type)return void(x=-1);if(v=i.params.get("name"),void 0===v)return this.emit("error",new ae(400,{body:"missing field name"})),void(x=-1);S=v.length>l,S&&(v=v.substring(0,l));let r=i.params.get("filename*")??i.params.get("filename");void 0===r||e||(r=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(r));const s=Ln(t["content-type"]);b=s?.mime??"text/plain";const a=s?.params.get("charset")?.toLowerCase()??o;if(y=Rn(a),g=t["content-transfer-encoding"]?.toLowerCase()??"7bit","application/octet-stream"===b||void 0!==r){if(_++===d&&this.emit("filesLimit"),_>d||0===this.listenerCount("file"))return void(x=-1);this.ge=new ii(f,this),++this.pe,this.emit("file",v,this.ge,{nameTruncated:S,filename:r,encoding:g,mimeType:b}),x=h}else{if(T++===w&&this.emit("fieldsLimit"),T>w||0===this.listenerCount("field"))return void(x=-1);m="",x=u}});let k=0;const N=Buffer.from(`\r\n--${a}`,"latin1");this.be=new Yn(N,(t,e,n,i,r)=>{try{if(n===i)return;if(k){if(1===k){if(13===e[n])k=2;else{if(45!==e[n])return void(k=0);k=3}if(++n===i)return}if(2!==k){if(k=0,45!==e[n])return;return this.me=!0,void(this.be=oi)}if(k=0,10!==e[n++])return;if(E++===p&&this.emit("partsLimit"),E>p)return;if(this.ye=$,n===i)return}if(this.ye){const t=this.ye.push(e,n,i);if(-1===t)return this.ye=void 0,$.reset(),void this.emit("error",new ae(400,{body:"malformed part header"}));if(t===i)return;n=t}if(x>=0){const t=Math.min(i,n+x);if(x-=i-n,this.ge){if(t>n){let i;r?i=e.subarray(n,t):(i=Buffer.allocUnsafe(t-n),e.copy(i,0,n,t)),this.ge.push(i)||(this.ge.ve??=this.Ee,this.Ee=void 0)}x<0&&(this.ge.emit("limit"),this.ge.truncated=!0)}else void 0!==m&&(m+=e.latin1Slice(n,t))}}finally{t&&(this.ye?(this.emit("error",new ae(400,{body:"unexpected end of headers"})),this.ye=void 0):this.ge?(this.ge.push(null),this.ge=void 0):void 0!==m&&(this.emit("field",v,y.decode(Buffer.from(m,"latin1")),{nameTruncated:S,valueTruncated:x<0,encoding:g,mimeType:b}),m=void 0),k=1,x=-1)}}),this.write(si)}Te(){if(this.ye)return new ae(400,{body:"malformed part header"});const t=this.ge;return t&&(this.ge=void 0,t.destroy(new ae(400,{body:"unexpected end of file"}))),this.me?null:new ae(400,{body:"unexpected end of form"})}}function Qn(t,e,n){this.Ee=n,this.be.push(t);const i=this.Ee;i&&(this.Ee=void 0,i())}function ti(t,e){this.ye=void 0,this.be=oi,t??=this.Te();const n=this.ge;n&&(this.ge=void 0,n.destroy(t??void 0)),e(t)}function ei(t){if(this.be.destroy(),!this.me)return t(new ae(400,{body:"unexpected end of form"}));this.pe?this._e=()=>t(this.Te()):t(this.Te())}class ni{constructor(t){this.xe=Object.create(null),this.Se=0,this.$e=0,this.m=0,this.ht="",this.ke="",this.Ne=0,this.he=t}reset(){this.xe=Object.create(null),this.Se=0,this.$e=0,this.m=0,this.ht="",this.ke="",this.Ne=0}push(t,e,n){let i=e,r=e;const o=Math.min(n,e+16384-this.$e);for(;r<o;)switch(this.m){case 0:for(;r<o&&Wn[t[r]];++r);if(r>i&&(this.ht+=t.latin1Slice(i,r)),r<o){if(58!==t[r])return-1;if(!this.ht)return-1;++r,this.m=1}break;case 1:for(;r<o;++r){const e=t[r];if(32!==e&&9!==e){i=r,this.m=2;break}}break;case 2:switch(this.Ne){case 0:for(;r<o;++r){const e=t[r];if(e<32||127===e){if(13!==e)return-1;++this.Ne;break}}this.ke+=t.latin1Slice(i,r),++r;break;case 1:if(10!==t[r++])return-1;++this.Ne;break;case 2:{const e=t[r];32===e||9===e?(i=r,this.Ne=0):(++this.Se<2e3&&(this.xe[this.ht.toLowerCase()]??=this.ke),13===e?(++this.Ne,++r):(i=r,this.Ne=0,this.m=0,this.ht="",this.ke=""));break}case 3:{if(10!==t[r++])return-1;const e=this.xe;return this.reset(),this.he(e),r}}}return o<n?-1:(this.$e+=o-e,o)}}class ii extends D{constructor(t,e){super({...t,read:ri}),this.truncated=!1,this.once("end",()=>{if(ri.call(this),0===--e.pe&&e._e){const t=e._e;e._e=void 0,process.nextTick(t)}})}}function ri(t){const e=this.ve;e&&(this.ve=void 0,e())}const oi={push:()=>{},destroy:()=>{}},si=/*@__PURE__*/Buffer.from("\r\n");class ai extends j{constructor({limits:t={},highWaterMark:e,defCharset:n="utf-8"},i){super({autoDestroy:!0,emitClose:!0,highWaterMark:e,write:ci,final:fi}),this.Oe=i.get("charset")??n,this.Ae=t.fieldSize??1048576,this.Re=t.fields??Number.POSITIVE_INFINITY,this.Pe=t.fieldNameSize??100,this.Ce=0,this.Fe=!0,this.Ue="",this.Me=this.Pe,this.Be=0,this.De="",this.Ie=!1,this.je=-2,this.qe=/^utf-?8$/i.test(this.Oe)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(this.Oe)?2:0,this.He=Rn(this.Oe)}}function ci(t,e,n){if(!t.byteLength)return n();if(this.Ce>=this.Re)return this.Ce||t===pi||(++this.Ce,this.emit("fieldsLimit")),n();const i=t.byteLength;let r=0,o=this.je;if(-2!==o){if(-1===o){if(16===(o=Xn[t[r++]]))return n(new ae(400,{body:"malformed urlencoded form"}));if(this.Be|=o,r===i)return this.je=o,n()}const e=Xn[t[r++]];if(16===e)return n(new ae(400,{body:"malformed urlencoded form"}));if(this.Ue+=String.fromCharCode((o<<4)+e),this.je=-2,r===i)return n()}for(wi[ui]=1,wi[hi]=1,wi[li]=1,wi[di]=this.Fe?1:0;;){const e=r;for(;r<i&&!wi[t[r]];++r);if(r>e&&this.Me>=0&&((this.Me-=r-e)<0?this.Ue+=t.latin1Slice(e,r+this.Me):this.Ue+=t.latin1Slice(e,r)),r===i)return n();switch(t[r++]){case ui:for(;;){if(--this.Me<0){wi[ui]=0,wi[li]=0;break}if(r===i)return this.je=-1,n();const e=Xn[t[r++]];if(16===e)return n(new ae(400,{body:"malformed urlencoded form"}));if(this.Be|=e,r===i)return this.je=e,n();const o=Xn[t[r++]];if(16===o)return n(new ae(400,{body:"malformed urlencoded form"}));if(this.Ue+=String.fromCharCode((e<<4)+o),r===i)return n();if(t[r]!==ui)break;r++}break;case hi:const e=!this.qe||1===this.qe&&8&this.Be?this.He.decode(Buffer.from(this.Ue,"latin1")):this.Ue;if(this.Fe?(e||this.Me<0)&&this.emit("field",this.Ue,"",{nameTruncated:this.Me<0,valueTruncated:!1,encoding:this.Oe,mimeType:"text/plain"}):(this.emit("field",this.De,e,{nameTruncated:this.Ie,valueTruncated:this.Me<0,encoding:this.Oe,mimeType:"text/plain"}),this.De="",this.Ie=!1,this.Fe=!0,wi[di]=1),wi[ui]=1,wi[li]=1,this.Ue="",this.Me=this.Pe,this.Be=0,++this.Ce===this.Re&&t!==pi)return this.emit("fieldsLimit"),n();break;case li:--this.Me<0?(wi[ui]=0,wi[li]=0):this.Ue+=" ";break;case di:this.De=!this.qe||1===this.qe&&8&this.Be?this.He.decode(Buffer.from(this.Ue,"latin1")):this.Ue,this.Ie=this.Me<0,this.Fe=!1,wi[di]=0,wi[ui]=1,wi[li]=1,this.Ue="",this.Be=0,this.Me=this.Ae}if(r===i)return n()}}function fi(t){ci.call(this,pi,void 0,t)}const ui=37,hi=38,li=43,di=61,wi=/*@__PURE__*/new Uint8Array(256),pi=/*@__PURE__*/Buffer.from([hi]);function mi(t,{closeAfterErrorDelay:e=500,...n}={}){W(e,"closeAfterErrorDelay",!0);const i=((t,e={})=>{const n=t["content-type"];if(!n)throw new ae(400,{body:"missing content-type"});const i=Ln(n);if(!i)throw new ae(400,{body:"malformed content-type"});const r="application/x-www-form-urlencoded"===i.mime?ai:"multipart/form-data"!==i.mime||e.blockMultipart?null:Kn;if(!r)throw new ae(415);return new r(e,i.params)})(t.headers,n);pn(t);const r=new V,o=(n,o)=>{if(r.fail(new ae(n,o)),i.removeAllListeners(),t.unpipe(i),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};i.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):i?o(400,{body:`value for ${JSON.stringify(t)} too long`}):void r.push({name:t,encoding:s,mimeType:a,type:"string",value:e}):o(400,{body:"missing field name"})),i.on("file",(t,e,{nameTruncated:n,filename:i,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):void(i?(e.once("limit",()=>o(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(i)} too large`})),r.push({name:t,encoding:s,mimeType:a,type:"file",value:e,filename:i})):e.resume()):o(400,{body:"missing field name"})),t.once("error",e=>{t.readableAborted?r.fail($t):o(500,{body:"request error",headers:{connection:"close"},cause:e})}),i.once("error",t=>o(400,{body:"error parsing form data",cause:t})),i.once("partsLimit",()=>o(400,{body:"too many parts"})),i.once("filesLimit",()=>o(400,{body:"too many files"})),i.once("fieldsLimit",()=>o(400,{body:"too many fields"}));const s=()=>r.close("complete");return i.once("close",s),_t(t,s),t.pipe(i),r}async function yi(t,e={}){const n=new FormData,i=new Map;for await(const r of mi(t,e))if("file"===r.type){const o=r.value;let s=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};_t(t,()=>a(0));const c=await wn(t),f=await c.save(o,{mode:384});await a(f.size);const h=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(h,f.path),n.append(r.name,h)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new 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 gi="win32"===/*@__PURE__*/R();function bi(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=at(t);if(i){if("/"===i.C)return[];n=i.C.split("/")}else{const e=K(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new ae(400,{body:"invalid path"});if(n.shift(),e){const t=gi?Ei:vi;if(n.some(e=>t.test(e)||e.includes(v)))throw new ae(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new ae(400,{body:"invalid path"})}return n}const vi=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Ei=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,Ti=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(Y,n):t.once("drain",n),t.uncork()});async function _i(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:o="utf-8",headerRow:a,end:c=!0}={}){"string"==typeof n&&(n=Buffer.from(n,o)),"string"==typeof i&&(i=Buffer.from(i,o));const f="string"==typeof r?Buffer.from(r,o):r,u=r+r,h=e=>{if(!e)return!0;const n=e.includes(r);return!n&&xi.test(e)?t.write(e,o):(t.write(f),n?t.write(e.replaceAll(r,u),o):t.write(e,o),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+o+(a?"; header=present":!1===a?"; header=absent":"")),t.cork();try{t.write(Y);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),h(i)||await Ti(t),++e;else for await(const i of r)e&&t.write(n),h(i)||await Ti(t),++e;t.write(i)||await Ti(t)}}finally{t.uncork()}c&&t.end()}const xi=/^[^"':;,\\\r\n\t ]*$/i;function Si(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 $i{constructor(t){(t=>"Le"in t&&"function"==typeof t.pipe)(t)&&(t=D.toWeb(t)),this.lt=t.getReader(),this.Je=null,this.ze=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.ze)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,i=t-this.ze;this.ze=e+1,this.m=1;const r=this,o=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.Je=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new B({start(t){if(r.Je){const e=r.Je;r.Je=null,o(e,t)}},async pull(t){if(n<=0)return r.m=0,void t.close();const e=await r.lt.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?o(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?o(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.lt.cancel(),this.lt.releaseLock()}}function ki(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let o=0;o<i.length;++o){const s=i[o];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++r,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)):r>0&&(i[o-r]=s)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function Ni(t,e,n,i){if("string"==typeof n||Si(n)||(i=ki(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const o=await Oi(n);return await d(o.We(r.start,r.end),e),void(o.Ge&&await o.Ge())}const r=e.getHeader("content-type"),o=l()+l()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${o}`);const s=i.ranges.map(t=>({o:[`--${o}`,...lt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Ve:t})),a=`--${o}--`;let c=a.length;for(const{o:t,Ve: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 Oi(n);try{for(const{o:t,Ve:n}of s)e.write(f+t,"ascii"),await d(u.We(n.start,n.end),e,{end:!1}),f="\r\n";e.end(f+a)}finally{u.Ge&&await u.Ge()}}async function Oi(t){if("string"==typeof t){const e=await N(t,"r");return{We:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ge:()=>e.close()}}if(Si(t))return{We:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new $i(t);return{We:(t,n)=>e.getRange(t,n),Ge:()=>e.close()}}}async function Ai(t,e,n,i=null,r){if(i||("string"==typeof n?i=await S(n):Si(n)&&(i=await n.stat())),i){if("GET"===t.method||"HEAD"===t.method){if(!Fn(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const o=xe(t,i.size,r);if(o&&Un(t,e,i))return Ni(t,e,n,ki(o,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=a(n):Si(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}function Ri(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:o="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,i??void 0)??(r?"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,o))),a?t.end(c,o):c&&t.write(c,o)}async function Pi(t,e,{replacer:n=null,space:i=null,undefinedAsNull:r=!1,encoding:o="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 i&&(i=" ".substring(0,i));const c={Ze:e=>t.write(e,o),Xe:()=>Ti(t),Ye:n,Ke:i??""};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Fi(null,"",e,c),Ui(e))r&&c.Ze("null");else{t.cork(),t.write(Y);try{await Ci(c,e,i?"\n":"")}finally{t.uncork()}}a&&t.end()}async function Ci(t,e,n){const i=(i,r,o)=>{t.Ze(i);const s=n+t.Ke,a=t.Ke?": ":":";let c=!0;return{i:async(n,i)=>{const r=Fi(e,n,i,t);o&&Ui(r)||(c?c=!1:t.Ze(","),t.Ze(s),o&&(t.Ze(JSON.stringify(n))||await t.Xe(),t.Ze(a)),await Ci(t,r,s))},Ge:()=>{c||t.Ze(n),t.Ze(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Mi(e))t.Ze(JSON.stringify(e)??"null")||await t.Xe();else if(e instanceof D){t.Ze('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Ze(e.substring(1,e.length-1))||await t.Xe()}t.Ze('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.i(n,i);t.Ge()}else if(Bi(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.i(String(t++),i);n.Ge()}else if(Di(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.i(String(t++),i);n.Ge()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.i(n,i);t.Ge()}}function Fi(t,e,n,i){return i.Ye&&(n=i.Ye.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Ui=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Mi=t=>JSON.isRawJSON?.(t)??!1,Bi=t=>Symbol.iterator in t,Di=t=>Symbol.asyncIterator in t;class Ii{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){W(n,"keepaliveInterval",!0),this.Qe=e,this.tn=n,this.F=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.en(),t.once("close",()=>this.close()),pt(t,()=>this.close(i,r))}get signal(){return this.F.signal}get open(){return!this.F.signal.aborted}en(){this.tn>0&&(this.nn=setTimeout(this.ping,this.tn))}ping(){!this.F.signal.aborted&&this.Qe.writable&&(clearTimeout(this.nn),this.Qe.write(":\n\n",()=>this.en()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){let e;this.F.signal.throwIfAborted(),this.Qe.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.Qe.write(e)," "===n[0]?this.Qe.write(": "):this.Qe.write(":"),this.Qe.write(n);/[\r\n]$/.test(i)?(this.Qe.write(e),this.Qe.write(":\n")):this.Qe.write("\n"),n=!0}if(!n)return;clearTimeout(this.nn),this.Qe.write("\n",()=>e())}finally{this.Qe.uncork()}await new Promise(t=>{e=t}),this.en()}async close(t=0,e=0){if(this.F.signal.aborted){if(this.Qe.closed)return;return new Promise(t=>this.Qe.once("close",t))}this.tn=0,clearTimeout(this.nn),this.F.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.Qe.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.Qe.end(`retry:${0|i}\n\n`,n)}else this.Qe.end(n)})}}const ji=async(t,{mode:e="dynamic",fallback:n,verbose:i,callback:r=qi,...o}={})=>{const s=await hn.build(E(process.cwd(),t),o);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 kt;let n=!1;const o=bi(t,f),s=[];let h=await u.find(o,t.headers,i?s:void 0);if(!h){if(!a)return i&&cn(t,new Error(s.join(", ")),"serving static content"),kt;if(n=!0,h=await u.find(a,t.headers,s),!h)throw new ae(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c),e.setHeader("content-type",h.mime??nn(m(h.canonicalPath))),h.encoding&&"identity"!==h.encoding&&e.setHeader("content-encoding",h.encoding);const i=u.vary;if(i){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+i)}await r(t,e,h,n),await Ai(t,e,h.handle,h.stats)}finally{h.handle.close().catch(()=>{})}}}};function qi(t,e,n){e.setHeader("etag",qe(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class Hi extends Error{constructor(t,{message:e,closeReason:n,...i}={}){super(e,i),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 Li(t,{softCloseStatusCode:e=Hi.GOING_AWAY,...n}={}){const i=(i,r,o)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(i,r,o,t=>{c.off("wsClientError",a),o=Y,s({return:t,onError:e=>{const n=Z(e,Hi);if(n)return void t.close(n.closeCode,n.closeReason);const i=Z(e,ae)??new ae(500),r=i.statusCode>=500?Hi.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>At(t,i)}class Ji{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Hi(Hi.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Hi(Hi.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class zi{constructor(t,{limit:e=-1,signal:n}={}){this.rn=new V;const i=e=>{t.off("message",o),t.off("close",r),this.rn.close(new Error(e))},r=()=>i("connection closed"),o=(t,n)=>{void 0!==n?this.rn.push(new Ji(t,n)):"string"==typeof t?this.rn.push(new Ji(Buffer.from(t,"utf-8"),!1)):this.rn.push(new Ji(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.rn.close(n.reason):2===t.readyState||3===t.readyState?this.rn.close(new Error("connection closed")):(t.on("message",o),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.rn.shift(t)}[Symbol.asyncIterator](){return this.rn[Symbol.asyncIterator]()}}function Wi(t,{timeout:e,signal:n}={}){const i=new zi(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function Gi(t){const e=ft(t);return"GET"===t.method&&(e.D?.has("websocket")??!1)}const Vi=t=>t.headers.origin??dt(t.headers["sec-websocket-origin"]),Zi=(t,e=5e3)=>async n=>{if(!Gi(n))return;const i=await t(n);let r;try{r=await Wi(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw $t;throw new Hi(Hi.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new Hi(Hi.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{V as BlockingQueue,kt as CONTINUE,hn as FileFinder,ae as HTTPError,Nt as NEXT_ROUTE,Ot as NEXT_ROUTER,Ge as Negotiator,Re as Property,G as Queue,te as Router,$t as STOP,Ii as ServerSentEvents,pe as WebListener,Hi as WebSocketError,Ji as WebSocketMessage,zi as WebSocketMessages,pn as acceptBody,At as acceptUpgrade,_t as addTeardown,Wt as anyHandler,Fn as checkIfModified,Un as checkIfRange,Mn as compareETag,rn as compressFileOffline,on as compressFilesInDir,Zt as conditionalErrorHandler,tn as decompressMime,Tt as defer,Rt as delegateUpgrade,cn as emitError,Gt as errorHandler,ji as fileServer,Z as findCause,He as generateStrongETag,qe as generateWeakETag,xt as getAbortSignal,Ht as getAbsolutePath,X as getAddressURL,Ee as getAuthorization,qn as getBodyJson,Dn as getBodyStream,jn as getBodyText,In as getBodyTextStream,Te as getCharset,yi as getFormData,mi as getFormFields,_e as getIfRange,nn as getMime,qt as getPathParameter,jt as getPathParameters,be as getQuery,xe as getRange,bi as getRemainingPathComponents,ye as getSearch,ge as getSearchParams,Rn as getTextDecoder,Pn as getTextDecoderStream,Vi as getWebSocketOrigin,Be as hasAuthScope,yt as isSoftClosed,Gi as isWebSocketRequest,fn as jsonErrorHandler,Li as makeAcceptWebSocket,H as makeAddressTester,gn as makeGetClient,Pe as makeMemo,wn as makeTempFileStorage,Zi as makeWebSocketFallbackTokenFetcher,We as negotiateEncoding,Wi as nextWebSocketMessage,q as parseAddress,mn as proxy,Oe as readHTTPDateSeconds,$e as readHTTPInteger,Ne as readHTTPKeyValues,ke as readHTTPQualityValues,Se as readHTTPUnquotedCommaSeparated,Qe as readMimeTypes,On as registerCharset,en as registerMime,An as registerUTF32,En as removeForwarded,Tn as replaceForwarded,Jt as requestHandler,De as requireAuthScope,Me as requireBearerAuth,Ke as resetMime,Lt as restoreAbsolutePath,_n as sanitiseAndAppendForwarded,_i as sendCSVStream,Ai as sendFile,Ri as sendJSON,Pi as sendJSONStream,Ni as sendRanges,qi as setDefaultCacheHeaders,pt as setSoftCloseHandler,xn as simpleAppendForwarded,ki as simplifyRange,ue as toListeners,Vt as typedErrorHandler,zt as upgradeHandler};
1
+ import{isIPv4 as t,isIPv6 as e}from"node:net";import{STATUS_CODES as n,createServer as i,Agent as r,request as o,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 w from"node:zlib";import{promisify as p}from"node:util";import{extname as m,join as y,dirname as g,basename as b,sep as v,resolve as E}from"node:path";import{readFile as _,writeFile as T,rm as x,stat as S,readdir as $,realpath as k,open as N,mkdtemp as O}from"node:fs/promises";import{tmpdir as A,platform as R}from"node:os";import{Agent as P,request as C}from"node:https";import{TransformStream as F,TextDecoderStream as U,DecompressionStream as M,ReadableStream as B}from"node:stream/web";import{Readable as D,Duplex as I,Writable as H}from"node:stream";function j(n){if(!n||"unknown"===n)return;const i=/^((?:\d{1,3}\.){3}\d{1,3})(?::(\d+))?$/.exec(n);if(i?.[1]&&t(i[1]))return{family:"IPv4",address:i[1],port:i[2]?Number.parseInt(i[2]):void 0};const r=/^\[([\da-fA-F:]+)\](?::(\d+))?$|^([\da-fA-F:]+)$/.exec(n);if(r?.[1]&&e(r[1]))return{family:"IPv6",address:r[1].toLowerCase(),port:r[2]?Number.parseInt(r[2]):void 0};if(r?.[3]&&e(r[3]))return{family:"IPv6",address:r[3].toLowerCase(),port:void 0};const o=/^(.*?):(\d+)$/i.exec(n);return o?.[2]?{family:"alias",address:o[1],port:Number.parseInt(o[2])}:{family:"alias",address:n,port:void 0}}function q(t){const e=new Set,n=[],i=[];for(const r of t){const t=/^((?:\d{1,3}\.){3}\d{1,3})(?:\/(\d+))?$/.exec(r);if(t?.[1]){const e=t[2]?Number.parseInt(t[2]):32,i=e<32?4294967295>>>e:0;n.push([J(t[1])|i,i]);continue}const o=/^\[?([\da-fA-F:]+)\]?(?:\/(\d+))?$/.exec(r);if(o?.[1]){const t=z(o[1]),e=o[2]?L>>BigInt(Number.parseInt(o[2])):0n;i.push([t|e,e]);continue}e.add(r)}return t=>{switch(t?.family){case"alias":return e.has(t.address);case"IPv4":const r=J(t.address);return n.some(([t,e])=>(r|e)===t);case"IPv6":const o=z(t.address);return i.some(([t,e])=>(o|e)===t);default:return!1}}}const L=/*@__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 W(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,i:null};this.o=e,this.u=e,void 0!==t&&this.push(t)}isEmpty(){return!this.o.i}clear(){this.o.i=null,this.o.t=null,this.u=this.o}push(t){const e={t,i:null};this.u.i=e,this.u=e}shift(){if(!this.o.i)return null;this.o=this.o.i;const t=this.o.t;return this.o.t=null,t}remove(t){for(let e=this.o;e.i;e=e.i)if(e.i.t===t){e.i=e.i.i;break}}[Symbol.iterator](){return{next:()=>{if(!this.o.i)return{value:null,done:!0};this.o=this.o.i;const t=this.o.t;return this.o.t=null,{value:t,done:!1}}}}}class V{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 W(t??0,"timeout"),this.l.isEmpty()?this.m?Promise.reject(this.T):new Promise((e,n)=>{const i={_:e,S:n,v:null};this.h.push(i),void 0!==t&&(i.v=setTimeout(()=>{this.h.remove(i),n(new Error(`timeout after ${t}ms`))},t))}):Promise.resolve(this.l.shift())}$(t){this.T=t;for(const e of this.h)e.S(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 Z(t,e){if(t instanceof e)return t;if(t&&"object"==typeof t){if("cause"in t)return Z(t.cause,e);if("error"in t)return Z(t.error,e)}}function X(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 Y=(t,e)=>new RegExp(t,(t.unicodeSets?"v":t.unicode?"u":"")+(t.ignoreCase||e?"i":"")),K=(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 i=Y(n,e);return t=>i.test(t)}const n=new Set,i=[];for(const r of t)"string"==typeof r?e?n.add(r.toLowerCase()):n.add(r):i.push(Y(r,e));return t=>n.has(e?t.toLowerCase():t)||i.some(e=>e.test(t))},Q=/*@__PURE__*/Buffer.alloc(0),tt=t=>new URL("http://localhost"+(t.url??"/"));class et extends Error{constructor(t,e,n){super(n??""),this.error=t,this.suppressed=e}}const nt=globalThis.SuppressedError??et;class it{constructor(){this.k=!1}N(t){this.k?t!==this.O&&(this.O=new nt(t,this.O)):(this.O=t,this.k=!0)}A(){this.k=!1,this.O=void 0}}const rt=new WeakMap;function ot(t,e,n){const i=rt.get(t);if(i)return i;const r=tt(t),o={R:t,P:r,C:decodeURIComponent(r.pathname),F:new AbortController,U:e,M:[],B:[],D:n?ct(t):null};return rt.set(t,o),o}function st(t,e,n){e||(t.D=null),t.I=n;const i=async()=>{t.F.abort(n.H.writableEnded?"complete":"client abort");const e=new it;await at(t.M,e,t),await at(t.B,e,t,()=>{t.j=async e=>{try{await e()}catch(e){t.U(e,"tearing down",t.R)}}}),e.k&&t.U(e.O,"tearing down",t.R)};return n.H.closed?i():n.H.once("close",i),t}async function at(t,e,n,i){for(;n.L;)await n.L;const r=(async()=>{for(;;){const n=t.pop();if(!n)return void i?.();try{await n()}catch(t){e.N(t)}}})().then(()=>{n.L===r&&(n.L=void 0)});n.L=r,await r}function ct(t){return new Set(t.headers.upgrade?.split(",").map(t=>t.trim().toLowerCase())??[])}const ft=t=>rt.get(t),ut=t=>rt.delete(t);function lt(t){const e=ft(t);if(!e)throw new RangeError("unknown request");return e}function ht(t,e,n=ht){throw t.code=e,Error.captureStackTrace(t,n),t}class dt{constructor(t){this.J=t,this.W=Object.create(null),this.G=!1}get headersSent(){return this.G}writeHead(t,e=n[t]??"-"){return this.G&&ht(new Error("Cannot write headers after they are sent to the client"),"ERR_HTTP_HEADERS_SENT"),this.J.write([`HTTP/1.1 ${t} ${mt(e)}`,...wt(this.W),"",""].join("\r\n"),"ascii"),this.G=!0,this}write(t,e="utf-8",n){return this.J.write(t,e,n)}end(t,e="utf-8",n){return this.J.end(t,e,n),this}setHeader(t,e){const n=t.toLowerCase();return this.W[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 wt(t){const e=[];for(const[n,i]of Object.entries(t)){const t=pt(i);t&&e.push(`${mt(n)}: ${mt(t)}`)}return e}const pt=t=>"string"==typeof t?t:"number"==typeof t?String(t):t?t.join(", "):"",mt=t=>t.replaceAll(/[^ \t!-~]/g,"");function yt(t,e){const n=ft(t);n&&gt(n,e)}function gt(t,e){t.V=e;const n=t.Z;n&&queueMicrotask(()=>Tt(e,n,t))}const bt=t=>Boolean(ft(t)?.Z);function vt(t,e,n){if(!t.Z){if(t.I&&!t.D){const e=t.I.H;e.headersSent||e.hasHeader("connection")||e.setHeader("connection","close")}t.I?.H.once("close",()=>t.R.socket.destroy()),t.Z={X:e,U:n},Tt(t.V,t.Z,t),_t(t)}}function Et(t){if(t.I){if(t.D){if(!t.Y&&t.I.H.writable){const e=new dt(t.I.H);e.setHeader("connection","close"),e.writeHead(503)}}else{const e=t.I.H;e.headersSent||(e.hasHeader("connection")||e.setHeader("connection","close"),e.writeHead(503))}t.I.H.end(()=>t.R.socket.destroy())}else t.R.socket.destroy()}function _t(t){if(clearTimeout(t.K),!t.tt||t.j)return;const e=Date.now();if(e>=t.tt)return void Et(t);let n=t.tt;t.et&&!t.Z&&(e<t.et.nt?n=t.et.nt:(t.Z=t.et,Tt(t.V,t.Z,t))),void 0===t.K&&t.B.push(()=>clearTimeout(t.K)),t.K=setTimeout(()=>_t(t),Math.min(n-e,6048e5))}async function Tt(t,e,n){try{await(t?.(e.X))}catch(t){e.U(t,"soft closing",n.R),Et(n)}}const xt=(t,e)=>{const n=lt(t);n.j?n.j(e):n.M.push(e)},St=(t,e)=>{const n=lt(t);n.j?n.j(e):n.B.push(e)},$t=t=>lt(t).F.signal;class kt extends Error{}const Nt=new kt("STOP"),Ot=new kt("CONTINUE"),At=new kt("NEXT_ROUTE"),Rt=new kt("NEXT_ROUTER");async function Pt(t,e){const n=lt(t);if(!n.I)throw new TypeError("cannot call acceptUpgrade from shouldUpgrade");if(!n.D)throw new TypeError("not an upgrade request");if(3===n.Y)throw new TypeError("upgrade already delegated");if(2===n.Y)return n.it;const i=n.I.H;if(!i.readable||!i.writable)throw Nt;n.Y=1;const r=await e(t,i,n.I.o);return n.I.o=Q,n.rt=r.onError,r.softCloseHandler&&gt(n,r.softCloseHandler),n.Y=2,n.it=r.return,r.return}function Ct(t){const e=lt(t);if(!e.I)throw new TypeError("cannot call delegateUpgrade from shouldUpgrade");if(!e.D)throw new TypeError("not an upgrade request");if(e.Y)throw new TypeError("upgrade already handled");e.Y=3}const Ft=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),Dt=/*@__PURE__*/(t=>e=>{const n=[];let i=0;for(;i<e.length;++i){const r=t.get(e[i]);if(!r)break;n.push([r,!0])}return[Object.fromEntries(n),e.substring(i)]})(
2
+ /*@__PURE__*/new Map([["i","ot"],["!","st"]])),It=(t,e)=>{Object.prototype.hasOwnProperty.call(t,e)&&delete t[e]},Ht=Object.freeze({});function jt(t,e,n){const i=t.R.url,r=t.C,o=t.ct??Ht;return t.R.url=encodeURIComponent(e).replaceAll(/%2F/g,"/")+t.P.search,t.C=e,n.length>0&&(t.ct=Object.freeze(Object.fromEntries([...Object.entries(o),...n]))),()=>{t.R.url=i,t.C=r,t.ct=o}}function qt(t){return ft(t)?.ct??Ht}function Lt(t,e){return n=qt(t),i=e,Object.prototype.hasOwnProperty.call(n,i)?n[i]:void 0;var n,i}function Jt(t){const e=ft(t);return e?e.P.pathname+e.P.search:t.url??"/"}function zt(t){const e=ft(t);e&&(t.url=e.P.pathname+e.P.search)}const Wt=t=>"function"==typeof t?{handleRequest:t}:t,Gt=(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,i,r)=>{if(r.response&&t(n))return e(n,i,r.response);throw n},shouldHandleError:(e,n,i)=>Boolean(i.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=[]}N(t,e,n,i,r){const o=n?((t,e)=>{const n=["^"],i=[],r=/[{}]|\/+|\\(.)|[:*]([a-zA-Z0-9_]*)/g,[{ot:o,st:s},a]=Dt(t);if("/"!==a[0])throw new TypeError("path must begin with '/' or flags");let c=0,f=0;for(const t of a.matchAll(r)){t.index>c&&n.push(Ft(a.substring(c,t.index)));const e=t[0];if("{"===e)n.push("(?:"),++f;else if("}"===e){if(0===f)throw new TypeError(`unbalanced optional braces in path at ${t.index}`);--f,n.push(")?")}else if("/"===e[0])n.push(e),s||n.push("+");else if("\\"===e[0])n.push(Ft(t[1]));else{const r=e[0],o=t[2];if(!o)throw new TypeError(`unnamed parameter or unescaped '${r}' at ${t.index}`);"*"===r?(n.push("(.*?)"),i.push({lt:o,ht:s?Mt:Bt})):(n.push("([^/]+?)"),i.push({lt:o,ht:Ut}))}c=t.index+e.length}if(c<a.length&&n.push(Ft(a.substring(c))),f>0)throw new TypeError("unbalanced optional braces in path");return e&&(n.push("(?:"),s?n.push("(?:(?<=/)|/)"):n.push("(?:/+|(?<=/))"),n.push("(?<rest>.*))?")),n.push("$"),{dt:new RegExp(n.join(""),o?"i":""),wt:i}})(n,i):{dt:null,wt:[]};if(r.some(t=>t instanceof Promise))throw new TypeError("expected handler, got Promise (did you forget to await?)");return this.ft.push({yt:t,gt:"string"==typeof e?e.toLowerCase():e,bt:o.dt,vt:o.wt,Et:r}),this}use(...t){return this.N(null,null,null,!0,t.map(Kt))}mount(t,...e){return this.N(null,null,t,!0,e.map(Kt))}within(t){const e=new ne;return this.mount(t,e),e}at(t,...e){return this.N(null,null,t,!1,e.map(Kt))}onRequest(t,e,...n){return this.N(re(t),ee,e,!1,n.map(Kt))}onUpgrade(t,e,n,...i){return this.N(re(t),e,n,!1,i.map(Qt))}onError(...t){return this.N(null,null,null,!0,t.map(Zt))}onReturn(...t){return this.ut.push(...t),this}get=(t,...e)=>this.N(ie,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._t(t,new it)}async handleUpgrade(t){return this._t(t,new it)}async handleError(t,e){const n=new it;return n.N(t),this._t(e,n)}shouldUpgrade(t){return this.Tt(lt(t))}Tt(t){for(const e of this.ft){const n=oe(t,e);if(!n)continue;let i=()=>{};if(!0!==n)try{i=jt(t,n.xt,[])}catch{continue}try{for(const n of e.Et)if(ce(n,t))return!0}finally{i()}}return!1}async _t(t,e){const n=lt(t),i=await this.St(n,e);if(e.k)throw e.O;return i}async St(t,e){for(const n of this.ft){const i=oe(t,n);if(!i)continue;let r=()=>{};if(!0!==i)try{const e=i.$t();r=jt(t,i.xt,e)}catch(t){e.N(t);continue}try{const i=await se(t,n.Et,this.ut,e);if(i===Rt)break;if(i===At)continue;return i}finally{r()}}return Ot}}const ie=new Set(["HEAD","GET"]),re=t=>t?"string"==typeof t?t:new Set(t):null;function oe(t,e){if("string"==typeof e.yt){if(e.yt!==t.R.method)return!1}else if(null!==e.yt&&!e.yt.has(t.R.method??""))return!1;if(e.gt===ee){if(t.D)return!1}else if(null!==e.gt&&!t.D?.has(e.gt))return!1;if(null===e.bt)return!0;const n=e.bt.exec(t.C);return!!n&&{xt:"/"+(n.groups?.rest??""),$t:()=>e.vt.map((t,e)=>[t.lt,t.ht(n[e+1])])}}async function se(t,e,n,i){for(const r of e){let e=await ae(r,t,i);if(e!==Ot){if(!t.D&&!(e instanceof kt)&&n.length)try{const i="object"==typeof e?e:void 0,r=t.R,o=t.I.H;for(const t of n)await t(i,r,o)}catch(t){i.N(t);continue}return e}}return At}async function ae(t,e,n){if(t instanceof ne)return t.St(e,n);let i=Ot;try{if(n.k){if(t.handleError){const r=n.O,o=e.D?{socket:e.I.H,head:e.I.o,hasUpgraded:Boolean(e.Y)}:{response:e.I.H};t.shouldHandleError&&!t.shouldHandleError(r,e.R,o)||(n.A(),i=await t.handleError(r,e.R,o))}}else if(e.D){if(t.handleUpgrade){const n=e.I;i=await t.handleUpgrade(e.R,n.H,n.o)}}else t.handleRequest&&(i=await t.handleRequest(e.R,e.I.H))}catch(t){t instanceof kt?i=t:n.N(t)}finally{e.M.length&&await((t,e)=>at(t.M,e,t))(e,n)}return i===Nt?void 0:i}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}}class fe extends Error{constructor(t,{message:e,statusMessage:i,headers:r,body:o,...s}={}){super(e??o,s),this.statusCode=0|t,this.statusMessage=i??n[this.statusCode]??"-",this.headers=(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,pt(e)]).filter(([t,e])=>e))})(r),this.body=o??"",this.name=`HTTPError(${this.statusCode} ${this.statusMessage})`}}const ue=(t,e,n)=>{const i=le(n);if(!i)return;const r=Z(t,fe)??new fe(500);i.setHeader("content-type","text/plain; charset=utf-8"),i.setHeaders(r.headers),i.setHeader("content-length",String(Buffer.byteLength(r.body,"utf-8"))),n.response||i.setHeader("connection","close"),i.writeHead(r.statusCode,r.statusMessage),i.end(r.body,"utf-8")};function le(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 dt(e);e.destroy()}function he(t,{onError:e=de,socketCloseTimeout:n=500}={}){W(n,"socketCloseTimeout");let i=0,r="",o=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)})};return{request:async(n,s)=>{let a;try{a=ot(n,e,!1)}catch(t){return e(t,"parsing request",n),void ue(new fe(400),0,{response:s})}if(st(a,!1,{H:s}),u(a),1===i)vt(a,r,o);else if(2===i)return Et(a),void ut(n);const c=new it,f=await ae(t,a,c);c.k||f!==Ot&&f!==At&&f!==Rt||c.N(new fe(404)),c.k&&(e(c.O,"handling request",n),ue(c.O,0,{response:s}),ut(n))},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 ue(new fe(400),0,{socket:a,hasUpgraded:!1})}if(st(f,!0,{H:a,o:c}),c=Q,u(f),1===i)vt(f,r,o);else if(2===i)return Et(f),void ut(s);const l=new it,h=await ae(t,f,l);l.k||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.N(new fe(404))),l.k&&(e(l.O,"handling upgrade",s),f.rt?f.rt(l.O):ue(l.O,0,{socket:a,head:f.I?.o??Q,hasUpgraded:Boolean(f.Y)}),ut(s))},shouldUpgrade:n=>{try{const i=ot(n,e,!0);return ce(t,i)}catch{return!1}},clientError:(t,n)=>{const i=n.kt,r=t.code;n.writable&&!i?.headersSent&&n.end(pe.get(r)??me),n.destroy(t),"HPE_INVALID_EOF_STATE"===r||e(t,"initialising request",void 0)},softClose(t,e,n){if(i<1){i=1,r=t,o=e;for(const n of a)vt(n,t,e)}f(n)},hardClose(t){if(i<2){i=2;for(const t of a)Et(t)}f(t)},countConnections:()=>a.size}}const de=(t,e,n)=>{(Z(t,fe)?.statusCode??500)>=500&&console.error("%s",`unhandled error while ${e} ${n?.url??"(no request information)"}:`,t)},we=t=>Buffer.from(`HTTP/1.1 ${t} ${n[t]}\r\nConnection: close\r\n\r\n`),pe=/*@__PURE__*/new Map([["HPE_HEADER_OVERFLOW",/*@__PURE__*/we(431)],["HPE_CHUNK_EXTENSIONS_OVERFLOW",/*@__PURE__*/we(413)],["ERR_HTTP_REQUEST_TIMEOUT",/*@__PURE__*/we(408)]]),me=/*@__PURE__*/we(400);class ye extends EventTarget{constructor(t){super(),this.Nt=t}attach(t,e={}){const n=(e,n,i)=>{const r={server:t,error:e,context:n,request:i};this.dispatchEvent(new CustomEvent("error",{detail:r,cancelable:!0}))&&de(e,n,i)},i=he(this.Nt,{...e,onError:n});!1===e.autoContinue&&t.addListener("checkContinue",i.request),!1===e.rejectNonStandardExpect&&t.addListener("checkExpectation",i.request),t.addListener("request",i.request),t.addListener("upgrade",i.upgrade);const r=t.shouldUpgradeCallback??(()=>!1);!1!==e.overrideShouldUpgradeCallback&&(t.shouldUpgradeCallback=i.shouldUpgrade),t.addListener("clientError",i.clientError);let o=()=>{o=void 0,t.removeListener("checkContinue",i.request),t.removeListener("checkExpectation",i.request),t.removeListener("request",i.request),t.removeListener("upgrade",i.upgrade),t.shouldUpgradeCallback===i.shouldUpgrade&&(t.shouldUpgradeCallback=r),t.removeListener("clientError",i.clientError)};return(t="",e=-1,r=!1,s)=>{if(W(e,"existingConnectionTimeout",!0),r||o?.(),e>0){const r=setTimeout(()=>{o?.(),i.hardClose()},e);i.softClose(t,n,()=>{o?.(),clearTimeout(r),s?.()})}else 0===e?(o?.(),i.hardClose(s)):(o?.(),s&&setImmediate(s));return i}}createServer(t={}){t.shouldUpgradeCallback&&(t={overrideShouldUpgradeCallback:!1,...t});const e=i(t),n=this.attach(e,t),r=Object.assign(e,{closeWithTimeout:(t,i)=>new Promise(r=>n(t,i,!0,()=>{e.close(()=>r()),e.closeAllConnections()}))});return r}listen(t,e,n={}){const i=this.createServer(n);return n.socketTimeout&&i.setTimeout(n.socketTimeout),new Promise((r,o)=>{i.once("error",o),i.listen(t,e,n.backlog??511,()=>{i.off("error",o),r(i)})})}}const ge=t=>ft(t)?.P??tt(t),be=t=>ge(t).search,ve=t=>new URLSearchParams(ge(t).searchParams),Ee=(t,e)=>ge(t).searchParams.get(e);function _e(t,e){const n=t.indexOf(e);return-1===n?[t]:[t.substring(0,n),t.substring(n+e.length)]}function Te(t){const e=t.headers.authorization;if(!e)return;const[n,i]=_e(e," ");return void 0!==i?[n.trim().toLowerCase(),i.trim()]:void 0}function xe(t){const e=/^text\/.*;\s*charset=([^;]+)/i.exec(t.headers["content-type"]??"");return e?.[1]?.trim().toLowerCase()??void 0}function Se(t){const e=t.headers["if-range"];return e&&"string"==typeof e?/^("|W\/")/.test(e)?{etag:[e]}:{modifiedSeconds:Re(e)}:{}}function $e(t,e,{maxRanges:n=10,maxNonSequential:i=2,maxWithOverlap:r=2}={}){const o=t.headers.range;if(!o||0===e)return;const[s,a]=_e(o,"=");if("bytes"!==s||!a)return;const c=new fe(416,{headers:{"content-range":`bytes */${e}`}}),f=t=>{const e=Ne(t);if(void 0===e)throw c;return e},u=[];for(const t of a.split(",")){const[i,r]=_e(t.trim(),"-");if(void 0===r)throw c;let o;if(i)o={start:f(i),end:r?Math.min(f(r),e-1):e-1};else{if(!r)throw c;o={start:Math.max(e-f(r),0),end:e-1}}if(!(o.start>=e)){if(o.end<o.start||u.length>=n)throw c;u.push(o)}}if(!u.length)throw c;if(u.length>i)for(let t=0;t<u.length-1;++t)if(u[t].start>u[t+1].start)throw c;if(u.length>r)for(let t=1;t<u.length;++t){const e=u[t];for(let n=0;n<t;++n){const t=u[n];if(e.end>=t.start&&t.end>=e.start)throw 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 Ne(t){if(t&&/^\s*-?\d+\s*$/.test(t))return Number.parseInt(t,10)}const Oe=t=>ke(t)?.map(t=>{const[e,...n]=t.split(";"),i=new Map(n.map(t=>{const[e,n]=_e(t,"=");return[e.trim(),n?.trim()??""]})),r=e.trim(),o="*/*"===r||"*"===r?0:r.endsWith("/*")?1:2,s=Math.max(0,Math.min(1,Number.parseFloat(i.get("q")??"1")));return{name:r,specifiers:i,specificity:o,q:s}});function Ae(t){const e=new Map,n=/\s*([^=]+)=([^";]*?|"(?:[^\\"]|\\.)*")\s*(?:;|$)/y;for(;n.lastIndex<t.length;){const i=n.exec(t);if(!i)throw new fe(400,{body:"invalid HTTP key values"});const r=i[1].toLowerCase();let o=i[2];'"'===o[0]&&(o=o.substring(1,o.length-1).replaceAll(/\\(.)/g,(t,e)=>e)),e.set(r,o)}return e}function Re(t){if("string"!=typeof t)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e/1e3|0}const Pe=t=>"function"==typeof t?t:()=>t;class Ce{constructor(t=Be){this.Ot=Pe(t)}set(t,e){Ue(lt(t)).set(this,e)}get(t){return Me(t,this,this.Ot)}clear(t){const e=ft(t);e?.At?.delete(this)}withValue(t){return Vt(e=>(this.set(e,t),Ot))}}const Fe=(t,...e)=>{const n=n=>t(n,...e);return t=>Me(t,n,n)};function Ue(t){return t.At||(t.At=new Map),t.At}function Me(t,e,n){const i=ft(t);if(!i)return n(t);const r=Ue(i);if(r.has(e))return r.get(e);const o=n(t);return r.set(e,o),o}const Be=()=>{throw new Error("property has not been set")};function De({realm:t,extractAndValidateToken:e,fallbackTokenFetcher:n,closeOnExpiry:i=!0,softCloseBufferTime:r=0,onSoftCloseError:o}){const s=Pe(t);return{...Vt(async t=>{const a=Date.now(),c=await s(t),f={"www-authenticate":`Bearer realm="${c}"`},u=Te(t),l="bearer"===u?.[0]?u[1]:await(n?.(t));if(!l)throw new fe(401,{headers:f,body:"no token provided"});let h;try{h=await e(l,c,t)}catch(t){throw new fe(401,{headers:f,body:"invalid token",cause:t})}if(!h)throw new fe(401,{headers:f,body:"invalid token"});if("object"==typeof h){if("nbf"in h&&"number"==typeof h.nbf&&a<1e3*h.nbf)throw new fe(401,{headers:f,body:"token not valid yet"});if("exp"in h&&"number"==typeof h.exp){const e=1e3*h.exp;if(a>=e-r)throw new fe(401,{headers:f,body:"token expired"});i&&((t,e,n,i=0,r)=>{const o=lt(t),s=n-Math.max(i,0),a=o.tt??Number.POSITIVE_INFINITY,c=o.et?.nt??a;s>=c&&n>=a||(n<a&&(o.tt=n),s<c&&(o.et={nt:s,X:e,U:r??o.U}),_t(o))})(t,"token expired",e,r,o)}}return je.set(t,{Rt:c,Pt:!0,Ct:h,Ft:qe(h)}),Ot}),getTokenData:t=>{const e=je.get(t);if(!e.Pt)throw new TypeError("cannot use getTokenData in an unauthenticated endpoint");return e.Ct}}}const Ie=(t,e)=>je.get(t).Ft.has(e),He=t=>Vt(e=>{const n=je.get(e);if(!n.Ft.has(t))throw new fe(403,{headers:{"www-authenticate":`Bearer realm="${n.Rt}", scope="${t}"`},body:`scope required: ${t}`});return Ot}),je=/*@__PURE__*/new Ce({Rt:"",Pt:!1,Ct:null,Ft:new Set});function qe(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 Je(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 ze={type:{Ut:"accept",Mt:"content-type"},language:{Ut:"accept-language",Mt:"content-language"},encoding:{Ut:"accept-encoding",Mt:"content-encoding"}},We=/*@__PURE__*/new Map([["zstd","{file}.zst"],["br","{file}.br"],["gzip","{file}.gz"],["deflate","{file}.deflate"],["identity","{file}"]]),Ge=t=>{return{feature:"encoding",options:(e=t,n=We,Array.isArray(e)?e.map(t=>({match:t,file:n.get(t)})):Object.entries(e).map(([t,e])=>({match:t,file:e})))};var e,n};class Ve{constructor(t,{maxFailedAttempts:e=10}={}){this.Bt=t.map(t=>{if(!Object.prototype.hasOwnProperty.call(ze,t.feature))throw new RangeError(`unknown negotiation feature: ${t.feature}`);return{Dt:t.feature,It:K(t.match,!0),Ht:t.options.map(t=>({jt:t.file,It:K(t.match,!0),qt:t.as??("string"==typeof t.match?t.match:"")}))}}).filter(t=>t.Ht.length>0),this.Lt=e}*options(t,e){const n=this.Bt,i=new Set,r=this.Lt,o={},s=new Set;let a=!1;r>0&&(yield*function*c(f,u){const l=n[u];if(!l)return void(i.has(f)||(i.add(f),a&&(o.vary=[...s].join(", "),a=!1),yield{filename:f,headers:o}));if(!l.It(t))return void(yield*c(f,u+1));const h=ze[l.Dt];s.add(ze[l.Dt].Ut),a=!0;const d=Oe(e[h.Ut])?.sort(Ze);if(!d?.length)return void(yield*c(f,u+1));const w=new Set,p=[];for(const t of l.Ht){const e=d.find(e=>t.It(e.name));e&&p.push({...e,Jt:t})}for(const t of p.sort(Ze)){const e=Xe(f,t.Jt.jt);if(!w.has(e)&&(w.add(e),o[h.Mt]=t.Jt.qt,yield*c(e,u+1),i.size>=r))return}delete o[h.Mt],!w.has(f)&&i.size<r&&(yield*c(f,u+1))}(t,0)),i.has(t)||(a&&(o.vary=[...s].join(", ")),yield{filename:t,headers:o})}}const Ze=(t,e)=>e.q-t.q||e.specificity-t.specificity;function Xe(t,e){return e.replaceAll(/\{(?:file|base|ext)\}/g,e=>"{file}"===e?t:"{base}"===e?t.replace(/\.[^.]*$/,""):m(t))}const Ye=/*@__PURE__*/en("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 Ke=/*@__PURE__*/new Map(Ye);function Qe(){Ke=new Map(Ye)}function tn(t){const e=new Map;for(const n of t.split("\n")){const[t,...i]=n.replaceAll(/\s+/g," ").trim().split(" ");if(!t.startsWith("#"))for(const n of i)e.set(n.toLowerCase(),t)}return e}function en(t){const e=new Map;for(const n of t.split(/[\n;]/g)){const[t,i,r]=/^ *([^=]+)=(.*)$/.exec(n)??[null,null,""];for(const t of i?.split(",")??[]){const[n,i,o="",s=""]=/^([^(]*)(?:\(([^)]*)\)(.*))?$/.exec(t),a=i+o+s,c=r.replace("{ext}",a);e.set(a.toLowerCase(),c),o&&e.set((i+s).toLowerCase(),c)}}return e}function nn(t){for(const[e,n]of t)Ke.set(e.toLowerCase(),n)}function rn(t,e="utf-8"){"."===t[0]&&(t=t.substring(1));const n=Ke.get(t)??"application/octet-stream";return n.startsWith("text/")&&!n.includes("charset=")?`${n}; charset=${e}`:n}const on=(t,e)=>!["image","video","audio","font"].includes(e.split("/")[0]);async function sn(t,e,{minCompression:n=0,deleteObsolete:i=!1,filter:r=on}={}){const o=await _(t),s={file:t,mime:rn(m(t)),rawSize:o.byteLength,bestSize:o.byteLength,created:0};if(!r(t,s.mime))return s;const a=s.rawSize-n;for(const n of e){const e=fn.get(n.match),r=y(g(t),Xe(b(t),n.file));if(!e||r===n.file)continue;const c=a>0?await e(o):void 0;c&&c.byteLength<=a?(await T(r,c),s.bestSize=Math.min(s.bestSize,c.byteLength),++s.created):i&&await x(r).catch(()=>{})}return s}async function an(t,e,n={}){const i=[];await cn(t,i);const r=new Set(i);for(const t of r)for(const n of e){const e=y(g(t),Xe(b(t),n.file));e!==t&&r.delete(e)}return Promise.all([...r].map(t=>sn(t,e,n)))}async function cn(t,e){const n=await S(t);if(n.isDirectory())for(const n of await $(t))await cn(y(t,n),e);else n.isFile()&&e.push(t)}const fn=/*@__PURE__*/new Map([["zstd",t=>p(w.zstdCompress)(t)],["br",t=>p(w.brotliCompress)(t,{params:{[w.constants.BROTLI_PARAM_QUALITY]:w.constants.BROTLI_MAX_QUALITY,[w.constants.BROTLI_PARAM_SIZE_HINT]:t.length}})],["gzip",t=>p(w.gzip)(t,{level:w.constants.Z_BEST_COMPRESSION})],["deflate",t=>p(w.deflate)(t)]]),un=(t,e,n)=>{const i=lt(t);i.U(e,n??(i.D?"handling upgrade":"handling request"),t)},ln=(t,{onlyIfRequested:e=!0,emitError:n=!0,forceStatus:i,contentType:r="application/json"}={})=>({handleError:(o,s,a)=>{if(a.hasUpgraded||e&&!hn(s,r))throw o;n&&un(s,o);const c=le(a);if(!c)return;const f=Z(o,fe)??new fe(500),u=JSON.stringify(t(f));c.setHeaders(f.headers),c.setHeader("content-type",r),c.setHeader("content-length",String(Buffer.byteLength(u,"utf-8"))),a.response||c.setHeader("connection","close"),i?c.writeHead(i):c.writeHead(f.statusCode,f.statusMessage),c.end(u,"utf-8")},shouldHandleError:(t,n,i)=>!i.hasUpgraded&&(!e||hn(n,r))}),hn=(t,e)=>Oe(t.headers.accept)?.some(t=>t.name===e||"application/json"===t.name)??!1;class dn{constructor(t,{subDirectories:e=!0,caseSensitive:n="exact",allowAllDotfiles:i=!1,allowAllTildefiles:r=!1,allowDirectIndexAccess:o=!1,allow:s=[".well-known"],hide:a=[],indexFiles:c=["index.htm","index.html"],implicitSuffixes:f=[],negotiator:u}){this.zt=t,this.Wt=!0===e?Number.POSITIVE_INFINITY:e||0,this.Gt=n,this.Vt=i,this.Zt=r,this.Xt=o,this.Yt=c,this.Kt=["",...f],this.Qt=new Set(s.map(t=>this.te(t))),this.ee=K(a,!n),this.ne=new Set(c.map(t=>this.te(t))),this.ie=u}static async build(t,e={}){return new dn(await k(t,{encoding:"utf-8"})+v,e)}te(t){return"exact"===this.Gt?t:t.toLowerCase()}re(t){if(this.Qt.has(t))return!0;const e=t.trim();return!(!("~"!==e[0]&&"~"!==e[e.length-1]||this.Zt)||"."===e[0]&&!this.Vt||this.ee(e))}toNormalisedPath(t){const e=t[t.length-1];return e&&this.ne.has(this.te(e))?t.slice(0,t.length-1):t}async find(t,e={},n){let i=t.join(v);"force-lowercase"===this.Gt&&(i=i.toLowerCase());let r=E(this.zt,i);if(!r.startsWith(this.zt)&&r+v!==this.zt)return n?.push(`${JSON.stringify(r)} is not inside root ${JSON.stringify(this.zt)}`),null;let o=null,s=null;for(const t of this.Kt){const e=r+t;if(o=e.substring(this.zt.length).split(v).filter(t=>t),o.length-1>this.Wt)return n?.push(`${JSON.stringify(r)} is nested too deeply (${o.length-1} > ${this.Wt})`),null;if(o.some(t=>!this.re(this.te(t))))return n?.push(`${JSON.stringify(r)} is not permitted`),null;const i=o[o.length-1]??"";if(!this.Xt&&this.ne.has(this.te(i))&&!this.Qt.has(this.te(i)))return n?.push(`${JSON.stringify(r)} is a hidden index file`),null;if(s=await k(e,{encoding:"utf-8"}).catch(()=>null),s){r=e;break}}if(!s||!o)return n?.push(`file ${JSON.stringify(r)} does not exist`),null;if(this.te(s)!==this.te(r))return n?.push(`realpath ${JSON.stringify(s)} does not match request ${JSON.stringify(r)}`),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(o.length>this.Wt)return n?.push(`${JSON.stringify(s)} index file is nested too deeply (${o.length} > ${this.Wt})`),null;for(const t of this.Yt){const e=y(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.ie)return pn({canonicalPath:a,negotiatedPath:a,headers:{}},n);const f=b(a),u=g(a);for(const t of this.ie.options(f,e)){if(!t.filename||t.filename.includes(v))continue;const e=await pn({canonicalPath:a,negotiatedPath:y(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 i=t.get(e);(!i||n.p>i.p)&&t.set(e,n)},n=new G({dir:[this.zt],depth:0});for(const{dir:t,depth:i}of n){const r=await $(y(...t),{withFileTypes:!0,encoding:"utf-8"}),o=new Set(r.map(t=>this.te(t.name)));for(const s of r){const r=this.te(s.name);if(!this.re(r))continue;const a=[...t,s.name];if(s.isDirectory())i<this.Wt&&n.push({dir:a,depth:i+1}),e(this.te(a.slice(1).join("/")),wn);else if(s.isFile()){const n={file:y(...a),dir:y(...t),basename:r,siblings:o},i=this.Yt.indexOf(r);if(-1!==i&&(e(this.te(t.slice(1).join("/")),{...n,p:this.Yt.length+1-i}),!this.Xt&&!this.Qt.has(r)))continue;const c=this.te(a.slice(1).join("/"));for(let t=0;t<this.Kt.length;++t){const i=this.Kt[t];s.name.endsWith(i)&&e(c.substring(0,c.length-i.length),{...n,p:-t})}}}}return{find:async(e,n={},i)=>{const r=t.get(this.te(e.join("/")));if(!r?.file)return i?.push(`${JSON.stringify(e.join("/"))} not found in static file paths`),null;if(!this.ie)return pn({canonicalPath:r.file,negotiatedPath:r.file,headers:{}},i);for(const t of this.ie.options(r.basename,n)){if(!r.siblings.has(this.te(t.filename)))continue;const e=await pn({canonicalPath:r.file,negotiatedPath:y(r.dir,t.filename),headers:t.headers},i);if(e)return e}return null},debugAllPaths:()=>Promise.resolve(new Set([...t].filter(([t,e])=>e.file).map(([t])=>t)))}}}const wn={file:"",dir:"",basename:"",siblings:new Set,p:1};async function pn(t,e){const n=await N(t.negotiatedPath,c.O_RDONLY).catch(()=>null);if(!n)return e?.push(`failed to open ${JSON.stringify(t.negotiatedPath)}`),null;const i=()=>(n.close().catch(()=>{}),null),r=await n.stat().catch(i);return r?.isFile()?{handle:n,stats:r,...t}:(e?.push(`${JSON.stringify(t.negotiatedPath)} exists but is not a file`),i())}const mn=/*@__PURE__*/Fe(async t=>{const e=$t(t);if(e.aborted)throw Nt;e.throwIfAborted();const n=await O(y(A(),"upload"));St(t,()=>x(n,{recursive:!0}));let i=0;const r=()=>{if(e.aborted)throw Nt;return y(n,(++i).toString(10).padStart(6,"0"))};return{dir:n,nextFile:r,save:async(t,{mode:n=384}={})=>{const i=r(),o=f(i,{mode:n});try{return await d(t,o,{signal:e}),{path:i,size:o.bytesWritten}}finally{o.close()}}}});function yn(t){const e=lt(t);if(!e.I)throw new TypeError("cannot call acceptBody from shouldUpgrade");if(e.F.signal.aborted)throw Nt;e.oe||e.D||(e.oe=!0,"100-continue"===t.headers.expect?.trim().toLowerCase()&&e.I.H.writeContinue())}function gn(t,{blockRequestHeaders:e=["connection","expect","host","keep-alive","proxy-authorization","transfer-encoding","upgrade","via"],requestHeaders:n=[],blockResponseHeaders:i=["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=o):(a??=new r({keepAlive:!0,...c}),u=C);const l=f.pathname,h=l+(l.endsWith("/")?"":"/"),w="a://a"+h;return Wt((t,r)=>new Promise((o,c)=>{if(r.closed||!r.writable)return c(Nt);const p=$t(t),m=t=>c(p.aborted?Nt:new fe(502,{cause:t})),y=new URL(w+t.url?.substring(1));if(!y.pathname.startsWith(h)&&y.pathname!==l)return c(new fe(400,{message:"directory traversal blocked"}));yn(t);let g={...t.headers};bn(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(r.closed||!r.writable)return c(Nt);if(!r.headersSent){let n={...e.headers};bn(n,i);for(const i of s)n=i(t,e,n);r.writeHead(e.statusCode??200,e.statusMessage,n)}d(e,r).then(o,c)}),d(t,b).catch(m)}))}function bn(t,e){for(const e of ke(t.connection)??[])It(t,e.toLowerCase());for(const n of e)It(t,n)}function vn({trustedProxyCount:t,trustedProxyAddresses:e,trustedHeaders:n}){const i=e?q(e):()=>!0,r=t??(e?Number.POSITIVE_INFINITY:0),o=new Set(n);return Fe(t=>{const e=e=>{if(o.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]?j(e[3]):void 0}),h=[En(t)];if(n)for(const t of n)try{const e=Ae(t);h.push({client:j(e.get("for")),server:j(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(j),e=a??[],n=c??f??u??[];let i=h[0].client;for(let r=0;r<t.length;++r){const o=t[r];h.push({client:o,server:l?.[r]??(i?{...i,port:void 0}:void 0),host:e[r],proto:n[r]}),i=o}}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+r,h.length);for(let t=0;t<d-1;++t)i(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 En=t=>({client:{...j(t.socket.remoteAddress)??_n,port:t.socket.remotePort},server:{...j(t.socket.localAddress)??_n,port:t.socket.localPort},host:t.headers.host,proto:void 0}),_n={family:"alias",address:"_disconnected",port:void 0};function Tn(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 xn(t,e){const n=Tn(0,e);return n.forwarded=kn([En(t)]),n}const Sn=(t,{onlyTrusted:e=!1}={})=>(n,i)=>{const r=Tn(0,i),o=t(n);return r.forwarded=kn([...e?o.trusted:o.outwardChain].reverse()),r};function $n(t,e){let n=t.headers.forwarded;const i=kn([En(t)]);n?n+=", "+i:n=i;const r=Tn(0,e);return r.forwarded=n,r}function kn(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 Nn{constructor(t,{fatal:e=!1}={}){this.se=t,this.ae=e,this.ce=new Uint8Array(4),this.fe=new DataView(this.ce.buffer),this.ue=0}decode(t,{stream:e=!1}={}){const n=t.byteLength,i=[];let r=0;if(this.ue>0){if(r=4-this.ue,n<r)return this.ce.set(t,this.ue),this.ue+=n,"";this.ce.set(t.subarray(0,r),this.ue),i.push(this.fe.getUint32(0,this.se)),this.ue=0}const o=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=r;for(const t=n-3;s<t;s+=4)i.push(o.getUint32(s,this.se));if(e?(s<n&&this.ce.set(t.subarray(s)),this.ue=n-s):(this.ue=0,s<n&&(this.ae?ht(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA"):i.push(65533))),i.length>0){try{return String.fromCodePoint(...i)}catch{this.ae&&ht(new TypeError("The encoded data was not valid for encoding utf-32"),"ERR_ENCODING_INVALID_ENCODED_DATA")}for(let t=0;t<i.length;++t)i[t]>1114111&&(i[t]=65533);return String.fromCodePoint(...i)}return""}}class On extends F{constructor(t){super({transform(e,n){try{const i=t.decode(e,{stream:!0});i&&n.enqueue(i)}catch(t){n.error(t)}},flush(e){try{const n=t.decode(Q);n&&e.enqueue(n)}catch(t){e.error(t)}}})}}const An=new Map;function Rn(t,e){An.set(t.toLowerCase(),e)}function Pn(){Rn("utf-32be",{decoder:t=>new Nn(!1,t)}),Rn("utf-32le",{decoder:t=>new Nn(!0,t)})}function Cn(t,e={}){const n=An.get(t.toLowerCase());if(n)return n.decoder(e);try{return new TextDecoder(t,e)}catch{throw new fe(415,{body:`unsupported charset: ${t}`})}}function Fn(t,e={}){const n=An.get(t.toLowerCase());if(n)return n.decoderStream?n.decoderStream(e):new On(n.decoder(e));try{return new U(t,e)}catch{throw new fe(415,{body:`unsupported charset: ${t}`})}}const Un=["utf-32be",null,"utf-16be","utf-16be","utf-32le","utf-16le",null,"utf-8"];function Mn(t,e,n){const i=Re(t.headers["if-modified-since"]),r=ke(t.headers["if-none-match"]);if(r){if(Dn(e,n,r))return!1}else if(i&&(n.mtimeMs/1e3|0)<=i)return!1;return!0}function Bn(t,e,n){let i=!0;const r=Se(t);return r.etag&&(i&&=Dn(e,n,r.etag)),r.modifiedSeconds&&(i&&=(n.mtimeMs/1e3|0)===r.modifiedSeconds),i}function Dn(t,e,n){if(n.includes("*"))return!0;const i=t.getHeader("etag");if("string"==typeof i){if(n.includes(i))return!0;if(i.startsWith('W/"'))return!1}return!!n.some(t=>t.startsWith('W/"'))&&n.includes(Le(t.getHeader("content-encoding"),e))}class In extends F{constructor(t,e){super({transform(i,r){n+=i.byteLength,n>t?r.error(e):r.enqueue(i)}});let n=0}}function Hn(t,{maxContentBytes:e=Number.POSITIVE_INFINITY,maxNetworkBytes:n=e,maxEncodingSteps:i=1}={}){const r=Ne(t.headers["content-length"]);if(void 0!==r&&r>n)throw new fe(413);const o=ke(t.headers["content-encoding"])??[];if(o.length>i)throw new fe(415,{body:"too many content-encoding stages"});yn(t);let s=D.toWeb(t);void 0===r&&Number.isFinite(n)&&(s=s.pipeThrough(new In(n,new fe(413))));for(const t of o.reverse())s=s.pipeThrough(Jn(t));return Number.isFinite(e)&&(s=s.pipeThrough(new In(e,new fe(413,{body:"decoded content too large"})))),s}function jn(t,e={}){const n=Hn(t,e),i=xe(t)??e.defaultCharset??"utf-8";return n.pipeThrough(Fn(i,e))}async function qn(t,e={}){const n=[];for await(const i of jn(t,e))n.push(i);return n.join("")}async function Ln(t,e={}){const n=await(async(t,e)=>{const n=t.getReader(),i=new Uint8Array(3);let r=0,o=null;for(;;){const t=await n.read(),e=3-r;if(t.done){0===r?(i[0]=1,i[1]=1):1===r&&(i[1]=i[0]),i[2]=i[0],o=null;break}if(o=t.value,o.byteLength>=e){i.set(o.subarray(0,e),r);break}i.set(o,r),r+=o.byteLength}const s=Un[(i[0]?4:0)|(i[1]?2:0)|(i[2]?1:0)];if(!s)throw n.cancel(),new fe(415,{body:"invalid JSON encoding"});const a=Fn(s,e),c=a.writable.getWriter();return r&&c.write(i.subarray(0,r)),o&&c.write(o),n.releaseLock(),c.releaseLock(),t.pipeThrough(a)})(Hn(t,e),e),i=[];for await(const t of n)i.push(t);return JSON.parse(i.join(""))}function Jn(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 I.toWeb(w.createBrotliDecompress())}case"zstd":try{return I.toWeb(w.createZstdDecompress())}catch{throw new fe(415,{body:"unsupported content encoding"})}default:throw new fe(415,{body:"unknown content encoding"})}}function zn(t){if(!t)return null;const[e,n]=_e(t,";"),i=new Map;if(n){const t=/\s*([!#-'*+\-.0-:>-Z^-z|~]+)=(?:([!#-'*+\-.0-:>-Z^-z|~]+)|"((?:[^\x00-\x08\x0a-\x1f"\\\x7f]|\\.)*)")\s*(;|$)/gy;for(;t.lastIndex!==n.length;){const e=t.exec(n);if(!e)return null;const r=e[1].toLowerCase(),o=e[2]??e[3]?.replaceAll(/\\(.)/g,"$1")??"";i.has(r)||i.set(r,o)}}return{mime:e.trim().toLowerCase(),params:i}}function Wn(t,e,n,i){const r=t.byteLength;for(;e<r;){for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)break;if(59!==t[e++])return!1;for(;e<r;++e){const n=t[e];if(32!==n&&9!==n)break}if(e===r)return!1;const o=e;for(;e<r;++e){const n=t[e];if(!Vn[n]){if(61===n)break;return!1}}if(e===r)return!1;const s=t.latin1Slice(o,e).toLowerCase();if("*"===s[s.length-1]){const i=++e;for(;e<r;++e){const n=t[e];if(!Xn[n]){if(39!==n)return!1;break}}if(e===r)return!1;const o=Cn(t.latin1Slice(i,e));for(++e;e<r&&39!==t[e];++e);if(e===r)return!1;if(++e===r)return!1;let a=e;const c=[];for(;e<r;++e){const n=t[e];if(1!==Zn[n]){if(37===n){let n,i;if(e+2<r&&16!==(n=Kn[t[e+1]])&&16!==(i=Kn[t[e+2]])){const r=(n<<4)+i;e>a&&c.push(o.decode(t.subarray(a,e),{stream:!0})),c.push(o.decode(Buffer.from([r]),{stream:!0})),a=(e+=2)+1;continue}return!1}break}}c.push(o.decode(t.subarray(a,e)));const f=c.join("");n.has(s)||n.set(s,f);continue}if(++e===r)return!1;if(34===t[e]){let o=++e,a=!1;const c=[];for(;e<r;++e){const n=t[e];if(92!==n){if(34===n){if(a){o=e,a=!1;continue}c.push(i.decode(t.subarray(o,e)));break}if(a&&(o=e-1,a=!1),!Yn[n])return!1}else a?(o=e,a=!1):(c.push(i.decode(t.subarray(o,e),{stream:!0})),a=!0)}if(e===r)return!1;++e,n.has(s)||n.set(s,c.join(""));continue}let a=e;for(;e<r;++e){const n=t[e];if(!Vn[n]){if(e===a)return!1;break}}n.has(s)||n.set(s,i.decode(t.subarray(a,e)))}return!0}const Gn=[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],Vn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Zn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,...Gn,0,1,0,1],33),t})(),Xn=/*@__PURE__*/(()=>{const t=new Uint8Array(256);return t.set([1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,...Gn,1,0,1,1],33),t})(),Yn=/*@__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})(),Kn=/*@__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 Qn{constructor(t,e){const n=t.byteLength;if(!n||n>65535)throw new RangeError("invalid needle");this.le=t,this.he=e,this.de=null,this.we=0,this.pe=null}push(t){let e=0;const n=t.byteLength,i=this.le,r=i.byteLength-1,o=n-r;let s=-this.we;if(this.we){const a=this.pe,c=this.de,f=i[r];if(o>0){const n=t[s+r];n!==f||t.compare(i,-s,r,0,s+r)?s+=a[n]:(this.he(!0,Q,0,0,!0),this.we=0,e=s+=r+1)}const u=o<0?o:0;for(;s<u;){const n=t[s+r];if(n===f&&!c.compare(i,0,-s,this.we+s,this.we)&&!t.compare(i,-s,r,0,s+r)){this.he(!0,c,0,this.we+s,!1),this.we=0,e=s+=r+1;break}s+=a[n]}const l=this.we;if(l>0){const e=i[0];for(;s<0;){const r=c.subarray(0,l).indexOf(e,l+s);if(-1===r){s=0;break}const o=l-r;if(!c.compare(i,1,o,r+1,l)&&!t.compare(i,o,o+n))return r&&(this.he(!1,c,0,r,!1),c.copy(c,0,r,o)),c.set(t,o),void(this.we+=n-r);s=r+1-l}this.he(!1,c,0,l,!1),this.we=0}}for(;s<o;){const n=t.indexOf(i,s);if(-1!==n){if(this.he(!0,t,e,n,!0),n===o+1)return;e=s=n+r+1}else s=o}const a=i[0];for(;s<n;){const o=t.indexOf(a,s);if(-1===o)return void this.he(!1,t,e,n,!0);if(!t.compare(i,1,n-o,o+1)){if(!this.de){this.de=Buffer.allocUnsafe(r),this.pe=new Uint16Array(256).fill(r+1);for(let t=0;t<r;++t)this.pe[i[t]]=r-t}return t.copy(this.de,0,o),this.we=n-o,void(o>e&&this.he(!1,t,e,o,!0))}s=o+1}n>e&&this.he(!1,t,e,n,!0)}destroy(){const t=this.we;t&&this.de&&this.he(!1,this.de,0,t,!1),this.we=0}}class ti extends H{constructor({limits:t={},preservePath:e,highWaterMark:n,fileHwm:i,defParamCharset:r="utf-8",defCharset:o="utf-8"},s){super({autoDestroy:!0,emitClose:!0,highWaterMark:n,write:ei,destroy:ni,final:ii});const a=s.get("boundary");if(!a)throw new fe(400,{body:"multipart boundary not found"});if(a.length>70)throw new fe(400,{body:"multipart boundary too long"});const c=Cn(r),f={autoDestroy:!0,emitClose:!0,highWaterMark:i},u=t.fieldSize??1048576,l=t.fileSize??Number.POSITIVE_INFINITY,h=t.fieldNameSize??100,d=t.files??Number.POSITIVE_INFINITY,w=t.fields??Number.POSITIVE_INFINITY,p=t.parts??Number.POSITIVE_INFINITY;let m,y,g,b,v,E=0,_=0,T=0,x=-1;this.me=0,this.ye=!1;let S=!1;const $=new ri(t=>{this.ge=void 0;const n=t["content-disposition"];if(!n)return void(x=-1);const i=((t,e)=>{if(!t.byteLength)return null;const n=new Map;let i=0;for(;i<t.byteLength;++i)if(!Vn[t[i]]){if(!Wn(t,i,n,e))return null;break}return{type:t.latin1Slice(0,i).toLowerCase(),params:n}})(Buffer.from(n,"latin1"),c);if("form-data"!==i?.type)return void(x=-1);if(v=i.params.get("name"),void 0===v)return this.emit("error",new fe(400,{body:"missing field name"})),void(x=-1);S=v.length>h,S&&(v=v.substring(0,h));let r=i.params.get("filename*")??i.params.get("filename");void 0===r||e||(r=(t=>{for(let e=t.length;e-- >0;)if("/"===t[e]||"\\"===t[e]){t=t.slice(e+1);break}return".."===t||"."===t?"":t})(r));const s=zn(t["content-type"]);b=s?.mime??"text/plain";const a=s?.params.get("charset")?.toLowerCase()??o;if(y=Cn(a),g=t["content-transfer-encoding"]?.toLowerCase()??"7bit","application/octet-stream"===b||void 0!==r){if(T++===d&&this.emit("filesLimit"),T>d||0===this.listenerCount("file"))return void(x=-1);this.be=new oi(f,this),++this.me,this.emit("file",v,this.be,{nameTruncated:S,filename:r,encoding:g,mimeType:b}),x=l}else{if(_++===w&&this.emit("fieldsLimit"),_>w||0===this.listenerCount("field"))return void(x=-1);m="",x=u}});let k=0;const N=Buffer.from(`\r\n--${a}`,"latin1");this.ve=new Qn(N,(t,e,n,i,r)=>{try{if(n===i)return;if(k){if(1===k){if(13===e[n])k=2;else{if(45!==e[n])return void(k=0);k=3}if(++n===i)return}if(2!==k){if(k=0,45!==e[n])return;return this.ye=!0,void(this.ve=ai)}if(k=0,10!==e[n++])return;if(E++===p&&this.emit("partsLimit"),E>p)return;if(this.ge=$,n===i)return}if(this.ge){const t=this.ge.push(e,n,i);if(-1===t)return this.ge=void 0,$.reset(),void this.emit("error",new fe(400,{body:"malformed part header"}));if(t===i)return;n=t}if(x>=0){const t=Math.min(i,n+x);if(x-=i-n,this.be){if(t>n){let i;r?i=e.subarray(n,t):(i=Buffer.allocUnsafe(t-n),e.copy(i,0,n,t)),this.be.push(i)||(this.be.Ee??=this._e,this._e=void 0)}x<0&&(this.be.emit("limit"),this.be.truncated=!0)}else void 0!==m&&(m+=e.latin1Slice(n,t))}}finally{t&&(this.ge?(this.emit("error",new fe(400,{body:"unexpected end of headers"})),this.ge=void 0):this.be?(this.be.push(null),this.be=void 0):void 0!==m&&(this.emit("field",v,y.decode(Buffer.from(m,"latin1")),{nameTruncated:S,valueTruncated:x<0,encoding:g,mimeType:b}),m=void 0),k=1,x=-1)}}),this.write(ci)}Te(){if(this.ge)return new fe(400,{body:"malformed part header"});const t=this.be;return t&&(this.be=void 0,t.destroy(new fe(400,{body:"unexpected end of file"}))),this.ye?null:new fe(400,{body:"unexpected end of form"})}}function ei(t,e,n){this._e=n,this.ve.push(t);const i=this._e;i&&(this._e=void 0,i())}function ni(t,e){this.ge=void 0,this.ve=ai,t??=this.Te();const n=this.be;n&&(this.be=void 0,n.destroy(t??void 0)),e(t)}function ii(t){if(this.ve.destroy(),!this.ye)return t(new fe(400,{body:"unexpected end of form"}));this.me?this.xe=()=>t(this.Te()):t(this.Te())}class ri{constructor(t){this.Se=Object.create(null),this.$e=0,this.ke=0,this.m=0,this.lt="",this.Ne="",this.Oe=0,this.he=t}reset(){this.Se=Object.create(null),this.$e=0,this.ke=0,this.m=0,this.lt="",this.Ne="",this.Oe=0}push(t,e,n){let i=e,r=e;const o=Math.min(n,e+16384-this.ke);for(;r<o;)switch(this.m){case 0:for(;r<o&&Vn[t[r]];++r);if(r>i&&(this.lt+=t.latin1Slice(i,r)),r<o){if(58!==t[r])return-1;if(!this.lt)return-1;++r,this.m=1}break;case 1:for(;r<o;++r){const e=t[r];if(32!==e&&9!==e){i=r,this.m=2;break}}break;case 2:switch(this.Oe){case 0:for(;r<o;++r){const e=t[r];if(e<32||127===e){if(13!==e)return-1;++this.Oe;break}}this.Ne+=t.latin1Slice(i,r),++r;break;case 1:if(10!==t[r++])return-1;++this.Oe;break;case 2:{const e=t[r];32===e||9===e?(i=r,this.Oe=0):(++this.$e<2e3&&(this.Se[this.lt.toLowerCase()]??=this.Ne),13===e?(++this.Oe,++r):(i=r,this.Oe=0,this.m=0,this.lt="",this.Ne=""));break}case 3:{if(10!==t[r++])return-1;const e=this.Se;return this.reset(),this.he(e),r}}}return o<n?-1:(this.ke+=o-e,o)}}class oi extends D{constructor(t,e){super({...t,read:si}),this.truncated=!1,this.once("end",()=>{if(si.call(this),0===--e.me&&e.xe){const t=e.xe;e.xe=void 0,process.nextTick(t)}})}}function si(t){const e=this.Ee;e&&(this.Ee=void 0,e())}const ai={push:()=>{},destroy:()=>{}},ci=/*@__PURE__*/Buffer.from("\r\n");class fi extends H{constructor({limits:t={},highWaterMark:e,defCharset:n="utf-8"},i){super({autoDestroy:!0,emitClose:!0,highWaterMark:e,write:ui,final:li}),this.Ae=i.get("charset")??n,this.Re=t.fieldSize??1048576,this.Pe=t.fields??Number.POSITIVE_INFINITY,this.Ce=t.fieldNameSize??100,this.Fe=0,this.Ue=!0,this.Me="",this.Be=this.Ce,this.De=0,this.Ie="",this.He=!1,this.je=-2,this.qe=/^utf-?8$/i.test(this.Ae)?1:/^(latin-?1|iso[\-_]?8859-?1|(us-)?ascii)$/i.test(this.Ae)?2:0,this.Le=Cn(this.Ae)}}function ui(t,e,n){if(!t.byteLength)return n();if(this.Fe>=this.Pe)return this.Fe||t===yi||(++this.Fe,this.emit("fieldsLimit")),n();const i=t.byteLength;let r=0,o=this.je;if(-2!==o){if(-1===o){if(16===(o=Kn[t[r++]]))return n(new fe(400,{body:"malformed urlencoded form"}));if(this.De|=o,r===i)return this.je=o,n()}const e=Kn[t[r++]];if(16===e)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Me+=String.fromCharCode((o<<4)+e),this.je=-2,r===i)return n()}for(mi[hi]=1,mi[di]=1,mi[wi]=1,mi[pi]=this.Ue?1:0;;){const e=r;for(;r<i&&!mi[t[r]];++r);if(r>e&&this.Be>=0&&((this.Be-=r-e)<0?this.Me+=t.latin1Slice(e,r+this.Be):this.Me+=t.latin1Slice(e,r)),r===i)return n();switch(t[r++]){case hi:for(;;){if(--this.Be<0){mi[hi]=0,mi[wi]=0;break}if(r===i)return this.je=-1,n();const e=Kn[t[r++]];if(16===e)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.De|=e,r===i)return this.je=e,n();const o=Kn[t[r++]];if(16===o)return n(new fe(400,{body:"malformed urlencoded form"}));if(this.Me+=String.fromCharCode((e<<4)+o),r===i)return n();if(t[r]!==hi)break;r++}break;case di:const e=!this.qe||1===this.qe&&8&this.De?this.Le.decode(Buffer.from(this.Me,"latin1")):this.Me;if(this.Ue?(e||this.Be<0)&&this.emit("field",this.Me,"",{nameTruncated:this.Be<0,valueTruncated:!1,encoding:this.Ae,mimeType:"text/plain"}):(this.emit("field",this.Ie,e,{nameTruncated:this.He,valueTruncated:this.Be<0,encoding:this.Ae,mimeType:"text/plain"}),this.Ie="",this.He=!1,this.Ue=!0,mi[pi]=1),mi[hi]=1,mi[wi]=1,this.Me="",this.Be=this.Ce,this.De=0,++this.Fe===this.Pe&&t!==yi)return this.emit("fieldsLimit"),n();break;case wi:--this.Be<0?(mi[hi]=0,mi[wi]=0):this.Me+=" ";break;case pi:this.Ie=!this.qe||1===this.qe&&8&this.De?this.Le.decode(Buffer.from(this.Me,"latin1")):this.Me,this.He=this.Be<0,this.Ue=!1,mi[pi]=0,mi[hi]=1,mi[wi]=1,this.Me="",this.De=0,this.Be=this.Re}if(r===i)return n()}}function li(t){ui.call(this,yi,void 0,t)}const hi=37,di=38,wi=43,pi=61,mi=/*@__PURE__*/new Uint8Array(256),yi=/*@__PURE__*/Buffer.from([di]);function gi(t,{closeAfterErrorDelay:e=500,...n}={}){W(e,"closeAfterErrorDelay",!0);const i=((t,e={})=>{const n=t["content-type"];if(!n)throw new fe(400,{body:"missing content-type"});const i=zn(n);if(!i)throw new fe(400,{body:"malformed content-type"});const r="application/x-www-form-urlencoded"===i.mime?fi:"multipart/form-data"!==i.mime||e.blockMultipart?null:ti;if(!r)throw new fe(415);return new r(e,i.params)})(t.headers,n);yn(t);const r=new V,o=(n,o)=>{if(r.fail(new fe(n,o)),i.removeAllListeners(),t.unpipe(i),t.resume(),e>=0){const n=setTimeout(()=>t.socket.destroy(),e);t.once("end",()=>clearTimeout(n))}};i.on("field",(t,e,{nameTruncated:n,valueTruncated:i,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):i?o(400,{body:`value for ${JSON.stringify(t)} too long`}):void r.push({name:t,encoding:s,mimeType:a,type:"string",value:e}):o(400,{body:"missing field name"})),i.on("file",(t,e,{nameTruncated:n,filename:i,encoding:s,mimeType:a})=>t?n?o(400,{body:`field name ${JSON.stringify(t)}... too long`}):void(i?(e.once("limit",()=>o(400,{body:`uploaded file for ${JSON.stringify(t)}: ${JSON.stringify(i)} too large`})),r.push({name:t,encoding:s,mimeType:a,type:"file",value:e,filename:i})):e.resume()):o(400,{body:"missing field name"})),t.once("error",e=>{t.readableAborted?r.fail(Nt):o(500,{body:"request error",headers:{connection:"close"},cause:e})}),i.once("error",t=>o(400,{body:"error parsing form data",cause:t})),i.once("partsLimit",()=>o(400,{body:"too many parts"})),i.once("filesLimit",()=>o(400,{body:"too many files"})),i.once("fieldsLimit",()=>o(400,{body:"too many fields"}));const s=()=>r.close("complete");return i.once("close",s),St(t,s),t.pipe(i),r}async function bi(t,e={}){const n=new FormData,i=new Map;for await(const r of gi(t,e))if("file"===r.type){const o=r.value;let s=await(e.preCheckFile?.({fieldName:r.name,filename:r.filename,encoding:r.encoding,mimeType:r.mimeType,maxBytes:e.limits?.fileSize}));const a=t=>{if("function"==typeof s){const e=s;return s=void 0,e({actualBytes:t})}};St(t,()=>a(0));const c=await mn(t),f=await c.save(o,{mode:384});await a(f.size);const l=new File([await u(f.path)],r.filename,{type:r.mimeType});i.set(l,f.path),n.append(r.name,l)}else{let t=r.value;e.trimAllValues&&(t=t.trim()),n.append(r.name,t)}return Object.assign(n,{getTempFilePath(t){const e=i.get(t);if(!e)throw new 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 vi="win32"===/*@__PURE__*/R();function Ei(t,{rejectPotentiallyUnsafe:e=!0}={}){let n=[];const i=ft(t);if(i){if("/"===i.C)return[];n=i.C.split("/")}else{const e=tt(t).pathname;if("/"===e)return[];n=e.split("/").map(decodeURIComponent)}if(""!==n[0])throw new fe(400,{body:"invalid path"});if(n.shift(),e){const t=vi?Ti:_i;if(n.some(e=>t.test(e)||e.includes(v)))throw new fe(400,{body:"invalid path"});if(n.slice(0,n.length-1).includes(""))throw new fe(400,{body:"invalid path"})}return n}const _i=/[\x00-\x1F\x7F/]|^(\.\.?|~)$/,Ti=/[\x00-\x1F"*/:<>?\\|\x7F]|^[\s.]*$|^(CON|PRN|AUX|NUL|(COM|LPT)[\d\xB9\xB2\xB3])(\.|$)/i,xi=t=>new Promise(e=>{const n=()=>{t.cork(),e()};t instanceof s?t.write(Q,n):t.once("drain",n),t.uncork()});async function Si(t,e,{delimiter:n=",",newline:i="\n",quote:r='"',encoding:o="utf-8",headerRow:a,end:c=!0}={}){"string"==typeof n&&(n=Buffer.from(n,o)),"string"==typeof i&&(i=Buffer.from(i,o));const f="string"==typeof r?Buffer.from(r,o):r,u=r+r,l=e=>{if(!e)return!0;const n=e.includes(r);return!n&&$i.test(e)?t.write(e,o):(t.write(f),n?t.write(e.replaceAll(r,u),o):t.write(e,o),t.write(f))};t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","text/csv; charset="+o+(a?"; header=present":!1===a?"; header=absent":"")),t.cork();try{t.write(Q);for await(const r of e){if(t.writableAborted)break;let e=0;if(Symbol.iterator in r)for(const i of r)e&&t.write(n),l(i)||await xi(t),++e;else for await(const i of r)e&&t.write(n),l(i)||await xi(t),++e;t.write(i)||await xi(t)}}finally{t.uncork()}c&&t.end()}const $i=/^[^"':;,\\\r\n\t ]*$/i;function ki(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 Ni{constructor(t){(t=>"Je"in t&&"function"==typeof t.pipe)(t)&&(t=D.toWeb(t)),this.ht=t.getReader(),this.ze=null,this.We=0,this.m=0}getRange(t,e){if(e<t)throw new RangeError("invalid range");if(t<this.We)throw new RangeError("non-sequential range");if(this.m)throw new TypeError("previous range still active");let n=e-t+1,i=t-this.We;this.We=e+1,this.m=1;const r=this,o=(t,e)=>{const r=t.byteLength;r<=i?i-=r:r>i+n?(this.ze=t.subarray(i+n),e.enqueue(t.subarray(i,i+n)),n=0):i>0?(e.enqueue(t.subarray(i)),n-=r-i,i=0):(e.enqueue(t),n-=r)};return new B({start(t){if(r.ze){const e=r.ze;r.ze=null,o(e,t)}},async pull(t){if(n<=0)return r.m=0,void t.close();const e=await r.ht.read();e.done?t.error(new RangeError("range exceeds content")):"string"==typeof e.value?o(Buffer.from(e.value,"utf-8"),t):e.value instanceof Uint8Array?o(e.value,t):t.error(new TypeError("invalid stream type: must contain bytes or UTF-8 text"))}})}async close(){await this.ht.cancel(),this.ht.releaseLock()}}function Oi(t,{forceSequential:e=!1,mergeOverlapDistance:n=100}={}){const i=[];if(n>=0)for(const e of t.ranges){let t=null,r=0;for(let o=0;o<i.length;++o){const s=i[o];e.end>=s.start-n-1&&s.end>=e.start-n-1?t?(++r,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)):r>0&&(i[o-r]=s)}t?i.length-=r:i.push({...e})}else i.push(...t.ranges);if(e)for(let t=0;t<i.length-1;++t)if(i[t].start>i[t+1].start){i.sort((t,e)=>t.start-e.start);break}return{ranges:i,totalSize:t.totalSize}}async function Ai(t,e,n,i){if(e.closed||!e.writable)return;if("string"==typeof n||ki(n)||(i=Oi(i,{mergeOverlapDistance:0,forceSequential:!0})),1===i.ranges.length){const r=i.ranges[0];if(e.setHeader("content-length",r.end-r.start+1),e.setHeader("content-range",`bytes ${r.start}-${r.end}/${i.totalSize??"*"}`),e.writeHead(206),"HEAD"===t.method)return void e.end();const o=await Ri(n);try{if(e.closed||!e.writable)return;await d(o.Ge(r.start,r.end),e)}finally{o.Ve&&await o.Ve()}return}const r=e.getHeader("content-type"),o=h()+h()+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";e.setHeader("content-type",`multipart/byteranges; boundary=${o}`);const s=i.ranges.map(t=>({o:[`--${o}`,...wt({"content-type":r,"content-range":`bytes ${t.start}-${t.end}/${i.totalSize??"*"}`}),"",""].join("\r\n"),Ze:t})),a=`--${o}--`;let c=a.length;for(const{o:t,Ze: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 Ri(n);try{for(const{o:t,Ze:n}of s){if(e.closed||!e.writable)return;e.write(f+t,"ascii"),await d(u.Ge(n.start,n.end),e,{end:!1}),f="\r\n"}e.end(f+a)}finally{u.Ve&&await u.Ve()}}async function Ri(t){if("string"==typeof t){const e=await N(t,"r");return{Ge:(t,n)=>e.createReadStream({start:t,end:n,autoClose:!1}),Ve:()=>e.close()}}if(ki(t))return{Ge:(e,n)=>t.createReadStream({start:e,end:n,autoClose:!1})};{const e=new Ni(t);return{Ge:(t,n)=>e.getRange(t,n),Ve:()=>e.close()}}}async function Pi(t,e,n,i=null,r){if(!e.closed&&e.writable&&(i||("string"==typeof n?i=await S(n):ki(n)&&(i=await n.stat()),!e.closed&&e.writable))){if(i){if("GET"===t.method||"HEAD"===t.method){if(!Mn(t,e,i))return void e.writeHead(304).end();e.setHeader("accept-ranges","bytes");const o=$e(t,i.size,r);if(o&&Bn(t,e,i))return Ai(t,e,n,Oi(o,r))}e.setHeader("content-length",i.size)}if(e.writeHead(e.statusCode,e.statusMessage),"HEAD"!==t.method)return"string"==typeof n?n=a(n):ki(n)&&(n=n.createReadStream({start:0,autoClose:!1})),d(n,e);e.end()}}function Ci(t,e,{replacer:n,space:i,undefinedAsNull:r=!1,encoding:o="utf-8",end:a=!0}={}){const c=JSON.stringify(e,n,i??void 0)??(r?"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,o))),a?t.end(c,o):c&&t.write(c,o)}async function Fi(t,e,{replacer:n=null,space:i=null,undefinedAsNull:r=!1,encoding:o="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 i&&(i=" ".substring(0,i));const c={Xe:e=>t.write(e,o),Ye:()=>xi(t),Ke:n,Qe:i??""};if(t instanceof s&&!t.headersSent&&!t.hasHeader("content-type")&&t.setHeader("content-type","application/json"),e=Mi(null,"",e,c),Bi(e))r&&c.Xe("null");else{t.cork(),t.write(Q);try{await Ui(c,e,i?"\n":"")}finally{t.uncork()}}a&&t.end()}async function Ui(t,e,n){const i=(i,r,o)=>{t.Xe(i);const s=n+t.Qe,a=t.Qe?": ":":";let c=!0;return{i:async(n,i)=>{const r=Mi(e,n,i,t);o&&Bi(r)||(c?c=!1:t.Xe(","),t.Xe(s),o&&(t.Xe(JSON.stringify(n))||await t.Ye(),t.Xe(a)),await Ui(t,r,s))},Ve:()=>{c||t.Xe(n),t.Xe(r)}}};if(null===e||"object"!=typeof e||e instanceof String||e instanceof Number||e instanceof Boolean||e instanceof Function||e instanceof Symbol||e instanceof BigInt||Di(e))t.Xe(JSON.stringify(e)??"null")||await t.Ye();else if(e instanceof D){t.Xe('"');for await(const n of e){if("string"!=typeof n)throw new TypeError("Readables must have an encoding");const e=JSON.stringify(n);t.Xe(e.substring(1,e.length-1))||await t.Ye()}t.Xe('"')}else if(e instanceof Map){const t=i("{","}",!0);for(const[n,i]of e)await t.i(n,i);t.Ve()}else if(Ii(e)){let t=0;const n=i("[","]",!1);for(const i of e)await n.i(String(t++),i);n.Ve()}else if(Hi(e)){let t=0;const n=i("[","]",!1);for await(const i of e)await n.i(String(t++),i);n.Ve()}else{const t=i("{","}",!0);for(const[n,i]of Object.entries(e))await t.i(n,i);t.Ve()}}function Mi(t,e,n,i){return i.Ke&&(n=i.Ke.call(t,e,n)),n&&"object"==typeof n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),n}const Bi=t=>void 0===t||"function"==typeof t||"symbol"==typeof t||t instanceof Function||t instanceof Symbol,Di=t=>JSON.isRawJSON?.(t)??!1,Ii=t=>Symbol.iterator in t,Hi=t=>Symbol.asyncIterator in t;class ji{constructor(t,e,{keepaliveInterval:n=15e3,softCloseReconnectDelay:i=500,softCloseReconnectStagger:r=2e3}={}){W(n,"keepaliveInterval",!0),this.tn=e,this.en=n,this.F=new AbortController,e.setHeader("content-type","text/event-stream"),e.setHeader("x-accel-buffering","no"),e.setHeader("cache-control","no-store"),e.writeHead(200),e.flushHeaders(),this.ping=this.ping.bind(this),this.nn(),t.once("close",()=>this.close()),yt(t,()=>this.close(i,r))}get signal(){return this.F.signal}get open(){return!this.F.signal.aborted}nn(){this.en>0&&(this.rn=setTimeout(this.ping,this.en))}ping(){!this.F.signal.aborted&&this.tn.writable&&(clearTimeout(this.rn),this.tn.write(":\n\n",()=>this.nn()))}send({event:t,id:e,data:n,reconnectDelay:i=-1}){return this.sendFields([["event",t],["id",e],["data",n],["retry",i>=0?String(0|i):void 0]])}async sendFields(t){let e;this.F.signal.throwIfAborted(),this.tn.cork();try{let n=!1;for(const[e,i]of t){if(void 0===i)continue;const t=i.split(/(?<=\n)|(?<=\r)(?!\n)/g);for(let n of t)this.tn.write(e)," "===n[0]?this.tn.write(": "):this.tn.write(":"),this.tn.write(n);/[\r\n]$/.test(i)?(this.tn.write(e),this.tn.write(":\n")):this.tn.write("\n"),n=!0}if(!n)return;clearTimeout(this.rn),this.tn.write("\n",()=>e())}finally{this.tn.uncork()}await new Promise(t=>{e=t}),this.nn()}async close(t=0,e=0){if(this.F.signal.aborted){if(this.tn.closed)return;return new Promise(t=>this.tn.once("close",t))}this.en=0,clearTimeout(this.rn),this.F.abort(new Error("ServerSentEvents closed")),await new Promise(n=>{if(this.tn.writable&&(t>0||e>0)){const i=t+Math.random()*e;this.tn.end(`retry:${0|i}\n\n`,n)}else this.tn.end(n)})}}const qi=async(t,{mode:e="dynamic",fallback:n,verbose:i,callback:r=Li,...o}={})=>{const s=await dn.build(E(process.cwd(),t),o);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 o=Ei(t,f),s=[];let l=await u.find(o,t.headers,i?s:void 0);if(!l){if(!a)return i&&un(t,new Error(s.join(", ")),"serving static content"),Ot;if(n=!0,l=await u.find(a,t.headers,s),!l)throw new fe(500,{message:`failed to find fallback file: ${s.join(", ")}`})}try{n&&(e.statusCode=c);const i=l.headers["content-type"]??rn(m(l.canonicalPath));e.setHeader("content-type",i);const o=l.headers["content-language"];o&&e.setHeader("content-language",o);const s=l.headers["content-encoding"];s&&"identity"!==s&&e.setHeader("content-encoding",s);const a=l.headers.vary;if(a){const t=e.getHeader("vary")??"";e.setHeader("vary",(t?t+", ":"")+a)}await r(t,e,l,n),await Pi(t,e,l.handle,l.stats)}finally{l.handle.close().catch(()=>{})}}}};function Li(t,e,n){e.setHeader("etag",Le(e.getHeader("content-encoding"),n.stats)),e.setHeader("last-modified",n.stats.mtime.toUTCString())}class Ji extends Error{constructor(t,{message:e,closeReason:n,...i}={}){super(e,i),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 zi(t,{softCloseStatusCode:e=Ji.GOING_AWAY,...n}={}){const i=(i,r,o)=>new Promise((s,a)=>{const c=new t({...n,noServer:!0,clientTracking:!1});c.once("wsClientError",a),c.handleUpgrade(i,r,o,t=>{c.off("wsClientError",a),o=Q,s({return:t,onError:e=>{const n=Z(e,Ji);if(n)return void t.close(n.closeCode,n.closeReason);const i=Z(e,fe)??new fe(500),r=i.statusCode>=500?Ji.INTERNAL_SERVER_ERROR:4e3+i.statusCode;t.close(r,i.statusMessage)},softCloseHandler:n=>t.close(e,n)})})});return t=>Pt(t,i)}class Wi{constructor(t,e){this.data=t,this.isBinary=e}get text(){if(this.isBinary)throw new Ji(Ji.UNSUPPORTED_DATA,{closeReason:"expected text"});return this.data.toString("utf-8")}get binary(){if(!this.isBinary)throw new Ji(Ji.UNSUPPORTED_DATA,{closeReason:"expected binary"});return this.data}}class Gi{constructor(t,{limit:e=-1,signal:n}={}){this.sn=new V;const i=e=>{t.off("message",o),t.off("close",r),this.sn.close(new Error(e))},r=()=>i("connection closed"),o=(t,n)=>{void 0!==n?this.sn.push(new Wi(t,n)):"string"==typeof t?this.sn.push(new Wi(Buffer.from(t,"utf-8"),!1)):this.sn.push(new Wi(t,!0)),e>0&&0===--e&&this.detach()};this.detach=()=>{},n?.aborted?this.sn.close(n.reason):2===t.readyState||3===t.readyState?this.sn.close(new Error("connection closed")):(t.on("message",o),t.on("close",r),n?.addEventListener("abort",()=>i("signal aborted")),this.detach=()=>i("WebSocket listener detached"))}next(t){return this.sn.shift(t)}[Symbol.asyncIterator](){return this.sn[Symbol.asyncIterator]()}}function Vi(t,{timeout:e,signal:n}={}){const i=new Gi(t,{limit:1,signal:n});return i.next(e).finally(()=>i.detach())}function Zi(t){const e=lt(t);return"GET"===t.method&&(e.D?.has("websocket")??!1)}const Xi=t=>t.headers.origin??pt(t.headers["sec-websocket-origin"]),Yi=(t,e=5e3)=>async n=>{if(!Zi(n))return;const i=await t(n);let r;try{r=await Vi(i,{timeout:e})}catch(t){if((i.readyState??0)>=2)throw Nt;throw new Ji(Ji.POLICY_VIOLATION,{closeReason:"timeout waiting for authentication token",cause:t})}if(r.isBinary)throw new Ji(Ji.UNSUPPORTED_DATA,{closeReason:"authentication token must be sent as text"});return r.data.toString("utf-8")};export{V as BlockingQueue,Ot as CONTINUE,dn as FileFinder,fe as HTTPError,At as NEXT_ROUTE,Rt as NEXT_ROUTER,Ve as Negotiator,Ce as Property,G as Queue,ne as Router,Nt as STOP,ji as ServerSentEvents,ye as WebListener,Ji as WebSocketError,Wi as WebSocketMessage,Gi as WebSocketMessages,yn as acceptBody,Pt as acceptUpgrade,St as addTeardown,Vt as anyHandler,Mn as checkIfModified,Bn as checkIfRange,Dn as compareETag,sn as compressFileOffline,an as compressFilesInDir,Yt as conditionalErrorHandler,en as decompressMime,xt as defer,Ct as delegateUpgrade,un as emitError,Zt as errorHandler,qi as fileServer,Z as findCause,Je as generateStrongETag,Le as generateWeakETag,$t as getAbortSignal,Jt as getAbsolutePath,X as getAddressURL,Te as getAuthorization,Ln as getBodyJson,Hn as getBodyStream,qn as getBodyText,jn as getBodyTextStream,xe as getCharset,bi as getFormData,gi as getFormFields,Se as getIfRange,rn as getMime,Lt as getPathParameter,qt as getPathParameters,Ee as getQuery,$e as getRange,Ei as getRemainingPathComponents,be as getSearch,ve as getSearchParams,Cn as getTextDecoder,Fn as getTextDecoderStream,Xi as getWebSocketOrigin,Ie as hasAuthScope,bt as isSoftClosed,Zi as isWebSocketRequest,ln as jsonErrorHandler,zi as makeAcceptWebSocket,q as makeAddressTester,vn as makeGetClient,Fe as makeMemo,mn as makeTempFileStorage,Yi as makeWebSocketFallbackTokenFetcher,Ge as negotiateEncoding,Vi as nextWebSocketMessage,j as parseAddress,gn as proxy,Re as readHTTPDateSeconds,Ne as readHTTPInteger,Ae as readHTTPKeyValues,Oe as readHTTPQualityValues,ke as readHTTPUnquotedCommaSeparated,tn as readMimeTypes,Rn as registerCharset,nn as registerMime,Pn as registerUTF32,Tn as removeForwarded,xn as replaceForwarded,Wt as requestHandler,He as requireAuthScope,De as requireBearerAuth,Qe as resetMime,zt as restoreAbsolutePath,Sn as sanitiseAndAppendForwarded,Si as sendCSVStream,Pi as sendFile,Ci as sendJSON,Fi as sendJSONStream,Ai as sendRanges,Li as setDefaultCacheHeaders,yt as setSoftCloseHandler,$n as simpleAppendForwarded,Oi as simplifyRange,K as stringPredicate,he as toListeners,Xt as typedErrorHandler,Gt as upgradeHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-listener",
3
- "version": "0.13.2",
3
+ "version": "0.14.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",
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 s}from"node:path";import{createServer as r}from"node:http";import{Router as i,requestHandler as n,addTeardown as a,CONTINUE as c,proxy as f,Negotiator as p,fileServer as l,getSearch as h,getQuery as u,getPathParameter as m,WebListener as d,findCause as g,HTTPError as w,compressFilesInDir as y,readMimeTypes as b,decompressMime as x,resetMime as $,registerMime as v}from"./index.js";const S=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"}],["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"}]]),j=new Map([["zstd",{match:"zstd",file:"{file}.zst"}],["brotli",{match:"br",file:"{file}.br"}],["gzip",{match:"gzip",file:"{file}.gz"}],["deflate",{match:"deflate",file:"{file}.deflate"}]]);const k=e=>(t,o)=>{if(t!==e)throw new C(`expected ${JSON.stringify(e)}`,o,8);return e},N=e=>(t,o)=>{if(!e.has(t))throw new C(`expected one of ${JSON.stringify(e)}`,o,7);return t},O=e=>(t,o)=>{const s=[];let r=9;for(const i of e)try{return i(t,o)}catch(e){if(e instanceof C){if(e.p>r)continue;e.p!==r&&(r=e.p,s.length=0)}else r=-1;s.push(e)}throw 1===s.length?s[0]:new AggregateError(s)},E=e=>(t,o)=>{if(!Array.isArray(t))throw new C("expected list, got "+typeof t,o);return t.map((t,s)=>e(t,{...o,path:`${o.path}[${s}]`}))},P=(e,t)=>{if("boolean"!=typeof e)throw new C("expected boolean, got "+typeof e,t);return e},T=(e,t,o)=>(s,r)=>{if("number"!=typeof s)throw new C("expected number, got "+typeof s,r);if(e&&(0|s)!==s)throw new C(`expected integer, got ${s}`,r);if("number"==typeof t&&s<t)throw new C(`value cannot be less than ${t}`,r);if("number"==typeof o&&s>o)throw new C(`value cannot be greater than ${o}`,r);return s},J=(e,t)=>(r,i)=>{if("string"!=typeof r)throw new C("expected string, got "+typeof r,i);if(e&&!e.test(r))throw new C(`expected string matching ${e}`,i);if("uri-reference"===t&&i.file){if(r.startsWith("file://"))return"file://"+s(o(i.file),r.substring(7));if(!r.includes("://"))return s(o(i.file),r)}return r},A=(e,t,o)=>(s,r)=>{if("object"!=typeof s)throw new C("expected object, got "+typeof s,r);if(!s)throw new C("expected object, got null",r);if(Array.isArray(s))throw new C("expected object, got list",r);const i=[],n=new Set;for(const[o,a]of Object.entries(s)){n.add(o);const s=(e.get(o)??t)(a,{...r,path:`${r.path}.${o}`});void 0!==s&&i.push([o,s])}for(const e of o)if(!n.has(e))throw new C(`missing required property ${JSON.stringify(e)}`,r);for(const[t,o]of e)if(!n.has(t)){const e=o(void 0,{...r,path:`${r.path}.${t}`});void 0!==e&&i.push([t,e])}return Object.fromEntries(i)},I=e=>e,q=(e,t)=>{throw new C("unknown property",t)};class C extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const D=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function M(e,t){return t.replaceAll(/\$\{([^${}:]+)(?::-(([^}\\]|\\.)*))?\}/g,(t,o,s)=>{let r;return r="?"===o?h(e):"?"===o[0]?u(e,o.substring(1)):m(e,o),"string"==typeof r?r:Array.isArray(r)?r.join("/"):s??""})}class G{constructor(e,t){this.t=!1,this.o=!1,this.i=!1,this.l=e,this.h=t,this.u=new Map}async set(e){if(!this.o&&!this.i)try{this.o=!0;const t=new Set,o=[];for(let s=0;s<e.length;++s){const r=e[s],i=r.port;i<=0||i>65535?this.l(0,`servers[${s}] must have a specific port from 1 to 65535`):t.has(i)?this.l(0,`skipping servers[${s}] because port ${i} has already been defined`):(t.add(i),o.push(async()=>{const e=await this.m(r,this.u.get(i));e?this.u.set(i,e):this.u.delete(i)}))}this.t||=o.length>0;for(const[e,s]of this.u)t.has(e)||(o.push(s.close),this.u.delete(e));await Promise.all(o.map(e=>e())),this.i?this.$():this.u.size?this.l(1,"all servers ready"):this.l(1,"no servers configured")}finally{this.o=!1}}async m({port:e,host:t,options:o,mount:s},h){const u=this.h("34",`http://${t}:${e}`),m=await(async(e,t=()=>{})=>{const o=new i;o.use(n((e,o)=>{const s=Date.now();return a(e,()=>{const r=Date.now()-s;t({method:e.method??"GET",path:e.url??"/",status:o.statusCode,duration:r})}),c}));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 p(t.options.negotiation):void 0;o.mount(t.path,await l(t.dir,{...t.options,negotiator:e}))}break;case"proxy":o.mount(t.path,f(t.target,t.options));break;case"fixture":const e=(e,o)=>{for(const[s,r]of Object.entries(t.headers))"string"==typeof r?o.setHeader(s,M(e,r)):"number"==typeof r?o.setHeader(s,r):o.setHeader(s,r.map(t=>M(e,t)));o.statusCode=t.status,o.end(M(e,t.body))};"GET"===t.method&&o.onRequest("HEAD",t.path,e),o.onRequest(t.method,t.path,e);break;case"redirect":o.at(t.path,n((e,o)=>{o.setHeader("location",M(e,t.target)),o.statusCode=t.status,o.end()}))}return o})(s,o.logRequests?e=>{const t=this.h("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),s=this.h(H[e.status/100|0]??"",String(e.status)),r=this.h("2",`(${e.duration}ms)`);this.l(0,`${u} ${t} ${o} ${s} ${r}`)}:()=>{}),y=new d(m);let b,x;if(y.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:s}=e.detail;(g(t,w)?.statusCode??500)>=500&&this.l(0,`${u} ${this.h("91","error")}: ${o} ${s?.url} ${t}`)}),h&&t===h.host&&((e,t)=>{for(const o of B)if(e[o]!==t[o])return!1;return!0})(o,h.options))b=h.server,this.l(2,`${u} updated`),h.detach();else{if(h?(this.l(2,`${u} ${this.h("2","restarting (step 1: shutdown)")}`),await h.close(),this.l(2,`${u} ${this.h("2","restarting (step 2: start)")}`)):this.l(2,`${u} ${this.h("2","starting")}`),this.i)return;b=r(o),b.setTimeout(o.socketTimeout),x=R(b,e,t,o.backlog)}const $=y.attach(b,o);return x&&(await x,await new Promise(e=>setTimeout(e,1)),this.l(2,`${u} ready`)),{host:t,options:o,server:b,detach:()=>$("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=$("shutdown",o.shutdownTimeout,!0,()=>{b.close(()=>{this.l(2,`${u} closed`),e()}),b.closeAllConnections()}).countConnections();t>0&&this.l(2,`${u} ${this.h("2",`closing (remaining connections: ${t})`)}`)})}}async $(){this.u.size&&(this.l(2,this.h("2","shutting down")),await Promise.all([...this.u.values()].map(e=>e.close()))),this.t&&this.l(2,"shutdown complete")}shutdown(){this.i||(this.i=!0,this.o||this.$())}}const H=["","37","32","36","31","41;97"],R=async(e,t,o,s=511)=>new Promise((r,i)=>{e.once("error",i),e.listen(t,o,s,()=>{e.off("error",i),r()})}),B=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function U(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 L=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),W=["none","ready","progress"];process.on("SIGUSR1",()=>{});let _=2;const F=(e,t)=>e<=_&&process.stderr.write(t+"\n");function Y(e){process.stdin.destroy(),F(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",Y),process.on("uncaughtException",Y);const Z=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,K=(e=>{const t=[];for(let o=0;o<e.length;++o){const s=e[o];if("--"===s)continue;const r=/^--([^ =\-][^ =]*)=(.*)$/.exec(s);if(r){t.push([r[1],r[2]]);continue}const i=/^-([^ =]*)([^ =])=(.*)$/.exec(s);if(i&&"-"!==s[1]){for(const e of i[1])t.push(["-"+e,""]);t.push(["-"+i[2],i[3]]);continue}if("-"!==s[0]||"-"===s){if(0!==o)throw new Error(`value without key: ${s}`);t.push(["",s]);continue}let n=e[o+1];if(n&&"-"===n[0]&&n.length>1&&(n=void 0),void 0!==n&&++o,"-"===s[1])t.push([s.slice(2),n??""]);else{for(const e of s.slice(1,s.length-1))t.push(["-"+e,""]);t.push(["-"+s[s.length-1],n??""])}}const o=new Map;for(const[e,s]of t){const t=(S.get(e)??e).toLowerCase(),r=z.get(t);if(!r)throw new Error(`unknown flag: ${e}`);let i;switch(r.type){case"string":i=s;break;case"number":i=Number.parseFloat(s);break;case"boolean":i=["","on","true","yes","y","1"].includes(s.toLowerCase())}if(r.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(i)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,i)}}return o})(process.argv.slice(2));if(K.get("version")||K.get("help")){const s=JSON.parse(await e(t(o(new URL(import.meta.url).pathname),"package.json"),"utf-8"));process.stdout.write(`${s.name} ${s.version}\n`),K.get("help")&&process.stdout.write((Q=s.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 ${Q} -- [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 ${Q} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${Q} /dev/null --proxy https://example.com`,"",` npx ${Q} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`,"",` npx ${Q} . --write-compressed --min-compress 500 --brotli --gzip`,"",` npx ${Q} . --write-compressed --brotli --no-serve`]).join("\n")+"\n"),process.exit(0)}var Q;(async()=>{const s=new G(F,Z);process.on("unhandledRejection",()=>s.shutdown()),process.on("uncaughtException",()=>s.shutdown());const r=function(e){const t=o=>{const s=o.$ref;if(s&&s.startsWith("#/$defs/")){const t=D(e.$defs,s.substring(8));if(!t)throw new Error(`unable to find ${s} in schema`);o={...t,...o}}const r=((e,t)=>{if(void 0!==e.const)return k(e.const);if(e.enum)return N(new Set(e.enum));if(e.anyOf)return O(e.anyOf.map(t));switch(e.type){case"array":return E(t(e.items));case"boolean":return P;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;return A(new Map(Object.entries(e.properties??{}).map(([e,o])=>[e,t(o)])),"object"==typeof o?t(o):o?I:q,e.required??[]);case"string":let s=null;return e.pattern&&(s=new RegExp(e.pattern)),J(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)=>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(),s.shutdown()}async function n(){const t=await(async(t,o)=>{const s=e=>o.get(e)??[],r=e=>o.get(e),i=e=>o.get(e),n=r("config-file"),a=r("config-json"),c=i("port"),f=r("host"),p=r("dir")||".",l=s("ext").map(e=>e.startsWith(".")?e:`.${e}`),h=r("404"),u=r("spa"),m=r("proxy"),d=i("min-compress"),g=s("mime"),w=s("mime-types"),y=r("log");if(Number(Boolean(n))+Number(Boolean(a))+Number(Boolean(m))>1)throw new Error("multiple config files are not supported");let b;if(n)b=t(JSON.parse(await e(n,"utf-8")),{file:n,path:""});else if(a)b=t(JSON.parse(a),{file:"",path:""});else{let e;u?e={statusCode:200,filePath:u}:h&&(e={statusCode:404,filePath:h});const o=[{type:"files",dir:p,options:{fallback:e}}];m&&o.push({type:"proxy",target:m}),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 s of o.mount)if("files"===s.type){s.options.negotiation??=[];let o=s.options.negotiation.find(t=>t.type===e);o||(o={type:e,options:[]},s.options.negotiation=[...s.options.negotiation,o]),o.options.find(e=>e.match===t.match)||o.options.push(t)}};for(const[e,t]of j)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!==d&&(b.minCompress=d),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})(r,K);_=W.indexOf(t.log),await(async t=>{const o=[];for(const s of Array.isArray(t)?t:[t])"string"!=typeof s?o.push(new Map(Object.entries(s))):s.startsWith("file://")?o.push(b(await e(s.substring(7),"utf-8"))):o.push(x(s));$();for(const e of o)v(e)})(t.mime),t.writeCompressed&&await(async(e,t,o)=>{let s=0;for(const r of e)for(const e of r.mount)if("files"===e.type){const r=e.options.negotiation?.find(e=>"encoding"===e.type)?.options;if(!r?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}o(2,`compressing files in ${e.dir} using ${r.map(e=>e.match).join(", ")}`);const i=await y(e.dir,r,{minCompression:t}),n=U(i.filter(({mime:e})=>e.startsWith("text/"))),a=U(i.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${L(n.rawSize)} / ${L(n.bestSize)} compressed`),o(2,`other: ${L(a.rawSize)} / ${L(a.bestSize)} compressed`),s+=n.created+a.created}o(2,`${((e,t,o=t+"s")=>1===e?`1 ${t}`:`${e} ${o}`)(s,"compressed file")} written`)})(t.servers,t.minCompress,F),t.noServe?i():s.set(t.servers)}function a(){return F(2,"refreshing config"),n()}n(),process.on("SIGHUP",()=>a()),process.stdin.on("data",e=>{e.includes("\n")&&a()}),process.on("SIGINT",()=>{F(2,""),i()})})();
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 i}from"node:http";import{Router as n,requestHandler as a,addTeardown as c,CONTINUE as f,proxy as p,Negotiator as l,fileServer as h,getSearch as u,getQuery as m,getPathParameter as d,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"}]]),E=new Map([["zstd",{match:"zstd",file:"{file}.zst"}],["brotli",{match:"br",file:"{file}.br"}],["gzip",{match:"gzip",file:"{file}.gz"}],["deflate",{match:"deflate",file:"{file}.deflate"}]]);const N=e=>(t,o)=>{if(t!==e)throw new G(`expected ${JSON.stringify(e)}`,o,8);return e},O=e=>(t,o)=>{if(!e.has(t))throw new G(`expected one of ${JSON.stringify(e)}`,o,7);return t},P=e=>(t,o)=>{const r=[];let s=9;for(const i of e)try{return i(t,o)}catch(e){if(e instanceof G){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)},T=e=>(t,o)=>{if(!Array.isArray(t))throw new G("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 G("expected boolean, got "+typeof e,t);return e},A=(e,t,o)=>(r,s)=>{if("number"!=typeof r)throw new G("expected number, got "+typeof r,s);if(e&&(0|r)!==r)throw new G(`expected integer, got ${r}`,s);if("number"==typeof t&&r<t)throw new G(`value cannot be less than ${t}`,s);if("number"==typeof o&&r>o)throw new G(`value cannot be greater than ${o}`,s);return r},I=()=>(e,t)=>{if("string"!=typeof e)throw new G("expected string, got "+typeof e,t);try{return new RegExp(e)}catch{throw new G("expected regular expression",t)}},q=(e,t)=>(s,i)=>{if("string"!=typeof s)throw new G("expected string, got "+typeof s,i);if(e&&!e.test(s))throw new G(`expected string matching ${e}`,i);if("uri-reference"===t&&i.file){if(s.startsWith("file://"))return"file://"+r(o(i.file),s.substring(7));if(!s.includes("://"))return r(o(i.file),s)}return s},C=(e,t,o)=>(r,s)=>{if("object"!=typeof r)throw new G("expected object, got "+typeof r,s);if(!r)throw new G("expected object, got null",s);if(Array.isArray(r))throw new G("expected object, got list",s);const i=[],n=new Set;for(const[o,a]of Object.entries(r)){n.add(o);const r=(e.get(o)??t)(a,{...s,path:`${s.path}.${o}`});void 0!==r&&i.push([o,r])}for(const e of o)if(!n.has(e))throw new G(`missing required property ${JSON.stringify(e)}`,s);for(const[t,o]of e)if(!n.has(t)){const e=o(void 0,{...s,path:`${s.path}.${t}`});void 0!==e&&i.push([t,e])}return Object.fromEntries(i)},D=e=>e,M=(e,t)=>{throw new G("unknown property",t)};class G extends Error{constructor(e,t,o=0){super(`${e} at ${t.path||"root"}`),this.p=o}}const H=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function R(e,t){return t.replaceAll(/\$\{([^${}:]+)(?::-(([^}\\]|\\.)*))?\}/g,(t,o,r)=>{let s;return s="?"===o?u(e):"?"===o[0]?m(e,o.substring(1)):d(e,o),"string"==typeof s?s:Array.isArray(s)?s.join("/"):r??""})}class B{constructor(e,t){this.t=!1,this.o=!1,this.i=!1,this.l=e,this.h=t,this.u=new Map}async set(e){if(!this.o&&!this.i)try{this.o=!0;const t=new Set,o=[];for(let r=0;r<e.length;++r){const s=e[r],i=s.port;i<=0||i>65535?this.l(0,`servers[${r}] must have a specific port from 1 to 65535`):t.has(i)?this.l(0,`skipping servers[${r}] because port ${i} has already been defined`):(t.add(i),o.push(async()=>{const e=await this.m(s,this.u.get(i));e?this.u.set(i,e):this.u.delete(i)}))}this.t||=o.length>0;for(const[e,r]of this.u)t.has(e)||(o.push(r.close),this.u.delete(e));await Promise.all(o.map(e=>e())),this.i?this.$():this.u.size?this.l(1,"all servers ready"):this.l(1,"no servers configured")}finally{this.o=!1}}async m({port:e,host:t,options:o,mount:r},s){const u=this.h("34",`http://${t}:${e}`),m=await(async(e,t=()=>{})=>{const o=new n;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 h(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,R(e,s)):"number"==typeof s?o.setHeader(r,s):o.setHeader(r,s.map(t=>R(e,t)));o.statusCode=t.status,o.end(R(e,t.body))};"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)=>{o.setHeader("location",R(e,t.target)),o.statusCode=t.status,o.end()}))}return o})(r,o.logRequests?e=>{const t=this.h("1",e.method.replaceAll(/[^a-zA-Z0-9\-_]/g,"?")),o=encodeURI(e.path),r=this.h(U[e.status/100|0]??"",String(e.status)),s=this.h("2",`(${e.duration}ms)`);this.l(0,`${u} ${t} ${o} ${r} ${s}`)}:()=>{}),d=new g(m);let b,x;if(d.addEventListener("error",e=>{e.preventDefault();const{error:t,context:o,request:r}=e.detail;(w(t,y)?.statusCode??500)>=500&&this.l(0,`${u} ${this.h("91","error")}: ${o} ${r?.url} ${t}`)}),s&&t===s.host&&((e,t)=>{for(const o of W)if(e[o]!==t[o])return!1;return!0})(o,s.options))b=s.server,this.l(2,`${u} updated`),s.detach();else{if(s?(this.l(2,`${u} ${this.h("2","restarting (step 1: shutdown)")}`),await s.close(),this.l(2,`${u} ${this.h("2","restarting (step 2: start)")}`)):this.l(2,`${u} ${this.h("2","starting")}`),this.i)return;b=i(o),b.setTimeout(o.socketTimeout),x=L(b,e,t,o.backlog)}const $=d.attach(b,o);return x&&(await x,await new Promise(e=>setTimeout(e,1)),this.l(2,`${u} ready`)),{host:t,options:o,server:b,detach:()=>$("restart",o.restartTimeout),close:()=>new Promise(e=>{const t=$("shutdown",o.shutdownTimeout,!0,()=>{b.close(()=>{this.l(2,`${u} closed`),e()}),b.closeAllConnections()}).countConnections();t>0&&this.l(2,`${u} ${this.h("2",`closing (remaining connections: ${t})`)}`)})}}async $(){this.u.size&&(this.l(2,this.h("2","shutting down")),await Promise.all([...this.u.values()].map(e=>e.close()))),this.t&&this.l(2,"shutdown complete")}shutdown(){this.i||(this.i=!0,this.o||this.$())}}const U=["","37","32","36","31","41;97"],L=async(e,t,o,r=511)=>new Promise((s,i)=>{e.once("error",i),e.listen(t,o,r,()=>{e.off("error",i),s()})}),W=["requestTimeout","keepAliveTimeout","keepAliveTimeoutBuffer","connectionsCheckingInterval","headersTimeout","highWaterMark","maxHeaderSize","noDelay","requireHostHeader","keepAlive","keepAliveInitialDelay","uniqueHeaders","backlog","socketTimeout"];function _(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 F=e=>e<2e3?`${e}B`.padStart(8," "):`${(e/1024).toFixed(1)}kB`.padStart(8," "),Y=["none","ready","progress"];process.on("SIGUSR1",()=>{});let Z=2;const K=(e,t)=>e<=Z&&process.stderr.write(t+"\n");function Q(e){process.stdin.destroy(),K(0,e instanceof Error?e.message:String(e))}process.on("unhandledRejection",Q),process.on("uncaughtException",Q);const V=process.stderr.isTTY&&!process.env.NO_COLOR?(e,t)=>e?`\x1b[${e}m${t}\x1b[0m`:t:(e,t)=>t,X=(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 i=/^-([^ =]*)([^ =])=(.*)$/.exec(r);if(i&&"-"!==r[1]){for(const e of i[1])t.push(["-"+e,""]);t.push(["-"+i[2],i[3]]);continue}if("-"!==r[0]||"-"===r){if(0!==o)throw new Error(`value without key: ${r}`);t.push(["",r]);continue}let n=e[o+1];if(n&&"-"===n[0]&&n.length>1&&(n=void 0),void 0!==n&&++o,"-"===r[1])t.push([r.slice(2),n??""]);else{for(const e of r.slice(1,r.length-1))t.push(["-"+e,""]);t.push(["-"+r[r.length-1],n??""])}}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 i;switch(s.type){case"string":i=r;break;case"number":i=Number.parseFloat(r);break;case"boolean":i=["","on","true","yes","y","1"].includes(r.toLowerCase())}if(s.multi){let e=o.get(t);e||(e=[],o.set(t,e)),e.push(i)}else{if(o.has(t))throw new Error(`multiple values for ${t}`);o.set(t,i)}}return o})(process.argv.slice(2));if(X.get("version")||X.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`),X.get("help")&&process.stdout.write((ee=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 ${ee} -- [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 ${ee} . --port 3000 --gzip --mime="foo=text/x-foo" --mime="bar=text/x-bar"`,"",` npx ${ee} /dev/null --proxy https://example.com`,"",` npx ${ee} -C '{"servers":[{"port":8080,"mount":[{"type":"files","dir":"."}]}]}'`,"",` npx ${ee} . --write-compressed --min-compress 500 --brotli --gzip`,"",` npx ${ee} . --write-compressed --brotli --no-serve`]).join("\n")+"\n"),process.exit(0)}var ee;(async()=>{const r=new B(K,V);process.on("unhandledRejection",()=>r.shutdown()),process.on("uncaughtException",()=>r.shutdown());const i=function(e){const t=o=>{const r=o.$ref;if(r&&r.startsWith("#/$defs/")){const t=H(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 N(e.const);if(e.enum)return O(new Set(e.enum));if(e.anyOf)return P(e.anyOf.map(t));switch(e.type){case"array":return T(t(e.items));case"boolean":return J;case"integer":return A(!0,e.minimum,e.maximum);case"number":return A(!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 n(){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),i=e=>o.get(e),n=s("config-file"),a=s("config-json"),c=i("port"),f=s("host"),p=s("dir")||".",l=r("ext").map(e=>e.startsWith(".")?e:`.${e}`),h=s("404"),u=s("spa"),m=s("proxy"),d=i("min-compress"),g=r("mime"),w=r("mime-types"),y=s("log");if(Number(Boolean(n))+Number(Boolean(a))+Number(Boolean(m))>1)throw new Error("multiple config files are not supported");let b;if(n)b=t(JSON.parse(await e(n,"utf-8")),{file:n,path:""});else if(a)b=t(JSON.parse(a),{file:"",path:""});else{let e;u?e={statusCode:200,filePath:u}:h&&(e={statusCode:404,filePath:h});const o=[{type:"files",dir:p,options:{fallback:e}}];m&&o.push({type:"proxy",target:m}),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.match===t.match)||o.options.push(t)}};for(const[e,t]of E)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!==d&&(b.minCompress=d),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})(i,X);Z=Y.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 i of e)for(const e of i.mount)if("files"===e.type){const i=e.options.negotiation?.find(e=>"encoding"===e.feature);if(!i?.options?.length){o(2,`skipping ${e.dir} because no compression is configured`);continue}const n=i.match?` matching ${i.match}`:"";o(2,`compressing files in ${e.dir}${n} using ${i.options.map(e=>e.match).join(", ")}`);const a=b(i.match,!0),c=await x(e.dir,i.options,{minCompression:t,filter:(e,t)=>!["image","video","audio","font"].includes(t.split("/")[0])&&a(s(e))}),f=_(c.filter(({mime:e})=>e.startsWith("text/"))),p=_(c.filter(({mime:e})=>!e.startsWith("text/")));o(2,`text: ${F(f.rawSize)} / ${F(f.bestSize)} compressed`),o(2,`other: ${F(p.rawSize)} / ${F(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,K),t.noServe?n():r.set(t.servers)}function c(){return K(2,"refreshing config"),a()}a(),process.on("SIGHUP",()=>c()),process.stdin.on("data",e=>{e.includes("\n")&&c()}),process.on("SIGINT",()=>{K(2,""),n()})})();
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":{"type":"string"}},"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,"properties":{"type":{"enum":["mime","language","encoding"]},"options":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["match","file"],"properties":{"match":{"type":"string"},"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":"/"}}]},"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"}},"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":["match","file"],"properties":{"match":{"$ref":"#/$defs/stringOrRegex"},"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}}}