deserved 0.4.0 → 0.5.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # deserved
2
2
 
3
- Tiny, zero-dependency Bun static file server.
3
+ Tiny (12.9 kB gzip), zero-dep Bun static server.
4
4
 
5
5
  ```bash
6
6
  bunx deserved .
package/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{resolve as W5}from"path";var c="0.4.0";import{statSync as i0,watch as m0}from"fs";import{networkInterfaces as p0}from"os";import{relative as l0,resolve as h0}from"path";import{readdirSync as Z0,realpathSync as s,statSync as C}from"fs";import{extname as Y0,join as r,normalize as N0,resolve as a,sep as t}from"path";import{promisify as X0}from"util";import{gzip as D0}from"zlib";var{escapeHTML:S}=globalThis.Bun;var J0=new TextEncoder,n="application/octet-stream",V0={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function j0($,x){let O=$.type;if(O&&O!==n&&O!=="")return O;let G=Y0(x).toLowerCase();return V0[G]??n}function q($){let x=$.split(";")[0]?.trim().toLowerCase()??"";return x.startsWith("text/")||x==="application/javascript"||x==="text/javascript"||x==="application/json"||x==="application/xml"||x==="image/svg+xml"||x.endsWith("+json")||x.endsWith("+xml")}function u0($){return $.startsWith("text/html")}function I0($,x,O=""){return`"${$}-${Math.trunc(x)}${O}"`}function k0($,x){let O=$.headers.get("If-None-Match");if(!O)return!1;return O.split(",").some((G)=>G.trim().replace(/^W\//,"")===x)}function B0($,x){let O=$.headers.get("If-Modified-Since");if(!O)return!1;let G=Date.parse(O);if(Number.isNaN(G))return!1;return Math.trunc(x/1000)*1000<=G}function w0($,x,O){return $.headers.get("If-None-Match")?k0($,x):B0($,O)}function U0($,x,O){let G=$.headers.get("If-Range");if(!G)return!0;if(G.startsWith('"')||G.startsWith("W/"))return G===x;let Z=Date.parse(G);if(Number.isNaN(Z))return!1;return Z===Math.trunc(O/1000)*1000}function i($){let x=$.headers.get("Accept");if(!x||x==="*/*")return!0;return x.includes("text/html")||x.includes("application/xhtml")}function F0($){let x=$.headers.get("Accept-Encoding")??"";if(x.includes("zstd"))return"zstd";if(x.includes("gzip"))return"gzip";return null}function S0($){if($.startsWith("/__"))return!1;let x=$.slice($.lastIndexOf("/")+1);if(!x)return!0;if(x.includes("."))return!1;return!0}function _0($,x,O){if(!x)return null;let G=O.replace(/^\/+/,""),Z=z0(G);for(let N of Z){let W=e($,N);if(!W)continue;let Q=$0(x,W);if(!Q)continue;try{let Y=C(Q);if(Y.isFile())return{path:Q,file:Bun.file(Q),size:Y.size,mtimeMs:Y.mtimeMs,kind:L0(N)}}catch{}}return null}var K0=4096,T0=500;function P0($,x,O){let G=new Map;function Z(N){let W=G.get(N);if(W&&(O||Date.now()-W.at<T0)){if(W.value===null)return null;try{let Y=C(W.value.real);if(Y.isFile())return{path:W.value.real,file:Bun.file(W.value.real),size:Y.size,mtimeMs:Y.mtimeMs,kind:W.value.kind}}catch{}}let Q=_0($,x,N);if(G.size>=K0)G.clear();return G.set(N,{value:Q?{real:Q.path,kind:Q.kind}:null,at:Date.now()}),Q}return{resolveCached:Z,invalidate:()=>G.clear(),size:()=>G.size}}function L0($){if($.endsWith("/index.html"))return"dir-index";if($.endsWith(".html")&&!$.endsWith("/index.html"))return"html-ext";return"file"}function z0($){if(!$||$===".")return["index.html"];let x=$.endsWith("/")?$.slice(0,-1):$;if(!x)return["index.html"];if($.endsWith("/"))return[`${x}/index.html`];return[x,`${x}.html`,`${x}/index.html`]}function e($,x){let O=a($),G=N0(r(O,x));if(G!==O&&!G.startsWith(O+t))return null;return G}function $0($,x){try{let O=s(x);if(O!==$&&!O.startsWith($+t))return null;return O}catch{return null}}var m=new Map;function H0($){let x=m.get($);if(x===void 0){try{x=s($)}catch{x=null}m.set($,x)}return x}function f0($,x,O){if(!x)return null;let G=O.replace(/^\/+/,"").replace(/\/+$/,""),Z=e($,G||".");if(!Z)return null;let N=$0(x,Z);if(!N)return null;try{if(C(N).isDirectory())return N}catch{return null}return null}function E0($){if($===null)return"-";if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} kB`;return`${($/1048576).toFixed(1)} MB`}function M0($){if($===null)return"-";let x=new Date($),O=x.getFullYear(),G=String(x.getMonth()+1).padStart(2,"0"),Z=String(x.getDate()).padStart(2,"0"),N=String(x.getHours()).padStart(2,"0"),W=String(x.getMinutes()).padStart(2,"0");return`${O}-${G}-${Z} ${N}:${W}`}function A0($){return Z0($,{withFileTypes:!0}).filter((x)=>!x.name.startsWith(".")).map((x)=>{let O=x.isDirectory(),G=null,Z=null;if(!O)try{let N=C(r($,x.name));G=N.size,Z=N.mtimeMs}catch{}return{name:x.name,dir:O,size:G,mtimeMs:Z}}).sort((x,O)=>{if(x.dir!==O.dir)return x.dir?-1:1;return x.name.localeCompare(O.name)})}function v0($,x){let O=$.endsWith("/")?$:`${$}/`,G=p(O),Z=C0($),N=x.map((Q)=>{let Y=R0(G,encodeURIComponent(Q.name))+(Q.dir?"/":""),X=Q.dir?`${Q.name}/`:Q.name,J=E0(Q.size),u=M0(Q.mtimeMs);return` <li><a href="${S(Y)}">${S(X)}</a> <span class="meta">${S(J)}</span> <span class="meta">${S(u)}</span></li>`}).join(`
4
- `),W=Z!==null?` <li><a href="${S(p(Z))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
3
+ import{resolve as $t}from"path";var U="0.5.0";import{statSync as Ze,watch as et}from"fs";import{networkInterfaces as tt}from"os";import{relative as nt,resolve as rt}from"path";import{readdirSync as be,realpathSync as re,statSync as z}from"fs";import{extname as xe,isAbsolute as ye,join as se,resolve as oe,sep as ie}from"path";var{escapeHTML:S}=globalThis.Bun;var we=new TextEncoder,j="application/octet-stream",ve={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function Re(e,t){let n=e.type;if(n&&n!==j&&n!=="")return n;let r=xe(t).toLowerCase();return ve[r]??j}function Ce(e){let t=e.indexOf(";"),n=(t===-1?e:e.slice(0,t)).trim().toLowerCase();return n.startsWith("text/")||n==="application/javascript"||n==="text/javascript"||n==="application/json"||n==="application/xml"||n==="image/svg+xml"||n.endsWith("+json")||n.endsWith("+xml")}function $e(e){return e.startsWith("text/html")}function Ee(e,t,n=""){return`"${e}-${Math.trunc(t)}${n}"`}function q(e){return e.startsWith("W/")?e.slice(2):e}function Se(e,t){if(e.indexOf(",")===-1)return q(e.trim())===t;return e.split(",").some((n)=>q(n.trim())===t)}function Te(e,t){let n=e.headers.get("If-Modified-Since");if(!n)return!1;let r=Date.parse(n);if(Number.isNaN(r))return!1;return Math.trunc(t/1000)*1000<=r}function Ae(e,t,n){let r=e.headers.get("If-None-Match");return r?Se(r,t):Te(e,n)}function Me(e,t,n){let r=e.headers.get("If-Range");if(!r)return!0;if(r.startsWith('"')||r.startsWith("W/"))return r===t;let a=Date.parse(r);if(Number.isNaN(a))return!1;return a===Math.trunc(n/1000)*1000}function Oe(e){let t=e.headers.get("Accept");if(!t||t==="*/*")return!0;return t.includes("text/html")||t.includes("application/xhtml")}function De(e){let t=e.headers.get("Accept-Encoding")??"";if(t.includes("zstd"))return"zstd";if(t.includes("gzip"))return"gzip";return null}function Ie(e){if(e.startsWith("/__"))return!1;let t=e.lastIndexOf("/");if(t===e.length-1)return!0;return e.indexOf(".",t+1)===-1}function Pe(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,""),a=Ne(r);for(let o of a){let i=ae(e,o);if(!i)continue;let s=le(t,i);if(!s)continue;let c=ce(s,He(o));if(c)return c}return null}function ce(e,t){try{let n=z(e);if(n.isFile())return{path:e,file:Bun.file(e),size:n.size,mtimeMs:n.mtimeMs,kind:t}}catch{}return null}var G=4096;function V(e,t){if(e.size<t)return;let n=e.keys().next().value;if(n!==void 0)e.delete(n)}function A(e,t,n){e.delete(t),e.set(t,n)}var K=500;function ze(e,t,n){let r=new Map,a=new Map;function o(s){let c=r.get(s);if(c&&(n||Date.now()-c.at<K)){if(c.value===null)return A(r,s,c),null;if(n)return A(r,s,c),c.value;let d=ce(c.value.path,c.value.kind);if(d)return A(r,s,c),d}let u=Pe(e,t,s);return V(r,G),r.set(s,{value:u,at:Date.now()}),u}function i(s){let c=a.get(s);if(c&&(n||Date.now()-c.at<K)){if(c.value===null)return A(a,s,c),null;try{if(z(c.value).isDirectory())return A(a,s,c),c.value}catch{}}let u=ke(e,t,s);return V(a,G),a.set(s,{value:u,at:Date.now()}),u}return{resolveCached:o,resolveDirCached:i,invalidate:()=>{r.clear(),a.clear()},size:()=>r.size}}function He(e){if(e.endsWith("/index.html"))return"dir-index";if(e.endsWith(".html"))return"html-ext";return"file"}function Ne(e){if(!e||e===".")return["index.html"];let t=e.endsWith("/"),n=t?e.slice(0,-1):e;if(!n)return["index.html"];if(t)return[`${n}/index.html`];return[n,`${n}.html`,`${n}/index.html`]}function ae(e,t){let n=ye(e)?e:oe(e),r=se(n,t);if(r!==n&&!r.startsWith(n+ie))return null;return r}function le(e,t){try{let n=re(t);if(n!==e&&!n.startsWith(e+ie))return null;return n}catch{return null}}function Fe(e){try{return re(e)}catch{return null}}function ke(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,"").replace(/\/+$/,""),a=ae(e,r||".");if(!a)return null;let o=le(t,a);if(!o)return null;try{return z(o).isDirectory()?o:null}catch{return null}}function Be(e){if(e===null)return"-";if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} kB`;return`${(e/1048576).toFixed(1)} MB`}function Le(e){if(e===null)return"-";let t=new Date(e),n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${a} ${o}:${i}`}function _e(e){let t=be(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.name.startsWith("."))continue;let a=r.isDirectory(),o=null,i=null;if(!a)try{let s=z(se(e,r.name));o=s.size,i=s.mtimeMs}catch{}n.push({name:r.name,dir:a,size:o,mtimeMs:i})}return n.sort((r,a)=>{if(r.dir!==a.dir)return r.dir?-1:1;return r.name.localeCompare(a.name)})}function We(e,t){let n=e.endsWith("/")?e:`${e}/`,r=Y(n),a=Ue(e),o=S(e),i=t.map((c)=>{let u=je(r,encodeURIComponent(c.name))+(c.dir?"/":""),d=c.dir?`${c.name}/`:c.name,p=Be(c.size),m=Le(c.mtimeMs);return` <li><a href="${S(u)}">${S(d)}</a> <span class="meta">${S(p)}</span> <span class="meta">${S(m)}</span></li>`}).join(`
4
+ `),s=a!==null?` <li><a href="${S(Y(a))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
5
5
  `:"";return`<!DOCTYPE html>
6
6
  <html lang="en">
7
7
  <head>
8
8
  <meta charset="utf-8">
9
9
  <meta name="viewport" content="width=device-width, initial-scale=1">
10
- <title>Index of ${S($)}</title>
10
+ <title>Index of ${o}</title>
11
11
  <style>
12
12
  :root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
13
13
  body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
@@ -20,19 +20,21 @@ import{resolve as W5}from"path";var c="0.4.0";import{statSync as i0,watch as m0}
20
20
  </style>
21
21
  </head>
22
22
  <body>
23
- <h1>Index of ${S($||"/")}</h1>
23
+ <h1>Index of ${o||"/"}</h1>
24
24
  <ul>
25
- ${W}${N}
25
+ ${s}${i}
26
26
  </ul>
27
27
  </body>
28
28
  </html>
29
- `}function C0($){if($==="/"||$==="")return null;let x=$.replace(/\/+$/,""),O=x.lastIndexOf("/");if(O<=0)return"/";return x.slice(0,O+1)}function p($){return $.split("/").map(encodeURIComponent).join("/")}function R0($,x){if($==="/")return`/${x}`;return`${$.replace(/\/+$/,"")}/${x}`}function x0($,x){let O=a($.root),G=H0(O),Z=P0(O,G,$.watch),N=c0(),W=async function(Y){let X=new URL(Y.url),J=Y.method.toUpperCase(),u;if(X.pathname.includes("%"))try{u=decodeURIComponent(X.pathname)}catch{let I=new Response("Bad Request",{status:400});return _(J,400,X.pathname,$.quiet),z(J,H(I,$))}else u=X.pathname;try{return await q0(Y,J,u,X,$,x,O,G,Z.resolveCached,N.getCompressed)}catch(I){console.error(I);let D=new Response("Internal Server Error",{status:500});return _(J,500,X.pathname,$.quiet),z(J,H(D,$))}};return W.invalidateResolutionCache=Z.invalidate,W.invalidateCompressedCache=N.invalidate,W.resolutionCacheSize=Z.size,W.compressedCacheBytes=N.bytes,W}function l($,x){let O=`${$.pathname}/${$.search}`,G=new Response(null,{status:301,headers:{Location:O}});return H(G,x)}async function q0($,x,O,G,Z,N,W,Q,Y,X){let J=(D)=>{return _(x,D.status,O,Z.quiet),z(x,H(D,Z))};if(x!=="GET"&&x!=="HEAD"){let D=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return J(D)}if(Z.watch&&O===A){let D=new Response(O0,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return J(D)}if(Z.watch&&O===v&&N){let D=N.subscribe();return _(x,200,O,Z.quiet),H(D,Z)}if(O===A||O===v)return z(x,H(new Response("Not Found",{status:404}),Z));let u=Y(O);if(u){if(u.kind==="dir-index"&&!O.endsWith("/")){let k=l(G,Z);return _(x,k.status,O,Z.quiet),z(x,k)}let D=await d(X,$,u,Z);return J(D)}if(Z.spa&&i($)&&S0(O)){let D=Y("/");if(D){let k=await d(X,$,D,Z,!0);return J(k)}}if(Z.dir){let D=f0(W,Q,O);if(D){if(!O.endsWith("/")){let B=l(G,Z);return _(x,B.status,O,Z.quiet),z(x,B)}let k=A0(D),j=v0(O,k),w=Z.watch?M(j):j,U=new Response(w,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return J(U)}}if(i($)){let D=Y("/404.html");if(D){let k=await D.file.text(),j=Z.watch?M(k):k,w=new Response(j,{status:404,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return J(w)}}let I=new Response("Not Found",{status:404});return J(I)}var g0=67108864,b0=X0(D0);async function y0($,x){if($==="zstd")return new Uint8Array(await Bun.zstdCompress(x));return new Uint8Array(await b0(x))}function c0(){let $=new Map,x=0,O=new Map;function G(W,Q){let Y=$.get(W);if(Y)$.delete(W),x-=Y.data.byteLength;$.set(W,Q),x+=Q.data.byteLength;while(x>g0&&$.size>1){let X=$.keys().next().value;if(X===void 0)break;let J=$.get(X);if($.delete(X),J)x-=J.data.byteLength}}let Z=async(W,Q,Y)=>{let X=`${W.key}:${Q}`,J=$.get(X);if(J&&J.size===W.size&&J.mtimeMs===W.mtimeMs)return G(X,J),J.data;let u=O.get(X);if(u&&u.size===W.size&&u.mtimeMs===W.mtimeMs)return u.promise;let I={size:W.size,mtimeMs:W.mtimeMs,promise:Promise.resolve(null)};return I.promise=(async()=>{try{let D=await Y(),k=await y0(Q,D);return G(X,{size:W.size,mtimeMs:W.mtimeMs,data:k}),k}catch{return null}finally{if(O.get(X)?.promise===I.promise)O.delete(X)}})(),O.set(X,I),I.promise};function N(){$.clear(),x=0,O.clear()}return{getCompressed:Z,invalidate:N,bytes:()=>x}}async function h($,x,O,G,Z){let N=F0(x);if(!N)return null;let W=await $(G,N,Z);if(!W)return null;return O.set("Content-Encoding",N),O.set("Content-Length",String(W.byteLength)),O.delete("Accept-Ranges"),O.set("Vary","Accept-Encoding"),new Response(W,{status:200,headers:O})}async function d($,x,O,G,Z=!1){let{path:N,file:W,size:Q,mtimeMs:Y}=O,X=j0(W,N),J=Z||u0(X),u=I0(Q,Y,G.watch&&J?"-live":""),I=G.compress&&q(X);if(w0(x,u,Y)){let j=o(u,G,J,Y);if(I)j.set("Vary","Accept-Encoding");return new Response(null,{status:304,headers:j})}let D=o(u,G,J,Y);if(D.set("Content-Type",X),D.set("Accept-Ranges","bytes"),I)D.set("Vary","Accept-Encoding");let k=x.headers.get("Range")&&U0(x,u,Y)?x.headers.get("Range"):null;if(k&&x.method==="GET"){let j=n0(k,Q);if(j==="invalid")return D.set("Content-Range",`bytes */${Q}`),new Response(null,{status:416,headers:D});if(j){let{start:w,end:U}=j,B=U-w+1;return D.set("Content-Range",`bytes ${w}-${U}/${Q}`),D.set("Content-Length",String(B)),new Response(W.slice(w,U+1),{status:206,headers:D})}}if(x.method==="HEAD")return D.set("Content-Length",String(Q)),new Response(null,{status:200,headers:D});if(G.watch&&J&&x.method==="GET"){if(G.compress&&q(X)){let w=await h($,x,D,{key:`${N}\x00live`,size:Q,mtimeMs:Y},async()=>J0.encode(M(await W.text())));if(w)return w}let j=M(await W.text());return D.set("Content-Length",String(Buffer.byteLength(j))),new Response(j,{status:200,headers:D})}if(G.compress&&x.method==="GET"&&q(X)&&Q<2000000){let j=await h($,x,D,{key:N,size:Q,mtimeMs:Y},async()=>new Uint8Array(await W.arrayBuffer()));if(j)return j}return D.set("Content-Length",String(Q)),new Response(W,{status:200,headers:D})}function o($,x,O,G){let Z=new Headers;if(Z.set("ETag",$),Z.set("Last-Modified",new Date(G).toUTCString()),x.watch||!x.cache||O)return Z.set("Cache-Control","no-cache"),Z;return Z.set("Cache-Control","public, max-age=31536000, immutable"),Z}function n0($,x){let O=/^bytes=(\d*)-(\d*)$/.exec($.trim());if(!O)return null;let G=O[1],Z=O[2],N,W;if(G===""&&Z==="")return"invalid";if(G===""){let Q=Number(Z);if(!Number.isFinite(Q)||Q<=0)return"invalid";N=Math.max(0,x-Q),W=x-1}else N=Number(G),W=Z===""?x-1:Number(Z);if(!Number.isFinite(N)||!Number.isFinite(W)||N<0||W<N||N>=x)return"invalid";return W=Math.min(W,x-1),{start:N,end:W}}function H($,x){if(!x.cors)return $;return $.headers.set("Access-Control-Allow-Origin","*"),$.headers.set("Access-Control-Allow-Headers","*"),$.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),$}function z($,x){if($!=="HEAD")return x;return new Response(null,{status:x.status,statusText:x.statusText,headers:x.headers})}var b={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class K extends Error{constructor($,x){super($,x);this.name="RootError"}}class f extends Error{constructor($,x,O){super(`could not bind to ${$}:${x}`,O);this.name="BindError"}}var d0=10;function G0($){if($&&typeof $==="object"&&"code"in $&&$.code==="EADDRINUSE")return!0;let x=$ instanceof Error?$.message:String($);return/EADDRINUSE|address already in use/i.test(x)}var A="/__live.js",v="/__events",O0=`(()=>{const e=new EventSource("${v}");e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,Q0=`<script src="${A}"></script>`;function o0($,x){return`http://${$.includes(":")?`[${$}]`:$}:${x}`}function M($){let x=$.toLowerCase().lastIndexOf("</body>");if(x===-1)return $+Q0;return $.slice(0,x)+Q0+$.slice(x)}function s0(){let $=new Set,x=new TextEncoder,O=x.encode(`: ping
29
+ `}function Ue(e){if(e==="/"||e==="")return null;let t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");if(n<=0)return"/";return t.slice(0,n+1)}function Y(e){return e.split("/").map(encodeURIComponent).join("/")}function je(e,t){if(e==="/")return`/${t}`;return`${e.replace(/\/+$/,"")}/${t}`}function qe(e){let t=e.indexOf("//"),n=e.indexOf("/",t===-1?0:t+2);if(n===-1)return"/";let r=e.length,a=e.indexOf("?",n);if(a!==-1&&a<r)r=a;let o=e.indexOf("#",n);if(o!==-1&&o<r)r=o;let i=e.slice(n,r);return i===""?"/":i}function ue(e,t){let n=oe(e.root),r=Fe(n),a=ze(n,r,e.watch),o=Je(),i={opts:e,hub:t,resolveCached:a.resolveCached,resolveDirCached:a.resolveDirCached,getCompressed:o.getCompressed,notFound:null},s=async function(u){let d=qe(u.url),p=u.method.toUpperCase(),m;if(d.includes("%"))try{m=decodeURIComponent(d)}catch{let l=new Response("Bad Request",{status:400});return F(p,d,e,l)}else m=d;try{return await Ge(u,p,m,d,i)}catch(l){console.error(l);let b=new Response("Internal Server Error",{status:500});return F(p,d,e,b)}};return s.invalidateResolutionCache=()=>{a.invalidate(),i.notFound=null},s.invalidateCompressedCache=o.invalidate,s.resolutionCacheSize=a.size,s.compressedCacheBytes=o.bytes,s}function F(e,t,n,r){return k(e,r.status,t,n.quiet),de(e,M(r,n))}function J(e,t){return new Response(null,{status:301,headers:{Location:`${e}/${new URL(t).search}`}})}function X(e,t,n=200){return new Response(t.watch?P(e):e,{status:n,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function Ge(e,t,n,r,a){let{opts:o,hub:i,resolveCached:s,resolveDirCached:c,getCompressed:u}=a,d=(l)=>F(t,n,o,l);if(t!=="GET"&&t!=="HEAD"){let l=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return d(l)}if(o.watch&&n===D){let l=new Response(fe,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return d(l)}if(o.watch&&n===I&&i){let l=i.subscribe();return k(t,200,n,o.quiet),M(l,o)}if(n===D||n===I)return de(t,M(new Response("Not Found",{status:404}),o));let p=s(n);if(p){if(p.kind==="dir-index"&&!n.endsWith("/"))return d(J(r,e.url));return d(await Z(u,e,p,o))}let m=Oe(e);if(o.spa&&m&&Ie(n)){let l=s("/");if(l)return d(await Z(u,e,l,o,!0))}if(o.dir){let l=c(n);if(l){if(!n.endsWith("/"))return d(J(r,e.url));let b=We(n,_e(l));return d(X(b,o))}}if(m){let l=s("/404.html");if(l){let b=a.notFound,x=b&&b.size===l.size&&b.mtimeMs===l.mtimeMs?b.html:await(async()=>{let h=await l.file.text();return a.notFound={size:l.size,mtimeMs:l.mtimeMs,html:h},h})();return d(X(x,o,404))}}return d(new Response("Not Found",{status:404}))}var Ve=67108864;async function Ke(e){let t=new CompressionStream("gzip"),n=t.writable.getWriter();return n.write(e),n.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function Ye(e,t){if(e==="zstd")return new Uint8Array(await Bun.zstdCompress(t));return Ke(t)}function Je(){let e=new Map,t=0,n=new Map;function r(i,s){let c=e.get(i);if(c)e.delete(i),t-=c.data.size;e.set(i,s),t+=s.data.size;while(t>Ve&&e.size>1){let u=e.keys().next().value;if(u===void 0)break;let d=e.get(u);if(e.delete(u),d)t-=d.data.size}}let a=async(i,s,c)=>{let u=`${i.key}:${s}`,d=e.get(u);if(d&&d.size===i.size&&d.mtimeMs===i.mtimeMs)return r(u,d),d.data;let p=n.get(u);if(p&&p.size===i.size&&p.mtimeMs===i.mtimeMs)return p.promise;let m=(async()=>{try{let b=await c(),x=new Blob([await Ye(s,b)]);return r(u,{size:i.size,mtimeMs:i.mtimeMs,data:x}),x}catch{return null}})(),l={size:i.size,mtimeMs:i.mtimeMs,promise:m};return n.set(u,l),m.finally(()=>{if(n.get(u)===l)n.delete(u)}),m};function o(){e.clear(),t=0,n.clear()}return{getCompressed:a,invalidate:o,bytes:()=>t}}async function Q(e,t,n,r,a){let o=De(t);if(!o)return null;let i=await e(r,o,a);if(!i)return null;return n["Content-Encoding"]=o,n["Content-Length"]=String(i.size),delete n["Accept-Ranges"],n.Vary="Accept-Encoding",new Response(i,{status:200,headers:n})}async function Z(e,t,n,r,a=!1){let{path:o,file:i,size:s,mtimeMs:c}=n,u=Re(i,o),d=a||$e(u),p=Ee(s,c,r.watch&&d?"-live":""),m=r.compress&&Ce(u);if(Ae(t,p,c)){let h=ne(p,r,d,c);if(m)h.Vary="Accept-Encoding";return new Response(null,{status:304,headers:h})}let l=ne(p,r,d,c);if(l["Content-Type"]=u,l["Accept-Ranges"]="bytes",m)l.Vary="Accept-Encoding";let b=t.headers.get("Range"),x=b&&Me(t,p,c)?b:null;if(x&&t.method==="GET"){let h=Qe(x,s);if(h==="invalid")return l["Content-Range"]=`bytes */${s}`,new Response(null,{status:416,headers:l});if(h){let{start:w,end:g}=h,y=g-w+1;return l["Content-Range"]=`bytes ${w}-${g}/${s}`,l["Content-Length"]=String(y),new Response(i.slice(w,g+1),{status:206,headers:l})}}if(t.method==="HEAD")return l["Content-Length"]=String(s),new Response(null,{status:200,headers:l});if(r.watch&&d&&t.method==="GET"){if(m){let w=await Q(e,t,l,{key:`${o}\x00live`,size:s,mtimeMs:c},async()=>we.encode(P(await i.text())));if(w)return w}let h=P(await i.text());return l["Content-Length"]=String(Buffer.byteLength(h)),new Response(h,{status:200,headers:l})}if(m&&t.method==="GET"&&s<2000000){let h=await Q(e,t,l,{key:o,size:s,mtimeMs:c},()=>i.bytes());if(h)return h}return l["Content-Length"]=String(s),new Response(i,{status:200,headers:l})}var ee=Number.NaN,te="";function Xe(e){if(e!==ee)ee=e,te=new Date(e).toUTCString();return te}function ne(e,t,n,r){return{ETag:e,"Last-Modified":Xe(r),"Cache-Control":t.watch||!t.cache||n?"no-cache":"public, max-age=31536000, immutable"}}function Qe(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n)return null;let r=n[1],a=n[2],o,i;if(r===""&&a==="")return"invalid";if(r===""){let s=Number(a);if(!Number.isFinite(s)||s<=0)return"invalid";o=Math.max(0,t-s),i=t-1}else o=Number(r),i=a===""?t-1:Number(a);if(!Number.isFinite(o)||!Number.isFinite(i)||o<0||i<o||o>=t)return"invalid";return i=Math.min(i,t-1),{start:o,end:i}}function M(e,t){if(!t.cors)return e;return e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Headers","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e}function de(e,t){if(e!=="HEAD")return t;return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})}var L={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class v extends Error{constructor(e,t){super(e,t);this.name="RootError"}}class T extends Error{constructor(e,t,n){super(`could not bind to ${e}:${t}`,n);this.name="BindError"}}var st=10;function pe(e){if(e&&typeof e==="object"&&"code"in e&&e.code==="EADDRINUSE")return!0;let t=e instanceof Error?e.message:String(e);return/EADDRINUSE|address already in use/i.test(t)}var D="/__live.js",I="/__events",fe=`(()=>{const e=new EventSource("${I}");e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,me=`<script src="${D}"></script>`;function ot(e,t){return`http://${e.includes(":")?`[${e}]`:e}:${t}`}function P(e){let t=e.toLowerCase().lastIndexOf("</body>");if(t===-1)return e+me;return e.slice(0,t)+me+e.slice(t)}function it(){let e=new Set,t=new TextEncoder,n=t.encode(`: ping
30
30
 
31
- `),G=setInterval(()=>{for(let Q of $)try{Q.enqueue(O)}catch{$.delete(Q)}},8000);G.unref();function Z(){let Q,Y=new ReadableStream({start(X){Q=X,$.add(X),X.enqueue(x.encode(`: connected
31
+ `),r=setInterval(()=>{for(let s of e)try{s.enqueue(n)}catch{e.delete(s)}},8000);r.unref();function a(){let s,c=new ReadableStream({start(u){s=u,e.add(u),u.enqueue(t.encode(`: connected
32
32
 
33
- `))},cancel(){$.delete(Q)}});return new Response(Y,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function N(Q="reload"){let Y=x.encode(`data: ${Q}
33
+ `))},cancel(){e.delete(s)}});return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function o(s="reload"){let c=t.encode(`data: ${s}
34
34
 
35
- `);for(let X of $)try{X.enqueue(Y)}catch{$.delete(X)}}function W(){clearInterval(G);for(let Q of $)try{Q.close()}catch{}$.clear()}return{subscribe:Z,broadcast:N,close:W}}var V={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},r0=/[\x00-\x1f\x7f]/g;function a0($){return $.replace(r0,"")}function _($,x,O,G){if(G)return;let Z=x<300?`${V.green}\u2713${V.reset}`:x<400?`${V.yellow}\u25CB${V.reset}`:`${V.red}\u2717${V.reset}`;console.log(`${Z} ${V.dim}${$}${V.reset} ${x} ${a0(O)}`)}function g($,x=!1){if(x)return;console.log(`${V.cyan}\u2502${V.reset} ${$}`)}function t0($){return $.split(/[/\\]/).some((x)=>x.startsWith(".")||x==="node_modules")}function e0($){if($.length===0)return"reload";return $.every((x)=>x?.endsWith(".css"))?"css":"reload"}function $5(){let $=p0();for(let x of Object.values($))for(let O of x??[])if(O.family==="IPv4"&&!O.internal)return O.address;return null}function x5($,x,O,G){if(console.log(),console.log(` ${V.bold}deserved${V.reset} ${V.dim}serving${V.reset} ${x}`),console.log(` ${V.green}->${V.reset} ${V.cyan}${$}${V.reset}`),G)console.log(` ${V.green}->${V.reset} ${V.cyan}${G}${V.reset}`);if(O.length)console.log(` ${V.dim}${O.join(" ")}${V.reset}`);console.log()}function O5($,x){if($)return;console.log(`${V.yellow}*${V.reset} ${x}`)}async function G5($){let x=process.platform;try{if(x==="darwin")await Bun.spawn(["open",$],{stdout:"ignore",stderr:"ignore"}).exited;else if(x==="win32")await Bun.spawn(["cmd","/c","start","",$],{stdout:"ignore",stderr:"ignore"}).exited;else await Bun.spawn(["xdg-open",$],{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${$}`)}}function Q5($){try{if(!i0($).isDirectory())throw new K(`not a directory: ${$}`)}catch(x){if(x instanceof K)throw x;if(x instanceof Error&&"code"in x&&x.code==="ENOENT")throw new K(`directory not found: ${$}`);throw new K(`not a directory: ${$}`)}}async function y($){let x=h0($.root);Q5(x);let O=$.watch?s0():void 0,G=x0({...$,root:x},O),Z=$.host==="localhost"?"127.0.0.1":$.host,N=async(B)=>{if($.cors&&B.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS"}});return G(B)},W=(B)=>Bun.serve({port:B,hostname:Z,fetch:N}),Q=!$.portExplicit&&$.port!==0,Y,X=$.port;try{Y=W(X)}catch(B){if(!Q||!G0(B))throw new f($.host,X,{cause:B});let F,T=$.port,P=B;for(let L=1;L<=d0;L++){T=$.port+L;try{F=W(T),X=T;break}catch(R){if(!G0(R))throw new f($.host,T,{cause:R});P=R}}if(!F)throw new f($.host,T,{cause:P});Y=F,g(`port ${$.port} in use, using ${X}`,$.quiet)}let J=$.host==="0.0.0.0"||$.host==="::",u=J?"localhost":$.host,I=o0(u,Y.port??$.port),D=J?$5():null,k=D?`http://${D}:${Y.port}`:void 0,j=[];if($.spa)j.push("--spa");if($.watch)j.push("--watch");if($.cors)j.push("--cors");if(!$.dir)j.push("--no-dir");if(!$.compress)j.push("--no-compress");if($.cache)j.push("--cache");x5(I,l0(process.cwd(),x)||".",j,k);let w;if($.watch&&O){let B=null,F=new Set;w=m0(x,{recursive:!0},(T,P)=>{if(P&&t0(P))return;if(G.invalidateResolutionCache(),G.invalidateCompressedCache(),F.add(P),B)clearTimeout(B);B=setTimeout(()=>{let L=e0([...F]);F.clear(),O5($.quiet,L),O.broadcast(L)},80)}),g("watching for changes",$.quiet)}let U=async()=>{w?.close(),O?.close(),await Y.stop(),g("server stopped",$.quiet)};if($.open)await G5(I);return{port:Y.port??$.port,hostname:u,url:I,stop:U}}async function F5($={}){let x=$.portExplicit??$.port!==void 0;return y({...b,...$,portExplicit:x})}function Z5(){console.log(`
35
+ `);for(let u of e)try{u.enqueue(c)}catch{e.delete(u)}}function i(){clearInterval(r);for(let s of e)try{s.close()}catch{}e.clear()}return{subscribe:a,broadcast:o,close:i}}var f={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},ct=/[\x00-\x1f\x7f]/g,at=/[\x00-\x1f\x7f]/;function lt(e){return at.test(e)?e.replace(ct,""):e}var ut=`${f.green}\u2713${f.reset}`,dt=`${f.yellow}\u25CB${f.reset}`,ft=`${f.red}\u2717${f.reset}`,{dim:pt,reset:mt}=f,O=[];function ht(){if(O.length===1)queueMicrotask(he)}function he(){if(O.length===0)return;let e=O.join(`
36
+ `);O=[],process.stdout.write(`${e}
37
+ `)}function k(e,t,n,r){if(r)return;let a=t<300?ut:t<400?dt:ft;O.push(`${a} ${pt}${e}${mt} ${t} ${lt(n)}`),ht()}function B(e,t=!1){if(t)return;console.log(`${f.cyan}\u2502${f.reset} ${e}`)}function gt(e){return e.split(/[/\\]/).some((t)=>t.startsWith(".")||t==="node_modules")}function bt(e){if(e.length===0)return"reload";return e.every((t)=>t?.endsWith(".css"))?"css":"reload"}function xt(){let e=tt();for(let t of Object.values(e))for(let n of t??[])if(n.family==="IPv4"&&!n.internal)return n.address;return null}function yt(e,t,n,r){if(console.log(),console.log(` ${f.bold}deserved${f.reset} ${f.dim}serving${f.reset} ${t}`),console.log(` ${f.green}->${f.reset} ${f.cyan}${e}${f.reset}`),r)console.log(` ${f.green}->${f.reset} ${f.cyan}${r}${f.reset}`);if(n.length)console.log(` ${f.dim}${n.join(" ")}${f.reset}`);console.log()}function wt(e,t){if(e)return;console.log(`${f.yellow}*${f.reset} ${t}`)}function vt(e){if(process.platform==="darwin")return["open",e];if(process.platform==="win32")return["cmd","/c","start","",e];return["xdg-open",e]}async function Rt(e){try{await Bun.spawn(vt(e),{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${e}`)}}function Ct(e){try{if(!Ze(e).isDirectory())throw new v(`not a directory: ${e}`)}catch(t){if(t instanceof v)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new v(`directory not found: ${e}`);throw new v(`not a directory: ${e}`)}}async function _(e){let t=rt(e.root);Ct(t);let n=e.watch?it():void 0,r=ue({...e,root:t},n),a=e.host==="localhost"?"127.0.0.1":e.host,o=async(g)=>{if(e.cors&&g.method==="OPTIONS")return M(new Response(null,{status:204}),e);return r(g)},i=(g)=>Bun.serve({port:g,hostname:a,fetch:o}),s=!e.portExplicit&&e.port!==0,c,u=e.port;try{c=i(u)}catch(g){if(!s||!pe(g))throw new T(e.host,u,{cause:g});let y,R=e.port,C=g;for(let E=1;E<=st;E++){R=e.port+E;try{y=i(R),u=R;break}catch(N){if(!pe(N))throw new T(e.host,R,{cause:N});C=N}}if(!y)throw new T(e.host,R,{cause:C});c=y,B(`port ${e.port} in use, using ${u}`,e.quiet)}let d=e.host==="0.0.0.0"||e.host==="::",p=d?"localhost":e.host,m=ot(p,c.port??e.port),l=d?xt():null,b=l?`http://${l}:${c.port}`:void 0,x=[];if(e.spa)x.push("--spa");if(e.watch)x.push("--watch");if(e.cors)x.push("--cors");if(!e.dir)x.push("--no-dir");if(!e.compress)x.push("--no-compress");if(e.cache)x.push("--cache");yt(m,nt(process.cwd(),t)||".",x,b);let h;if(e.watch&&n){let g=null,y=new Set;h=et(t,{recursive:!0},(R,C)=>{if(C&&gt(C))return;if(r.invalidateResolutionCache(),r.invalidateCompressedCache(),y.add(C),g)clearTimeout(g);g=setTimeout(()=>{let E=bt([...y]);y.clear(),wt(e.quiet,E),n.broadcast(E)},80)}),B("watching for changes",e.quiet)}let w=async()=>{h?.close(),n?.close(),await c.stop(),he(),B("server stopped",e.quiet)};if(e.open)await Rt(m);return{port:c.port??e.port,hostname:p,url:m,stop:w}}async function Ft(e={}){let t=e.portExplicit??e.port!==void 0;return _({...L,...e,portExplicit:t})}function Et(){console.log(`
36
38
  deserved - tiny Bun static file server
37
39
 
38
40
  Usage
@@ -62,4 +64,4 @@ ${W}${N}
62
64
  deserved dist --port 8080
63
65
  deserved docs --watch --open
64
66
  PORT=8080 deserved dist
65
- `)}function Y5($,x=Bun.env){let O=$.slice(2),G={...b},Z=G.root,N=!1;for(let W=0;W<O.length;W++){let Q=O[W];if(Q===void 0)break;if(Q==="-h"||Q==="--help")Z5(),process.exit(0);if(Q==="-v"||Q==="--version")console.log(c),process.exit(0);if(Q==="-s"||Q==="--spa"){G.spa=!0;continue}if(Q==="-w"||Q==="--watch"){G.watch=!0;continue}if(Q==="-o"||Q==="--open"){G.open=!0;continue}if(Q==="--cors"){G.cors=!0;continue}if(Q==="--dir"){G.dir=!0;continue}if(Q==="--no-dir"){G.dir=!1;continue}if(Q==="--cache"){G.cache=!0;continue}if(Q==="--no-cache"){G.cache=!1;continue}if(Q==="--compress"){G.compress=!0;continue}if(Q==="--no-compress"){G.compress=!1;continue}if(Q==="-q"||Q==="--quiet"){G.quiet=!0;continue}if(Q==="-p"||Q==="--port"){let Y=O[++W];if(!Y||Y.startsWith("-"))E(`Missing value for ${Q}`);let X=Number(Y);if(!Number.isInteger(X)||X<0||X>65535)E(`Invalid port: ${Y}`);G.port=X,N=!0;continue}if(Q==="-H"||Q==="--host"){let Y=O[++W];if(!Y||Y.startsWith("-"))E(`Missing value for ${Q}`);G.host=Y;continue}if(Q.startsWith("--port=")){let Y=Number(Q.slice(7));if(!Number.isInteger(Y)||Y<0||Y>65535)E(`Invalid port: ${Q}`);G.port=Y,N=!0;continue}if(Q.startsWith("--host=")){G.host=Q.slice(7);continue}if(Q.startsWith("-"))E(`Unknown option: ${Q}`);Z=Q}if(!N&&x.PORT!==void 0){let W=Number(x.PORT);if(!Number.isInteger(W)||W<0||W>65535)E(`Invalid port: ${x.PORT}`);G.port=W}return G.portExplicit=N,G.root=W5(Z),G}function E($){console.error(`Error: ${$}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let $=Y5(process.argv),x;try{x=await y($)}catch(G){if(G instanceof K)console.error(`Error: ${G.message}`),console.error("Run deserved --help."),process.exit(1);if(G instanceof f)console.error(`Error: ${G.message}`),console.error(G.cause instanceof Error?G.cause.message:String(G.cause)),process.exit(1);throw G}let O=async()=>{await x.stop(),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O)}export{Y5 as parseArgs};
67
+ `)}function St(e,t=Bun.env){let n=e.slice(2),r={...L},a=r.root,o=!1;for(let i=0;i<n.length;i++){let s=n[i];if(s===void 0)break;if(s==="-h"||s==="--help")Et(),process.exit(0);if(s==="-v"||s==="--version")console.log(U),process.exit(0);if(s==="-s"||s==="--spa"){r.spa=!0;continue}if(s==="-w"||s==="--watch"){r.watch=!0;continue}if(s==="-o"||s==="--open"){r.open=!0;continue}if(s==="--cors"){r.cors=!0;continue}if(s==="--dir"){r.dir=!0;continue}if(s==="--no-dir"){r.dir=!1;continue}if(s==="--cache"){r.cache=!0;continue}if(s==="--no-cache"){r.cache=!1;continue}if(s==="--compress"){r.compress=!0;continue}if(s==="--no-compress"){r.compress=!1;continue}if(s==="-q"||s==="--quiet"){r.quiet=!0;continue}if(s==="-p"||s==="--port"){let c=n[++i];if(!c||c.startsWith("-"))H(`Missing value for ${s}`);r.port=W(c,c),o=!0;continue}if(s==="-H"||s==="--host"){let c=n[++i];if(!c||c.startsWith("-"))H(`Missing value for ${s}`);r.host=c;continue}if(s.startsWith("--port=")){r.port=W(s.slice(7),s),o=!0;continue}if(s.startsWith("--host=")){r.host=s.slice(7);continue}if(s.startsWith("-"))H(`Unknown option: ${s}`);a=s}if(!o&&t.PORT!==void 0)r.port=W(t.PORT,t.PORT);return r.portExplicit=o,r.root=$t(a),r}function W(e,t){let n=Number(e);if(!Number.isInteger(n)||n<0||n>65535)H(`Invalid port: ${t}`);return n}function H(e){console.error(`Error: ${e}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let e=St(process.argv),t;try{t=await _(e)}catch(r){if(r instanceof v)console.error(`Error: ${r.message}`),console.error("Run deserved --help."),process.exit(1);if(r instanceof T)console.error(`Error: ${r.message}`),console.error(r.cause instanceof Error?r.cause.message:String(r.cause)),process.exit(1);throw r}let n=async()=>{await t.stop(),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n)}export{St as parseArgs};
package/handlers.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { type createSseHub, type Options } from "./server";
2
+ export type ResolvedFile = {
3
+ path: string;
4
+ file: Bun.BunFile;
5
+ size: number;
6
+ mtimeMs: number;
7
+ kind: "file" | "html-ext" | "dir-index";
8
+ };
9
+ export type Handler = {
10
+ (req: Request): Promise<Response>;
11
+ invalidateResolutionCache(): void;
12
+ invalidateCompressedCache(): void;
13
+ resolutionCacheSize(): number;
14
+ compressedCacheBytes(): number;
15
+ };
16
+ type Hub = ReturnType<typeof createSseHub>;
17
+ export declare function contentType(file: Bun.BunFile, path: string): string;
18
+ export declare function isCompressible(type: string): boolean;
19
+ export declare function isHtml(type: string): boolean;
20
+ export declare function makeEtag(size: number, mtimeMs: number, tag?: string): string;
21
+ export declare function notModified(req: Request, etag: string): boolean;
22
+ export declare function notModifiedSince(req: Request, mtimeMs: number): boolean;
23
+ export declare function isNotModified(req: Request, etag: string, mtimeMs: number): boolean;
24
+ export declare function ifRangeSatisfied(req: Request, etag: string, mtimeMs: number): boolean;
25
+ export declare function acceptsHtml(req: Request): boolean;
26
+ export type CompressionEncoding = "zstd" | "gzip";
27
+ export declare function pickEncoding(req: Request): CompressionEncoding | null;
28
+ export declare function shouldSpaFallback(pathname: string): boolean;
29
+ export declare function resolveFileWithRoot(rootAbs: string, realRoot: string | null, pathname: string): ResolvedFile | null;
30
+ export declare const RESOLUTION_CACHE_LIMIT = 4096;
31
+ export declare const RESOLUTION_TTL_MS = 500;
32
+ export declare function buildCandidates(relative: string): string[];
33
+ export declare function safeJoin(root: string, relative: string): string | null;
34
+ export declare function realContainedPath(rootAbs: string, full: string): string | null;
35
+ export declare function resolveDirWithRoot(rootAbs: string, realRoot: string | null, pathname: string): string | null;
36
+ type DirEntry = {
37
+ name: string;
38
+ dir: boolean;
39
+ size: number | null;
40
+ mtimeMs: number | null;
41
+ };
42
+ export declare function listDir(dir: string): DirEntry[];
43
+ export declare function directoryListing(pathname: string, entries: DirEntry[]): string;
44
+ export declare function createHandler(opts: Options, hub?: Hub): Handler;
45
+ export declare const COMPRESSED_CACHE_BYTE_BUDGET: number;
46
+ export declare function compress(encoding: CompressionEncoding, raw: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
47
+ export declare function baseHeaders(etag: string, opts: Options, isHtmlFile: boolean, mtimeMs: number): Record<string, string>;
48
+ export declare function parseRange(header: string, size: number): {
49
+ start: number;
50
+ end: number;
51
+ } | null | "invalid";
52
+ export declare function withCors(res: Response, opts: Options): Response;
53
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { createHandler } from "./handlers";
2
+ export { BindError, DEFAULT_OPTIONS, type Options, RootError, type ServerHandle, serve, startServer, } from "./server";
package/index.js CHANGED
@@ -1,18 +1,20 @@
1
1
  // @bun
2
- import{readdirSync as LQ,realpathSync as s,statSync as q}from"fs";import{extname as wQ,join as t,normalize as zQ,resolve as e,sep as QQ}from"path";import{promisify as SQ}from"util";import{gzip as HQ}from"zlib";var{escapeHTML:w}=globalThis.Bun;import{statSync as YQ,watch as GQ}from"fs";import{networkInterfaces as XQ}from"os";import{relative as JQ,resolve as WQ}from"path";var m={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class P extends Error{constructor(Q,Z){super(Q,Z);this.name="RootError"}}class E extends Error{constructor(Q,Z,$){super(`could not bind to ${Q}:${Z}`,$);this.name="BindError"}}var OQ=10;function g(Q){if(Q&&typeof Q==="object"&&"code"in Q&&Q.code==="EADDRINUSE")return!0;let Z=Q instanceof Error?Q.message:String(Q);return/EADDRINUSE|address already in use/i.test(Z)}var C="/__live.js",R="/__events",c=`(()=>{const e=new EventSource("${R}");e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,b=`<script src="${C}"></script>`;function VQ(Q,Z){return`http://${Q.includes(":")?`[${Q}]`:Q}:${Z}`}function A(Q){let Z=Q.toLowerCase().lastIndexOf("</body>");if(Z===-1)return Q+b;return Q.slice(0,Z)+b+Q.slice(Z)}function jQ(){let Q=new Set,Z=new TextEncoder,$=Z.encode(`: ping
2
+ import{readdirSync as Le,realpathSync as oe,statSync as I}from"fs";import{extname as _e,isAbsolute as ke,join as ie,resolve as ce,sep as ae}from"path";var{escapeHTML:S}=globalThis.Bun;import{statSync as pe,watch as me}from"fs";import{networkInterfaces as ge}from"os";import{relative as he,resolve as ye}from"path";var U={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class E extends Error{constructor(e,t){super(e,t);this.name="RootError"}}class T extends Error{constructor(e,t,n){super(`could not bind to ${e}:${t}`,n);this.name="BindError"}}var xe=10;function _(e){if(e&&typeof e==="object"&&"code"in e&&e.code==="EADDRINUSE")return!0;let t=e instanceof Error?e.message:String(e);return/EADDRINUSE|address already in use/i.test(t)}var D="/__live.js",z="/__events",W=`(()=>{const e=new EventSource("${z}");e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,k=`<script src="${D}"></script>`;function be(e,t){return`http://${e.includes(":")?`[${e}]`:e}:${t}`}function H(e){let t=e.toLowerCase().lastIndexOf("</body>");if(t===-1)return e+k;return e.slice(0,t)+k+e.slice(t)}function we(){let e=new Set,t=new TextEncoder,n=t.encode(`: ping
3
3
 
4
- `),Y=setInterval(()=>{for(let J of Q)try{J.enqueue($)}catch{Q.delete(J)}},8000);Y.unref();function G(){let J,V=new ReadableStream({start(j){J=j,Q.add(j),j.enqueue(Z.encode(`: connected
4
+ `),r=setInterval(()=>{for(let s of e)try{s.enqueue(n)}catch{e.delete(s)}},8000);r.unref();function c(){let s,a=new ReadableStream({start(u){s=u,e.add(u),u.enqueue(t.encode(`: connected
5
5
 
6
- `))},cancel(){Q.delete(J)}});return new Response(V,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function W(J="reload"){let V=Z.encode(`data: ${J}
6
+ `))},cancel(){e.delete(s)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function o(s="reload"){let a=t.encode(`data: ${s}
7
7
 
8
- `);for(let j of Q)try{j.enqueue(V)}catch{Q.delete(j)}}function X(){clearInterval(Y);for(let J of Q)try{J.close()}catch{}Q.clear()}return{subscribe:G,broadcast:W,close:X}}var N={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},DQ=/[\x00-\x1f\x7f]/g;function NQ(Q){return Q.replace(DQ,"")}function L(Q,Z,$,Y){if(Y)return;let G=Z<300?`${N.green}\u2713${N.reset}`:Z<400?`${N.yellow}\u25CB${N.reset}`:`${N.red}\u2717${N.reset}`;console.log(`${G} ${N.dim}${Q}${N.reset} ${Z} ${NQ($)}`)}function y(Q,Z=!1){if(Z)return;console.log(`${N.cyan}\u2502${N.reset} ${Q}`)}function xQ(Q){return Q.split(/[/\\]/).some((Z)=>Z.startsWith(".")||Z==="node_modules")}function BQ(Q){if(Q.length===0)return"reload";return Q.every((Z)=>Z?.endsWith(".css"))?"css":"reload"}function UQ(){let Q=XQ();for(let Z of Object.values(Q))for(let $ of Z??[])if($.family==="IPv4"&&!$.internal)return $.address;return null}function kQ(Q,Z,$,Y){if(console.log(),console.log(` ${N.bold}deserved${N.reset} ${N.dim}serving${N.reset} ${Z}`),console.log(` ${N.green}->${N.reset} ${N.cyan}${Q}${N.reset}`),Y)console.log(` ${N.green}->${N.reset} ${N.cyan}${Y}${N.reset}`);if($.length)console.log(` ${N.dim}${$.join(" ")}${N.reset}`);console.log()}function FQ(Q,Z){if(Q)return;console.log(`${N.yellow}*${N.reset} ${Z}`)}async function _Q(Q){let Z=process.platform;try{if(Z==="darwin")await Bun.spawn(["open",Q],{stdout:"ignore",stderr:"ignore"}).exited;else if(Z==="win32")await Bun.spawn(["cmd","/c","start","",Q],{stdout:"ignore",stderr:"ignore"}).exited;else await Bun.spawn(["xdg-open",Q],{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${Q}`)}}function IQ(Q){try{if(!YQ(Q).isDirectory())throw new P(`not a directory: ${Q}`)}catch(Z){if(Z instanceof P)throw Z;if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")throw new P(`directory not found: ${Q}`);throw new P(`not a directory: ${Q}`)}}async function h(Q){let Z=WQ(Q.root);IQ(Z);let $=Q.watch?jQ():void 0,Y=u({...Q,root:Z},$),G=Q.host==="localhost"?"127.0.0.1":Q.host,W=async(F)=>{if(Q.cors&&F.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"*","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS"}});return Y(F)},X=(F)=>Bun.serve({port:F,hostname:G,fetch:W}),J=!Q.portExplicit&&Q.port!==0,V,j=Q.port;try{V=X(j)}catch(F){if(!J||!g(F))throw new E(Q.host,j,{cause:F});let K,z=Q.port,S=F;for(let H=1;H<=OQ;H++){z=Q.port+H;try{K=X(z),j=z;break}catch(v){if(!g(v))throw new E(Q.host,z,{cause:v});S=v}}if(!K)throw new E(Q.host,z,{cause:S});V=K,y(`port ${Q.port} in use, using ${j}`,Q.quiet)}let D=Q.host==="0.0.0.0"||Q.host==="::",B=D?"localhost":Q.host,U=VQ(B,V.port??Q.port),O=D?UQ():null,k=O?`http://${O}:${V.port}`:void 0,x=[];if(Q.spa)x.push("--spa");if(Q.watch)x.push("--watch");if(Q.cors)x.push("--cors");if(!Q.dir)x.push("--no-dir");if(!Q.compress)x.push("--no-compress");if(Q.cache)x.push("--cache");kQ(U,JQ(process.cwd(),Z)||".",x,k);let _;if(Q.watch&&$){let F=null,K=new Set;_=GQ(Z,{recursive:!0},(z,S)=>{if(S&&xQ(S))return;if(Y.invalidateResolutionCache(),Y.invalidateCompressedCache(),K.add(S),F)clearTimeout(F);F=setTimeout(()=>{let H=BQ([...K]);K.clear(),FQ(Q.quiet,H),$.broadcast(H)},80)}),y("watching for changes",Q.quiet)}let I=async()=>{_?.close(),$?.close(),await V.stop(),y("server stopped",Q.quiet)};if(Q.open)await _Q(U);return{port:V.port??Q.port,hostname:B,url:U,stop:I}}async function KQ(Q={}){let Z=Q.portExplicit??Q.port!==void 0;return h({...m,...Q,portExplicit:Z})}var PQ=new TextEncoder,l="application/octet-stream",TQ={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function MQ(Q,Z){let $=Q.type;if($&&$!==l&&$!=="")return $;let Y=wQ(Z).toLowerCase();return TQ[Y]??l}function f(Q){let Z=Q.split(";")[0]?.trim().toLowerCase()??"";return Z.startsWith("text/")||Z==="application/javascript"||Z==="text/javascript"||Z==="application/json"||Z==="application/xml"||Z==="image/svg+xml"||Z.endsWith("+json")||Z.endsWith("+xml")}function EQ(Q){return Q.startsWith("text/html")}function AQ(Q,Z,$=""){return`"${Q}-${Math.trunc(Z)}${$}"`}function CQ(Q,Z){let $=Q.headers.get("If-None-Match");if(!$)return!1;return $.split(",").some((Y)=>Y.trim().replace(/^W\//,"")===Z)}function RQ(Q,Z){let $=Q.headers.get("If-Modified-Since");if(!$)return!1;let Y=Date.parse($);if(Number.isNaN(Y))return!1;return Math.trunc(Z/1000)*1000<=Y}function qQ(Q,Z,$){return Q.headers.get("If-None-Match")?CQ(Q,Z):RQ(Q,$)}function vQ(Q,Z,$){let Y=Q.headers.get("If-Range");if(!Y)return!0;if(Y.startsWith('"')||Y.startsWith("W/"))return Y===Z;let G=Date.parse(Y);if(Number.isNaN(G))return!1;return G===Math.trunc($/1000)*1000}function p(Q){let Z=Q.headers.get("Accept");if(!Z||Z==="*/*")return!0;return Z.includes("text/html")||Z.includes("application/xhtml")}function yQ(Q){let Z=Q.headers.get("Accept-Encoding")??"";if(Z.includes("zstd"))return"zstd";if(Z.includes("gzip"))return"gzip";return null}function uQ(Q){if(Q.startsWith("/__"))return!1;let Z=Q.slice(Q.lastIndexOf("/")+1);if(!Z)return!0;if(Z.includes("."))return!1;return!0}function fQ(Q,Z,$){if(!Z)return null;let Y=$.replace(/^\/+/,""),G=hQ(Y);for(let W of G){let X=ZQ(Q,W);if(!X)continue;let J=$Q(Z,X);if(!J)continue;try{let V=q(J);if(V.isFile())return{path:J,file:Bun.file(J),size:V.size,mtimeMs:V.mtimeMs,kind:cQ(W)}}catch{}}return null}var gQ=4096,bQ=500;function mQ(Q,Z,$){let Y=new Map;function G(W){let X=Y.get(W);if(X&&($||Date.now()-X.at<bQ)){if(X.value===null)return null;try{let V=q(X.value.real);if(V.isFile())return{path:X.value.real,file:Bun.file(X.value.real),size:V.size,mtimeMs:V.mtimeMs,kind:X.value.kind}}catch{}}let J=fQ(Q,Z,W);if(Y.size>=gQ)Y.clear();return Y.set(W,{value:J?{real:J.path,kind:J.kind}:null,at:Date.now()}),J}return{resolveCached:G,invalidate:()=>Y.clear(),size:()=>Y.size}}function cQ(Q){if(Q.endsWith("/index.html"))return"dir-index";if(Q.endsWith(".html")&&!Q.endsWith("/index.html"))return"html-ext";return"file"}function hQ(Q){if(!Q||Q===".")return["index.html"];let Z=Q.endsWith("/")?Q.slice(0,-1):Q;if(!Z)return["index.html"];if(Q.endsWith("/"))return[`${Z}/index.html`];return[Z,`${Z}.html`,`${Z}/index.html`]}function ZQ(Q,Z){let $=e(Q),Y=zQ(t($,Z));if(Y!==$&&!Y.startsWith($+QQ))return null;return Y}function $Q(Q,Z){try{let $=s(Z);if($!==Q&&!$.startsWith(Q+QQ))return null;return $}catch{return null}}var n=new Map;function lQ(Q){let Z=n.get(Q);if(Z===void 0){try{Z=s(Q)}catch{Z=null}n.set(Q,Z)}return Z}function pQ(Q,Z,$){if(!Z)return null;let Y=$.replace(/^\/+/,"").replace(/\/+$/,""),G=ZQ(Q,Y||".");if(!G)return null;let W=$Q(Z,G);if(!W)return null;try{if(q(W).isDirectory())return W}catch{return null}return null}function nQ(Q){if(Q===null)return"-";if(Q<1024)return`${Q} B`;if(Q<1048576)return`${(Q/1024).toFixed(1)} kB`;return`${(Q/1048576).toFixed(1)} MB`}function iQ(Q){if(Q===null)return"-";let Z=new Date(Q),$=Z.getFullYear(),Y=String(Z.getMonth()+1).padStart(2,"0"),G=String(Z.getDate()).padStart(2,"0"),W=String(Z.getHours()).padStart(2,"0"),X=String(Z.getMinutes()).padStart(2,"0");return`${$}-${Y}-${G} ${W}:${X}`}function dQ(Q){return LQ(Q,{withFileTypes:!0}).filter((Z)=>!Z.name.startsWith(".")).map((Z)=>{let $=Z.isDirectory(),Y=null,G=null;if(!$)try{let W=q(t(Q,Z.name));Y=W.size,G=W.mtimeMs}catch{}return{name:Z.name,dir:$,size:Y,mtimeMs:G}}).sort((Z,$)=>{if(Z.dir!==$.dir)return Z.dir?-1:1;return Z.name.localeCompare($.name)})}function oQ(Q,Z){let $=Q.endsWith("/")?Q:`${Q}/`,Y=i($),G=rQ(Q),W=Z.map((J)=>{let V=aQ(Y,encodeURIComponent(J.name))+(J.dir?"/":""),j=J.dir?`${J.name}/`:J.name,D=nQ(J.size),B=iQ(J.mtimeMs);return` <li><a href="${w(V)}">${w(j)}</a> <span class="meta">${w(D)}</span> <span class="meta">${w(B)}</span></li>`}).join(`
9
- `),X=G!==null?` <li><a href="${w(i(G))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
8
+ `);for(let u of e)try{u.enqueue(a)}catch{e.delete(u)}}function i(){clearInterval(r);for(let s of e)try{s.close()}catch{}e.clear()}return{subscribe:c,broadcast:o,close:i}}var f={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},Ce=/[\x00-\x1f\x7f]/g,Re=/[\x00-\x1f\x7f]/;function ve(e){return Re.test(e)?e.replace(Ce,""):e}var $e=`${f.green}\u2713${f.reset}`,Ee=`${f.yellow}\u25CB${f.reset}`,Se=`${f.red}\u2717${f.reset}`,{dim:Te,reset:Ae}=f,A=[];function Me(){if(A.length===1)queueMicrotask(j)}function j(){if(A.length===0)return;let e=A.join(`
9
+ `);A=[],process.stdout.write(`${e}
10
+ `)}function B(e,t,n,r){if(r)return;let c=t<300?$e:t<400?Ee:Se;A.push(`${c} ${Te}${e}${Ae} ${t} ${ve(n)}`),Me()}function P(e,t=!1){if(t)return;console.log(`${f.cyan}\u2502${f.reset} ${e}`)}function Oe(e){return e.split(/[/\\]/).some((t)=>t.startsWith(".")||t==="node_modules")}function De(e){if(e.length===0)return"reload";return e.every((t)=>t?.endsWith(".css"))?"css":"reload"}function ze(){let e=ge();for(let t of Object.values(e))for(let n of t??[])if(n.family==="IPv4"&&!n.internal)return n.address;return null}function He(e,t,n,r){if(console.log(),console.log(` ${f.bold}deserved${f.reset} ${f.dim}serving${f.reset} ${t}`),console.log(` ${f.green}->${f.reset} ${f.cyan}${e}${f.reset}`),r)console.log(` ${f.green}->${f.reset} ${f.cyan}${r}${f.reset}`);if(n.length)console.log(` ${f.dim}${n.join(" ")}${f.reset}`);console.log()}function Ie(e,t){if(e)return;console.log(`${f.yellow}*${f.reset} ${t}`)}function Fe(e){if(process.platform==="darwin")return["open",e];if(process.platform==="win32")return["cmd","/c","start","",e];return["xdg-open",e]}async function Pe(e){try{await Bun.spawn(Fe(e),{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${e}`)}}function Ne(e){try{if(!pe(e).isDirectory())throw new E(`not a directory: ${e}`)}catch(t){if(t instanceof E)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new E(`directory not found: ${e}`);throw new E(`not a directory: ${e}`)}}async function q(e){let t=ye(e.root);Ne(t);let n=e.watch?we():void 0,r=N({...e,root:t},n),c=e.host==="localhost"?"127.0.0.1":e.host,o=async(h)=>{if(e.cors&&h.method==="OPTIONS")return M(new Response(null,{status:204}),e);return r(h)},i=(h)=>Bun.serve({port:h,hostname:c,fetch:o}),s=!e.portExplicit&&e.port!==0,a,u=e.port;try{a=i(u)}catch(h){if(!s||!_(h))throw new T(e.host,u,{cause:h});let b,C=e.port,R=h;for(let v=1;v<=xe;v++){C=e.port+v;try{b=i(C),u=C;break}catch(F){if(!_(F))throw new T(e.host,C,{cause:F});R=F}}if(!b)throw new T(e.host,C,{cause:R});a=b,P(`port ${e.port} in use, using ${u}`,e.quiet)}let d=e.host==="0.0.0.0"||e.host==="::",p=d?"localhost":e.host,m=be(p,a.port??e.port),l=d?ze():null,y=l?`http://${l}:${a.port}`:void 0,x=[];if(e.spa)x.push("--spa");if(e.watch)x.push("--watch");if(e.cors)x.push("--cors");if(!e.dir)x.push("--no-dir");if(!e.compress)x.push("--no-compress");if(e.cache)x.push("--cache");He(m,he(process.cwd(),t)||".",x,y);let g;if(e.watch&&n){let h=null,b=new Set;g=me(t,{recursive:!0},(C,R)=>{if(R&&Oe(R))return;if(r.invalidateResolutionCache(),r.invalidateCompressedCache(),b.add(R),h)clearTimeout(h);h=setTimeout(()=>{let v=De([...b]);b.clear(),Ie(e.quiet,v),n.broadcast(v)},80)}),P("watching for changes",e.quiet)}let w=async()=>{g?.close(),n?.close(),await a.stop(),j(),P("server stopped",e.quiet)};if(e.open)await Pe(m);return{port:a.port??e.port,hostname:p,url:m,stop:w}}async function Be(e={}){let t=e.portExplicit??e.port!==void 0;return q({...U,...e,portExplicit:t})}var Ue=new TextEncoder,G="application/octet-stream",We={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function je(e,t){let n=e.type;if(n&&n!==G&&n!=="")return n;let r=_e(t).toLowerCase();return We[r]??G}function qe(e){let t=e.indexOf(";"),n=(t===-1?e:e.slice(0,t)).trim().toLowerCase();return n.startsWith("text/")||n==="application/javascript"||n==="text/javascript"||n==="application/json"||n==="application/xml"||n==="image/svg+xml"||n.endsWith("+json")||n.endsWith("+xml")}function Ge(e){return e.startsWith("text/html")}function Ve(e,t,n=""){return`"${e}-${Math.trunc(t)}${n}"`}function V(e){return e.startsWith("W/")?e.slice(2):e}function Ke(e,t){if(e.indexOf(",")===-1)return V(e.trim())===t;return e.split(",").some((n)=>V(n.trim())===t)}function Ye(e,t){let n=e.headers.get("If-Modified-Since");if(!n)return!1;let r=Date.parse(n);if(Number.isNaN(r))return!1;return Math.trunc(t/1000)*1000<=r}function Je(e,t,n){let r=e.headers.get("If-None-Match");return r?Ke(r,t):Ye(e,n)}function Xe(e,t,n){let r=e.headers.get("If-Range");if(!r)return!0;if(r.startsWith('"')||r.startsWith("W/"))return r===t;let c=Date.parse(r);if(Number.isNaN(c))return!1;return c===Math.trunc(n/1000)*1000}function Qe(e){let t=e.headers.get("Accept");if(!t||t==="*/*")return!0;return t.includes("text/html")||t.includes("application/xhtml")}function Ze(e){let t=e.headers.get("Accept-Encoding")??"";if(t.includes("zstd"))return"zstd";if(t.includes("gzip"))return"gzip";return null}function et(e){if(e.startsWith("/__"))return!1;let t=e.lastIndexOf("/");if(t===e.length-1)return!0;return e.indexOf(".",t+1)===-1}function tt(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,""),c=st(r);for(let o of c){let i=ue(e,o);if(!i)continue;let s=de(t,i);if(!s)continue;let a=le(s,rt(o));if(a)return a}return null}function le(e,t){try{let n=I(e);if(n.isFile())return{path:e,file:Bun.file(e),size:n.size,mtimeMs:n.mtimeMs,kind:t}}catch{}return null}var K=4096;function Y(e,t){if(e.size<t)return;let n=e.keys().next().value;if(n!==void 0)e.delete(n)}function O(e,t,n){e.delete(t),e.set(t,n)}var J=500;function nt(e,t,n){let r=new Map,c=new Map;function o(s){let a=r.get(s);if(a&&(n||Date.now()-a.at<J)){if(a.value===null)return O(r,s,a),null;if(n)return O(r,s,a),a.value;let d=le(a.value.path,a.value.kind);if(d)return O(r,s,a),d}let u=tt(e,t,s);return Y(r,K),r.set(s,{value:u,at:Date.now()}),u}function i(s){let a=c.get(s);if(a&&(n||Date.now()-a.at<J)){if(a.value===null)return O(c,s,a),null;try{if(I(a.value).isDirectory())return O(c,s,a),a.value}catch{}}let u=it(e,t,s);return Y(c,K),c.set(s,{value:u,at:Date.now()}),u}return{resolveCached:o,resolveDirCached:i,invalidate:()=>{r.clear(),c.clear()},size:()=>r.size}}function rt(e){if(e.endsWith("/index.html"))return"dir-index";if(e.endsWith(".html"))return"html-ext";return"file"}function st(e){if(!e||e===".")return["index.html"];let t=e.endsWith("/"),n=t?e.slice(0,-1):e;if(!n)return["index.html"];if(t)return[`${n}/index.html`];return[n,`${n}.html`,`${n}/index.html`]}function ue(e,t){let n=ke(e)?e:ce(e),r=ie(n,t);if(r!==n&&!r.startsWith(n+ae))return null;return r}function de(e,t){try{let n=oe(t);if(n!==e&&!n.startsWith(e+ae))return null;return n}catch{return null}}function ot(e){try{return oe(e)}catch{return null}}function it(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,"").replace(/\/+$/,""),c=ue(e,r||".");if(!c)return null;let o=de(t,c);if(!o)return null;try{return I(o).isDirectory()?o:null}catch{return null}}function ct(e){if(e===null)return"-";if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} kB`;return`${(e/1048576).toFixed(1)} MB`}function at(e){if(e===null)return"-";let t=new Date(e),n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),c=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${c} ${o}:${i}`}function lt(e){let t=Le(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.name.startsWith("."))continue;let c=r.isDirectory(),o=null,i=null;if(!c)try{let s=I(ie(e,r.name));o=s.size,i=s.mtimeMs}catch{}n.push({name:r.name,dir:c,size:o,mtimeMs:i})}return n.sort((r,c)=>{if(r.dir!==c.dir)return r.dir?-1:1;return r.name.localeCompare(c.name)})}function ut(e,t){let n=e.endsWith("/")?e:`${e}/`,r=X(n),c=dt(e),o=S(e),i=t.map((a)=>{let u=ft(r,encodeURIComponent(a.name))+(a.dir?"/":""),d=a.dir?`${a.name}/`:a.name,p=ct(a.size),m=at(a.mtimeMs);return` <li><a href="${S(u)}">${S(d)}</a> <span class="meta">${S(p)}</span> <span class="meta">${S(m)}</span></li>`}).join(`
11
+ `),s=c!==null?` <li><a href="${S(X(c))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
10
12
  `:"";return`<!DOCTYPE html>
11
13
  <html lang="en">
12
14
  <head>
13
15
  <meta charset="utf-8">
14
16
  <meta name="viewport" content="width=device-width, initial-scale=1">
15
- <title>Index of ${w(Q)}</title>
17
+ <title>Index of ${o}</title>
16
18
  <style>
17
19
  :root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
18
20
  body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
@@ -25,10 +27,10 @@ import{readdirSync as LQ,realpathSync as s,statSync as q}from"fs";import{extname
25
27
  </style>
26
28
  </head>
27
29
  <body>
28
- <h1>Index of ${w(Q||"/")}</h1>
30
+ <h1>Index of ${o||"/"}</h1>
29
31
  <ul>
30
- ${X}${W}
32
+ ${s}${i}
31
33
  </ul>
32
34
  </body>
33
35
  </html>
34
- `}function rQ(Q){if(Q==="/"||Q==="")return null;let Z=Q.replace(/\/+$/,""),$=Z.lastIndexOf("/");if($<=0)return"/";return Z.slice(0,$+1)}function i(Q){return Q.split("/").map(encodeURIComponent).join("/")}function aQ(Q,Z){if(Q==="/")return`/${Z}`;return`${Q.replace(/\/+$/,"")}/${Z}`}function u(Q,Z){let $=e(Q.root),Y=lQ($),G=mQ($,Y,Q.watch),W=ZZ(),X=async function(V){let j=new URL(V.url),D=V.method.toUpperCase(),B;if(j.pathname.includes("%"))try{B=decodeURIComponent(j.pathname)}catch{let U=new Response("Bad Request",{status:400});return L(D,400,j.pathname,Q.quiet),T(D,M(U,Q))}else B=j.pathname;try{return await sQ(V,D,B,j,Q,Z,$,Y,G.resolveCached,W.getCompressed)}catch(U){console.error(U);let O=new Response("Internal Server Error",{status:500});return L(D,500,j.pathname,Q.quiet),T(D,M(O,Q))}};return X.invalidateResolutionCache=G.invalidate,X.invalidateCompressedCache=W.invalidate,X.resolutionCacheSize=G.size,X.compressedCacheBytes=W.bytes,X}function d(Q,Z){let $=`${Q.pathname}/${Q.search}`,Y=new Response(null,{status:301,headers:{Location:$}});return M(Y,Z)}async function sQ(Q,Z,$,Y,G,W,X,J,V,j){let D=(O)=>{return L(Z,O.status,$,G.quiet),T(Z,M(O,G))};if(Z!=="GET"&&Z!=="HEAD"){let O=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return D(O)}if(G.watch&&$===C){let O=new Response(c,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return D(O)}if(G.watch&&$===R&&W){let O=W.subscribe();return L(Z,200,$,G.quiet),M(O,G)}if($===C||$===R)return T(Z,M(new Response("Not Found",{status:404}),G));let B=V($);if(B){if(B.kind==="dir-index"&&!$.endsWith("/")){let k=d(Y,G);return L(Z,k.status,$,G.quiet),T(Z,k)}let O=await r(j,Q,B,G);return D(O)}if(G.spa&&p(Q)&&uQ($)){let O=V("/");if(O){let k=await r(j,Q,O,G,!0);return D(k)}}if(G.dir){let O=pQ(X,J,$);if(O){if(!$.endsWith("/")){let F=d(Y,G);return L(Z,F.status,$,G.quiet),T(Z,F)}let k=dQ(O),x=oQ($,k),_=G.watch?A(x):x,I=new Response(_,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return D(I)}}if(p(Q)){let O=V("/404.html");if(O){let k=await O.file.text(),x=G.watch?A(k):k,_=new Response(x,{status:404,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return D(_)}}let U=new Response("Not Found",{status:404});return D(U)}var tQ=67108864,eQ=SQ(HQ);async function QZ(Q,Z){if(Q==="zstd")return new Uint8Array(await Bun.zstdCompress(Z));return new Uint8Array(await eQ(Z))}function ZZ(){let Q=new Map,Z=0,$=new Map;function Y(X,J){let V=Q.get(X);if(V)Q.delete(X),Z-=V.data.byteLength;Q.set(X,J),Z+=J.data.byteLength;while(Z>tQ&&Q.size>1){let j=Q.keys().next().value;if(j===void 0)break;let D=Q.get(j);if(Q.delete(j),D)Z-=D.data.byteLength}}let G=async(X,J,V)=>{let j=`${X.key}:${J}`,D=Q.get(j);if(D&&D.size===X.size&&D.mtimeMs===X.mtimeMs)return Y(j,D),D.data;let B=$.get(j);if(B&&B.size===X.size&&B.mtimeMs===X.mtimeMs)return B.promise;let U={size:X.size,mtimeMs:X.mtimeMs,promise:Promise.resolve(null)};return U.promise=(async()=>{try{let O=await V(),k=await QZ(J,O);return Y(j,{size:X.size,mtimeMs:X.mtimeMs,data:k}),k}catch{return null}finally{if($.get(j)?.promise===U.promise)$.delete(j)}})(),$.set(j,U),U.promise};function W(){Q.clear(),Z=0,$.clear()}return{getCompressed:G,invalidate:W,bytes:()=>Z}}async function o(Q,Z,$,Y,G){let W=yQ(Z);if(!W)return null;let X=await Q(Y,W,G);if(!X)return null;return $.set("Content-Encoding",W),$.set("Content-Length",String(X.byteLength)),$.delete("Accept-Ranges"),$.set("Vary","Accept-Encoding"),new Response(X,{status:200,headers:$})}async function r(Q,Z,$,Y,G=!1){let{path:W,file:X,size:J,mtimeMs:V}=$,j=MQ(X,W),D=G||EQ(j),B=AQ(J,V,Y.watch&&D?"-live":""),U=Y.compress&&f(j);if(qQ(Z,B,V)){let x=a(B,Y,D,V);if(U)x.set("Vary","Accept-Encoding");return new Response(null,{status:304,headers:x})}let O=a(B,Y,D,V);if(O.set("Content-Type",j),O.set("Accept-Ranges","bytes"),U)O.set("Vary","Accept-Encoding");let k=Z.headers.get("Range")&&vQ(Z,B,V)?Z.headers.get("Range"):null;if(k&&Z.method==="GET"){let x=$Z(k,J);if(x==="invalid")return O.set("Content-Range",`bytes */${J}`),new Response(null,{status:416,headers:O});if(x){let{start:_,end:I}=x,F=I-_+1;return O.set("Content-Range",`bytes ${_}-${I}/${J}`),O.set("Content-Length",String(F)),new Response(X.slice(_,I+1),{status:206,headers:O})}}if(Z.method==="HEAD")return O.set("Content-Length",String(J)),new Response(null,{status:200,headers:O});if(Y.watch&&D&&Z.method==="GET"){if(Y.compress&&f(j)){let _=await o(Q,Z,O,{key:`${W}\x00live`,size:J,mtimeMs:V},async()=>PQ.encode(A(await X.text())));if(_)return _}let x=A(await X.text());return O.set("Content-Length",String(Buffer.byteLength(x))),new Response(x,{status:200,headers:O})}if(Y.compress&&Z.method==="GET"&&f(j)&&J<2000000){let x=await o(Q,Z,O,{key:W,size:J,mtimeMs:V},async()=>new Uint8Array(await X.arrayBuffer()));if(x)return x}return O.set("Content-Length",String(J)),new Response(X,{status:200,headers:O})}function a(Q,Z,$,Y){let G=new Headers;if(G.set("ETag",Q),G.set("Last-Modified",new Date(Y).toUTCString()),Z.watch||!Z.cache||$)return G.set("Cache-Control","no-cache"),G;return G.set("Cache-Control","public, max-age=31536000, immutable"),G}function $Z(Q,Z){let $=/^bytes=(\d*)-(\d*)$/.exec(Q.trim());if(!$)return null;let Y=$[1],G=$[2],W,X;if(Y===""&&G==="")return"invalid";if(Y===""){let J=Number(G);if(!Number.isFinite(J)||J<=0)return"invalid";W=Math.max(0,Z-J),X=Z-1}else W=Number(Y),X=G===""?Z-1:Number(G);if(!Number.isFinite(W)||!Number.isFinite(X)||W<0||X<W||W>=Z)return"invalid";return X=Math.min(X,Z-1),{start:W,end:X}}function M(Q,Z){if(!Z.cors)return Q;return Q.headers.set("Access-Control-Allow-Origin","*"),Q.headers.set("Access-Control-Allow-Headers","*"),Q.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),Q}function T(Q,Z){if(Q!=="HEAD")return Z;return new Response(null,{status:Z.status,statusText:Z.statusText,headers:Z.headers})}export{h as startServer,KQ as serve,u as createHandler,P as RootError,m as DEFAULT_OPTIONS,E as BindError};
36
+ `}function dt(e){if(e==="/"||e==="")return null;let t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");if(n<=0)return"/";return t.slice(0,n+1)}function X(e){return e.split("/").map(encodeURIComponent).join("/")}function ft(e,t){if(e==="/")return`/${t}`;return`${e.replace(/\/+$/,"")}/${t}`}function pt(e){let t=e.indexOf("//"),n=e.indexOf("/",t===-1?0:t+2);if(n===-1)return"/";let r=e.length,c=e.indexOf("?",n);if(c!==-1&&c<r)r=c;let o=e.indexOf("#",n);if(o!==-1&&o<r)r=o;let i=e.slice(n,r);return i===""?"/":i}function N(e,t){let n=ce(e.root),r=ot(n),c=nt(n,r,e.watch),o=xt(),i={opts:e,hub:t,resolveCached:c.resolveCached,resolveDirCached:c.resolveDirCached,getCompressed:o.getCompressed,notFound:null},s=async function(u){let d=pt(u.url),p=u.method.toUpperCase(),m;if(d.includes("%"))try{m=decodeURIComponent(d)}catch{let l=new Response("Bad Request",{status:400});return L(p,d,e,l)}else m=d;try{return await mt(u,p,m,d,i)}catch(l){console.error(l);let y=new Response("Internal Server Error",{status:500});return L(p,d,e,y)}};return s.invalidateResolutionCache=()=>{c.invalidate(),i.notFound=null},s.invalidateCompressedCache=o.invalidate,s.resolutionCacheSize=c.size,s.compressedCacheBytes=o.bytes,s}function L(e,t,n,r){return B(e,r.status,t,n.quiet),fe(e,M(r,n))}function Q(e,t){return new Response(null,{status:301,headers:{Location:`${e}/${new URL(t).search}`}})}function Z(e,t,n=200){return new Response(t.watch?H(e):e,{status:n,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function mt(e,t,n,r,c){let{opts:o,hub:i,resolveCached:s,resolveDirCached:a,getCompressed:u}=c,d=(l)=>L(t,n,o,l);if(t!=="GET"&&t!=="HEAD"){let l=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return d(l)}if(o.watch&&n===D){let l=new Response(W,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return d(l)}if(o.watch&&n===z&&i){let l=i.subscribe();return B(t,200,n,o.quiet),M(l,o)}if(n===D||n===z)return fe(t,M(new Response("Not Found",{status:404}),o));let p=s(n);if(p){if(p.kind==="dir-index"&&!n.endsWith("/"))return d(Q(r,e.url));return d(await te(u,e,p,o))}let m=Qe(e);if(o.spa&&m&&et(n)){let l=s("/");if(l)return d(await te(u,e,l,o,!0))}if(o.dir){let l=a(n);if(l){if(!n.endsWith("/"))return d(Q(r,e.url));let y=ut(n,lt(l));return d(Z(y,o))}}if(m){let l=s("/404.html");if(l){let y=c.notFound,x=y&&y.size===l.size&&y.mtimeMs===l.mtimeMs?y.html:await(async()=>{let g=await l.file.text();return c.notFound={size:l.size,mtimeMs:l.mtimeMs,html:g},g})();return d(Z(x,o,404))}}return d(new Response("Not Found",{status:404}))}var gt=67108864;async function ht(e){let t=new CompressionStream("gzip"),n=t.writable.getWriter();return n.write(e),n.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function yt(e,t){if(e==="zstd")return new Uint8Array(await Bun.zstdCompress(t));return ht(t)}function xt(){let e=new Map,t=0,n=new Map;function r(i,s){let a=e.get(i);if(a)e.delete(i),t-=a.data.size;e.set(i,s),t+=s.data.size;while(t>gt&&e.size>1){let u=e.keys().next().value;if(u===void 0)break;let d=e.get(u);if(e.delete(u),d)t-=d.data.size}}let c=async(i,s,a)=>{let u=`${i.key}:${s}`,d=e.get(u);if(d&&d.size===i.size&&d.mtimeMs===i.mtimeMs)return r(u,d),d.data;let p=n.get(u);if(p&&p.size===i.size&&p.mtimeMs===i.mtimeMs)return p.promise;let m=(async()=>{try{let y=await a(),x=new Blob([await yt(s,y)]);return r(u,{size:i.size,mtimeMs:i.mtimeMs,data:x}),x}catch{return null}})(),l={size:i.size,mtimeMs:i.mtimeMs,promise:m};return n.set(u,l),m.finally(()=>{if(n.get(u)===l)n.delete(u)}),m};function o(){e.clear(),t=0,n.clear()}return{getCompressed:c,invalidate:o,bytes:()=>t}}async function ee(e,t,n,r,c){let o=Ze(t);if(!o)return null;let i=await e(r,o,c);if(!i)return null;return n["Content-Encoding"]=o,n["Content-Length"]=String(i.size),delete n["Accept-Ranges"],n.Vary="Accept-Encoding",new Response(i,{status:200,headers:n})}async function te(e,t,n,r,c=!1){let{path:o,file:i,size:s,mtimeMs:a}=n,u=je(i,o),d=c||Ge(u),p=Ve(s,a,r.watch&&d?"-live":""),m=r.compress&&qe(u);if(Je(t,p,a)){let g=se(p,r,d,a);if(m)g.Vary="Accept-Encoding";return new Response(null,{status:304,headers:g})}let l=se(p,r,d,a);if(l["Content-Type"]=u,l["Accept-Ranges"]="bytes",m)l.Vary="Accept-Encoding";let y=t.headers.get("Range"),x=y&&Xe(t,p,a)?y:null;if(x&&t.method==="GET"){let g=wt(x,s);if(g==="invalid")return l["Content-Range"]=`bytes */${s}`,new Response(null,{status:416,headers:l});if(g){let{start:w,end:h}=g,b=h-w+1;return l["Content-Range"]=`bytes ${w}-${h}/${s}`,l["Content-Length"]=String(b),new Response(i.slice(w,h+1),{status:206,headers:l})}}if(t.method==="HEAD")return l["Content-Length"]=String(s),new Response(null,{status:200,headers:l});if(r.watch&&d&&t.method==="GET"){if(m){let w=await ee(e,t,l,{key:`${o}\x00live`,size:s,mtimeMs:a},async()=>Ue.encode(H(await i.text())));if(w)return w}let g=H(await i.text());return l["Content-Length"]=String(Buffer.byteLength(g)),new Response(g,{status:200,headers:l})}if(m&&t.method==="GET"&&s<2000000){let g=await ee(e,t,l,{key:o,size:s,mtimeMs:a},()=>i.bytes());if(g)return g}return l["Content-Length"]=String(s),new Response(i,{status:200,headers:l})}var ne=Number.NaN,re="";function bt(e){if(e!==ne)ne=e,re=new Date(e).toUTCString();return re}function se(e,t,n,r){return{ETag:e,"Last-Modified":bt(r),"Cache-Control":t.watch||!t.cache||n?"no-cache":"public, max-age=31536000, immutable"}}function wt(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n)return null;let r=n[1],c=n[2],o,i;if(r===""&&c==="")return"invalid";if(r===""){let s=Number(c);if(!Number.isFinite(s)||s<=0)return"invalid";o=Math.max(0,t-s),i=t-1}else o=Number(r),i=c===""?t-1:Number(c);if(!Number.isFinite(o)||!Number.isFinite(i)||o<0||i<o||o>=t)return"invalid";return i=Math.min(i,t-1),{start:o,end:i}}function M(e,t){if(!t.cors)return e;return e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Headers","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e}function fe(e,t){if(e!=="HEAD")return t;return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})}export{T as BindError,U as DEFAULT_OPTIONS,E as RootError,N as createHandler,Be as serve,q as startServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deserved",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A tiny Bun static file server: SPA, live reload, zero dependencies",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,7 +9,11 @@
9
9
  },
10
10
  "module": "./index.js",
11
11
  "exports": {
12
- ".": "./index.js"
12
+ ".": {
13
+ "types": "./index.d.ts",
14
+ "default": "./index.js"
15
+ }
13
16
  },
14
- "main": "./index.js"
17
+ "main": "./index.js",
18
+ "types": "./index.d.ts"
15
19
  }
package/server.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export type Options = {
2
+ root: string;
3
+ port: number;
4
+ portExplicit: boolean;
5
+ host: string;
6
+ spa: boolean;
7
+ watch: boolean;
8
+ open: boolean;
9
+ cors: boolean;
10
+ dir: boolean;
11
+ cache: boolean;
12
+ compress: boolean;
13
+ quiet: boolean;
14
+ };
15
+ export declare const DEFAULT_OPTIONS: {
16
+ root: string;
17
+ port: number;
18
+ portExplicit: false;
19
+ host: string;
20
+ spa: false;
21
+ watch: false;
22
+ open: false;
23
+ cors: false;
24
+ dir: true;
25
+ cache: false;
26
+ compress: true;
27
+ quiet: false;
28
+ };
29
+ export type ServerHandle = {
30
+ port: number;
31
+ hostname: string;
32
+ url: string;
33
+ stop: () => Promise<void>;
34
+ };
35
+ export declare class RootError extends Error {
36
+ constructor(message: string, options?: ErrorOptions);
37
+ }
38
+ export declare class BindError extends Error {
39
+ constructor(host: string, port: number, options?: ErrorOptions);
40
+ }
41
+ export declare const LIVE_PATH = "/__live.js";
42
+ export declare const EVENTS_PATH = "/__events";
43
+ export declare const LIVE_SCRIPT = "(()=>{const e=new EventSource(\"/__events\");e.onmessage=(m)=>{if(m.data===\"css\"){for(const l of document.querySelectorAll('link[rel=\"stylesheet\"]')){const h=l.href.split(\"?\")[0];l.href=h+\"?t=\"+Date.now()}}else{location.reload()}};e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()";
44
+ export declare function formatUrl(host: string, port: number): string;
45
+ export declare function injectLiveReload(html: string): string;
46
+ export declare function createSseHub(): {
47
+ subscribe: () => Response;
48
+ broadcast: (data?: string) => void;
49
+ close: () => void;
50
+ };
51
+ export declare function flushLogs(): void;
52
+ export declare function logRequest(method: string, status: number, path: string, quiet: boolean): void;
53
+ export declare function isIgnoredWatchPath(filename: string): boolean;
54
+ export declare function classifyBatch(files: (string | null)[]): "css" | "reload";
55
+ export declare function startServer(opts: Options): Promise<ServerHandle>;
56
+ export declare function serve(options?: Partial<Options>): Promise<ServerHandle>;