@uppercut-labs/static-file-server 0.1.0 → 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/README.md +26 -3
- package/dist/cli.js +0 -0
- package/dist/server.d.ts +14 -0
- package/dist/server.js +41 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ console.log(site.url); // http://127.0.0.1:<free port>
|
|
|
15
15
|
await site.close();
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
To use your own server, build a handler:
|
|
18
|
+
To use your own server, or to answer some routes yourself first, build a handler:
|
|
19
19
|
|
|
20
20
|
```ts
|
|
21
21
|
import { createServer } from 'node:http';
|
|
@@ -25,6 +25,25 @@ const handle = createStaticHandler({ root: './dist', cleanUrls: true });
|
|
|
25
25
|
createServer((req, res) => void handle(req, res)).listen(3000);
|
|
26
26
|
```
|
|
27
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
|
+
|
|
28
47
|
Command line:
|
|
29
48
|
|
|
30
49
|
```sh
|
|
@@ -52,7 +71,7 @@ npx static-file-server ./dist --port 8080 --spa
|
|
|
52
71
|
| `host` | `127.0.0.1` | Interface for `startStaticServer` |
|
|
53
72
|
| `index` | `index.html` | Index file name |
|
|
54
73
|
| `spaFallback` | `false` | Send the index file for unknown paths without an extension. `{ exclude: ['/api'] }` keeps prefixes out |
|
|
55
|
-
| `cleanUrls` | `false` | Try `<path>.html` and `<path>/index.html` |
|
|
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) |
|
|
56
75
|
| `ranges` | `true` | Answer `Range` requests with 206 and 416 |
|
|
57
76
|
| `cacheControl` | `no-cache` | A string, or a function of the URL path |
|
|
58
77
|
| `headers` | none | Extra response headers, or a function of the file path |
|
|
@@ -62,8 +81,12 @@ npx static-file-server ./dist --port 8080 --spa
|
|
|
62
81
|
| `basePath` | none | URL prefix the site is served under |
|
|
63
82
|
| `allowedHosts` | any | Accepted `Host` names; others get 403 |
|
|
64
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.
|
|
65
88
|
|
|
66
|
-
|
|
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).
|
|
67
90
|
|
|
68
91
|
Command line flags: `--port`, `--host`, `--spa`, `--clean-urls`, `--no-ranges`, `--cache`, `--dotfiles`. Paths with dot segments are hidden unless `--dotfiles` is given.
|
|
69
92
|
|
package/dist/cli.js
CHANGED
|
File without changes
|
package/dist/server.d.ts
CHANGED
|
@@ -41,6 +41,20 @@ export interface StaticOptions {
|
|
|
41
41
|
basePath?: string;
|
|
42
42
|
/** Accepted `Host` header names (without port). Others get 403. Default: any host. */
|
|
43
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>;
|
|
44
58
|
/** Called once per finished request. */
|
|
45
59
|
onRequest?: (request: ServedRequest) => void;
|
|
46
60
|
}
|
package/dist/server.js
CHANGED
|
@@ -13,7 +13,11 @@ export function createStaticHandler(options) {
|
|
|
13
13
|
const basePath = normalizeBase(options.basePath);
|
|
14
14
|
const hosts = options.allowedHosts ? new Set(options.allowedHosts.map((host) => host.toLowerCase())) : null;
|
|
15
15
|
const exclude = typeof options.spaFallback === 'object' ? (options.spaFallback.exclude ?? []) : [];
|
|
16
|
-
|
|
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) {
|
|
17
21
|
const first = await resolveStaticPath(root, local);
|
|
18
22
|
if (!first.ok) {
|
|
19
23
|
if (first.problem === 'bad-request')
|
|
@@ -22,8 +26,15 @@ export function createStaticHandler(options) {
|
|
|
22
26
|
return 'forbidden';
|
|
23
27
|
}
|
|
24
28
|
else if (first.isDirectory) {
|
|
25
|
-
if (!local.endsWith('/'))
|
|
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
|
+
}
|
|
26
36
|
return 'redirect';
|
|
37
|
+
}
|
|
27
38
|
const inner = await resolveStaticPath(root, `${local}${indexName}`);
|
|
28
39
|
if (inner.ok && !inner.isDirectory)
|
|
29
40
|
return { file: inner.file, served: 'index' };
|
|
@@ -41,7 +52,7 @@ export function createStaticHandler(options) {
|
|
|
41
52
|
}
|
|
42
53
|
}
|
|
43
54
|
const excluded = exclude.some((prefix) => decoded === prefix || decoded.startsWith(`${prefix.replace(/\/$/, '')}/`));
|
|
44
|
-
if (options.spaFallback && extensionless && !excluded) {
|
|
55
|
+
if (options.spaFallback && extensionless && !excluded && !mounted) {
|
|
45
56
|
const shell = await resolveStaticPath(root, `/${indexName}`);
|
|
46
57
|
if (shell.ok && !shell.isDirectory)
|
|
47
58
|
return { file: shell.file, served: 'fallback' };
|
|
@@ -114,11 +125,16 @@ export function createStaticHandler(options) {
|
|
|
114
125
|
if (!hosts.has(host))
|
|
115
126
|
return reply(403, request.url ?? '/', 'Host not allowed\n');
|
|
116
127
|
}
|
|
128
|
+
if (options.before && (await options.before(request, response)) === true)
|
|
129
|
+
return;
|
|
117
130
|
if (method !== 'GET' && method !== 'HEAD')
|
|
118
131
|
return reply(405, request.url ?? '/', 'Method not allowed\n', { allow: 'GET, HEAD' });
|
|
119
132
|
let urlPath;
|
|
133
|
+
let search;
|
|
120
134
|
try {
|
|
121
|
-
|
|
135
|
+
const parsed = new URL(request.url ?? '/', 'http://localhost');
|
|
136
|
+
urlPath = parsed.pathname;
|
|
137
|
+
search = parsed.search;
|
|
122
138
|
decodeURIComponent(urlPath);
|
|
123
139
|
}
|
|
124
140
|
catch {
|
|
@@ -127,7 +143,7 @@ export function createStaticHandler(options) {
|
|
|
127
143
|
let local = urlPath;
|
|
128
144
|
if (basePath !== '') {
|
|
129
145
|
if (urlPath === basePath) {
|
|
130
|
-
response.writeHead(301, { location: `${basePath}
|
|
146
|
+
response.writeHead(301, { location: `${basePath}/${search}` });
|
|
131
147
|
response.end();
|
|
132
148
|
return finish(301, urlPath, 'none');
|
|
133
149
|
}
|
|
@@ -138,9 +154,27 @@ export function createStaticHandler(options) {
|
|
|
138
154
|
const decoded = safeDecode(local);
|
|
139
155
|
if (options.blockDotfiles && decoded.split('/').some((segment) => segment.startsWith('.')))
|
|
140
156
|
return await notFound(urlPath);
|
|
141
|
-
|
|
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);
|
|
142
176
|
if (outcome === 'redirect') {
|
|
143
|
-
response.writeHead(301, { location: `${urlPath}
|
|
177
|
+
response.writeHead(301, { location: `${urlPath}/${search}` });
|
|
144
178
|
response.end();
|
|
145
179
|
return finish(301, urlPath, 'none');
|
|
146
180
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uppercut-labs/static-file-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Dependency-free Node static file server with a path-traversal guard, MIME map, range requests and optional SPA fallback.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Uppercut Labs <packages@uppercut-labs.com>",
|