@uppercut-labs/static-file-server 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Uppercut Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # @uppercut-labs/static-file-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Serves a folder over HTTP from Node with no dependencies. It rejects path traversal (including encoded dots and symlinks that leave the folder), sends the right content type, answers range requests so video can seek, and can fall back to `index.html` for client-side routes. It works as a function you call from code and as a small command line tool.
4
+
5
+ ```sh
6
+ npm install @uppercut-labs/static-file-server
7
+ ```
8
+
9
+ ```ts
10
+ import { startStaticServer } from '@uppercut-labs/static-file-server';
11
+
12
+ const site = await startStaticServer({ root: './dist', spaFallback: true });
13
+ console.log(site.url); // http://127.0.0.1:<free port>
14
+ // ...
15
+ await site.close();
16
+ ```
17
+
18
+ To use your own server, or to answer some routes yourself first, build a handler:
19
+
20
+ ```ts
21
+ import { createServer } from 'node:http';
22
+ import { createStaticHandler } from '@uppercut-labs/static-file-server';
23
+
24
+ const handle = createStaticHandler({ root: './dist', cleanUrls: true });
25
+ createServer((req, res) => void handle(req, res)).listen(3000);
26
+ ```
27
+
28
+ Stub routes, test controls and extra folders fit in two options:
29
+
30
+ ```ts
31
+ const site = await startStaticServer({
32
+ root: './dist',
33
+ cleanUrls: true,
34
+ // Answer a request yourself: return true when you did.
35
+ before: (req, res) => {
36
+ if (req.url === '/api/contact') {
37
+ res.writeHead(405).end('disabled');
38
+ return true;
39
+ }
40
+ return false;
41
+ },
42
+ // Serve another folder under a URL prefix.
43
+ mounts: { '/media': './media-files' },
44
+ });
45
+ ```
46
+
47
+ Command line:
48
+
49
+ ```sh
50
+ npx static-file-server ./dist --port 8080 --spa
51
+ ```
52
+
53
+ ## Functions
54
+
55
+ | Function | Returns |
56
+ | --- | --- |
57
+ | `startStaticServer(options)` | `Promise<{ server, host, port, url, close() }>`, listening |
58
+ | `createStaticServer(options)` | an `http.Server`, not yet listening |
59
+ | `createStaticHandler(options)` | `(request, response) => Promise<void>` |
60
+ | `resolveStaticPath(root, urlPath)` | `{ ok: true, file, isDirectory }` or `{ ok: false, problem }` where `problem` is `bad-request`, `forbidden` or `not-found` |
61
+ | `parseRange(header, size)` | `{ start, end }`, `'unsatisfiable'`, or `null` to send the whole file |
62
+ | `contentTypeFor(file, extra?)` | content type string |
63
+ | `MIME_TYPES` | the built-in extension table |
64
+
65
+ ## Options
66
+
67
+ | Option | Default | Meaning |
68
+ | --- | --- | --- |
69
+ | `root` | required | Folder to serve |
70
+ | `port` | `0` | Port for `startStaticServer`; 0 picks a free one |
71
+ | `host` | `127.0.0.1` | Interface for `startStaticServer` |
72
+ | `index` | `index.html` | Index file name |
73
+ | `spaFallback` | `false` | Send the index file for unknown paths without an extension. `{ exclude: ['/api'] }` keeps prefixes out |
74
+ | `cleanUrls` | `false` | Try `<path>.html` and `<path>/index.html`. When a folder and a `<path>.html` page share a name, the page is served (as in a static export) |
75
+ | `ranges` | `true` | Answer `Range` requests with 206 and 416 |
76
+ | `cacheControl` | `no-cache` | A string, or a function of the URL path |
77
+ | `headers` | none | Extra response headers, or a function of the file path |
78
+ | `mime` | none | Extra content types by extension |
79
+ | `notFoundFile` | none | File sent with 404 responses |
80
+ | `blockDotfiles` | `false` | 404 for any path segment that starts with a dot |
81
+ | `basePath` | none | URL prefix the site is served under |
82
+ | `allowedHosts` | any | Accepted `Host` names; others get 403 |
83
+ | `onRequest` | none | Called with `{ method, path, status, served }` for each request |
84
+ | `before` | none | `(request, response) => boolean \| Promise<boolean>`, called after the `allowedHosts` check. Return `true` when the hook answered the request; anything else lets it continue. Handled requests are not reported to `onRequest`. A throw becomes a 500 |
85
+ | `mounts` | none | `{ '/prefix': './folder' }`: serve more folders under URL prefixes with the same guard, ranges, headers and caching. The longest prefix wins, a mount shadows same-named files in `root`, and `spaFallback` never applies to a mount |
86
+
87
+ Only `GET` and `HEAD` are accepted; other methods get 405. A directory requested without a trailing slash is redirected with 301, and the query string is kept.
88
+
89
+ Changed in 0.2.0: added `before` and `mounts`; with `cleanUrls`, `<path>.html` is now served instead of a redirect when a folder has the same name; redirects keep the query string (0.1.0 dropped it).
90
+
91
+ Command line flags: `--port`, `--host`, `--spa`, `--clean-urls`, `--no-ranges`, `--cache`, `--dotfiles`. Paths with dot segments are hidden unless `--dotfiles` is given.
92
+
93
+ ## Errors
94
+
95
+ `startStaticServer` rejects if the port cannot be bound. Requests never throw: bad paths get 400, paths outside the root get 403, and read failures get 500.
96
+
97
+ ## License
98
+
99
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { startStaticServer } from './server.js';
4
+ const HELP = `Usage: static-file-server [folder] [options]
5
+
6
+ Serves a folder over HTTP. The folder defaults to the current directory.
7
+
8
+ Options:
9
+ -p, --port <n> Port to listen on (default 8080, 0 picks a free port)
10
+ --host <name> Interface to bind (default 127.0.0.1)
11
+ --spa Answer extensionless unknown paths with index.html
12
+ --clean-urls Try <path>.html and <path>/index.html
13
+ --no-ranges Ignore Range requests
14
+ --cache <value> Cache-Control header (default no-cache)
15
+ --dotfiles Serve paths with dot segments (hidden by default)
16
+ -h, --help Show this help
17
+ `;
18
+ async function main(argv) {
19
+ let parsed;
20
+ try {
21
+ parsed = parseArgs({
22
+ args: argv,
23
+ allowPositionals: true,
24
+ options: {
25
+ port: { type: 'string', short: 'p' },
26
+ host: { type: 'string' },
27
+ spa: { type: 'boolean' },
28
+ 'clean-urls': { type: 'boolean' },
29
+ 'no-ranges': { type: 'boolean' },
30
+ cache: { type: 'string' },
31
+ dotfiles: { type: 'boolean' },
32
+ help: { type: 'boolean', short: 'h' },
33
+ },
34
+ });
35
+ }
36
+ catch (error) {
37
+ process.stderr.write(`${error.message}\n\n${HELP}`);
38
+ return 2;
39
+ }
40
+ const { values, positionals } = parsed;
41
+ if (values.help) {
42
+ process.stdout.write(HELP);
43
+ return 0;
44
+ }
45
+ if (positionals.length > 1) {
46
+ process.stderr.write(`Expected at most one folder.\n\n${HELP}`);
47
+ return 2;
48
+ }
49
+ const port = values.port === undefined ? 8080 : Number(values.port);
50
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
51
+ process.stderr.write(`Invalid port: ${values.port}\n`);
52
+ return 2;
53
+ }
54
+ const folder = positionals[0] ?? '.';
55
+ const running = await startStaticServer({
56
+ root: folder,
57
+ port,
58
+ host: values.host,
59
+ spaFallback: values.spa,
60
+ cleanUrls: values['clean-urls'],
61
+ ranges: !values['no-ranges'],
62
+ cacheControl: values.cache,
63
+ blockDotfiles: !values.dotfiles,
64
+ });
65
+ process.stdout.write(`Serving ${folder} at ${running.url}\n`);
66
+ const stop = () => {
67
+ void running.close().then(() => process.exit(0));
68
+ };
69
+ process.on('SIGINT', stop);
70
+ process.on('SIGTERM', stop);
71
+ return -1;
72
+ }
73
+ main(process.argv.slice(2)).then((code) => {
74
+ if (code >= 0)
75
+ process.exit(code);
76
+ }, (error) => {
77
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
78
+ process.exit(1);
79
+ });
@@ -0,0 +1,7 @@
1
+ export { MIME_TYPES, contentTypeFor } from './mime.js';
2
+ export { isInside, resolveStaticPath } from './path.js';
3
+ export type { PathProblem, ResolvedPath } from './path.js';
4
+ export { parseRange } from './range.js';
5
+ export type { ByteRange } from './range.js';
6
+ export { createStaticHandler, createStaticServer, startStaticServer } from './server.js';
7
+ export type { RunningServer, ServedRequest, StartOptions, StaticHandler, StaticOptions } from './server.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { MIME_TYPES, contentTypeFor } from './mime.js';
2
+ export { isInside, resolveStaticPath } from './path.js';
3
+ export { parseRange } from './range.js';
4
+ export { createStaticHandler, createStaticServer, startStaticServer } from './server.js';
package/dist/mime.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** Content types for common web files. Text types carry a UTF-8 charset. */
2
+ export declare const MIME_TYPES: Readonly<Record<string, string>>;
3
+ /**
4
+ * Content type for a file name. `extra` entries (keys like `.glb`, case-insensitive) win over the
5
+ * built-in table. Unknown extensions get `application/octet-stream`.
6
+ */
7
+ export declare function contentTypeFor(file: string, extra?: Readonly<Record<string, string>>): string;
package/dist/mime.js ADDED
@@ -0,0 +1,50 @@
1
+ import path from 'node:path';
2
+ /** Content types for common web files. Text types carry a UTF-8 charset. */
3
+ export const MIME_TYPES = {
4
+ '.html': 'text/html; charset=utf-8',
5
+ '.htm': 'text/html; charset=utf-8',
6
+ '.js': 'text/javascript; charset=utf-8',
7
+ '.mjs': 'text/javascript; charset=utf-8',
8
+ '.css': 'text/css; charset=utf-8',
9
+ '.json': 'application/json; charset=utf-8',
10
+ '.map': 'application/json; charset=utf-8',
11
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
12
+ '.txt': 'text/plain; charset=utf-8',
13
+ '.md': 'text/markdown; charset=utf-8',
14
+ '.xml': 'application/xml; charset=utf-8',
15
+ '.csv': 'text/csv; charset=utf-8',
16
+ '.svg': 'image/svg+xml',
17
+ '.png': 'image/png',
18
+ '.jpg': 'image/jpeg',
19
+ '.jpeg': 'image/jpeg',
20
+ '.gif': 'image/gif',
21
+ '.webp': 'image/webp',
22
+ '.avif': 'image/avif',
23
+ '.ico': 'image/x-icon',
24
+ '.woff': 'font/woff',
25
+ '.woff2': 'font/woff2',
26
+ '.ttf': 'font/ttf',
27
+ '.otf': 'font/otf',
28
+ '.mp3': 'audio/mpeg',
29
+ '.wav': 'audio/wav',
30
+ '.ogg': 'audio/ogg',
31
+ '.mp4': 'video/mp4',
32
+ '.webm': 'video/webm',
33
+ '.pdf': 'application/pdf',
34
+ '.wasm': 'application/wasm',
35
+ '.zip': 'application/zip',
36
+ };
37
+ /**
38
+ * Content type for a file name. `extra` entries (keys like `.glb`, case-insensitive) win over the
39
+ * built-in table. Unknown extensions get `application/octet-stream`.
40
+ */
41
+ export function contentTypeFor(file, extra) {
42
+ const ext = path.extname(file).toLowerCase();
43
+ if (extra) {
44
+ for (const [key, value] of Object.entries(extra)) {
45
+ if (key.toLowerCase() === ext)
46
+ return value;
47
+ }
48
+ }
49
+ return MIME_TYPES[ext] ?? 'application/octet-stream';
50
+ }
package/dist/path.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /** Why a URL path could not be turned into a file inside the root. */
2
+ export type PathProblem = 'bad-request' | 'forbidden' | 'not-found';
3
+ export type ResolvedPath = {
4
+ ok: true;
5
+ file: string;
6
+ isDirectory: boolean;
7
+ } | {
8
+ ok: false;
9
+ problem: PathProblem;
10
+ };
11
+ /**
12
+ * Maps a URL path (no query string) to a file or directory inside `root`.
13
+ *
14
+ * The path is percent-decoded first, so `%2e%2e` is treated like `..`. Backslashes and NUL bytes are
15
+ * rejected (`bad-request`), a path that leaves the root is `forbidden`, and a missing entry is
16
+ * `not-found`. The real path after following symlinks must still be inside the real root, so a link
17
+ * that points outside the folder is `forbidden`. Names that merely contain `..`, such as `a..b.txt`,
18
+ * are allowed.
19
+ */
20
+ export declare function resolveStaticPath(root: string, urlPath: string): Promise<ResolvedPath>;
21
+ /** True when `target` is `root` itself or lies below it. */
22
+ export declare function isInside(root: string, target: string): boolean;
package/dist/path.js ADDED
@@ -0,0 +1,52 @@
1
+ import { realpath, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * Maps a URL path (no query string) to a file or directory inside `root`.
5
+ *
6
+ * The path is percent-decoded first, so `%2e%2e` is treated like `..`. Backslashes and NUL bytes are
7
+ * rejected (`bad-request`), a path that leaves the root is `forbidden`, and a missing entry is
8
+ * `not-found`. The real path after following symlinks must still be inside the real root, so a link
9
+ * that points outside the folder is `forbidden`. Names that merely contain `..`, such as `a..b.txt`,
10
+ * are allowed.
11
+ */
12
+ export async function resolveStaticPath(root, urlPath) {
13
+ let decoded;
14
+ try {
15
+ decoded = decodeURIComponent(urlPath);
16
+ }
17
+ catch {
18
+ return { ok: false, problem: 'bad-request' };
19
+ }
20
+ if (decoded.includes('\0') || decoded.includes(String.fromCharCode(92)))
21
+ return { ok: false, problem: 'bad-request' };
22
+ const base = path.resolve(root);
23
+ const candidate = path.resolve(base, `.${decoded.startsWith('/') ? decoded : `/${decoded}`}`);
24
+ if (!isInside(base, candidate))
25
+ return { ok: false, problem: 'forbidden' };
26
+ let info;
27
+ let real;
28
+ try {
29
+ info = await stat(candidate);
30
+ real = await realpath(candidate);
31
+ }
32
+ catch {
33
+ return { ok: false, problem: 'not-found' };
34
+ }
35
+ let realRoot;
36
+ try {
37
+ realRoot = await realpath(base);
38
+ }
39
+ catch {
40
+ return { ok: false, problem: 'not-found' };
41
+ }
42
+ if (!isInside(realRoot, real))
43
+ return { ok: false, problem: 'forbidden' };
44
+ return { ok: true, file: candidate, isDirectory: info.isDirectory() };
45
+ }
46
+ /** True when `target` is `root` itself or lies below it. */
47
+ export function isInside(root, target) {
48
+ if (target === root)
49
+ return true;
50
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
51
+ return target.startsWith(prefix);
52
+ }
@@ -0,0 +1,13 @@
1
+ export interface ByteRange {
2
+ start: number;
3
+ end: number;
4
+ }
5
+ /**
6
+ * Parses one `Range: bytes=...` header against a file size.
7
+ *
8
+ * Returns a satisfiable inclusive range, `'unsatisfiable'` when it lies outside the file (answer 416),
9
+ * or `null` when the whole file should be sent: no header, another unit, a malformed value or several
10
+ * ranges. Suffix ranges (`bytes=-500`) and open-ended ranges (`bytes=100-`) are supported, and an end
11
+ * past the last byte is clamped.
12
+ */
13
+ export declare function parseRange(header: string | undefined, size: number): ByteRange | 'unsatisfiable' | null;
package/dist/range.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Parses one `Range: bytes=...` header against a file size.
3
+ *
4
+ * Returns a satisfiable inclusive range, `'unsatisfiable'` when it lies outside the file (answer 416),
5
+ * or `null` when the whole file should be sent: no header, another unit, a malformed value or several
6
+ * ranges. Suffix ranges (`bytes=-500`) and open-ended ranges (`bytes=100-`) are supported, and an end
7
+ * past the last byte is clamped.
8
+ */
9
+ export function parseRange(header, size) {
10
+ if (header === undefined)
11
+ return null;
12
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
13
+ if (match === null)
14
+ return null;
15
+ const [, first, last] = match;
16
+ if (first === '' && last === '')
17
+ return null;
18
+ if (first === '') {
19
+ const suffix = Number(last);
20
+ if (suffix === 0 || size === 0)
21
+ return 'unsatisfiable';
22
+ return { start: Math.max(0, size - suffix), end: size - 1 };
23
+ }
24
+ const start = Number(first);
25
+ const end = last === '' ? size - 1 : Math.min(Number(last), size - 1);
26
+ if (start >= size || start > end)
27
+ return 'unsatisfiable';
28
+ return { start, end };
29
+ }
@@ -0,0 +1,81 @@
1
+ import type { IncomingMessage, Server, ServerResponse } from 'node:http';
2
+ export interface ServedRequest {
3
+ method: string;
4
+ /** URL path of the request, or the raw target when it could not be parsed. */
5
+ path: string;
6
+ status: number;
7
+ /**
8
+ * `file`: the file named by the URL. `index`: a directory's index file. `clean-url`: `.html` or
9
+ * `/index.html` added to the path. `fallback`: the SPA index for a client route. `none`: no file was sent.
10
+ */
11
+ served: 'file' | 'index' | 'clean-url' | 'fallback' | 'none';
12
+ }
13
+ export interface StaticOptions {
14
+ /** Folder to serve. */
15
+ root: string;
16
+ /** Name of a directory's index file. Default `index.html`. */
17
+ index?: string;
18
+ /**
19
+ * Answer unknown paths without a file extension with the index file (status 200), for client-side
20
+ * routing. Paths whose last segment has an extension stay 404, so a missing asset is never hidden.
21
+ * Pass `{ exclude: ['/api'] }` to keep path prefixes out of the fallback.
22
+ */
23
+ spaFallback?: boolean | {
24
+ exclude?: string[];
25
+ };
26
+ /** Try `<path>.html` and `<path>/index.html` for extensionless paths. Default false. */
27
+ cleanUrls?: boolean;
28
+ /** Answer `Range` requests with 206 and 416. Default true. */
29
+ ranges?: boolean;
30
+ /** `Cache-Control` value, or a function of the URL path. Default `no-cache`. */
31
+ cacheControl?: string | ((urlPath: string) => string);
32
+ /** Extra response headers, or a function of the file path that returns them. */
33
+ headers?: Record<string, string> | ((file: string) => Record<string, string>);
34
+ /** Extra content types by extension, for example `{ '.glb': 'model/gltf-binary' }`. */
35
+ mime?: Record<string, string>;
36
+ /** File inside the root sent with 404 responses, for example `404.html`. */
37
+ notFoundFile?: string;
38
+ /** Answer 404 for any path with a segment that starts with a dot. Default false. */
39
+ blockDotfiles?: boolean;
40
+ /** URL prefix the site is mounted under, for example `/docs`. Paths outside it are 404. */
41
+ basePath?: string;
42
+ /** Accepted `Host` header names (without port). Others get 403. Default: any host. */
43
+ allowedHosts?: string[];
44
+ /**
45
+ * Run before anything is served, after the `allowedHosts` check. Return `true` (or a promise of `true`)
46
+ * when the hook has answered the request itself, for example a stub route or a test control. Any other
47
+ * result lets the request continue to the folder. Handled requests are not passed to `onRequest`.
48
+ * If the hook throws, the request gets a 500 unless the hook already sent headers.
49
+ */
50
+ before?: (request: IncomingMessage, response: ServerResponse) => boolean | Promise<boolean>;
51
+ /**
52
+ * Serve more folders under URL prefixes, for example `{ '/media': './catalog' }`. A request below a
53
+ * prefix is looked up in that folder with the prefix removed, using the same path guard, ranges,
54
+ * headers and caching. The longest matching prefix wins, and a mount shadows files of the same name in
55
+ * `root`. The `spaFallback` never applies to a mounted folder, so a missing file is a 404.
56
+ */
57
+ mounts?: Record<string, string>;
58
+ /** Called once per finished request. */
59
+ onRequest?: (request: ServedRequest) => void;
60
+ }
61
+ export interface StartOptions extends StaticOptions {
62
+ /** Port to listen on; 0 picks a free one. Default 0. */
63
+ port?: number;
64
+ /** Interface to bind. Default `127.0.0.1`. */
65
+ host?: string;
66
+ }
67
+ export interface RunningServer {
68
+ server: Server;
69
+ host: string;
70
+ port: number;
71
+ /** `http://host:port`. */
72
+ url: string;
73
+ close(): Promise<void>;
74
+ }
75
+ export type StaticHandler = (request: IncomingMessage, response: ServerResponse) => Promise<void>;
76
+ /** Builds a `(req, res)` handler that serves `options.root`. Use it with `http.createServer` or inside another server. */
77
+ export declare function createStaticHandler(options: StaticOptions): StaticHandler;
78
+ /** An `http.Server` that serves `options.root`. It is not listening yet. */
79
+ export declare function createStaticServer(options: StaticOptions): Server;
80
+ /** Starts serving `options.root` and resolves once the server is listening. */
81
+ export declare function startStaticServer(options: StartOptions): Promise<RunningServer>;
package/dist/server.js ADDED
@@ -0,0 +1,242 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import path from 'node:path';
5
+ import { contentTypeFor } from './mime.js';
6
+ import { resolveStaticPath } from './path.js';
7
+ import { parseRange } from './range.js';
8
+ /** Builds a `(req, res)` handler that serves `options.root`. Use it with `http.createServer` or inside another server. */
9
+ export function createStaticHandler(options) {
10
+ const root = path.resolve(options.root);
11
+ const indexName = options.index ?? 'index.html';
12
+ const rangesOn = options.ranges ?? true;
13
+ const basePath = normalizeBase(options.basePath);
14
+ const hosts = options.allowedHosts ? new Set(options.allowedHosts.map((host) => host.toLowerCase())) : null;
15
+ const exclude = typeof options.spaFallback === 'object' ? (options.spaFallback.exclude ?? []) : [];
16
+ const mounts = Object.entries(options.mounts ?? {})
17
+ .map(([prefix, folder]) => ({ prefix: normalizeBase(prefix), root: path.resolve(folder) }))
18
+ .filter((mount) => mount.prefix !== '')
19
+ .sort((a, b) => b.prefix.length - a.prefix.length);
20
+ async function locate(root, local, decoded, mounted) {
21
+ const first = await resolveStaticPath(root, local);
22
+ if (!first.ok) {
23
+ if (first.problem === 'bad-request')
24
+ return 'bad-request';
25
+ if (first.problem === 'forbidden')
26
+ return 'forbidden';
27
+ }
28
+ else if (first.isDirectory) {
29
+ if (!local.endsWith('/')) {
30
+ // A static export has both `docs.html` and a `docs/` folder: the page wins over the redirect.
31
+ if (options.cleanUrls) {
32
+ const page = await resolveStaticPath(root, `${local}.html`);
33
+ if (page.ok && !page.isDirectory)
34
+ return { file: page.file, served: 'clean-url' };
35
+ }
36
+ return 'redirect';
37
+ }
38
+ const inner = await resolveStaticPath(root, `${local}${indexName}`);
39
+ if (inner.ok && !inner.isDirectory)
40
+ return { file: inner.file, served: 'index' };
41
+ }
42
+ else {
43
+ return { file: first.file, served: 'file' };
44
+ }
45
+ const lastSegment = decoded.split('/').filter(Boolean).pop() ?? '';
46
+ const extensionless = path.extname(lastSegment) === '';
47
+ if (options.cleanUrls && extensionless && lastSegment !== '' && !decoded.endsWith('/')) {
48
+ for (const candidate of [`${local}.html`, `${local}/${indexName}`]) {
49
+ const hit = await resolveStaticPath(root, candidate);
50
+ if (hit.ok && !hit.isDirectory)
51
+ return { file: hit.file, served: 'clean-url' };
52
+ }
53
+ }
54
+ const excluded = exclude.some((prefix) => decoded === prefix || decoded.startsWith(`${prefix.replace(/\/$/, '')}/`));
55
+ if (options.spaFallback && extensionless && !excluded && !mounted) {
56
+ const shell = await resolveStaticPath(root, `/${indexName}`);
57
+ if (shell.ok && !shell.isDirectory)
58
+ return { file: shell.file, served: 'fallback' };
59
+ }
60
+ return null;
61
+ }
62
+ return async (request, response) => {
63
+ const method = request.method ?? 'GET';
64
+ let logged = false;
65
+ const finish = (status, urlPath, served) => {
66
+ if (logged)
67
+ return;
68
+ logged = true;
69
+ options.onRequest?.({ method, path: urlPath, status, served });
70
+ };
71
+ const reply = (status, urlPath, body, extra = {}) => {
72
+ response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...extra });
73
+ response.end(method === 'HEAD' ? undefined : body);
74
+ finish(status, urlPath, 'none');
75
+ };
76
+ const notFound = async (urlPath) => {
77
+ if (options.notFoundFile) {
78
+ const page = await resolveStaticPath(root, `/${options.notFoundFile}`);
79
+ if (page.ok && !page.isDirectory) {
80
+ const body = await readFile(page.file);
81
+ response.writeHead(404, { 'content-type': contentTypeFor(page.file, options.mime), 'content-length': body.length, 'cache-control': 'no-store' });
82
+ response.end(method === 'HEAD' ? undefined : body);
83
+ finish(404, urlPath, 'none');
84
+ return;
85
+ }
86
+ }
87
+ reply(404, urlPath, 'Not found\n');
88
+ };
89
+ const send = async (found, urlPath) => {
90
+ const info = await stat(found.file);
91
+ const cache = typeof options.cacheControl === 'function' ? options.cacheControl(urlPath) : (options.cacheControl ?? 'no-cache');
92
+ const custom = typeof options.headers === 'function' ? options.headers(found.file) : (options.headers ?? {});
93
+ const headers = {
94
+ ...custom,
95
+ 'content-type': contentTypeFor(found.file, options.mime),
96
+ 'cache-control': cache,
97
+ 'last-modified': info.mtime.toUTCString(),
98
+ };
99
+ if (rangesOn)
100
+ headers['accept-ranges'] = 'bytes';
101
+ const range = rangesOn ? parseRange(request.headers.range, info.size) : null;
102
+ if (range === 'unsatisfiable') {
103
+ response.writeHead(416, { ...headers, 'content-range': `bytes */${info.size}`, 'content-length': 0 });
104
+ response.end();
105
+ finish(416, urlPath, 'none');
106
+ return;
107
+ }
108
+ const status = range === null ? 200 : 206;
109
+ headers['content-length'] = range === null ? info.size : range.end - range.start + 1;
110
+ if (range !== null)
111
+ headers['content-range'] = `bytes ${range.start}-${range.end}/${info.size}`;
112
+ response.writeHead(status, headers);
113
+ finish(status, urlPath, found.served);
114
+ if (method === 'HEAD' || info.size === 0) {
115
+ response.end();
116
+ return;
117
+ }
118
+ createReadStream(found.file, range === null ? undefined : { start: range.start, end: range.end })
119
+ .on('error', () => response.destroy())
120
+ .pipe(response);
121
+ };
122
+ try {
123
+ if (hosts !== null) {
124
+ const host = (request.headers.host ?? '').toLowerCase().replace(/:\d+$/, '').replace(/^\[(.*)\]$/, '$1');
125
+ if (!hosts.has(host))
126
+ return reply(403, request.url ?? '/', 'Host not allowed\n');
127
+ }
128
+ if (options.before && (await options.before(request, response)) === true)
129
+ return;
130
+ if (method !== 'GET' && method !== 'HEAD')
131
+ return reply(405, request.url ?? '/', 'Method not allowed\n', { allow: 'GET, HEAD' });
132
+ let urlPath;
133
+ let search;
134
+ try {
135
+ const parsed = new URL(request.url ?? '/', 'http://localhost');
136
+ urlPath = parsed.pathname;
137
+ search = parsed.search;
138
+ decodeURIComponent(urlPath);
139
+ }
140
+ catch {
141
+ return reply(400, request.url ?? '/', 'Bad request\n');
142
+ }
143
+ let local = urlPath;
144
+ if (basePath !== '') {
145
+ if (urlPath === basePath) {
146
+ response.writeHead(301, { location: `${basePath}/${search}` });
147
+ response.end();
148
+ return finish(301, urlPath, 'none');
149
+ }
150
+ if (!urlPath.startsWith(`${basePath}/`))
151
+ return await notFound(urlPath);
152
+ local = urlPath.slice(basePath.length);
153
+ }
154
+ const decoded = safeDecode(local);
155
+ if (options.blockDotfiles && decoded.split('/').some((segment) => segment.startsWith('.')))
156
+ return await notFound(urlPath);
157
+ let folder = root;
158
+ let inFolder = local;
159
+ let inFolderDecoded = decoded;
160
+ let mounted = false;
161
+ for (const mount of mounts) {
162
+ if (local === mount.prefix) {
163
+ response.writeHead(301, { location: `${urlPath}/${search}` });
164
+ response.end();
165
+ return finish(301, urlPath, 'none');
166
+ }
167
+ if (local.startsWith(`${mount.prefix}/`)) {
168
+ folder = mount.root;
169
+ inFolder = local.slice(mount.prefix.length);
170
+ inFolderDecoded = safeDecode(inFolder);
171
+ mounted = true;
172
+ break;
173
+ }
174
+ }
175
+ const outcome = await locate(folder, inFolder, inFolderDecoded, mounted);
176
+ if (outcome === 'redirect') {
177
+ response.writeHead(301, { location: `${urlPath}/${search}` });
178
+ response.end();
179
+ return finish(301, urlPath, 'none');
180
+ }
181
+ if (outcome === 'bad-request')
182
+ return reply(400, urlPath, 'Bad request\n');
183
+ if (outcome === 'forbidden')
184
+ return reply(403, urlPath, 'Forbidden\n');
185
+ if (outcome === null)
186
+ return await notFound(urlPath);
187
+ await send(outcome, urlPath);
188
+ }
189
+ catch {
190
+ if (!response.headersSent) {
191
+ response.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
192
+ response.end('Server error\n');
193
+ }
194
+ else
195
+ response.destroy();
196
+ finish(500, request.url ?? '/', 'none');
197
+ }
198
+ };
199
+ }
200
+ /** An `http.Server` that serves `options.root`. It is not listening yet. */
201
+ export function createStaticServer(options) {
202
+ const handler = createStaticHandler(options);
203
+ return createServer((request, response) => {
204
+ void handler(request, response);
205
+ });
206
+ }
207
+ /** Starts serving `options.root` and resolves once the server is listening. */
208
+ export async function startStaticServer(options) {
209
+ const host = options.host ?? '127.0.0.1';
210
+ const server = createStaticServer(options);
211
+ await new Promise((resolve, reject) => {
212
+ server.once('error', reject);
213
+ server.listen(options.port ?? 0, host, () => {
214
+ server.off('error', reject);
215
+ resolve();
216
+ });
217
+ });
218
+ const port = server.address().port;
219
+ const shown = host.includes(':') ? `[${host}]` : host;
220
+ return {
221
+ server,
222
+ host,
223
+ port,
224
+ url: `http://${shown}:${port}`,
225
+ close: () => new Promise((resolve) => {
226
+ server.close(() => resolve());
227
+ server.closeAllConnections();
228
+ }),
229
+ };
230
+ }
231
+ function normalizeBase(base) {
232
+ const trimmed = (base ?? '').split('/').filter(Boolean).join('/');
233
+ return trimmed === '' ? '' : `/${trimmed}`;
234
+ }
235
+ function safeDecode(value) {
236
+ try {
237
+ return decodeURIComponent(value);
238
+ }
239
+ catch {
240
+ return value;
241
+ }
242
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@uppercut-labs/static-file-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Dependency-free Node static file server with a path-traversal guard, MIME map, range requests and optional SPA fallback.",
5
+ "license": "MIT",
6
+ "author": "Uppercut Labs <packages@uppercut-labs.com>",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "main": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "bin": {
17
+ "static-file-server": "./dist/cli.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "sideEffects": false,
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.json",
27
+ "prepack": "node -e \"require('fs').copyFileSync('../../LICENSE','LICENSE')\""
28
+ },
29
+ "keywords": [
30
+ "static",
31
+ "file-server",
32
+ "http",
33
+ "spa",
34
+ "range",
35
+ "preview"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/uppercut-labs/js-kit.git",
40
+ "directory": "packages/static-file-server"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/uppercut-labs/js-kit/issues"
44
+ },
45
+ "homepage": "https://github.com/uppercut-labs/js-kit/tree/main/packages/static-file-server#readme",
46
+ "engines": {
47
+ "node": ">=18"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }