deserved 0.1.0 → 0.3.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 +2 -2
- package/cli.js +12 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ bunx deserved [path] [options]
|
|
|
31
31
|
| `-o, --open` | Open the browser |
|
|
32
32
|
| `--cors` | Enable CORS |
|
|
33
33
|
| `--no-dir` | Disable directory listing |
|
|
34
|
-
| `--
|
|
34
|
+
| `--cache` | Long-lived, immutable cache headers for assets |
|
|
35
35
|
| `--no-compress` | Disable gzip |
|
|
36
36
|
| `-q, --quiet` | Suppress request logs |
|
|
37
37
|
|
|
@@ -56,6 +56,6 @@ bunx deserved dist --watch
|
|
|
56
56
|
- SPA mode (HTML Accept only; assets still 404)
|
|
57
57
|
- Optional live reload (`--watch`) via Server-Sent Events
|
|
58
58
|
- Gzip compression
|
|
59
|
-
-
|
|
59
|
+
- Cache headers off by default (`no-cache`); opt in per-run with `--cache` for long-lived, immutable asset caching
|
|
60
60
|
- Directory listings (disable with `--no-dir`)
|
|
61
61
|
- Colored request logs
|
package/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{resolve as
|
|
4
|
-
`),
|
|
3
|
+
import{resolve as i0}from"path";var z="0.3.0";import{watch as T0}from"fs";import{networkInterfaces as f0}from"os";import{relative as z0,resolve as H0}from"path";import{readdirSync as t,realpathSync as q,statSync as c}from"fs";import{extname as a,join as e,normalize as $0,resolve as i,sep as n}from"path";import{promisify as O0}from"util";import{gzip as D0}from"zlib";var{escapeHTML:K}=globalThis.Bun;var G0=new TextEncoder,H="application/octet-stream",Q0={".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 Y0($,O){let D=$.type;if(D&&D!==H&&D!=="")return D;let Y=a(O).toLowerCase();return Q0[Y]??H}function T($){let O=$.split(";")[0]?.trim().toLowerCase()??"";return O.startsWith("text/")||O==="application/javascript"||O==="text/javascript"||O==="application/json"||O==="application/xml"||O==="image/svg+xml"||O.endsWith("+json")||O.endsWith("+xml")}function Z0($){return $.startsWith("text/html")}function X0($,O,D=""){return`"${$}-${Math.trunc(O)}${D}"`}function N0($,O){let D=$.headers.get("If-None-Match");if(!D)return!1;return D.split(",").some((Y)=>Y.trim().replace(/^W\//,"")===O)}function W0($,O){let D=$.headers.get("If-Modified-Since");if(!D)return!1;let Y=Date.parse(D);if(Number.isNaN(Y))return!1;return Math.trunc(O/1000)*1000<=Y}function x0($,O,D){return $.headers.get("If-None-Match")?N0($,O):W0($,D)}function k0($,O,D){let Y=$.headers.get("If-Range");if(!Y)return!0;if(Y.startsWith('"')||Y.startsWith("W/"))return Y===O;let G=Date.parse(Y);if(Number.isNaN(G))return!1;return G===Math.trunc(D/1000)*1000}function M($){let O=$.headers.get("Accept");if(!O||O==="*/*")return!0;return O.includes("text/html")||O.includes("application/xhtml")}function B0($){let O=$.headers.get("Accept-Encoding")??"";if(O.includes("zstd"))return"zstd";if(O.includes("gzip"))return"gzip";return null}function J0($){if($.startsWith("/__"))return!1;let O=$.slice($.lastIndexOf("/")+1);if(!O)return!0;if(O.includes("."))return!1;return!0}function f($,O,D){if(!O)return null;let Y=D.replace(/^\/+/,""),G=V0(Y);for(let Z of G){let X=m($,Z);if(!X)continue;let N=h(O,X);if(!N)continue;try{let k=c(N);if(k.isFile())return{path:N,file:Bun.file(N),size:k.size,mtimeMs:k.mtimeMs,kind:j0(Z)}}catch{}}return null}function j0($){if($.endsWith("/index.html"))return"dir-index";if($.endsWith(".html")&&!$.endsWith("/index.html"))return"html-ext";return"file"}function V0($){if(!$||$===".")return["index.html"];let O=$.endsWith("/")?$.slice(0,-1):$;if(!O)return["index.html"];if($.endsWith("/"))return[`${O}/index.html`];return[O,`${O}.html`,`${O}/index.html`]}function m($,O){let D=i($),Y=$0(e(D,O));if(Y!==D&&!Y.startsWith(D+n))return null;return Y}function h($,O){try{let D=q(O);if(D!==$&&!D.startsWith($+n))return null;return D}catch{return null}}var C=new Map;function I0($){let O=C.get($);if(O===void 0){try{O=q($)}catch{O=null}C.set($,O)}return O}function U0($,O,D){if(!O)return null;let Y=D.replace(/^\/+/,"").replace(/\/+$/,""),G=m($,Y||".");if(!G)return null;let Z=h(O,G);if(!Z)return null;try{if(c(Z).isDirectory())return Z}catch{return null}return null}function u0($){return t($,{withFileTypes:!0}).filter((O)=>!O.name.startsWith(".")).map((O)=>({name:O.name,dir:O.isDirectory()})).sort((O,D)=>{if(O.dir!==D.dir)return O.dir?-1:1;return O.name.localeCompare(D.name)})}function _0($,O){let D=$.endsWith("/")?$:`${$}/`,Y=v(D),G=E0($),Z=O.map((N)=>{let k=K0(Y,encodeURIComponent(N.name))+(N.dir?"/":""),j=N.dir?`${N.name}/`:N.name;return` <li><a href="${K(k)}">${K(j)}</a></li>`}).join(`
|
|
4
|
+
`),X=G!==null?` <li><a href="${K(v(G))}">../</a></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 ${
|
|
10
|
+
<title>Index of ${K($)}</title>
|
|
11
11
|
<style>
|
|
12
12
|
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
13
13
|
body { max-width: 40rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
@@ -19,17 +19,17 @@ import{resolve as M0}from"path";var L="0.1.0";import{watch as j0}from"fs";import
|
|
|
19
19
|
</style>
|
|
20
20
|
</head>
|
|
21
21
|
<body>
|
|
22
|
-
<h1>Index of ${
|
|
22
|
+
<h1>Index of ${K($||"/")}</h1>
|
|
23
23
|
<ul>
|
|
24
|
-
${
|
|
24
|
+
${X}${Z}
|
|
25
25
|
</ul>
|
|
26
26
|
</body>
|
|
27
27
|
</html>
|
|
28
|
-
`}function
|
|
28
|
+
`}function E0($){if($==="/"||$==="")return null;let O=$.replace(/\/+$/,""),D=O.lastIndexOf("/");if(D<=0)return"/";return O.slice(0,D+1)}function v($){return $.split("/").map(encodeURIComponent).join("/")}function K0($,O){if($==="/")return`/${O}`;return`${$.replace(/\/+$/,"")}/${O}`}function l($,O){let D=i($.root),Y=I0(D);return async function(Z){let X=new URL(Z.url),N=Z.method.toUpperCase(),k;try{k=decodeURIComponent(X.pathname)}catch{let j=new Response("Bad Request",{status:400});return u(N,400,X.pathname,$.quiet),_(N,E(j,$))}try{return await F0(Z,N,k,X,$,O,D,Y)}catch(j){console.error(j);let I=new Response("Internal Server Error",{status:500});return u(N,500,X.pathname,$.quiet),_(N,E(I,$))}}}function A($,O){let D=`${$.pathname}/${$.search}`,Y=new Response(null,{status:301,headers:{Location:D}});return E(Y,O)}async function F0($,O,D,Y,G,Z,X,N){let k=(W)=>{return u(O,W.status,D,G.quiet),_(O,E(W,G))};if(O!=="GET"&&O!=="HEAD"){let W=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return k(W)}if(G.watch&&D===w){let W=new Response(p,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return k(W)}if(G.watch&&D===L&&Z){let W=Z.subscribe();return u(O,200,D,G.quiet),E(W,G)}if(D===w||D===L)return _(O,E(new Response("Not Found",{status:404}),G));let j=f(X,N,D);if(j){if(j.kind==="dir-index"&&!D.endsWith("/")){let x=A(Y,G);return u(O,x.status,D,G.quiet),_(O,x)}let W=await g($,j,G);return k(W)}if(G.spa&&M($)&&J0(D)){let W=f(X,N,"/");if(W){let x=await g($,W,G,!0);return k(x)}}if(G.dir){let W=U0(X,N,D);if(W){if(!D.endsWith("/")){let U=A(Y,G);return u(O,U.status,D,G.quiet),_(O,U)}let x=u0(W),V=_0(D,x),Q=G.watch?F(V):V,J=new Response(Q,{headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return k(J)}}if(M($)){let W=f(X,N,"/404.html");if(W){let x=await W.file.text(),V=G.watch?F(x):x,Q=new Response(V,{status:404,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}});return k(Q)}}let I=new Response("Not Found",{status:404});return k(I)}var y=new Map,P=new Map,S0=O0(D0);async function P0($,O){if($==="zstd")return new Uint8Array(await Bun.zstdCompress(O));return new Uint8Array(await S0(O))}async function w0($,O,D){let Y=`${$.key}:${O}`,G=y.get(Y);if(G&&G.size===$.size&&G.mtimeMs===$.mtimeMs)return G.data;let Z=P.get(Y);if(Z&&Z.size===$.size&&Z.mtimeMs===$.mtimeMs)return Z.promise;let X={size:$.size,mtimeMs:$.mtimeMs,promise:Promise.resolve(null)};return X.promise=(async()=>{try{let N=await D(),k=await P0(O,N);return y.set(Y,{size:$.size,mtimeMs:$.mtimeMs,data:k}),k}catch{return null}finally{if(P.get(Y)?.promise===X.promise)P.delete(Y)}})(),P.set(Y,X),X.promise}async function b($,O,D,Y){let G=B0($);if(!G)return null;let Z=await w0(D,G,Y);if(!Z)return null;return O.set("Content-Encoding",G),O.set("Content-Length",String(Z.byteLength)),O.delete("Accept-Ranges"),O.set("Vary","Accept-Encoding"),new Response(Z,{status:200,headers:O})}async function g($,O,D,Y=!1){let{path:G,file:Z,size:X,mtimeMs:N}=O,k=Y0(Z,G),j=Y||Z0(k),I=X0(X,N,D.watch&&j?"-live":""),W=D.compress&&T(k);if(x0($,I,N)){let Q=R(I,D,j,N);if(W)Q.set("Vary","Accept-Encoding");return new Response(null,{status:304,headers:Q})}let x=R(I,D,j,N);if(x.set("Content-Type",k),x.set("Accept-Ranges","bytes"),W)x.set("Vary","Accept-Encoding");let V=$.headers.get("Range")&&k0($,I,N)?$.headers.get("Range"):null;if(V&&$.method==="GET"){let Q=L0(V,X);if(Q==="invalid")return x.set("Content-Range",`bytes */${X}`),new Response(null,{status:416,headers:x});if(Q){let{start:J,end:U}=Q,r=U-J+1;return x.set("Content-Range",`bytes ${J}-${U}/${X}`),x.set("Content-Length",String(r)),new Response(Z.slice(J,U+1),{status:206,headers:x})}}if($.method==="HEAD")return x.set("Content-Length",String(X)),new Response(null,{status:200,headers:x});if(D.watch&&j&&$.method==="GET"){if(D.compress&&T(k)){let J=await b($,x,{key:`${G}\x00live`,size:X,mtimeMs:N},async()=>G0.encode(F(await Z.text())));if(J)return J}let Q=F(await Z.text());return x.set("Content-Length",String(Buffer.byteLength(Q))),new Response(Q,{status:200,headers:x})}if(D.compress&&$.method==="GET"&&T(k)&&X<2000000){let Q=await b($,x,{key:G,size:X,mtimeMs:N},async()=>new Uint8Array(await Z.arrayBuffer()));if(Q)return Q}return x.set("Content-Length",String(X)),new Response(Z,{status:200,headers:x})}function R($,O,D,Y){let G=new Headers;if(G.set("ETag",$),G.set("Last-Modified",new Date(Y).toUTCString()),O.watch||!O.cache||D)return G.set("Cache-Control","no-cache"),G;return G.set("Cache-Control","public, max-age=31536000, immutable"),G}function L0($,O){let D=/^bytes=(\d*)-(\d*)$/.exec($.trim());if(!D)return null;let Y=D[1],G=D[2],Z,X;if(Y===""&&G==="")return"invalid";if(Y===""){let N=Number(G);if(!Number.isFinite(N)||N<=0)return"invalid";Z=Math.max(0,O-N),X=O-1}else Z=Number(Y),X=G===""?O-1:Number(G);if(!Number.isFinite(Z)||!Number.isFinite(X)||Z<0||X<Z||Z>=O)return"invalid";return X=Math.min(X,O-1),{start:Z,end:X}}function E($,O){if(!O.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 _($,O){if($!=="HEAD")return O;return new Response(null,{status:O.status,statusText:O.statusText,headers:O.headers})}var w="/__live.js",L="/__events",p=`(()=>{const e=new EventSource("${L}");e.onmessage=()=>location.reload();e.onerror=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,d=`<script src="${w}"></script>`;function M0($,O){return`http://${$.includes(":")?`[${$}]`:$}:${O}`}function F($){let O=$.toLowerCase().lastIndexOf("</body>");if(O===-1)return $+d;return $.slice(0,O)+d+$.slice(O)}function C0(){let $=new Set,O=new TextEncoder;function D(){let G,Z=new ReadableStream({start(X){G=X,$.add(X),X.enqueue(O.encode(`: connected
|
|
29
29
|
|
|
30
|
-
`))},cancel(){
|
|
30
|
+
`))},cancel(){$.delete(G)}});return new Response(Z,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function Y(G="reload"){let Z=O.encode(`data: ${G}
|
|
31
31
|
|
|
32
|
-
`);for(let
|
|
32
|
+
`);for(let X of $)try{X.enqueue(Z)}catch{$.delete(X)}}return{subscribe:D,broadcast:Y}}var B={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},v0=/[\x00-\x1f\x7f]/g;function A0($){return $.replace(v0,"")}function u($,O,D,Y){if(Y)return;let G=O<300?`${B.green}\u2713${B.reset}`:O<400?`${B.yellow}\u25CB${B.reset}`:`${B.red}\u2717${B.reset}`;console.log(`${G} ${B.dim}${$}${B.reset} ${O} ${A0(D)}`)}function y0($,O=!1){if(O)return;console.log(`${B.cyan}\u2502${B.reset} ${$}`)}function b0($){return $.split(/[/\\]/).some((O)=>O.startsWith(".")||O==="node_modules")}function g0(){let $=f0();for(let O of Object.values($))for(let D of O??[])if(D.family==="IPv4"&&!D.internal)return D.address;return null}function R0($,O,D,Y){if(console.log(),console.log(` ${B.bold}deserved${B.reset} ${B.dim}serving${B.reset} ${O}`),console.log(` ${B.green}->${B.reset} ${B.cyan}${$}${B.reset}`),Y)console.log(` ${B.green}->${B.reset} ${B.cyan}${Y}${B.reset}`);if(D.length)console.log(` ${B.dim}${D.join(" ")}${B.reset}`);console.log()}function q0($){if($)return;console.log(`${B.yellow}*${B.reset} reload`)}async function c0($){let O=process.platform;try{if(O==="darwin")await Bun.spawn(["open",$],{stdout:"ignore",stderr:"ignore"}).exited;else if(O==="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 ${$}`)}}async function o($){let O=H0($.root),D=$.watch?C0():void 0,Y=l({...$,root:O},D),G=$.host==="localhost"?"127.0.0.1":$.host,Z;try{Z=Bun.serve({port:$.port,hostname:G,fetch:async(Q)=>{if($.cors&&Q.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(Q)}})}catch(Q){console.error(`Error: could not bind to ${$.host}:${$.port}`),console.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}let X=$.host==="0.0.0.0"||$.host==="::",N=X?"localhost":$.host,k=M0(N,Z.port??$.port),j=X?g0():null,I=j?`http://${j}:${Z.port}`:void 0,W=[];if($.spa)W.push("--spa");if($.watch)W.push("--watch");if($.cors)W.push("--cors");if(!$.dir)W.push("--no-dir");if(!$.compress)W.push("--no-compress");if($.cache)W.push("--cache");R0(k,z0(process.cwd(),O)||".",W,I);let x;if($.watch&&D){let Q=null;x=T0(O,{recursive:!0},(J,U)=>{if(U&&b0(U))return;if(Q)clearTimeout(Q);Q=setTimeout(()=>{q0($.quiet),D.broadcast("reload")},80)}),y0("watching for changes",$.quiet)}let V=async()=>{x?.close(),await Z.stop(),process.exit(0)};if(process.on("SIGINT",V),process.on("SIGTERM",V),$.open)await c0(k);return Z}function n0(){console.log(`
|
|
33
33
|
deserved - tiny Bun static file server
|
|
34
34
|
|
|
35
35
|
Usage
|
|
@@ -44,9 +44,9 @@ ${Q}${Z}
|
|
|
44
44
|
--cors Enable CORS
|
|
45
45
|
--dir Enable directory listing (default)
|
|
46
46
|
--no-dir Disable directory listing
|
|
47
|
-
--cache
|
|
48
|
-
--no-cache Disable cache headers
|
|
49
|
-
--compress
|
|
47
|
+
--cache Long-lived, immutable cache headers for assets
|
|
48
|
+
--no-cache Disable cache headers (default)
|
|
49
|
+
--compress zstd or gzip, negotiated per request (default)
|
|
50
50
|
--no-compress Disable compression
|
|
51
51
|
-q, --quiet Suppress request logs
|
|
52
52
|
-h, --help Show help
|
|
@@ -57,4 +57,4 @@ ${Q}${Z}
|
|
|
57
57
|
deserved dist --spa
|
|
58
58
|
deserved dist --port 8080
|
|
59
59
|
deserved docs --watch --open
|
|
60
|
-
`)}function
|
|
60
|
+
`)}function m0($){let O=$.slice(2),D=".",Y=3000,G="localhost",Z=!1,X=!1,N=!1,k=!1,j=!0,I=!1,W=!0,x=!1;for(let V=0;V<O.length;V++){let Q=O[V];if(Q===void 0)break;if(Q==="-h"||Q==="--help")n0(),process.exit(0);if(Q==="-v"||Q==="--version")console.log(z),process.exit(0);if(Q==="-s"||Q==="--spa"){Z=!0;continue}if(Q==="-w"||Q==="--watch"){X=!0;continue}if(Q==="-o"||Q==="--open"){N=!0;continue}if(Q==="--cors"){k=!0;continue}if(Q==="--dir"){j=!0;continue}if(Q==="--no-dir"){j=!1;continue}if(Q==="--cache"){I=!0;continue}if(Q==="--no-cache"){I=!1;continue}if(Q==="--compress"){W=!0;continue}if(Q==="--no-compress"){W=!1;continue}if(Q==="-q"||Q==="--quiet"){x=!0;continue}if(Q==="-p"||Q==="--port"){let J=O[++V];if(!J||J.startsWith("-"))S(`Missing value for ${Q}`);let U=Number(J);if(!Number.isInteger(U)||U<0||U>65535)S(`Invalid port: ${J}`);Y=U;continue}if(Q==="-H"||Q==="--host"){let J=O[++V];if(!J||J.startsWith("-"))S(`Missing value for ${Q}`);G=J;continue}if(Q.startsWith("--port=")){let J=Number(Q.slice(7));if(!Number.isInteger(J)||J<0||J>65535)S(`Invalid port: ${Q}`);Y=J;continue}if(Q.startsWith("--host=")){G=Q.slice(7);continue}if(Q.startsWith("-"))S(`Unknown option: ${Q}`);D=Q}return{root:i0(D),port:Y,host:G,spa:Z,watch:X,open:N,cors:k,dir:j,cache:I,compress:W,quiet:x}}function S($){console.error(`Error: ${$}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let $=m0(process.argv);await o($)}export{m0 as parseArgs};
|