zero-http 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 +21 -0
- package/README.md +311 -0
- package/documentation/controllers/cleanup.js +25 -0
- package/documentation/controllers/echo.js +14 -0
- package/documentation/controllers/headers.js +1 -0
- package/documentation/controllers/proxy.js +112 -0
- package/documentation/controllers/root.js +1 -0
- package/documentation/controllers/uploads.js +289 -0
- package/documentation/full-server.js +129 -0
- package/documentation/public/data/api.json +167 -0
- package/documentation/public/data/examples.json +62 -0
- package/documentation/public/data/options.json +13 -0
- package/documentation/public/index.html +414 -0
- package/documentation/public/prism-overrides.css +40 -0
- package/documentation/public/scripts/app.js +44 -0
- package/documentation/public/scripts/data-sections.js +300 -0
- package/documentation/public/scripts/helpers.js +166 -0
- package/documentation/public/scripts/playground.js +71 -0
- package/documentation/public/scripts/proxy.js +98 -0
- package/documentation/public/scripts/ui.js +210 -0
- package/documentation/public/scripts/uploads.js +459 -0
- package/documentation/public/styles.css +310 -0
- package/documentation/public/vendor/icons/fetch.svg +23 -0
- package/documentation/public/vendor/icons/plug.svg +27 -0
- package/documentation/public/vendor/icons/static.svg +35 -0
- package/documentation/public/vendor/icons/stream.svg +22 -0
- package/documentation/public/vendor/icons/zero.svg +21 -0
- package/documentation/public/vendor/prism-copy-to-clipboard.min.js +27 -0
- package/documentation/public/vendor/prism-javascript.min.js +1 -0
- package/documentation/public/vendor/prism-json.min.js +1 -0
- package/documentation/public/vendor/prism-okaidia.css +1 -0
- package/documentation/public/vendor/prism-toolbar.css +27 -0
- package/documentation/public/vendor/prism-toolbar.min.js +41 -0
- package/documentation/public/vendor/prism.min.js +1 -0
- package/index.js +43 -0
- package/lib/app.js +159 -0
- package/lib/body/index.js +14 -0
- package/lib/body/json.js +54 -0
- package/lib/body/multipart.js +310 -0
- package/lib/body/raw.js +40 -0
- package/lib/body/rawBuffer.js +74 -0
- package/lib/body/sendError.js +17 -0
- package/lib/body/text.js +43 -0
- package/lib/body/typeMatch.js +22 -0
- package/lib/body/urlencoded.js +166 -0
- package/lib/cors.js +72 -0
- package/lib/fetch.js +218 -0
- package/lib/logger.js +68 -0
- package/lib/rateLimit.js +64 -0
- package/lib/request.js +76 -0
- package/lib/response.js +165 -0
- package/lib/router.js +87 -0
- package/lib/static.js +196 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tony Wiedman
|
|
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
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
# zero-http
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/zero-http)
|
|
4
|
+
[](https://www.npmjs.com/package/zero-http)
|
|
5
|
+
[](https://github.com/tonywied17/zero-http-npm)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
[](https://nodejs.org)
|
|
8
|
+
[](package.json)
|
|
9
|
+
|
|
10
|
+
> **Zero-dependency, minimal Express-like HTTP server with a tiny fetch replacement and streaming multipart parsing.**
|
|
11
|
+
|
|
12
|
+
## Features
|
|
13
|
+
|
|
14
|
+
- **Zero dependencies** — implemented using Node core APIs only
|
|
15
|
+
- **Express-like API** — `createApp()`, `use()`, `get()`, `post()`, `put()`, `delete()`, `patch()`, `head()`, `options()`, `all()`, `listen()`
|
|
16
|
+
- **Built-in middlewares** — `cors()`, `json()`, `urlencoded()`, `text()`, `raw()`, `multipart()`, `rateLimit()`, `logger()`
|
|
17
|
+
- **Streaming multipart parser** — writes file parts to disk and exposes `req.body.files` and `req.body.fields`
|
|
18
|
+
- **Tiny `fetch` replacement** — convenient server-side HTTP client with progress callbacks
|
|
19
|
+
- **Static file serving** — 60+ MIME types, dotfile policy, caching, extension fallback
|
|
20
|
+
- **Error handling** — automatic 500 responses for thrown errors, global error handler via `app.onError()`
|
|
21
|
+
- **Path-prefix middleware** — `app.use('/api', handler)` with automatic URL rewriting
|
|
22
|
+
- **Rate limiting** — in-memory IP-based rate limiter with configurable windows
|
|
23
|
+
- **Request logger** — colorized dev/short/tiny log formats
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install zero-http
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
const { createApp, json } = require('zero-http')
|
|
34
|
+
const app = createApp()
|
|
35
|
+
|
|
36
|
+
app.use(json())
|
|
37
|
+
app.post('/echo', (req, res) => res.json({ received: req.body }))
|
|
38
|
+
app.listen(3000)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Demo
|
|
42
|
+
|
|
43
|
+
You can view the live documentation and playground at https://zero-http.molex.cloud, or run the demo locally:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
node documentation/full-server.js
|
|
47
|
+
# open http://localhost:3000
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## API Reference
|
|
51
|
+
|
|
52
|
+
All exports are available from the package root:
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
const { createApp, cors, fetch, json, urlencoded, text, raw, multipart, static: serveStatic, rateLimit, logger } = require('zero-http')
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
| Export | Type | Description |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `createApp()` | function | Create a new application instance (router + middleware stack). |
|
|
61
|
+
| `cors` | function | CORS middleware factory. |
|
|
62
|
+
| `fetch` | function | Small Node HTTP client with progress callbacks. |
|
|
63
|
+
| `json` | function | JSON body parser factory. |
|
|
64
|
+
| `urlencoded` | function | urlencoded body parser factory. |
|
|
65
|
+
| `text` | function | Text body parser factory. |
|
|
66
|
+
| `raw` | function | Raw bytes parser factory. |
|
|
67
|
+
| `multipart` | function | Streaming multipart parser factory. |
|
|
68
|
+
| `static` | function | Static file serving middleware factory. |
|
|
69
|
+
| `rateLimit` | function | In-memory rate-limiting middleware factory. |
|
|
70
|
+
| `logger` | function | Request-logging middleware factory. |
|
|
71
|
+
|
|
72
|
+
createApp() methods
|
|
73
|
+
|
|
74
|
+
| Method | Signature | Description |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `use` | `use(fn)` or `use(path, fn)` | Register middleware globally or scoped to a path prefix. |
|
|
77
|
+
| `get` | `get(path, ...handlers)` | Register GET route handlers. |
|
|
78
|
+
| `post` | `post(path, ...handlers)` | Register POST route handlers. |
|
|
79
|
+
| `put` | `put(path, ...handlers)` | Register PUT route handlers. |
|
|
80
|
+
| `delete` | `delete(path, ...handlers)` | Register DELETE route handlers. |
|
|
81
|
+
| `patch` | `patch(path, ...handlers)` | Register PATCH route handlers. |
|
|
82
|
+
| `options` | `options(path, ...handlers)` | Register OPTIONS route handlers. |
|
|
83
|
+
| `head` | `head(path, ...handlers)` | Register HEAD route handlers. |
|
|
84
|
+
| `all` | `all(path, ...handlers)` | Register handlers for ALL HTTP methods. |
|
|
85
|
+
| `onError` | `onError(fn)` | Register a global error handler `fn(err, req, res, next)`. |
|
|
86
|
+
| `listen` | `listen(port = 3000, cb)` | Start the HTTP server. Returns the server instance. |
|
|
87
|
+
| `handler` | property | Bound request handler for `http.createServer(app.handler)`. |
|
|
88
|
+
|
|
89
|
+
Request (`req`) properties & helpers
|
|
90
|
+
|
|
91
|
+
| Property / Method | Type | Description |
|
|
92
|
+
|---|---|---|
|
|
93
|
+
| `method` | string | HTTP method (GET, POST, etc.). |
|
|
94
|
+
| `url` | string | Request URL (path + query). |
|
|
95
|
+
| `headers` | object | Raw request headers. |
|
|
96
|
+
| `query` | object | Parsed query string. |
|
|
97
|
+
| `params` | object | Route parameters (populated by router). |
|
|
98
|
+
| `body` | any | Parsed body (populated by body parsers). |
|
|
99
|
+
| `ip` | string | Remote IP address of the client. |
|
|
100
|
+
| `get(name)` | function | Get a request header (case-insensitive). |
|
|
101
|
+
| `is(type)` | function | Check if Content-Type matches a type (e.g. `'json'`, `'text/html'`). |
|
|
102
|
+
| `raw` | object | Underlying `http.IncomingMessage`. |
|
|
103
|
+
|
|
104
|
+
Response (`res`) helpers
|
|
105
|
+
|
|
106
|
+
| Method | Signature | Description |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| `status` | `status(code)` | Set HTTP status code. Chainable. |
|
|
109
|
+
| `set` | `set(name, value)` | Set a response header. Chainable. |
|
|
110
|
+
| `get` | `get(name)` | Get a previously-set response header. |
|
|
111
|
+
| `type` | `type(ct)` | Set Content-Type (accepts shorthand like `'json'`, `'html'`, `'text'`). Chainable. |
|
|
112
|
+
| `send` | `send(body)` | Send a response; auto-detects Content-Type for strings, objects, and Buffers. |
|
|
113
|
+
| `json` | `json(obj)` | Set JSON Content-Type and send object. |
|
|
114
|
+
| `text` | `text(str)` | Set text/plain and send string. |
|
|
115
|
+
| `html` | `html(str)` | Set text/html and send string. |
|
|
116
|
+
| `redirect` | `redirect([status], url)` | Redirect to URL (default 302). |
|
|
117
|
+
|
|
118
|
+
### Body parsers
|
|
119
|
+
|
|
120
|
+
The package exposes parser factory functions under `json`, `urlencoded`, `text`, `raw`, and `multipart`.
|
|
121
|
+
|
|
122
|
+
json([opts])
|
|
123
|
+
|
|
124
|
+
| Option | Type | Default | Description |
|
|
125
|
+
|---|---:|---|---|
|
|
126
|
+
| `limit` | number|string | none | Maximum body size (bytes or unit string like `'1mb'`). |
|
|
127
|
+
| `reviver` | function | — | Function passed to `JSON.parse` for custom reviving. |
|
|
128
|
+
| `strict` | boolean | `true` | When `true` only accepts objects/arrays (rejects primitives). |
|
|
129
|
+
| `type` | string|function | `'application/json'` | MIME matcher for the parser. |
|
|
130
|
+
|
|
131
|
+
urlencoded([opts])
|
|
132
|
+
|
|
133
|
+
| Option | Type | Default | Description |
|
|
134
|
+
|---|---:|---|---|
|
|
135
|
+
| `extended` | boolean | `false` | When `true` supports rich nested bracket syntax (a[b]=1, a[]=1). |
|
|
136
|
+
| `limit` | number|string | none | Maximum body size. |
|
|
137
|
+
| `type` | string|function | `'application/x-www-form-urlencoded'` | MIME matcher. |
|
|
138
|
+
|
|
139
|
+
text([opts])
|
|
140
|
+
|
|
141
|
+
| Option | Type | Default | Description |
|
|
142
|
+
|---|---:|---|---|
|
|
143
|
+
| `type` | string|function | `text/*` | MIME matcher for text bodies. |
|
|
144
|
+
| `limit` | number|string | none | Maximum body size. |
|
|
145
|
+
| `encoding` | string | `utf8` | Character encoding used to decode bytes. |
|
|
146
|
+
|
|
147
|
+
raw([opts])
|
|
148
|
+
|
|
149
|
+
| Option | Type | Default | Description |
|
|
150
|
+
|---|---:|---|---|
|
|
151
|
+
| `type` | string|function | `application/octet-stream` | MIME matcher for raw parser. |
|
|
152
|
+
| `limit` | number|string | none | Maximum body size. |
|
|
153
|
+
|
|
154
|
+
multipart(opts)
|
|
155
|
+
|
|
156
|
+
Streaming multipart parser that writes file parts to disk and collects fields.
|
|
157
|
+
|
|
158
|
+
| Option | Type | Default | Description |
|
|
159
|
+
|---|---:|---|---|
|
|
160
|
+
| `dir` | string | `os.tmpdir()/zero-http-uploads` | Directory to store uploaded files (absolute or relative to `process.cwd()`). |
|
|
161
|
+
| `maxFileSize` | number | none | Maximum allowed file size in bytes. Exceeding this returns HTTP 413 and aborts the upload. |
|
|
162
|
+
|
|
163
|
+
Behavior: `multipart` writes file parts to disk with a generated name preserving the original extension when possible. On completion `req.body` will be `{ fields, files }` where `files` contains metadata: `originalFilename`, `storedName`, `path`, `contentType`, `size`.
|
|
164
|
+
|
|
165
|
+
### static(rootPath, opts)
|
|
166
|
+
|
|
167
|
+
Serve static files from `rootPath`.
|
|
168
|
+
|
|
169
|
+
| Option | Type | Default | Description |
|
|
170
|
+
|---|---:|---|---|
|
|
171
|
+
| `index` | string|false | `'index.html'` | File to serve for directory requests; set `false` to disable. |
|
|
172
|
+
| `maxAge` | number|string | `0` | Cache-Control `max-age` (ms or unit string like `'1h'`). |
|
|
173
|
+
| `dotfiles` | string | `'ignore'` | `'allow'|'deny'|'ignore'` — how to handle dotfiles. |
|
|
174
|
+
| `extensions` | string[] | — | Fallback extensions to try when a request omits an extension. |
|
|
175
|
+
| `setHeaders` | function | — | Hook `(res, filePath) => {}` to set custom headers per file. |
|
|
176
|
+
|
|
177
|
+
### cors([opts])
|
|
178
|
+
|
|
179
|
+
Small CORS middleware. Typical options:
|
|
180
|
+
|
|
181
|
+
| Option | Type | Default | Description |
|
|
182
|
+
|---|---:|---|---|
|
|
183
|
+
| `origin` | string|boolean|array | `'*'` | Allowed origin(s). Use `false` to disable CORS. |
|
|
184
|
+
| `methods` | string | `'GET,POST,PUT,DELETE,OPTIONS'` | Allowed methods. |
|
|
185
|
+
| `credentials` | boolean | `false` | When true and a specific origin matches, sets `Access-Control-Allow-Credentials`.
|
|
186
|
+
| `allowedHeaders` | string | — | Headers allowed in requests. |
|
|
187
|
+
|
|
188
|
+
### fetch(url, opts)
|
|
189
|
+
|
|
190
|
+
Small Node HTTP client returning an object with `status`, `headers` and helpers: `text()`, `json()`, `arrayBuffer()`.
|
|
191
|
+
|
|
192
|
+
| Option | Type | Default | Description |
|
|
193
|
+
|---|---:|---|---|
|
|
194
|
+
| `method` | string | `GET` | HTTP method. |
|
|
195
|
+
| `headers` | object | — | Request headers. |
|
|
196
|
+
| `agent` | object | — | Optional `http`/`https` agent for connection pooling or proxies. |
|
|
197
|
+
| `body` | Buffer|string|Stream|URLSearchParams|object | — | Request body. Plain objects are JSON-encoded and `Content-Type` is set to `application/json` if not provided; `URLSearchParams` produce urlencoded bodies. |
|
|
198
|
+
| `timeout` | number | — | Request timeout in milliseconds. |
|
|
199
|
+
| `signal` | AbortSignal | — | Optional `AbortSignal` to cancel the request. |
|
|
200
|
+
| `onUploadProgress` / `onDownloadProgress` | function | — | Callbacks receiving `{ loaded, total }` during transfer. |
|
|
201
|
+
|
|
202
|
+
Response: resolved value includes `ok`, `statusText`, and helpers `arrayBuffer()`, `text()`, `json()`.
|
|
203
|
+
|
|
204
|
+
Example usage:
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
const r = await fetch('https://jsonplaceholder.typicode.com/todos/1', { timeout: 5000 })
|
|
208
|
+
const data = await r.json()
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### rateLimit([opts])
|
|
212
|
+
|
|
213
|
+
In-memory, per-IP rate-limiting middleware. Sets standard `X-RateLimit-*` headers.
|
|
214
|
+
|
|
215
|
+
| Option | Type | Default | Description |
|
|
216
|
+
|---|---:|---|---|
|
|
217
|
+
| `windowMs` | number | `60000` | Time window in milliseconds. |
|
|
218
|
+
| `max` | number | `100` | Maximum requests per window per key. |
|
|
219
|
+
| `message` | string | `'Too many requests…'` | Error message returned when limit is exceeded. |
|
|
220
|
+
| `statusCode` | number | `429` | HTTP status for rate-limited responses. |
|
|
221
|
+
| `keyGenerator` | function | `(req) => req.ip` | Custom key extraction function. |
|
|
222
|
+
|
|
223
|
+
Example:
|
|
224
|
+
|
|
225
|
+
```js
|
|
226
|
+
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }))
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### logger([opts])
|
|
230
|
+
|
|
231
|
+
Request-logging middleware that prints method, url, status, and response time.
|
|
232
|
+
|
|
233
|
+
| Option | Type | Default | Description |
|
|
234
|
+
|---|---:|---|---|
|
|
235
|
+
| `format` | string | `'dev'` | Log format: `'dev'` (colorized), `'short'`, or `'tiny'`. |
|
|
236
|
+
| `logger` | function | `console.log` | Custom log function. |
|
|
237
|
+
| `colors` | boolean | auto (TTY) | Enable/disable ANSI colors. |
|
|
238
|
+
|
|
239
|
+
Example:
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
app.use(logger({ format: 'dev' }))
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Error handling
|
|
246
|
+
|
|
247
|
+
Thrown errors in route handlers are automatically caught and return a 500 JSON response. Register a custom error handler for more control:
|
|
248
|
+
|
|
249
|
+
```js
|
|
250
|
+
app.onError((err, req, res, next) => {
|
|
251
|
+
console.error(err)
|
|
252
|
+
res.status(500).json({ error: err.message })
|
|
253
|
+
})
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### Path-prefix middleware
|
|
257
|
+
|
|
258
|
+
Mount middleware on a path prefix. The URL is rewritten so downstream middleware sees relative paths:
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
app.use('/api', myApiRouter)
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
## Examples
|
|
265
|
+
|
|
266
|
+
Small JSON API:
|
|
267
|
+
|
|
268
|
+
```js
|
|
269
|
+
const { createApp, json, cors } = require('zero-http')
|
|
270
|
+
const app = createApp()
|
|
271
|
+
|
|
272
|
+
app.use(cors({ origin: ['https://example.com'] }))
|
|
273
|
+
app.use(json({ limit: '10kb' }))
|
|
274
|
+
|
|
275
|
+
const items = []
|
|
276
|
+
app.post('/items', (req, res) => {
|
|
277
|
+
items.push(req.body)
|
|
278
|
+
res.status(201)
|
|
279
|
+
res.json({ ok: true })
|
|
280
|
+
})
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Upload handler (writes files to disk by default):
|
|
284
|
+
|
|
285
|
+
```js
|
|
286
|
+
app.post('/upload', multipart({ dir: uploadsDir, maxFileSize: 10 * 1024 * 1024 }), (req, res) => {
|
|
287
|
+
res.json({ files: req.body.files })
|
|
288
|
+
})
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Static server example:
|
|
292
|
+
|
|
293
|
+
```js
|
|
294
|
+
app.use(static(path.join(__dirname, 'documentation', 'public'), { index: 'index.html', maxAge: '1h' }))
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
## File layout
|
|
298
|
+
|
|
299
|
+
- `lib/` — core helpers and middleware (router, fetch, body parsers, static, rate limiter, logger)
|
|
300
|
+
- `documentation/` — demo server, controllers and public UI used to showcase features
|
|
301
|
+
- `test/` — integration tests
|
|
302
|
+
|
|
303
|
+
## Testing
|
|
304
|
+
|
|
305
|
+
```bash
|
|
306
|
+
node test/test.js
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
## License
|
|
310
|
+
|
|
311
|
+
MIT
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Clean up temp files older than ?seconds (default 60) */
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
exports.cleanup = (tmpDirPath) => (req, res) =>
|
|
6
|
+
{
|
|
7
|
+
const olderThan = (Number(req.query.seconds) || 60) * 1000;
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
const removed = [];
|
|
10
|
+
try
|
|
11
|
+
{
|
|
12
|
+
if (fs.existsSync(tmpDirPath))
|
|
13
|
+
{
|
|
14
|
+
for (const f of fs.readdirSync(tmpDirPath))
|
|
15
|
+
{
|
|
16
|
+
try
|
|
17
|
+
{
|
|
18
|
+
const st = fs.statSync(path.join(tmpDirPath, f));
|
|
19
|
+
if (now - st.mtimeMs > olderThan) { fs.unlinkSync(path.join(tmpDirPath, f)); removed.push(f); }
|
|
20
|
+
} catch (e) { }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
} catch (e) { return res.status(500).json({ error: String(e) }); }
|
|
24
|
+
res.json({ removed });
|
|
25
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Echo JSON body back as { received: ... } */
|
|
2
|
+
const echoBody = (req, res) => res.json({ received: req.body });
|
|
3
|
+
|
|
4
|
+
exports.echoJson = echoBody;
|
|
5
|
+
exports.echo = echoBody;
|
|
6
|
+
exports.echoUrlencoded = echoBody;
|
|
7
|
+
|
|
8
|
+
exports.echoText = (req, res) => res.text(req.body || '');
|
|
9
|
+
|
|
10
|
+
exports.echoRaw = (req, res) =>
|
|
11
|
+
{
|
|
12
|
+
const b = req.body || Buffer.alloc(0);
|
|
13
|
+
res.json({ length: b.length, preview: b.slice(0, 64).toString('hex') });
|
|
14
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports.getHeaders = (req, res) => res.json({ headers: req.headers });
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Controller for proxy endpoint using built-in fetch.
|
|
3
|
+
* Proxies an external URL provided via ?url= query parameter.
|
|
4
|
+
*/
|
|
5
|
+
exports.proxy = (fetch) => async (req, res) =>
|
|
6
|
+
{
|
|
7
|
+
const url = req.query.url;
|
|
8
|
+
if (!url || typeof url !== 'string' || !/^https?:\/\//.test(url))
|
|
9
|
+
{
|
|
10
|
+
return res.status(400).json({ error: 'Missing or invalid url query parameter (must start with http/https)' });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// helper: normalize headers object from various fetch implementations
|
|
14
|
+
const normalizeResponseHeaders = (headers) =>
|
|
15
|
+
{
|
|
16
|
+
const out = {};
|
|
17
|
+
if (!headers) return out;
|
|
18
|
+
if (typeof headers.raw === 'function')
|
|
19
|
+
{
|
|
20
|
+
try { Object.assign(out, headers.raw() || {}); } catch (e) { }
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
if (headers.raw && typeof headers.raw === 'object')
|
|
24
|
+
{
|
|
25
|
+
Object.assign(out, headers.raw);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
if (typeof headers.entries === 'function')
|
|
29
|
+
{
|
|
30
|
+
for (const [k, v] of headers.entries()) { out[k] = out[k] ? out[k] + ', ' + v : v; }
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
if (typeof headers === 'object')
|
|
34
|
+
{
|
|
35
|
+
Object.assign(out, headers);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
try
|
|
41
|
+
{
|
|
42
|
+
// forward client headers useful for media requests
|
|
43
|
+
const forwardHeaders = {};
|
|
44
|
+
try
|
|
45
|
+
{
|
|
46
|
+
const inHeaders = (req.raw && req.raw.headers) ? req.raw.headers : (req.headers || {});
|
|
47
|
+
['range', 'if-range', 'accept', 'accept-encoding', 'user-agent'].forEach(h =>
|
|
48
|
+
{
|
|
49
|
+
const v = inHeaders[h] || inHeaders[h.toLowerCase()];
|
|
50
|
+
if (v) forwardHeaders[h] = v;
|
|
51
|
+
});
|
|
52
|
+
} catch (e) { }
|
|
53
|
+
|
|
54
|
+
const r = await fetch(url, { headers: forwardHeaders });
|
|
55
|
+
|
|
56
|
+
// if upstream returned an error status, try to show body (json or text)
|
|
57
|
+
if (r.status >= 400)
|
|
58
|
+
{
|
|
59
|
+
try
|
|
60
|
+
{
|
|
61
|
+
const j = await r.json();
|
|
62
|
+
return res.status(r.status).json(j);
|
|
63
|
+
} catch (e)
|
|
64
|
+
{
|
|
65
|
+
try { const txt = await r.text(); return res.status(r.status).send(txt); } catch (e2) { return res.status(r.status).send('Upstream error'); }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// If JSON response, parse and return JSON
|
|
70
|
+
const headersObj = normalizeResponseHeaders(r.headers);
|
|
71
|
+
const contentType = (headersObj['content-type'] || headersObj['Content-Type'] || '').toString();
|
|
72
|
+
if (contentType.includes('application/json'))
|
|
73
|
+
{
|
|
74
|
+
const body = await r.json();
|
|
75
|
+
return res.status(r.status).json(body);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Forward headers to raw response before streaming
|
|
79
|
+
try { res.raw.statusCode = r.status; } catch (e) { }
|
|
80
|
+
try
|
|
81
|
+
{
|
|
82
|
+
Object.entries(headersObj).forEach(([k, v]) =>
|
|
83
|
+
{
|
|
84
|
+
try { res.raw.setHeader(k, Array.isArray(v) ? v.join(', ') : v); } catch (e) { }
|
|
85
|
+
});
|
|
86
|
+
} catch (e) { }
|
|
87
|
+
|
|
88
|
+
// If upstream exposes a readable stream, pipe it directly to client
|
|
89
|
+
if (r.body && typeof r.body.pipe === 'function')
|
|
90
|
+
{
|
|
91
|
+
try
|
|
92
|
+
{
|
|
93
|
+
r.body.on && r.body.on('error', () => { try { res.raw.end(); } catch (e) { } });
|
|
94
|
+
return r.body.pipe(res.raw);
|
|
95
|
+
} catch (e) { /* fallthrough to buffering */ }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Fallback: buffer then send (some fetch implementations)
|
|
99
|
+
try
|
|
100
|
+
{
|
|
101
|
+
const ab = await r.arrayBuffer();
|
|
102
|
+
const buf = Buffer.from(ab);
|
|
103
|
+
return res.raw.end(buf);
|
|
104
|
+
} catch (e)
|
|
105
|
+
{
|
|
106
|
+
return res.status(500).json({ error: 'Failed to stream proxied response' });
|
|
107
|
+
}
|
|
108
|
+
} catch (e)
|
|
109
|
+
{
|
|
110
|
+
return res.status(500).json({ error: String(e) });
|
|
111
|
+
}
|
|
112
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
exports.getRoot = (req, res) => res.json({ ok: true, msg: 'zero-http full-server example' });
|